2 # vim:ts=4:sw=4:expandtab
3 use strict; use warnings;
5 use File::Temp qw(tmpnam tempfile tempdir);
10 use lib qw(@abs_top_srcdir@/AnyEvent-I3/blib/lib);
12 use List::Util qw(first);
13 use Time::HiRes qw(sleep);
15 use POSIX ':sys_wait_h';
16 use Scalar::Util qw(blessed);
18 use i3test::Util qw(slurp);
29 get_output_for_workspace
55 is_net_wm_state_focused
61 i3test - Testcase setup module
69 my $ws = fresh_workspace;
70 is_num_children($ws, 0, 'no containers on this workspace yet');
72 is_num_children($ws, 1, 'one container after "open"');
78 This module is used in every i3 testcase and takes care of automatically
79 starting i3 before any test instructions run. It also saves you typing of lots
80 of boilerplate in every test file.
83 i3test automatically "use"s C<Test::More>, C<Data::Dumper>, C<AnyEvent::I3>,
84 C<Time::HiRes>’s C<sleep> and C<i3test::Test> so that all of them are available
85 to you in your testcase.
87 See also C<i3test::Test> (L<https://build.i3wm.org/docs/lib-i3test-test.html>)
88 which provides additional test instructions (like C<ok> or C<is>).
92 my $tester = Test::Builder->new();
93 my $_cached_socket_path = undef;
94 my $_sync_window = undef;
95 my $tmp_socket_path = undef;
100 my $window_count = 0;
102 return $window_count++;
110 # Skip the remaining cleanup for testcases which set i3_autostart => 0:
111 return if !defined($i3_pid) && !$i3_autostart;
113 # don't trigger SIGCHLD handler
116 # From perldoc -v '$?':
117 # Inside an "END" subroutine $? contains the value
118 # that is going to be given to "exit()".
120 # Since waitpid sets $?, we need to localize it,
121 # otherwise TAP would be misinterpreted our return status
124 # When measuring code coverage, try to exit i3 cleanly (otherwise, .gcda
125 # files are not written)
126 if ($ENV{COVERAGE} || $ENV{VALGRIND}) {
127 exit_gracefully($i3_pid, "/tmp/nested-$ENV{DISPLAY}");
131 or $tester->BAIL_OUT("could not kill i3: $!");
138 my ($class, %args) = @_;
141 $x ||= i3test::X11->new;
142 # set the pointer to a predictable position in case a previous test has
145 0, # src_window (None)
146 $x->get_root_window(), # dst_window (None)
153 # Synchronize with X11 to ensure the pointer has been warped before i3
155 $x->get_input_focus_reply($x->get_input_focus()->{sequence});
157 $i3_autostart = delete($args{i3_autostart}) // 1;
158 my $i3_config = delete($args{i3_config}) // '-default';
160 my $cv = launch_with_config($i3_config, dont_block => 1)
163 my $test_more_args = '';
164 $test_more_args = join(' ', 'qw(', %args, ')') if keys %args;
168 use Test::More $test_more_args;
171 use Time::HiRes qw(sleep);
174 $tester->BAIL_OUT("$@") if $@;
175 feature->import(":5.10");
179 $cv->recv if $i3_autostart;
182 goto \&Exporter::import;
187 =head2 wait_for_event($timeout, $callback)
189 Waits for the next event and calls the given callback for every event to
190 determine if this is the event we are waiting for.
192 Can be used to wait until a window is mapped, until a ClientMessage is
195 wait_for_event 0.25, sub { $_[0]->{response_type} == MAP_NOTIFY };
199 my ($timeout, $cb) = @_;
203 while (defined(my $event = $x->wait_for_event)) {
204 return 1 if $cb->($event);
208 =head2 wait_for_map($window)
210 Thin wrapper around wait_for_event which waits for MAP_NOTIFY.
211 Make sure to include 'structure_notify' in the window’s event_mask attribute.
213 This function is called by C<open_window>, so in most cases, you don’t need to
214 call it on your own. If you need special setup of the window before mapping,
215 you might have to map it on your own and use this function:
217 my $window = open_window(dont_map => 1);
218 # Do something special with the window first
221 # Now map it and wait until it’s been mapped
223 wait_for_map($window);
228 my $id = (blessed($win) && $win->isa('X11::XCB::Window')) ? $win->id : $win;
229 wait_for_event 4, sub {
230 $_[0]->{response_type} == MAP_NOTIFY and $_[0]->{window} == $id
234 =head2 wait_for_unmap($window)
236 Wrapper around C<wait_for_event> which waits for UNMAP_NOTIFY. Also calls
237 C<sync_with_i3> to make sure i3 also picked up and processed the UnmapNotify
240 my $ws = fresh_workspace;
241 my $window = open_window;
242 is_num_children($ws, 1, 'one window on workspace');
245 is_num_children($ws, 0, 'no more windows on this workspace');
250 # my $id = (blessed($win) && $win->isa('X11::XCB::Window')) ? $win->id : $win;
251 wait_for_event 4, sub {
252 $_[0]->{response_type} == UNMAP_NOTIFY # and $_[0]->{window} == $id
257 =head2 open_window([ $args ])
259 Opens a new window (see C<X11::XCB::Window>), maps it, waits until it got mapped
260 and synchronizes with i3.
262 The following arguments can be passed:
268 The X11 window class (e.g. WINDOW_CLASS_INPUT_OUTPUT), not to be confused with
273 An arrayref with 4 members specifying the initial geometry (position and size)
274 of the window, e.g. C<< [ 0, 100, 70, 50 ] >> for a window appearing at x=0, y=100
275 with width=70 and height=50.
277 Note that this is entirely irrelevant for tiling windows.
279 =item background_color
281 The background pixel color of the window, formatted as "#rrggbb", like HTML
282 color codes (e.g. #c0c0c0). This is useful to tell windows apart when actually
283 watching the testcases.
287 An arrayref containing strings which describe the X11 event mask we use for that
288 window. The default is C<< [ 'structure_notify' ] >>.
292 The window’s C<_NET_WM_NAME> (UTF-8 window title). By default, this is "Window
293 n" with n being replaced by a counter to keep windows apart.
297 Set to a true value to avoid mapping the window (making it visible).
301 A coderef which is called before the window is mapped (unless C<dont_map> is
302 true). The freshly created C<$window> is passed as C<$_> and as the first
307 The default values are equivalent to this call:
310 class => WINDOW_CLASS_INPUT_OUTPUT
311 rect => [ 0, 0, 30, 30 ]
312 background_color => '#c0c0c0'
313 event_mask => [ 'structure_notify' ]
317 Usually, though, calls are simpler:
319 my $top_window = open_window;
321 To identify the resulting window object in i3 commands, use the id property:
323 my $top_window = open_window;
324 cmd '[id="' . $top_window->id . '"] kill';
328 my %args = @_ == 1 ? %{$_[0]} : @_;
330 my $dont_map = delete $args{dont_map};
331 my $before_map = delete $args{before_map};
333 $args{class} //= WINDOW_CLASS_INPUT_OUTPUT;
334 $args{rect} //= [ 0, 0, 30, 30 ];
335 $args{background_color} //= '#c0c0c0';
336 $args{event_mask} //= [ 'structure_notify' ];
337 $args{name} //= 'Window ' . counter_window();
339 my $window = $x->root->create_child(%args);
340 $window->add_hint('input');
343 # TODO: investigate why _create is not needed
345 $before_map->($window) for $window;
348 return $window if $dont_map;
351 wait_for_map($window);
353 # MapWindow is sent before i3 even starts rendering: the window is placed at
354 # temporary off-screen coordinates first, and x_push_changes() sends further
355 # X11 requests to set focus etc. Hence, we sync with i3 before continuing.
361 =head2 open_floating_window([ $args ])
363 Thin wrapper around open_window which sets window_type to
364 C<_NET_WM_WINDOW_TYPE_UTILITY> to make the window floating.
366 The arguments are the same as those of C<open_window>.
369 sub open_floating_window {
370 my %args = @_ == 1 ? %{$_[0]} : @_;
372 $args{window_type} = $x->atom(name => '_NET_WM_WINDOW_TYPE_UTILITY');
374 return open_window(\%args);
380 my $reply = $i3->command('open')->recv;
381 return $reply->[0]->{id};
384 =head2 get_workspace_names()
386 Returns an arrayref containing the name of every workspace (regardless of its
387 output) which currently exists.
389 my $workspace_names = get_workspace_names;
390 is(scalar @$workspace_names, 3, 'three workspaces exist currently');
393 sub get_workspace_names {
394 my $i3 = i3(get_socket_path());
395 my $tree = $i3->get_tree->recv;
396 my @outputs = @{$tree->{nodes}};
398 for my $output (@outputs) {
399 next if $output->{name} eq '__i3';
400 # get the first CT_CON of each output
401 my $content = first { $_->{type} eq 'con' } @{$output->{nodes}};
402 @cons = (@cons, @{$content->{nodes}});
404 [ map { $_->{name} } @cons ]
407 =head2 get_output_for_workspace()
409 Returns the name of the output on which this workspace resides
411 cmd 'focus output fake-1';
413 is(get_output_for_workspace('1', 'fake-0', 'Workspace 1 in output fake-0');
416 sub get_output_for_workspace {
417 my $ws_name = shift @_;
418 my $i3 = i3(get_socket_path());
419 my $tree = $i3->get_tree->recv;
420 my @outputs = @{$tree->{nodes}};
422 foreach (grep { not $_->{name} =~ /^__/ } @outputs) {
423 my $output = $_->{name};
424 foreach (grep { $_->{name} =~ "content" } @{$_->{nodes}}) {
425 return $output if $_->{nodes}[0]->{name} =~ $ws_name;
430 =head2 get_unused_workspace
432 Returns a workspace name which has not yet been used. See also
433 C<fresh_workspace> which directly switches to an unused workspace.
435 my $ws = get_unused_workspace;
439 sub get_unused_workspace {
440 my @names = get_workspace_names();
442 do { $tmp = tmpnam() } while ((scalar grep { $_ eq $tmp } @names) > 0);
446 =head2 fresh_workspace([ $args ])
448 Switches to an unused workspace and returns the name of that workspace.
450 Optionally switches to the specified output first.
452 my $ws = fresh_workspace;
454 # Get a fresh workspace on the second output.
455 my $ws = fresh_workspace(output => 1);
458 sub fresh_workspace {
460 if (exists($args{output})) {
461 my $i3 = i3(get_socket_path());
462 my $tree = $i3->get_tree->recv;
463 my $output = first { $_->{name} eq "fake-$args{output}" }
465 die "BUG: Could not find output $args{output}" unless defined($output);
466 # Get the focused workspace on that output and switch to it.
467 my $content = first { $_->{type} eq 'con' } @{$output->{nodes}};
468 my $focused = $content->{focus}->[0];
469 my $workspace = first { $_->{id} == $focused } @{$content->{nodes}};
470 $workspace = $workspace->{name};
471 cmd("workspace $workspace");
474 my $unused = get_unused_workspace;
475 cmd("workspace $unused");
479 =head2 get_ws($workspace)
481 Returns the container (from the i3 layout tree) which represents C<$workspace>.
483 my $ws = fresh_workspace;
484 my $ws_con = get_ws($ws);
485 ok(!$ws_con->{urgent}, 'fresh workspace not marked urgent');
487 Here is an example which counts the number of urgent containers recursively,
488 starting from the workspace container:
493 my @children = (@{$con->{nodes}}, @{$con->{floating_nodes}});
494 my $urgent = grep { $_->{urgent} } @children;
495 $urgent += count_urgent($_) for @children;
498 my $urgent = count_urgent(get_ws($ws));
499 is($urgent, 3, "three urgent windows on workspace $ws");
505 my $i3 = i3(get_socket_path());
506 my $tree = $i3->get_tree->recv;
508 my @outputs = @{$tree->{nodes}};
510 for my $output (@outputs) {
511 # get the first CT_CON of each output
512 my $content = first { $_->{type} eq 'con' } @{$output->{nodes}};
513 @workspaces = (@workspaces, @{$content->{nodes}});
516 # as there can only be one workspace with this name, we can safely
517 # return the first entry
518 return first { $_->{name} eq $name } @workspaces;
521 =head2 get_ws_content($workspace)
523 Returns the content (== tree, starting from the node of a workspace)
524 of a workspace. If called in array context, also includes the focus
525 stack of the workspace.
527 my $nodes = get_ws_content($ws);
528 is(scalar @$nodes, 4, 'there are four containers at workspace-level');
530 Or, in array context:
532 my $window = open_window;
533 my ($nodes, $focus) = get_ws_content($ws);
534 is($focus->[0], $window->id, 'newly opened window focused');
536 Note that this function does not do recursion for you! It only returns the
537 containers B<on workspace level>. If you want to work with all containers (even
538 nested ones) on a workspace, you have to use recursion:
540 # NB: This function does not count floating windows
545 for my $con (@$nodes) {
546 $urgent++ if $con->{urgent};
547 $urgent += count_urgent($con->{nodes});
552 my $nodes = get_ws_content($ws);
553 my $urgent = count_urgent($nodes);
554 is($urgent, 3, "three urgent windows on workspace $ws");
556 If you also want to deal with floating windows, you have to use C<get_ws>
557 instead and access C<< ->{nodes} >> and C<< ->{floating_nodes} >> on your own.
562 my $con = get_ws($name);
563 return wantarray ? ($con->{nodes}, $con->{focus}) : $con->{nodes};
566 =head2 get_focused($workspace)
568 Returns the container ID of the currently focused container on C<$workspace>.
570 Note that the container ID is B<not> the X11 window ID, so comparing the result
571 of C<get_focused> with a window's C<< ->{id} >> property does B<not> work.
573 my $ws = fresh_workspace;
574 my $first_window = open_window;
575 my $first_id = get_focused();
577 my $second_window = open_window;
578 my $second_id = get_focused();
582 is(get_focused($ws), $first_id, 'second window focused');
587 my $con = get_ws($ws);
589 my @focused = @{$con->{focus}};
591 while (@focused > 0) {
593 last unless defined($con->{focus});
594 @focused = @{$con->{focus}};
595 my @cons = grep { $_->{id} == $lf } (@{$con->{nodes}}, @{$con->{'floating_nodes'}});
602 =head2 get_dock_clients([ $dockarea ])
604 Returns an array of all dock containers in C<$dockarea> (one of "top" or
605 "bottom"). If C<$dockarea> is not specified, returns an array of all dock
606 containers in any dockarea.
608 my @docked = get_dock_clients;
609 is(scalar @docked, 0, 'no dock clients yet');
612 sub get_dock_clients {
615 my $tree = i3(get_socket_path())->get_tree->recv;
616 my @outputs = @{$tree->{nodes}};
617 # Children of all dockareas
619 for my $output (@outputs) {
620 if (!defined($which)) {
621 @docked = (@docked, map { @{$_->{nodes}} }
622 grep { $_->{type} eq 'dockarea' }
623 @{$output->{nodes}});
624 } elsif ($which eq 'top') {
625 my $first = first { $_->{type} eq 'dockarea' } @{$output->{nodes}};
626 @docked = (@docked, @{$first->{nodes}}) if defined($first);
627 } elsif ($which eq 'bottom') {
628 my @matching = grep { $_->{type} eq 'dockarea' } @{$output->{nodes}};
629 my $last = $matching[-1];
630 @docked = (@docked, @{$last->{nodes}}) if defined($last);
638 Sends the specified command to i3 and returns the output.
640 my $ws = unused_workspace;
646 i3(get_socket_path())->command(@_)->recv
649 =head2 workspace_exists($workspace)
651 Returns true if C<$workspace> is the name of an existing workspace.
653 my $old_ws = focused_ws;
654 # switch away from where we currently are
657 ok(workspace_exists($old_ws), 'old workspace still exists');
660 sub workspace_exists {
662 (scalar grep { $_ eq $name } @{get_workspace_names()}) > 0;
667 Returns the name of the currently focused workspace.
670 is($ws, '1', 'i3 starts on workspace 1');
674 my $i3 = i3(get_socket_path());
675 my $tree = $i3->get_tree->recv;
676 my $focused = $tree->{focus}->[0];
677 my $output = first { $_->{id} == $focused } @{$tree->{nodes}};
678 my $content = first { $_->{type} eq 'con' } @{$output->{nodes}};
679 my $first = first { $_->{fullscreen_mode} == 1 } @{$content->{nodes}};
680 return $first->{name}
683 =head2 sync_with_i3([ $args ])
685 Sends an I3_SYNC ClientMessage with a random value to the root window.
686 i3 will reply with the same value, but, due to the order of events it
687 processes, only after all other events are done.
689 This can be used to ensure the results of a cmd 'focus left' are pushed to
690 X11 and that C<< $x->input_focus >> returns the correct value afterwards.
692 See also L<https://build.i3wm.org/docs/testsuite.html> for a longer explanation.
694 my $window = open_window;
695 $window->add_hint('urgency');
696 # Ensure i3 picked up the change
699 The only time when you need to use the C<no_cache> argument is when you just
700 killed your own X11 connection:
703 # We need to re-establish the X11 connection which we just killed :).
704 $x = i3test::X11->new;
705 sync_with_i3(no_cache => 1);
709 my %args = @_ == 1 ? %{$_[0]} : @_;
711 # Since we need a (mapped) window for receiving a ClientMessage, we create
712 # one on the first call of sync_with_i3. It will be re-used in all
714 if (!exists($args{window_id}) &&
715 (!defined($_sync_window) || exists($args{no_cache}))) {
716 $_sync_window = open_window(
717 rect => [ -15, -15, 10, 10 ],
718 override_redirect => 1,
723 my $window_id = delete $args{window_id};
724 $window_id //= $_sync_window->id;
726 my $root = $x->get_root_window();
727 # Generate a random number to identify this particular ClientMessage.
728 my $myrnd = int(rand(255)) + 1;
730 # Generate a ClientMessage, see xcb_client_message_t
731 my $msg = pack "CCSLLLLLLL",
732 CLIENT_MESSAGE, # response_type
735 $root, # destination window
736 $x->atom(name => 'I3_SYNC')->id,
738 $window_id, # data[0]: our own window id
739 $myrnd, # data[1]: a random value to identify the request
744 # Send it to the root window -- since i3 uses the SubstructureRedirect
745 # event mask, it will get the ClientMessage.
746 $x->send_event(0, $root, EVENT_MASK_SUBSTRUCTURE_REDIRECT, $msg);
748 return $myrnd if $args{dont_wait_for_event};
750 # now wait until the reply is here
751 return wait_for_event 4, sub {
754 return 0 unless $event->{response_type} == 161;
756 my ($win, $rnd) = unpack "LL", $event->{data};
757 return ($rnd == $myrnd);
761 =head2 exit_gracefully($pid, [ $socketpath ])
763 Tries to exit i3 gracefully (with the 'exit' cmd) or kills the PID if that fails.
765 If C<$socketpath> is not specified, C<get_socket_path()> will be called.
767 You only need to use this function if you have launched i3 on your own with
768 C<launch_with_config>. Otherwise, it will be automatically called when the
771 use i3test i3_autostart => 0;
772 my $pid = launch_with_config($config);
774 exit_gracefully($pid);
777 sub exit_gracefully {
778 my ($pid, $socketpath) = @_;
779 $socketpath ||= get_socket_path();
783 say "Exiting i3 cleanly...";
784 i3($socketpath)->command('exit')->recv;
790 or $tester->BAIL_OUT("could not kill i3: $!");
793 if ($socketpath =~ m,^/tmp/i3-test-socket-,) {
801 =head2 exit_forcefully($pid, [ $signal ])
803 Tries to exit i3 forcefully by sending a signal (defaults to SIGTERM).
805 You only need to use this function if you want to test signal handling
806 (in which case you must have launched i3 on your own with
807 C<launch_with_config>).
809 use i3test i3_autostart => 0;
810 my $pid = launch_with_config($config);
812 exit_forcefully($pid);
815 sub exit_forcefully {
816 my ($pid, $signal) = @_;
819 # Send the given signal to the i3 instance and wait for up to 10s
820 # for it to terminate.
822 or $tester->BAIL_OUT("could not kill i3: $!");
826 $status = waitpid $pid, WNOHANG;
832 } while ($status <= 0 && $timeout > 0);
836 or $tester->BAIL_OUT("could not kill i3: $!");
842 =head2 get_socket_path([ $cache ])
844 Gets the socket path from the C<I3_SOCKET_PATH> atom stored on the X11 root
845 window. After the first call, this function will return a cached version of the
846 socket path unless you specify a false value for C<$cache>.
848 my $i3 = i3(get_socket_path());
849 $i3->command('nop test example')->recv;
853 my $i3 = i3(get_socket_path(0));
856 sub get_socket_path {
860 if ($cache && defined($_cached_socket_path)) {
861 return $_cached_socket_path;
863 my $socketpath = i3test::Util::get_socket_path($x);
864 $_cached_socket_path = $socketpath;
868 =head2 launch_with_config($config, [ $args ])
870 Launches a new i3 process with C<$config> as configuration file. Useful for
871 tests which test specific config file directives.
873 use i3test i3_autostart => 0;
876 # i3 config file (v4)
877 for_window [class="borderless"] border none
878 for_window [title="special borderless title"] border none
881 my $pid = launch_with_config($config);
885 exit_gracefully($pid);
888 sub launch_with_config {
889 my ($config, %args) = @_;
891 $tmp_socket_path = "/tmp/nested-$ENV{DISPLAY}";
893 $args{dont_create_temp_dir} //= 0;
894 $args{validate_config} //= 0;
896 my ($fh, $tmpfile) = tempfile("i3-cfg-for-$ENV{TESTNAME}-XXXXX", UNLINK => 1);
898 say $fh "ipc-socket $tmp_socket_path"
899 unless $args{dont_add_socket_path};
901 if ($config ne '-default') {
904 open(my $conf_fh, '<', '@abs_top_srcdir@/testcases/i3-test.config')
905 or $tester->BAIL_OUT("could not open default config: $!");
907 say $fh scalar <$conf_fh>;
912 my $cv = AnyEvent->condvar;
913 $i3_pid = activate_i3(
914 unix_socket_path => "$tmp_socket_path-activation",
915 display => $ENV{DISPLAY},
916 configfile => $tmpfile,
917 outdir => $ENV{OUTDIR},
918 testname => $ENV{TESTNAME},
919 valgrind => $ENV{VALGRIND},
920 strace => $ENV{STRACE},
921 xtrace => $ENV{XTRACE},
922 restart => $ENV{RESTART},
924 dont_create_temp_dir => $args{dont_create_temp_dir},
925 validate_config => $args{validate_config},
926 inject_randr15 => $args{inject_randr15},
927 inject_randr15_outputinfo => $args{inject_randr15_outputinfo},
930 # If we called i3 with -C, we wait for it to exit and then return as
931 # there's nothing else we need to do.
932 if ($args{validate_config}) {
936 # We need this since exit_gracefully will not be called in this case.
939 return ${^CHILD_ERROR_NATIVE};
942 # force update of the cached socket path in lib/i3test
943 # as soon as i3 has started
944 $cv->cb(sub { get_socket_path(0) });
946 return $cv if $args{dont_block};
948 # blockingly wait until i3 is ready
956 Returns the content of the log file for the current test.
960 my $logfile = "$ENV{OUTDIR}/i3-log-for-$ENV{TESTNAME}";
961 return slurp($logfile);
964 =head2 kill_all_windows
966 Kills all windows to clean up between tests.
969 sub kill_all_windows {
970 # Sync in case not all windows are managed by i3 just yet.
972 cmd '[title=".*"] kill';
975 =head2 events_for($subscribecb, [ $rettype ], [ $eventcbs ])
977 Helper function which returns an array containing all events of type $rettype
978 which were generated by i3 while $subscribecb was running.
980 Set $eventcbs to subscribe to multiple event types and/or perform your own event
985 my ($subscribecb, $rettype, $eventcbs) = @_;
989 if (defined($rettype)) {
990 $eventcbs->{$rettype} = sub { push @events, shift };
992 my $subscribed = AnyEvent->condvar;
993 my $flushed = AnyEvent->condvar;
994 $eventcbs->{tick} = sub {
996 if ($event->{first}) {
997 $subscribed->send($event);
999 $flushed->send($event);
1002 my $i3 = i3(get_socket_path(0));
1004 $i3->subscribe($eventcbs)->recv;
1006 # Subscription established, run the callback.
1008 # Now generate a tick event, which we know we’ll receive (and at which point
1009 # all other events have been received).
1010 my $nonce = int(rand(255)) + 1;
1011 $i3->send_tick($nonce);
1013 my $tick = $flushed->recv;
1014 $tester->is_eq($tick->{payload}, $nonce, 'tick nonce received');
1018 =head2 listen_for_binding($cb)
1020 Helper function to evaluate whether sending KeyPress/KeyRelease events via XTEST
1021 triggers an i3 key binding or not. Expects key bindings to be configured in the
1022 form “bindsym <binding> nop <binding>”, e.g. “bindsym Mod4+Return nop
1025 is(listen_for_binding(
1027 xtest_key_press(133); # Super_L
1028 xtest_key_press(36); # Return
1029 xtest_key_release(36); # Return
1030 xtest_key_release(133); # Super_L
1035 'triggered the "Mod4+Return" keybinding');
1039 sub listen_for_binding {
1041 my $triggered = AnyEvent->condvar;
1042 my @events = events_for(
1046 $tester->is_eq(scalar @events, 1, 'Received precisely one event');
1047 $tester->is_eq($events[0]->{change}, 'run', 'change is "run"');
1048 # We look at the command (which is “nop <binding>”) because that is easier
1049 # than re-assembling the string representation of $event->{binding}.
1050 my $command = $events[0]->{binding}->{command};
1051 $command =~ s/^nop //g;
1055 =head2 is_net_wm_state_focused
1057 Returns true if the given window has the _NET_WM_STATE_FOCUSED atom.
1059 ok(is_net_wm_state_focused($window), '_NET_WM_STATE_FOCUSED set');
1062 sub is_net_wm_state_focused {
1066 my $atom = $x->atom(name => '_NET_WM_STATE_FOCUSED');
1067 my $cookie = $x->get_property(
1070 $x->atom(name => '_NET_WM_STATE')->id,
1071 GET_PROPERTY_TYPE_ANY,
1076 my $reply = $x->get_property_reply($cookie->{sequence});
1077 my $len = $reply->{length};
1078 return 0 if $len == 0;
1080 my @atoms = unpack("L$len", $reply->{value});
1081 for (my $i = 0; $i < $len; $i++) {
1082 return 1 if $atoms[$i] == $atom->id;
1088 =head2 cmp_tree([ $args ])
1090 Compares the tree layout before and after an operation inside a subtest.
1092 The following arguments can be passed:
1098 Required argument. The initial layout to be created. For example,
1099 'H[ V[ a* S[ b c ] d ] e ]' or 'V[a b] T[c d*]'.
1100 The layout will be converted to a JSON file which will be passed to i3's
1101 append_layout command.
1103 The syntax's rules, assertions and limitations are:
1109 Upper case letters H, V, S, T mean horizontal, vertical, stacked and tabbed
1110 layout respectively. They must be followed by an opening square bracket and must
1111 be closed with a closing square bracket.
1112 Each of the non-leaf containers is marked with their corresponding letter
1113 followed by a number indicating the position of the container relative to other
1114 containers of the same type. For example, 'H[V[xxx] V[xxx] H[xxx]]' will mark
1115 the non-leaf containers as H1, V1, V2, H2.
1123 Other alphanumeric characters mean a new window which uses the provided
1124 character for its class and name. Eg 'H[a b]' will open windows with classes 'a'
1125 and 'b' inside a horizontal split. Windows use a single character for their
1126 class, eg 'H[xxx]' will open 3 windows with class 'x'.
1130 Asterisks after a window mean that the window must be focused after the layout
1131 is loaded. Currently, focusing non-leaf containers must be done manually, in the
1132 callback (C<cb>) function.
1138 Subroutine to be called after the layout provided by C<layout_before> is created
1139 but before the resulting layout (C<layout_after>) is checked.
1143 Required argument. The final layout in which the tree is expected to be after
1144 the callback is called. Uses the same syntax with C<layout_before>.
1145 For non-leaf containers, their layout (horizontal, vertical, stacked, tabbed)
1146 is compared with the corresponding letter (H, V, S, T).
1147 For leaf containers, their name is compared with the provided alphanumeric.
1151 The workspace in which the layout will be created. Will switch focus to it. If
1152 not provided, a new one is created.
1156 Message to prepend to the subtest's name. If not empty, it will be followed by ': '.
1160 By default, all windows are killed before the C<layout_before> layout is loaded.
1161 Set to 1 to avoid this.
1167 local $Test::Builder::Level = $Test::Builder::Level + 1;
1172 cmd "workspace $ws";
1174 $ws = fresh_workspace;
1178 $msg = $args{msg} . ': ';
1180 die unless $args{layout_before};
1181 die unless $args{layout_after};
1183 kill_all_windows unless $args{dont_kill};
1184 my @windows = create_layout($args{layout_before});
1185 Test::More::subtest $msg . $args{layout_before} . ' -> ' . $args{layout_after} => sub {
1186 $args{cb}->(\@windows) if $args{cb};
1187 verify_layout($args{layout_after}, $ws);
1200 my %layout_counts = (H => 0, V => 0, S => 0, T => 0);
1202 foreach my $char (split('', $layout)) {
1204 $r = $r . '{"layout": "splith",';
1205 $r = $r . '"marks": ["H' . ++$layout_counts{H} . '"],';
1206 } elsif ($char eq 'V') {
1207 $r = $r . '{"layout": "splitv",';
1208 $r = $r . '"marks": ["V' . ++$layout_counts{V} . '"],';
1209 } elsif ($char eq 'S') {
1210 $r = $r . '{"layout": "stacked",';
1211 $r = $r . '"marks": ["S' . ++$layout_counts{S} . '"],';
1212 } elsif ($char eq 'T') {
1213 $r = $r . '{"layout": "tabbed",';
1214 $r = $r . '"marks": ["T' . ++$layout_counts{T} . '"],';
1215 } elsif ($char eq '[') {
1217 $r = $r . '"nodes": [';
1218 } elsif ($char eq ']') {
1219 # End of nodes array: delete trailing comma.
1221 # When we are at depth 0 we need to split using newlines, making
1222 # multiple "JSON texts".
1224 $r = $r . ']}' . ($depth == 0 ? "\n" : ',');
1225 } elsif ($char eq ' ') {
1226 } elsif ($char eq '*') {
1227 $focus = $windows[$#windows];
1228 } elsif ($char =~ /[[:alnum:]]/) {
1229 push @windows, $char;
1231 $r = $r . '{"swallows": [{';
1232 $r = $r . '"class": "^' . "$char" . '$"';
1235 die "Could not understand $char";
1239 die "Invalid layout, depth is $depth > 0" unless $depth == 0;
1241 Test::More::diag($r);
1242 my ($fh, $tmpfile) = tempfile("layout-XXXXXX", UNLINK => 1);
1246 my $return = cmd "append_layout $tmpfile";
1247 die 'Could not parse layout json file' unless $return->[0]->{success};
1250 push @result_windows, open_window(wm_class => "$_", name => "$_") foreach @windows;
1251 cmd '[class=' . $focus . '] focus' if $focus;
1253 return @result_windows;
1257 my ($layout, $ws) = @_;
1259 my $nodes = get_ws_content($ws);
1264 foreach my $char (split('', $layout)) {
1268 $node_layout = 'splith';
1269 } elsif ($char eq 'V') {
1270 $node_layout = 'splitv';
1271 } elsif ($char eq 'S') {
1272 $node_layout = 'stacked';
1273 } elsif ($char eq 'T') {
1274 $node_layout = 'tabbed';
1275 } elsif ($char eq '[') {
1277 delete $counters{$depth};
1278 } elsif ($char eq ']') {
1280 } elsif ($char eq ' ') {
1281 } elsif ($char eq '*') {
1282 $tester->is_eq($node->{focused}, 1, 'Correct node focused');
1283 } elsif ($char =~ /[[:alnum:]]/) {
1286 die "Could not understand $char";
1289 if ($node_layout || $node_name) {
1290 if (exists($counters{$depth})) {
1291 $counters{$depth} = $counters{$depth} + 1;
1293 $counters{$depth} = 0;
1296 $node = $nodes->[$counters{0}];
1297 for my $i (1 .. $depth) {
1298 $node = $node->{nodes}->[$counters{$i}];
1302 $tester->is_eq($node->{layout}, $node_layout, "Layouts match in depth $depth, node number " . $counters{$depth});
1304 $tester->is_eq($node->{name}, $node_name, "Names match in depth $depth, node number " . $counters{$depth});
1314 Michael Stapelberg <michael@i3wm.org>
1318 package i3test::X11;
1319 use parent 'X11::XCB::Connection';
1323 i3test::sync_with_i3();
1325 return $self->SUPER::input_focus(@_);