2 # vim:ts=4:sw=4:expandtab
3 use strict; use warnings;
5 use File::Temp qw(tmpnam tempfile tempdir);
11 use List::Util qw(first);
12 use Time::HiRes qw(sleep);
14 use Scalar::Util qw(blessed);
50 i3test - Testcase setup module
58 my $ws = fresh_workspace;
59 is_num_children($ws, 0, 'no containers on this workspace yet');
61 is_num_children($ws, 1, 'one container after "open"');
67 This module is used in every i3 testcase and takes care of automatically
68 starting i3 before any test instructions run. It also saves you typing of lots
69 of boilerplate in every test file.
72 i3test automatically "use"s C<Test::More>, C<Data::Dumper>, C<AnyEvent::I3>,
73 C<Time::HiRes>’s C<sleep> and C<i3test::Test> so that all of them are available
74 to you in your testcase.
76 See also C<i3test::Test> (L<http://build.i3wm.org/docs/lib-i3test-test.html>)
77 which provides additional test instructions (like C<ok> or C<is>).
81 my $tester = Test::Builder->new();
82 my $_cached_socket_path = undef;
83 my $_sync_window = undef;
84 my $tmp_socket_path = undef;
91 return $window_count++;
100 # testcases which start i3 manually should always call exit_gracefully
101 # on their own. Let’s see, whether they really did.
102 if (! $i3_autostart) {
103 return unless $i3_pid;
105 $tester->ok(undef, 'testcase called exit_gracefully()');
108 # don't trigger SIGCHLD handler
111 # From perldoc -v '$?':
112 # Inside an "END" subroutine $? contains the value
113 # that is going to be given to "exit()".
115 # Since waitpid sets $?, we need to localize it,
116 # otherwise TAP would be misinterpreted our return status
119 # When measuring code coverage, try to exit i3 cleanly (otherwise, .gcda
120 # files are not written)
121 if ($ENV{COVERAGE} || $ENV{VALGRIND}) {
122 exit_gracefully($i3_pid, "/tmp/nested-$ENV{DISPLAY}");
126 or $tester->BAIL_OUT("could not kill i3");
133 my ($class, %args) = @_;
136 $i3_autostart = delete($args{i3_autostart}) // 1;
138 my $cv = launch_with_config('-default', dont_block => 1)
141 my $test_more_args = '';
142 $test_more_args = join(' ', 'qw(', %args, ')') if keys %args;
146 use Test::More $test_more_args;
149 use Time::HiRes qw(sleep);
152 $tester->BAIL_OUT("$@") if $@;
153 feature->import(":5.10");
157 $x ||= i3test::X11->new;
158 # set the pointer to a predictable position in case a previous test has
160 $x->root->warp_pointer(0, 0);
161 $cv->recv if $i3_autostart;
164 goto \&Exporter::import;
169 =head2 wait_for_event($timeout, $callback)
171 Waits for the next event and calls the given callback for every event to
172 determine if this is the event we are waiting for.
174 Can be used to wait until a window is mapped, until a ClientMessage is
177 wait_for_event 0.25, sub { $_[0]->{response_type} == MAP_NOTIFY };
181 my ($timeout, $cb) = @_;
187 # unfortunately, there is no constant for this
190 my $guard = AE::io $x->get_file_descriptor, $ae_read, sub {
191 while (defined(my $event = $x->poll_for_event)) {
199 # Trigger timeout after $timeout seconds (can be fractional)
200 my $t = AE::timer $timeout, 0, sub { warn "timeout ($timeout secs)"; $cv->send(0) };
202 my $result = $cv->recv;
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 2, 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 2, 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);
342 # TODO: investigate why _create is not needed
344 $before_map->($window) for $window;
347 return $window if $dont_map;
350 wait_for_map($window);
354 =head2 open_floating_window([ $args ])
356 Thin wrapper around open_window which sets window_type to
357 C<_NET_WM_WINDOW_TYPE_UTILITY> to make the window floating.
359 The arguments are the same as those of C<open_window>.
362 sub open_floating_window {
363 my %args = @_ == 1 ? %{$_[0]} : @_;
365 $args{window_type} = $x->atom(name => '_NET_WM_WINDOW_TYPE_UTILITY');
367 return open_window(\%args);
373 my $reply = $i3->command('open')->recv;
374 return $reply->[0]->{id};
377 =head2 get_workspace_names()
379 Returns an arrayref containing the name of every workspace (regardless of its
380 output) which currently exists.
382 my $workspace_names = get_workspace_names;
383 is(scalar @$workspace_names, 3, 'three workspaces exist currently');
386 sub get_workspace_names {
387 my $i3 = i3(get_socket_path());
388 my $tree = $i3->get_tree->recv;
389 my @outputs = @{$tree->{nodes}};
391 for my $output (@outputs) {
392 next if $output->{name} eq '__i3';
393 # get the first CT_CON of each output
394 my $content = first { $_->{type} == 2 } @{$output->{nodes}};
395 @cons = (@cons, @{$content->{nodes}});
397 [ map { $_->{name} } @cons ]
400 =head2 get_unused_workspace
402 Returns a workspace name which has not yet been used. See also
403 C<fresh_workspace> which directly switches to an unused workspace.
405 my $ws = get_unused_workspace;
409 sub get_unused_workspace {
410 my @names = get_workspace_names();
412 do { $tmp = tmpnam() } while ((scalar grep { $_ eq $tmp } @names) > 0);
416 =head2 fresh_workspace([ $args ])
418 Switches to an unused workspace and returns the name of that workspace.
420 Optionally switches to the specified output first.
422 my $ws = fresh_workspace;
424 # Get a fresh workspace on the second output.
425 my $ws = fresh_workspace(output => 1);
428 sub fresh_workspace {
430 if (exists($args{output})) {
431 my $i3 = i3(get_socket_path());
432 my $tree = $i3->get_tree->recv;
433 my $output = first { $_->{name} eq "fake-$args{output}" }
435 die "BUG: Could not find output $args{output}" unless defined($output);
436 # Get the focused workspace on that output and switch to it.
437 my $content = first { $_->{type} == 2 } @{$output->{nodes}};
438 my $focused = $content->{focus}->[0];
439 my $workspace = first { $_->{id} == $focused } @{$content->{nodes}};
440 $workspace = $workspace->{name};
441 cmd("workspace $workspace");
444 my $unused = get_unused_workspace;
445 cmd("workspace $unused");
449 =head2 get_ws($workspace)
451 Returns the container (from the i3 layout tree) which represents C<$workspace>.
453 my $ws = fresh_workspace;
454 my $ws_con = get_ws($ws);
455 ok(!$ws_con->{urgent}, 'fresh workspace not marked urgent');
457 Here is an example which counts the number of urgent containers recursively,
458 starting from the workspace container:
463 my @children = (@{$con->{nodes}}, @{$con->{floating_nodes}});
464 my $urgent = grep { $_->{urgent} } @children;
465 $urgent += count_urgent($_) for @children;
468 my $urgent = count_urgent(get_ws($ws));
469 is($urgent, 3, "three urgent windows on workspace $ws");
475 my $i3 = i3(get_socket_path());
476 my $tree = $i3->get_tree->recv;
478 my @outputs = @{$tree->{nodes}};
480 for my $output (@outputs) {
481 # get the first CT_CON of each output
482 my $content = first { $_->{type} == 2 } @{$output->{nodes}};
483 @workspaces = (@workspaces, @{$content->{nodes}});
486 # as there can only be one workspace with this name, we can safely
487 # return the first entry
488 return first { $_->{name} eq $name } @workspaces;
491 =head2 get_ws_content($workspace)
493 Returns the content (== tree, starting from the node of a workspace)
494 of a workspace. If called in array context, also includes the focus
495 stack of the workspace.
497 my $nodes = get_ws_content($ws);
498 is(scalar @$nodes, 4, 'there are four containers at workspace-level');
500 Or, in array context:
502 my $window = open_window;
503 my ($nodes, $focus) = get_ws_content($ws);
504 is($focus->[0], $window->id, 'newly opened window focused');
506 Note that this function does not do recursion for you! It only returns the
507 containers B<on workspace level>. If you want to work with all containers (even
508 nested ones) on a workspace, you have to use recursion:
510 # NB: This function does not count floating windows
515 for my $con (@$nodes) {
516 $urgent++ if $con->{urgent};
517 $urgent += count_urgent($con->{nodes});
522 my $nodes = get_ws_content($ws);
523 my $urgent = count_urgent($nodes);
524 is($urgent, 3, "three urgent windows on workspace $ws");
526 If you also want to deal with floating windows, you have to use C<get_ws>
527 instead and access C<< ->{nodes} >> and C<< ->{floating_nodes} >> on your own.
532 my $con = get_ws($name);
533 return wantarray ? ($con->{nodes}, $con->{focus}) : $con->{nodes};
536 =head2 get_focused($workspace)
538 Returns the container ID of the currently focused container on C<$workspace>.
540 Note that the container ID is B<not> the X11 window ID, so comparing the result
541 of C<get_focused> with a window's C<< ->{id} >> property does B<not> work.
543 my $ws = fresh_workspace;
544 my $first_window = open_window;
545 my $first_id = get_focused();
547 my $second_window = open_window;
548 my $second_id = get_focused();
552 is(get_focused($ws), $first_id, 'second window focused');
557 my $con = get_ws($ws);
559 my @focused = @{$con->{focus}};
561 while (@focused > 0) {
563 last unless defined($con->{focus});
564 @focused = @{$con->{focus}};
565 my @cons = grep { $_->{id} == $lf } (@{$con->{nodes}}, @{$con->{'floating_nodes'}});
572 =head2 get_dock_clients([ $dockarea ])
574 Returns an array of all dock containers in C<$dockarea> (one of "top" or
575 "bottom"). If C<$dockarea> is not specified, returns an array of all dock
576 containers in any dockarea.
578 my @docked = get_dock_clients;
579 is(scalar @docked, 0, 'no dock clients yet');
582 sub get_dock_clients {
585 my $tree = i3(get_socket_path())->get_tree->recv;
586 my @outputs = @{$tree->{nodes}};
587 # Children of all dockareas
589 for my $output (@outputs) {
590 if (!defined($which)) {
591 @docked = (@docked, map { @{$_->{nodes}} }
592 grep { $_->{type} == 5 }
593 @{$output->{nodes}});
594 } elsif ($which eq 'top') {
595 my $first = first { $_->{type} == 5 } @{$output->{nodes}};
596 @docked = (@docked, @{$first->{nodes}}) if defined($first);
597 } elsif ($which eq 'bottom') {
598 my @matching = grep { $_->{type} == 5 } @{$output->{nodes}};
599 my $last = $matching[-1];
600 @docked = (@docked, @{$last->{nodes}}) if defined($last);
608 Sends the specified command to i3.
610 my $ws = unused_workspace;
616 i3(get_socket_path())->command(@_)->recv
619 =head2 workspace_exists($workspace)
621 Returns true if C<$workspace> is the name of an existing workspace.
623 my $old_ws = focused_ws;
624 # switch away from where we currently are
627 ok(workspace_exists($old_ws), 'old workspace still exists');
630 sub workspace_exists {
632 (scalar grep { $_ eq $name } @{get_workspace_names()}) > 0;
637 Returns the name of the currently focused workspace.
640 is($ws, '1', 'i3 starts on workspace 1');
644 my $i3 = i3(get_socket_path());
645 my $tree = $i3->get_tree->recv;
646 my $focused = $tree->{focus}->[0];
647 my $output = first { $_->{id} == $focused } @{$tree->{nodes}};
648 my $content = first { $_->{type} == 2 } @{$output->{nodes}};
649 my $first = first { $_->{fullscreen_mode} == 1 } @{$content->{nodes}};
650 return $first->{name}
653 =head2 sync_with_i3([ $args ])
655 Sends an I3_SYNC ClientMessage with a random value to the root window.
656 i3 will reply with the same value, but, due to the order of events it
657 processes, only after all other events are done.
659 This can be used to ensure the results of a cmd 'focus left' are pushed to
660 X11 and that C<< $x->input_focus >> returns the correct value afterwards.
662 See also L<http://build.i3wm.org/docs/testsuite.html> for a longer explanation.
664 my $window = open_window;
665 $window->add_hint('urgency');
666 # Ensure i3 picked up the change
669 The only time when you need to use the C<no_cache> argument is when you just
670 killed your own X11 connection:
673 # We need to re-establish the X11 connection which we just killed :).
674 $x = i3test::X11->new;
675 sync_with_i3(no_cache => 1);
679 my %args = @_ == 1 ? %{$_[0]} : @_;
681 # Since we need a (mapped) window for receiving a ClientMessage, we create
682 # one on the first call of sync_with_i3. It will be re-used in all
684 if (!exists($args{window_id}) &&
685 (!defined($_sync_window) || exists($args{no_cache}))) {
686 $_sync_window = open_window(
687 rect => [ -15, -15, 10, 10 ],
688 override_redirect => 1,
692 my $window_id = delete $args{window_id};
693 $window_id //= $_sync_window->id;
695 my $root = $x->get_root_window();
696 # Generate a random number to identify this particular ClientMessage.
697 my $myrnd = int(rand(255)) + 1;
699 # Generate a ClientMessage, see xcb_client_message_t
700 my $msg = pack "CCSLLLLLLL",
701 CLIENT_MESSAGE, # response_type
704 $root, # destination window
705 $x->atom(name => 'I3_SYNC')->id,
707 $window_id, # data[0]: our own window id
708 $myrnd, # data[1]: a random value to identify the request
713 # Send it to the root window -- since i3 uses the SubstructureRedirect
714 # event mask, it will get the ClientMessage.
715 $x->send_event(0, $root, EVENT_MASK_SUBSTRUCTURE_REDIRECT, $msg);
717 # now wait until the reply is here
718 return wait_for_event 2, sub {
721 return 0 unless $event->{response_type} == 161;
723 my ($win, $rnd) = unpack "LL", $event->{data};
724 return ($rnd == $myrnd);
728 =head2 exit_gracefully($pid, [ $socketpath ])
730 Tries to exit i3 gracefully (with the 'exit' cmd) or kills the PID if that fails.
732 If C<$socketpath> is not specified, C<get_socket_path()> will be called.
734 You only need to use this function if you have launched i3 on your own with
735 C<launch_with_config>. Otherwise, it will be automatically called when the
738 use i3test i3_autostart => 0;
739 my $pid = launch_with_config($config);
741 exit_gracefully($pid);
744 sub exit_gracefully {
745 my ($pid, $socketpath) = @_;
746 $socketpath ||= get_socket_path();
750 say "Exiting i3 cleanly...";
751 i3($socketpath)->command('exit')->recv;
757 or $tester->BAIL_OUT("could not kill i3");
760 if ($socketpath =~ m,^/tmp/i3-test-socket-,) {
768 =head2 get_socket_path([ $cache ])
770 Gets the socket path from the C<I3_SOCKET_PATH> atom stored on the X11 root
771 window. After the first call, this function will return a cached version of the
772 socket path unless you specify a false value for C<$cache>.
774 my $i3 = i3(get_socket_path());
775 $i3->command('nop test example')->recv;
779 my $i3 = i3(get_socket_path(0));
782 sub get_socket_path {
786 if ($cache && defined($_cached_socket_path)) {
787 return $_cached_socket_path;
790 my $atom = $x->atom(name => 'I3_SOCKET_PATH');
791 my $cookie = $x->get_property(0, $x->get_root_window(), $atom->id, GET_PROPERTY_TYPE_ANY, 0, 256);
792 my $reply = $x->get_property_reply($cookie->{sequence});
793 my $socketpath = $reply->{value};
794 if ($socketpath eq "/tmp/nested-$ENV{DISPLAY}") {
795 $socketpath .= '-activation';
797 $_cached_socket_path = $socketpath;
801 =head2 launch_with_config($config, [ $args ])
803 Launches a new i3 process with C<$config> as configuration file. Useful for
804 tests which test specific config file directives.
806 use i3test i3_autostart => 0;
809 # i3 config file (v4)
810 for_window [class="borderless"] border none
811 for_window [title="special borderless title"] border none
814 my $pid = launch_with_config($config);
818 exit_gracefully($pid);
821 sub launch_with_config {
822 my ($config, %args) = @_;
824 $tmp_socket_path = "/tmp/nested-$ENV{DISPLAY}";
826 $args{dont_create_temp_dir} //= 0;
828 my ($fh, $tmpfile) = tempfile("i3-cfg-for-$ENV{TESTNAME}-XXXXX", UNLINK => 1);
830 if ($config ne '-default') {
833 open(my $conf_fh, '<', './i3-test.config')
834 or $tester->BAIL_OUT("could not open default config: $!");
836 say $fh scalar <$conf_fh>;
839 say $fh "ipc-socket $tmp_socket_path"
840 unless $args{dont_add_socket_path};
844 my $cv = AnyEvent->condvar;
845 $i3_pid = activate_i3(
846 unix_socket_path => "$tmp_socket_path-activation",
847 display => $ENV{DISPLAY},
848 configfile => $tmpfile,
849 outdir => $ENV{OUTDIR},
850 testname => $ENV{TESTNAME},
851 valgrind => $ENV{VALGRIND},
852 strace => $ENV{STRACE},
853 xtrace => $ENV{XTRACE},
854 restart => $ENV{RESTART},
856 dont_create_temp_dir => $args{dont_create_temp_dir},
859 # force update of the cached socket path in lib/i3test
860 # as soon as i3 has started
861 $cv->cb(sub { get_socket_path(0) });
863 return $cv if $args{dont_block};
865 # blockingly wait until i3 is ready
873 Michael Stapelberg <michael@i3wm.org>
878 use parent 'X11::XCB::Connection';
882 i3test::sync_with_i3();
884 return $self->SUPER::input_focus(@_);