korgwm.pm untested

filter: Statementstmt 0.0% 0 / 470 Branchbran 0.0% 0 / 168 Conditioncond 0.0% 0 / 158 MC/DCmcdc 0.0% 0 / 92 Subroutinesub 0.0% 0 / 29 Podpod 0.0% 0 / 5 totaltotal 0.0% 0 / 922 CC 85 SCAR 72.6
CC
85
Cov
0%
FireInTheHole
2862.0
handle_screens
420.0
annihilate_window
110.0
CRAP 1428.2
1 #!/usr/bin/perl
2 # made by: KorG
3 # vim: cc=119 et sw=4 ts=4 :
4 package X11::korgwm;
5 use strict;
6 use warnings;
7 use feature 'signatures';
8  
9 our $VERSION = "6.1";
10  
11 # Third-party includes
12 use X11::XCB 0.24 ':all';
13 use X11::XCB::Connection;
14 use AnyEvent;
15 use List::Util qw( any first min max none );
16  
17 # Those two should be included prior any DEBUG stuf
18 use X11::korgwm::Common;
19 use X11::korgwm::Config;
20  
21 # Early initialize debug output, if needed. Should run after Common & Config
22 BEGIN {
23 DEBUG1 and do {
24 require Data::Dumper;
25 Data::Dumper->import();
26 $Data::Dumper::Sortkeys = 1;
27 };
28 }
29  
30 # Load all other modules
31 use X11::korgwm::Panel::Battery;
32 use X11::korgwm::Panel::Clock;
33 use X11::korgwm::Panel::Lang;
34 use X11::korgwm::Panel;
35 use X11::korgwm::Layout;
36 use X11::korgwm::Window;
37 use X11::korgwm::Screen;
38 use X11::korgwm::EWMH;
39 use X11::korgwm::Xkb;
40 use X11::korgwm::Expose;
41 use X11::korgwm::API;
42 use X11::korgwm::Mouse;
43 use X11::korgwm::Hotkeys;
44 use X11::korgwm::Notifications;
45  
46 # Should you want understand this, first read carefully:
47 # - libxcb source code
48 # - X11::XCB source code
49 # - https://www.x.org/releases/X11R7.7/doc/xproto/x11protocol.txt
50 # - https://specifications.freedesktop.org/wm-spec/wm-spec-latest.html
51 # ... though this code is written once to read never.
52  
53 ## Define internal variables
54 # Ignore CHLD
55 $SIG{CHLD} = "IGNORE";
56 # Aliases for event masks
57 my %evt_masks = (x => CONFIG_WINDOW_X, y => CONFIG_WINDOW_Y, w => CONFIG_WINDOW_WIDTH, h => CONFIG_WINDOW_HEIGHT);
58 # Default event mask for new windows
59 my $new_window_event_mask = EVENT_MASK_ENTER_WINDOW | EVENT_MASK_PROPERTY_CHANGE | EVENT_MASK_FOCUS_CHANGE;
60 # Caching variable for $X->root
61 my $ROOT;
62 # Caching variable for WM_STATE atom
63 my $atom_wmstate;
64 # Flag shows that we want to ignore errors with type "Window"
65 my $prevent_window_errors;
66 # Set to True whenever we want to exit
67 our $exit_trigger;
68 # Array for selecting preferred tag during screen change event
69 my @preferred_tags = ();
70 # Array of CODErefs to be called at the end of handle_screens()
71 our @handle_screens_post_hooks;
72  
73 ## Define functions
74 # Handle any screen change
75 sub handle_screens {
76 my @xscreens = @{ $X->screens() };
77  
78 # Drop information about visible area
79 undef $visible_min_x;
80 undef $visible_min_y;
81 undef $visible_max_x;
82 undef $visible_max_y;
83  
84 # Count current screens
85 my %curr_screens;
86 for my $s (@xscreens) {
87 my ($x, $y, $w, $h) = map { $s->rect->$_ } qw( x y width height );
88 $curr_screens{"$w,$h,$x,$y"} = undef;
89  
90 # Update visible area information
91 $visible_min_x = defined $visible_min_x ? min($visible_min_x, $x) : $x;
92 $visible_min_y = defined $visible_min_y ? min($visible_min_y, $y) : $y;
93 $visible_max_x = defined $visible_max_x ? max($visible_max_x, $x + $w) : $x + $w;
94 $visible_max_y = defined $visible_max_y ? max($visible_max_y, $y + $h) : $y + $h;
95 }
96  
97 # Categorize them
98 my @del_screens = grep { not exists $curr_screens{$_} } keys %screens;
99 my @new_screens = grep { not defined $screens{$_} } keys %curr_screens;
100 my @not_changed_screens = grep { defined $screens{$_} } keys %curr_screens;
101  
102 # NOTE we do not want to throw any warnings here to make this function reentrant
103 return if @del_screens == 0 and @new_screens == 0;
104  
105 # Create screens for new displays
106 $screens{$_} = X11::korgwm::Screen->new(split ",", $_) for @new_screens;
107  
108 # Find a screen to move windows from the screen being deleted
109 my $screen_for_abandoned_windows = (@new_screens, @not_changed_screens)[0];
110 $screen_for_abandoned_windows = $screens{$screen_for_abandoned_windows};
111 croak "Unable to get the screen for abandoned windows" unless defined $screen_for_abandoned_windows;
112  
113 DEBUG1 and carp "Moving stale windows to screen: $screen_for_abandoned_windows";
114  
115 # Unfortunately, in case we have to change screen configuration, we must save preferred position for all windows
116 # Now iterate over the screens we're not going to delete (the latter will be processed inside destroy() below)
117 for my $screen (grep { my $s = $_; ! first { $s == $_ } @del_screens } @screens) {
118 my $old_screen_idx = $screen->{idx};
119  
120 for my $tag (@{ $screen->{tags} }) {
121 my $old_tag_idx = $tag->{idx};
122 $_->{pref_position}->[@screens] = [$old_screen_idx, $old_tag_idx] for $tag->windows();
123 }
124 }
125  
126 # Save preferred_tags
127 $preferred_tags[@screens] = [ map { $_->{tag_curr} } @screens ];
128  
129 # Call destroy on old screens and remove them saving pref_position for all their windows
130 for my $s (@del_screens) {
131 $screens{$s}->destroy($screen_for_abandoned_windows);
132 delete $screens{$s};
133 }
134  
135 # Sort screens based on X axis and store them in @screens
136 DEBUG2 and carp "Old screens: (@screens)";
137 @screens = map { $screens{$_} } sort {
138 (split /,/, $a)[2] <=> (split /,/, $b)[2] or # sort by x
139 (split /,/, $a)[3] <=> (split /,/, $b)[3] or # sort by y
140 $a cmp $b # sort somehow
141 } keys %screens;
142 DEBUG2 and carp "New screens: (@screens)";
143  
144 # Assign indexes to use them during possible next handle_screens events
145 $screens[$_]->{idx} = $_ for 0..$#screens;
146  
147 # Move the windows to preferred displays, if possible
148 for my $win (values %{ $windows }) {
149 # Skip always_on window because they can live only after manual creation
150 next if $win->{always_on};
151  
152 # Try to get preferred position for the window
153 my $pref_position = $win->{pref_position}->[ @screens ];
154 unless ($pref_position) {
155 # Here is the last chance for windows having no preferred position. We're almost ready to skip them
156 my $rules = $cfg->{rules}->{ $win->{cached_class} } or next;
157 my ($pref_screen, $pref_tag);
158  
159 for my $section (qw( soft_placement placement )) {
160 if (ref(my $placement = $rules->{ $section }) eq 'ARRAY') {
161 if (ref(my $desired = $placement->[ @screens ]) eq 'ARRAY') {
162 ($pref_screen, $pref_tag) = map { max($_ - 1, 0) } @{ $desired };
163 }
164 }
165 }
166  
167 next unless defined $pref_screen and defined $pref_tag;
168 next if $pref_screen >= @screens or $pref_tag >= @{ $cfg->{ws_names} };
169  
170 # I solemnly swear that I am up to no good
171 $pref_position = [ $pref_screen, $pref_tag ];
172 }
173  
174 my @win_screens = $win->screens();
175 my @win_tags = $win->tags();
176  
177 my $old_screen = $win_screens[0];
178 my $old_tag = $win_tags[0];
179  
180 # Die here if we catch strange windows
181 croak "Unimplemented preferred $win position for multiple screens=(@win_screens)" if @win_screens != 1;
182 croak "Unimplemented preferred $win position for multiple tags=(@win_tags)" if @win_tags != 1;
183  
184 # Below we consider the window belongs to a single screen and tag, so just check if they're preferred
185 next if $old_screen->{idx} == $pref_position->[0];
186  
187 my $new_screen = $screens[$pref_position->[0]] or croak "Invalid screen in pref_position";
188 my $new_tag = $new_screen->{tags}->[$pref_position->[1]] or croak "Invalid tag in pref_position";
189  
190 $new_tag->win_add($win);
191 $old_tag->win_remove($win);
192 $win->floating_move_screen($old_screen, $new_screen);
193 $win->hide() unless $new_tag == $new_screen->current_tag();
194 }
195  
196 # Select preferred tags, if possible
197 if (my $preferred_tags = $preferred_tags[@screens]) {
198 for my $screen (@screens) {
199 my $pref_tag = $preferred_tags->[ $screen->{idx} ] // croak "Invalid tag in preferred_tags";
200 $screen->tag_set_active($pref_tag, rotate => 0);
201 }
202 } else {
203 # there is no $preferred_tags for this screen configuration, try to select the only tag with a window
204 for my $screen (@screens) {
205 my @tags_with_windows = grep { defined $_->first_window(1) } @{ $screen->{tags} };
206 next if @tags_with_windows != 1;
207 next if $screen->current_tag() == $tags_with_windows[0];
208 $screen->tag_set_active($tags_with_windows[0]->{idx}, rotate => 0);
209 }
210 }
211  
212 # Refresh all the screens as we could've moved some windows around
213 $_->refresh() for @screens;
214  
215 # Call all required hooks at the end of handle_screens()
216 $_->() for @handle_screens_post_hooks;
217 }
218  
219 # Scan for existing windows and handle them
220 sub handle_existing_windows {
221 # Query for windows and process them
222 my %transients;
223 for my $wid (
224 map { $_->[0] }
225 grep { $_->[1]->{map_state} == MAP_STATE_VIEWABLE and not $_->[1]->{override_redirect} }
226 map { [ $_ => $X->get_window_attributes_reply($X->get_window_attributes($_)->{sequence}) ] }
227 @{ $X->get_query_tree_children($ROOT->id) }
228 ) {
229 if (my $transient_for = X11::korgwm::Window::_transient_for($wid)) {
230 $transients{$wid} = $transient_for;
231 next;
232 }
233 my $win = ($windows->{$wid} = X11::korgwm::Window->new($wid));
234 }
235  
236 # Process transients
237 for my $wid (keys %transients) {
238 my $win = ($windows->{$wid} = X11::korgwm::Window->new($wid));
239 $win->{transient_for} = $windows->{$transients{$wid}};
240 $windows->{$transients{$wid}}->{children}->{$wid} = undef;
241 }
242  
243 # Set proper window information
244 for my $win (values %{ $windows }) {
245 $win->{floating} = 1;
246 $X->composite_redirect_window($win->{id}, COMPOSITE_REDIRECT_AUTOMATIC);
247 $X->change_window_attributes($win->{id}, CW_EVENT_MASK, $new_window_event_mask);
248 $X->change_property(PROP_MODE_REPLACE, $win->{id}, $atom_wmstate, $atom_wmstate, 32, 1, pack L => 1);
249  
250 my ($x, $y, $w, $h) = $win->query_geometry();
251 $y = $cfg->{panel_height} if $y < $cfg->{panel_height};
252 my $bw = $cfg->{border_width};
253 my $screen = screen_by_xy($x, $y) || $focus->{screen};
254  
255 # Fix window position if they're outside of the visible screen
256 unless ($screen->contains_xy($x, $y)) {
257 $x = $screen->{x} + int(($screen->{w} - $w) / 2);
258 $y = $screen->{y} + int(($screen->{h} - $h) / 2);
259 }
260  
261 @{ $win }{qw( x y w h )} = ($x, $y, $w, $h);
262  
263 my $class = $win->class();
264 if (defined $class) {
265 push @{ $cached_classes->{ lc $class } }, $win;
266 $win->{cached_class} = lc $class;
267 }
268  
269 $win->resize_and_move($x, $y, $w + 2 * $bw, $h + 2 * $bw);
270 $screen->win_add($win)
271 }
272 $_->refresh() for reverse @screens;
273 }
274  
275 # Destroy and Unmap events handler
276 sub annihilate_window($wid) {
277 my $win = delete $windows->{$wid};
278  
279 # Window is unmanaged or unknown, teardown and return
280 unless ($win) {
281 pinned_remove(X11::korgwm::Window->mock($wid));
282 return;
283 }
284  
285 $win->{_hidden} = 1;
286  
287 # Ignore Window errors [code=3] closing multiple window at a time
288 $prevent_window_errors = AE::timer 0.1, 0, sub { $prevent_window_errors = undef };
289  
290 if ($win->{transient_for}) {
291 delete $win->{transient_for}->{children}->{$wid};
292 }
293  
294 for my $tag ($win->tags()) {
295 if ($win->{urgent}) {
296 delete $tag->{urgent_windows}->{$win};
297 $tag->{screen}->{panel}->ws_set_urgent($tag->{idx} + 1, 0) unless keys %{ $tag->{urgent_windows} };
298 }
299  
300 $tag->win_remove($win);
301 if ($win == $tag->{screen}->{focus}) {
302 $tag->{screen}->{focus} = undef;
303 $tag->{screen}->{panel}->title();
304 }
305 }
306  
307 # Remove from all the tags where it is appended
308 $_->win_remove($win) for values %{ $win->{also_tags} // {} };
309  
310 if (my $on_screen = $win->{always_on}) {
311 # Drop focus and title
312 if (($on_screen->{focus} // 0) == $win) {
313 $on_screen->{focus} = undef;
314 $on_screen->{panel}->title();
315 }
316  
317 # Remove from always_on
318 my $arr = $on_screen->{always_on};
319 $win->{always_on} = undef;
320 @{ $arr } = grep { $win != $_ } @{ $arr };
321 }
322  
323 if ($win == $focus->{window}) {
324 $focus->{window} = undef;
325 $focus->{screen}->focus();
326 }
327  
328 focus_prev_remove($win);
329 pinned_remove($win);
330  
331 # Clean-up cached classes index
332 if (my $class = $win->{cached_class}) {
333 @{ $cached_classes->{ $class } } = grep { $win != $_ } @{ $cached_classes->{ $class } };
334 }
335  
336 # Delete $win reference from %marked_windows
337 delete $marked_windows{$_} for grep { $win == $marked_windows{$_} } keys %marked_windows;
338 }
339  
340 # Main routine
341 sub FireInTheHole {
342 # Establish X11 connection
343 $X = X11::XCB::Connection->new;
344 die "Errors connecting to X11" if $X->has_error();
345  
346 # Save root window
347 $ROOT = $X->root;
348  
349 # Preload some atoms, create non-existent ones
350 $atom_wmstate = atom("WM_STATE");
351  
352 # Check for another WM
353 my $wm = $X->change_window_attributes_checked($ROOT->id, CW_EVENT_MASK,
354 EVENT_MASK_SUBSTRUCTURE_REDIRECT |
355 EVENT_MASK_SUBSTRUCTURE_NOTIFY |
356 EVENT_MASK_POINTER_MOTION
357 );
358 die "Looks like another WM is in use" if $X->request_check($wm->{sequence});
359  
360 DEBUG1 and carp "It's time to chew bubble gum with debug level=$cfg->{debug}";
361  
362 # Set root color
363 if ($cfg->{set_root_color}) {
364 $X->change_window_attributes($ROOT->id, CW_BACK_PIXEL, $cfg->{color_bg});
365 $X->clear_area(0, $ROOT->id, 0, 0, $ROOT->_rect->width, $ROOT->_rect->height);
366 }
367  
368 # Initialize RANDR
369 $X->flush();
370 qx($cfg->{randr_cmd});
371 $X->randr_select_input($ROOT->id, RANDR_NOTIFY_MASK_SCREEN_CHANGE);
372  
373 my ($RANDR_EVENT_BASE);
374 init_extension("RANDR", \$RANDR_EVENT_BASE);
375  
376 # Initialize XComposite
377 init_extension("Composite", undef);
378  
379 # Process existing screens
380 handle_screens();
381 die "No screens found" unless keys %screens;
382  
383 # Update EWMH supported declaration
384 &X11::korgwm::EWMH::declare_support();
385  
386 # Initial fill of focus structure
387 $focus = {
388 screen => $screens[0],
389 window => undef,
390 };
391  
392 # Scan for existing windows and handle them
393 handle_existing_windows();
394  
395 # Ignore not interesting events
396 add_event_ignore(CREATE_NOTIFY());
397 add_event_ignore(CONFIGURE_NOTIFY());
398 add_event_ignore(FOCUS_OUT());
399  
400 # We have to parse MapNotifies as some windows ignore substructure redirection
401 add_event_cb(MAP_NOTIFY(), sub($evt) {
402 my $wid = $evt->{window};
403 return if exists $windows->{$wid};
404  
405 # Process rules for unmanaged windows
406 my $class = X11::korgwm::Window::_class($wid) or return;
407 my $rule = $cfg->{rules}->{$class} or return;
408 $rule->{pinned} and pinned_add(X11::korgwm::Window->mock($wid));
409 });
410  
411 # Add several important event handlers
412 add_event_cb(MAP_REQUEST(), sub($evt) {
413 my ($wid, $follow, $win, $screen, $tag, $floating) = ($evt->{window}, 1);
414  
415 # Ignore windows with no class (hello Google Chrome)
416 my $class = X11::korgwm::Window::_class($wid);
417 unless (defined $class) {
418 my $wmname = X11::korgwm::Window::_title($wid) // return;
419 return S_DEBUG(1, "Ignored window $wmname with no class") unless $cfg->{noclass_whitelist}->{$wmname};
420 }
421  
422 # Create a window if needed
423 $win = $windows->{$wid};
424 if (defined $win) {
425 delete $win->{_hidden};
426 } else {
427 $win = $windows->{$wid} = X11::korgwm::Window->new($wid);
428  
429 # Ask X11 for composition redirect
430 $X->composite_redirect_window($wid, COMPOSITE_REDIRECT_AUTOMATIC);
431  
432 $X->change_window_attributes($wid, CW_EVENT_MASK, $new_window_event_mask);
433  
434 # Unconditionally set NormalState for any windows, we do not want to correctly process this property
435 $X->change_property(PROP_MODE_REPLACE, $wid, $atom_wmstate, $atom_wmstate, 32, 1, pack L => 1);
436  
437 # Fix geometry if needed
438 unless (defined $win->{x}) {
439 # Ask X11 about regular geometry
440 @{ $win }{qw( x y w h )} = $win->query_geometry();
441  
442 # Respect also WM_SIZE_HINTS
443 my $hints = $win->size_hints_get();
444  
445 if ($hints->{flags} & ICCCM_SIZE_HINT_P_MIN_SIZE) {
446 $win->{w} = $hints->{min_width} if $win->{w} < $hints->{min_width};
447 $win->{h} = $hints->{min_height} if $win->{h} < $hints->{min_height};
448 }
449  
450 if ($hints->{flags} & ICCCM_SIZE_HINT_P_MAX_SIZE) {
451 $win->{w} = $hints->{max_width} if $win->{w} > $hints->{max_width};
452 $win->{h} = $hints->{max_height} if $win->{h} > $hints->{max_height};
453 }
454 }
455 }
456  
457 # Apply rules. At this point both $screen and $tag are not defined
458 my $rule = $cfg->{rules}->{$class // ""};
459 if ($rule) {
460 defined $rule->{follow} and $follow = $rule->{follow};
461 defined $rule->{floating} and $floating = $rule->{floating};
462  
463 # XXX awaiting bugs with idx 0
464 defined $rule->{screen} and $screen = $screens[ $rule->{screen} - 1 ] // $screens[0];
465 defined $rule->{tag} and $tag = $screen->{tags}->[ $rule->{tag} - 1 ];
466  
467 # Process preferred position rules with optional fallback to previous $screen & $tag
468 my $preferred;
469 if (ref $rule->{placement} eq 'ARRAY' && ref($preferred = $rule->{placement}->[ @screens ]) eq 'ARRAY') {
470 $screen = $screens[ $preferred->[0] - 1 ] // $screen // $focus->{screen};
471 $tag = $screen->{tags}->[ $preferred->[1] - 1 ] // $tag // $screen->current_tag();
472 }
473 }
474  
475 # Process transients
476 my $transient_for = $win->transient_for() // -1;
477 $transient_for = undef unless defined $windows->{$transient_for};
478 if ($transient_for) {
479 my $parent = $windows->{$transient_for};
480  
481 # toggle_floating() won't do for transient, so do some things manually
482 $win->{floating} = 1;
483 $rule->{follow} //= $cfg->{mouse_follow};
484 $win->{transient_for} = $parent;
485 $parent->{children}->{$wid} = undef;
486  
487 $tag = ($parent->tags_visible())[0] // ($parent->tags())[0];
488 $screen = $tag->{screen};
489 $follow = 0 unless $tag == $screen->current_tag();
490 }
491  
492 # Set default screen & tag, and fix position
493 $screen //= $focus->{screen};
494 $tag //= $screen->current_tag();
495  
496 # First and simple check and correction
497 if ($win->{x} == 0) {
498 $win->{x} = $screen->{x} + int(($screen->{w} - $win->{w}) / 2);
499 $win->{y} = $screen->{y} + int(($screen->{h} - $win->{h}) / 2);
500 } elsif ($win->{x} < $screen->{x}) {
501 $win->{x} += $screen->{x};
502 }
503  
504 # Make index by initial value of WM_CLASS, save the value to Window as well for proper garbage collection
505 if (defined $class) {
506 push @{ $cached_classes->{ lc $class } }, $win;
507 $win->{cached_class} = lc $class;
508 }
509  
510 DEBUG3 and carp "Mapping $win [$class] (@{ $win }{qw( x y w h )}) screen($screen->{id}) tag($tag->{idx})";
511  
512 # Just add win to a proper tag. win->show() will be called from tag->show() during screen->refresh()
513 $tag->win_add($win);
514  
515 if ($win->{transient_for}) {
516 if ($win->{w} and $win->{h}) {
517 $win->resize_and_move(@{ $win }{qw( x y w h )});
518 } else {
519 $win->move(@{ $win }{qw( x y )});
520 }
521 }
522  
523 # This lines will apply rules
524 $win->toggle_floating(1) if $floating;
525 $win->urgency_raise(1) if $rule->{urgent};
526 $win->toggle_pinned() if $rule->{pinned};
527  
528 # I'm not sure if we properly maximize it in case we already have $tag->{maximized}
529 $win->toggle_maximize(1, allow_invisible => 1) if first {
530 atom("_NET_WM_STATE_FULLSCREEN") == $_
531 } @{ $win->get_property("_NET_WM_STATE", "ATOM") // [] };
532  
533 # We probably want to prevent EnterNotify for any MapRequest despite floatingness of the window
534 prevent_enter_notify();
535  
536 if ($tag->{max_window} and not $win == $tag->{max_window} and not $win->relative_for($tag->{max_window})) {
537 # There is some maximized window on the tag and $win is not transient for it or its children
538 # TODO consider if we want to respect $follow here
539 DEBUG2 and carp "Window $win is starting _hidden() behind some maximized one";
540 $win->show_hidden();
541 } elsif ($follow) {
542 $screen->tag_set_active($tag->{idx}, rotate => 0);
543 $screen->refresh();
544 $win->focus();
545 $win->warp_pointer() if $rule->{follow};
546 } else {
547 if ($screen->current_tag() == $tag) {
548 $screen->refresh();
549 } else {
550 $win->urgency_raise(1);
551 $win->show_hidden();
552 }
553 }
554  
555 $X->flush();
556 });
557  
558 add_event_cb(DESTROY_NOTIFY(), sub($evt) {
559 annihilate_window($evt->{window});
560 });
561  
562 add_event_cb(UNMAP_NOTIFY(), sub($evt) {
563 # We do not call unmap(), so delete any window that is being unmapped by client
564 annihilate_window($evt->{window});
565 });
566  
567 add_event_cb(CONFIGURE_REQUEST(), sub($evt) {
568 # Configure window on the server
569 my $win_id = $evt->{window};
570  
571 my $win = $windows->{$win_id};
572 unless ($win) {
573 # Send xcb_configure_notify_event_t to the window's client
574 X11::korgwm::Window::_configure_notify($win_id, @{ $evt }{qw( sequence x y w h )});
575 $X->flush();
576 return;
577 }
578  
579 # This ugly code is an answer to bad apps like Google Chrome
580 my %geom;
581 my $bw = $cfg->{border_width};
582  
583 # Parse masked fields from $evt
584 $evt->{value_mask} & $evt_masks{$_} and $geom{$_} = $evt->{$_} for qw( x y w h );
585  
586 # Try to extract missing fields
587 $geom{$_} //= $win->{$_} // $win->{"real_$_"} for qw( x y w h );
588  
589 # Ignore events for not fully configured windows. We've done our best.
590 return unless 4 == grep defined, values %geom;
591  
592 # Save desired x y w h
593 $win->{$_} = $geom{$_} for keys %geom;
594  
595 # Fix y
596 $geom{y} = $cfg->{panel_height} if $geom{y} < $cfg->{panel_height};
597  
598 # Handle floating windows properly
599 if ($win->{floating}) {
600 # Prevent ConfigureRequest moving the window out of already assigned screen (if real_* set)
601 # Otherwise: set new_screen using required win geometry if possible, or use currently focused screen.
602 my $new_screen = screen_by_xy(@{ $win }{qw( real_x real_y )}) //
603 screen_by_xy(@geom{qw( x y )}) // $focus->{screen};
604  
605 # Fix window position if it asked to place it outside of selected screen
606 unless ($new_screen->contains_xy(@geom{qw( x y )})) {
607 $geom{x} = $new_screen->{x} + int(($new_screen->{w} - $geom{w}) / 2);
608 $geom{y} = $new_screen->{y} + int(($new_screen->{h} - $geom{h}) / 2);
609  
610 # Certainly save new position
611 @{ $win }{qw( x y )} = @geom{qw( x y )};
612 }
613  
614 # For floating we need fixup border
615 $win->resize_and_move($geom{x}, $geom{y}, $geom{w} + 2 * $bw, $geom{h} + 2 * $bw);
616 } else {
617 # If window is tiled or maximized, tell it it's real size
618 @geom{qw( x y w h )} = @{ $win }{qw( real_x real_y real_w real_h )};
619  
620 # Two reasons: 1. some windows prefer not to know about their border; 2. $Layout::hide_border
621 $bw = 0 if 0 == ($win->{real_bw} // $cfg->{border_width});
622 $geom{x} += $bw;
623 $geom{y} += $bw;
624 $geom{w} -= 2 * $bw;
625 $geom{h} -= 2 * $bw;
626 }
627  
628 # Send notification to the client and return
629 $win->configure_notify($evt->{sequence}, @geom{qw( x y w h )}, 0, 0, $bw);
630 $X->flush();
631 });
632  
633 # Under certain conditions X11 grants focus to other window generating FocusIn, we'll respect this
634 add_event_cb(FOCUS_IN(), sub($evt) {
635 # Sometimes X11 sends FocusIn on rapid EnterNotifies: when pointer is not where it thinks it should be
636 return if $prevent_focus_in;
637  
638 # Skip grab-initiated events
639 return unless $evt->{mode} == 0;
640  
641 # Skip unknown and already focused windows
642 my $win = $windows->{$evt->{event}} or return;
643 return if $focus->{window} == $win;
644  
645 $win->select();
646 });
647  
648 # This will handle RandR screen change event
649 add_event_cb($RANDR_EVENT_BASE, sub($evt) {
650 qx($cfg->{randr_cmd});
651 handle_screens();
652 });
653  
654 # X11 Error handler
655 add_event_cb(XCB_NONE(), sub($evt) {
656 # https://www.x.org/releases/X11R7.7/doc/xproto/x11protocol.html#Encoding::Errors
657  
658 # Ignore Window errors [code=3] closing multiple window at a time
659 return if 3 == ($evt->{error_code} || 0) and $prevent_window_errors;
660  
661 # Log unexpected errors
662 carp sprintf "X11 Error: code=%s seq=%s res=%s %s/%s", @{ $evt }{qw( error_code sequence
663 resource_id major_code minor_code )};
664 });
665  
666 # Init our extensions
667 $_->() for our @extensions;
668  
669 # Execute autostart, if any
670 my $autostart = ref $cfg->{autostart} eq "ARRAY" ? $cfg->{autostart} : [];
671 for my $cmd (@{ $autostart }) {
672 my $cb;
673 eval { $cb = X11::korgwm::Executor::parse($cmd); 1; } or next;
674 ref $cb eq "CODE" and $cb->();
675 }
676  
677 # Set the initial pointer position, if needed
678 if (my $pos = $cfg->{initial_pointer_position}) {
679 if ($pos eq "center") {
680 my $screen = $screens[$#screens / 2];
681 $ROOT->warp_pointer(map { $screen->{$_ eq "w" ? "x" : "y"} + int($screen->{$_} / 2) - 1 } qw( w h ));
682 $screen->focus();
683 } elsif ($pos eq "hidden") {
684 $ROOT->warp_pointer($ROOT->_rect->width, $ROOT->_rect->height);
685 } else {
686 croak "Unknown initial_pointer_position: $pos";
687 }
688 }
689  
690 # Main event loop
691 for(;;) {
692 die "Segmentation fault (core dumped)\n" if $exit_trigger;
693  
694 my $limit = 1024;
695 while ($limit--) {
696 my $evt = $X->poll_for_event();
697 unless ($evt) {
698 Gtk3::main_iteration_do(0);
699 last;
700 }
701  
702 # MotionNotifies(6) are ignored anyways. No room for error
703 DEBUG9 and $evt->{response_type} != 6 and warn Dumper $evt;
704  
705 # Highest bit indicates that the source is another client
706 my $type = $evt->{response_type} & 0x7F;
707  
708 if (defined(my $evt_cb = $xcb_events{$type})) {
709 $evt_cb->($evt);
710 } elsif (exists $xcb_events_ignore{$type}) {
711 DEBUG9 and carp "Manually ignored event type: $type";
712 } else {
713 carp "Warning: missing handler for event $type";
714 }
715 }
716  
717 my $pause = AE::cv;
718 my $w = AE::timer $cpu_saver, 0, sub { $pause->send };
719 $pause->recv;
720 }
721  
722 # Not reachable code
723 die qq(Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0\n at Main.main(Main.java:26)\n);
724 }
725  
726 "Sergei Zhmylev loves FreeBSD";
727  
728 __END__