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);
45 my $tester = Test::Builder->new();
46 my $_cached_socket_path = undef;
47 my $_sync_window = undef;
48 my $tmp_socket_path = undef;
55 return $window_count++;
64 # testcases which start i3 manually should always call exit_gracefully
65 # on their own. Let’s see, whether they really did.
66 if (! $i3_autostart) {
67 return unless $i3_pid;
69 $tester->ok(undef, 'testcase called exit_gracefully()');
72 # don't trigger SIGCHLD handler
75 # From perldoc -v '$?':
76 # Inside an "END" subroutine $? contains the value
77 # that is going to be given to "exit()".
79 # Since waitpid sets $?, we need to localize it,
80 # otherwise TAP would be misinterpreted our return status
83 # When measuring code coverage, try to exit i3 cleanly (otherwise, .gcda
84 # files are not written)
85 if ($ENV{COVERAGE} || $ENV{VALGRIND}) {
86 exit_gracefully($i3_pid, "/tmp/nested-$ENV{DISPLAY}");
90 or $tester->BAIL_OUT("could not kill i3");
97 my ($class, %args) = @_;
100 $i3_autostart = delete($args{i3_autostart}) // 1;
102 my $cv = launch_with_config('-default', dont_block => 1)
105 my $test_more_args = '';
106 $test_more_args = join(' ', 'qw(', %args, ')') if keys %args;
110 use Test::More $test_more_args;
113 use Time::HiRes qw(sleep);
115 $tester->BAIL_OUT("$@") if $@;
116 feature->import(":5.10");
120 $x ||= i3test::X11->new;
121 $cv->recv if $i3_autostart;
124 goto \&Exporter::import;
128 # Waits for the next event and calls the given callback for every event to
129 # determine if this is the event we are waiting for.
131 # Can be used to wait until a window is mapped, until a ClientMessage is
134 # wait_for_event $x, 0.25, sub { $_[0]->{response_type} == MAP_NOTIFY };
137 my ($timeout, $cb) = @_;
143 # unfortunately, there is no constant for this
146 my $guard = AE::io $x->get_file_descriptor, $ae_read, sub {
147 while (defined(my $event = $x->poll_for_event)) {
155 # Trigger timeout after $timeout seconds (can be fractional)
156 my $t = AE::timer $timeout, 0, sub { warn "timeout ($timeout secs)"; $cv->send(0) };
158 my $result = $cv->recv;
164 # thin wrapper around wait_for_event which waits for MAP_NOTIFY
165 # make sure to include 'structure_notify' in the window’s event_mask attribute
168 my $id = (blessed($win) && $win->isa('X11::XCB::Window')) ? $win->id : $win;
169 wait_for_event 2, sub {
170 $_[0]->{response_type} == MAP_NOTIFY and $_[0]->{window} == $id
174 # Wrapper around wait_for_event which waits for UNMAP_NOTIFY. Also calls
175 # sync_with_i3 to make sure i3 also picked up and processed the UnmapNotify
179 # my $id = (blessed($win) && $win->isa('X11::XCB::Window')) ? $win->id : $win;
180 wait_for_event 2, sub {
181 $_[0]->{response_type} == UNMAP_NOTIFY # and $_[0]->{window} == $id
187 # Opens a new window (see X11::XCB::Window), maps it, waits until it got mapped
188 # and synchronizes with i3.
190 # set dont_map to a true value to avoid mapping
192 # if you want to change aspects of your window before it would be mapped,
193 # set before_map to a coderef. $window gets passed as $_ and as first argument.
195 # if you set both dont_map and before_map, the coderef will be called nevertheless
199 # class => WINDOW_CLASS_INPUT_OUTPUT
200 # rect => [ 0, 0, 30, 30 ]
201 # background_color => '#c0c0c0'
202 # event_mask => [ 'structure_notify' ]
203 # name => 'Window <n>'
206 my %args = @_ == 1 ? %{$_[0]} : @_;
208 my $dont_map = delete $args{dont_map};
209 my $before_map = delete $args{before_map};
211 $args{class} //= WINDOW_CLASS_INPUT_OUTPUT;
212 $args{rect} //= [ 0, 0, 30, 30 ];
213 $args{background_color} //= '#c0c0c0';
214 $args{event_mask} //= [ 'structure_notify' ];
215 $args{name} //= 'Window ' . counter_window();
217 my $window = $x->root->create_child(%args);
220 # TODO: investigate why _create is not needed
222 $before_map->($window) for $window;
225 return $window if $dont_map;
228 wait_for_map($window);
232 # Thin wrapper around open_window which sets window_type to
233 # _NET_WM_WINDOW_TYPE_UTILITY to make the window floating.
234 sub open_floating_window {
235 my %args = @_ == 1 ? %{$_[0]} : @_;
237 $args{window_type} = $x->atom(name => '_NET_WM_WINDOW_TYPE_UTILITY');
239 return open_window(\%args);
245 my $reply = $i3->command('open')->recv;
249 sub get_workspace_names {
250 my $i3 = i3(get_socket_path());
251 my $tree = $i3->get_tree->recv;
252 my @outputs = @{$tree->{nodes}};
254 for my $output (@outputs) {
255 # get the first CT_CON of each output
256 my $content = first { $_->{type} == 2 } @{$output->{nodes}};
257 @cons = (@cons, @{$content->{nodes}});
259 [ map { $_->{name} } @cons ]
262 sub get_unused_workspace {
263 my @names = get_workspace_names();
265 do { $tmp = tmpnam() } while ($tmp ~~ @names);
269 sub fresh_workspace {
270 my $unused = get_unused_workspace;
271 cmd("workspace $unused");
277 my $i3 = i3(get_socket_path());
278 my $tree = $i3->get_tree->recv;
280 my @outputs = @{$tree->{nodes}};
282 for my $output (@outputs) {
283 # get the first CT_CON of each output
284 my $content = first { $_->{type} == 2 } @{$output->{nodes}};
285 @workspaces = (@workspaces, @{$content->{nodes}});
288 # as there can only be one workspace with this name, we can safely
289 # return the first entry
290 return first { $_->{name} eq $name } @workspaces;
294 # returns the content (== tree, starting from the node of a workspace)
295 # of a workspace. If called in array context, also includes the focus
296 # stack of the workspace
300 my $con = get_ws($name);
301 return wantarray ? ($con->{nodes}, $con->{focus}) : $con->{nodes};
306 my $con = get_ws($ws);
308 my @focused = @{$con->{focus}};
310 while (@focused > 0) {
312 last unless defined($con->{focus});
313 @focused = @{$con->{focus}};
314 my @cons = grep { $_->{id} == $lf } (@{$con->{nodes}}, @{$con->{'floating_nodes'}});
321 sub get_dock_clients {
324 my $tree = i3(get_socket_path())->get_tree->recv;
325 my @outputs = @{$tree->{nodes}};
326 # Children of all dockareas
328 for my $output (@outputs) {
329 if (!defined($which)) {
330 @docked = (@docked, map { @{$_->{nodes}} }
331 grep { $_->{type} == 5 }
332 @{$output->{nodes}});
333 } elsif ($which eq 'top') {
334 my $first = first { $_->{type} == 5 } @{$output->{nodes}};
335 @docked = (@docked, @{$first->{nodes}});
336 } elsif ($which eq 'bottom') {
337 my @matching = grep { $_->{type} == 5 } @{$output->{nodes}};
338 my $last = $matching[-1];
339 @docked = (@docked, @{$last->{nodes}});
346 i3(get_socket_path())->command(@_)->recv
349 sub workspace_exists {
351 ($name ~~ @{get_workspace_names()})
355 my $i3 = i3(get_socket_path());
356 my $tree = $i3->get_tree->recv;
357 my @outputs = @{$tree->{nodes}};
359 for my $output (@outputs) {
360 # get the first CT_CON of each output
361 my $content = first { $_->{type} == 2 } @{$output->{nodes}};
362 my $first = first { $_->{fullscreen_mode} == 1 } @{$content->{nodes}};
363 return $first->{name}
368 # Sends an I3_SYNC ClientMessage with a random value to the root window.
369 # i3 will reply with the same value, but, due to the order of events it
370 # processes, only after all other events are done.
372 # This can be used to ensure the results of a cmd 'focus left' are pushed to
373 # X11 and that $x->input_focus returns the correct value afterwards.
375 # See also docs/testsuite for a long explanation
378 # Since we need a (mapped) window for receiving a ClientMessage, we create
379 # one on the first call of sync_with_i3. It will be re-used in all
381 if (!defined($_sync_window)) {
382 $_sync_window = open_window(
383 rect => [ -15, -15, 10, 10 ],
384 override_redirect => 1,
388 my $root = $x->get_root_window();
389 # Generate a random number to identify this particular ClientMessage.
390 my $myrnd = int(rand(255)) + 1;
392 # Generate a ClientMessage, see xcb_client_message_t
393 my $msg = pack "CCSLLLLLLL",
394 CLIENT_MESSAGE, # response_type
397 $root, # destination window
398 $x->atom(name => 'I3_SYNC')->id,
400 $_sync_window->id, # data[0]: our own window id
401 $myrnd, # data[1]: a random value to identify the request
406 # Send it to the root window -- since i3 uses the SubstructureRedirect
407 # event mask, it will get the ClientMessage.
408 $x->send_event(0, $root, EVENT_MASK_SUBSTRUCTURE_REDIRECT, $msg);
410 # now wait until the reply is here
411 return wait_for_event 2, sub {
414 return 0 unless $event->{response_type} == 161;
416 my ($win, $rnd) = unpack "LL", $event->{data};
417 return ($rnd == $myrnd);
422 my $tree = i3(get_socket_path())->get_tree->recv;
423 my @nodes = @{$tree->{nodes}};
424 my $ok = (@nodes > 0);
425 $tester->ok($ok, 'i3 still lives');
429 # Tries to exit i3 gracefully (with the 'exit' cmd) or kills the PID if that fails
430 sub exit_gracefully {
431 my ($pid, $socketpath) = @_;
432 $socketpath ||= get_socket_path();
436 say "Exiting i3 cleanly...";
437 i3($socketpath)->command('exit')->recv;
443 or $tester->BAIL_OUT("could not kill i3");
446 if ($socketpath =~ m,^/tmp/i3-test-socket-,) {
454 # Gets the socket path from the I3_SOCKET_PATH atom stored on the X11 root window
455 sub get_socket_path {
459 if ($cache && defined($_cached_socket_path)) {
460 return $_cached_socket_path;
463 my $atom = $x->atom(name => 'I3_SOCKET_PATH');
464 my $cookie = $x->get_property(0, $x->get_root_window(), $atom->id, GET_PROPERTY_TYPE_ANY, 0, 256);
465 my $reply = $x->get_property_reply($cookie->{sequence});
466 my $socketpath = $reply->{value};
467 $_cached_socket_path = $socketpath;
472 # launches a new i3 process with the given string as configuration file.
473 # useful for tests which test specific config file directives.
475 # be sure to use !NO_I3_INSTANCE! somewhere in the file to signal
476 # complete-run.pl that it should not create an instance of i3
478 sub launch_with_config {
479 my ($config, %args) = @_;
481 $tmp_socket_path = "/tmp/nested-$ENV{DISPLAY}";
483 my ($fh, $tmpfile) = tempfile("i3-cfg-for-$ENV{TESTNAME}-XXXXX", UNLINK => 1);
485 if ($config ne '-default') {
488 open(my $conf_fh, '<', './i3-test.config')
489 or $tester->BAIL_OUT("could not open default config: $!");
491 say $fh scalar <$conf_fh>;
494 say $fh "ipc-socket $tmp_socket_path"
495 unless $args{dont_add_socket_path};
499 my $cv = AnyEvent->condvar;
500 $i3_pid = activate_i3(
501 unix_socket_path => "$tmp_socket_path-activation",
502 display => $ENV{DISPLAY},
503 configfile => $tmpfile,
504 outdir => $ENV{OUTDIR},
505 testname => $ENV{TESTNAME},
506 valgrind => $ENV{VALGRIND},
507 strace => $ENV{STRACE},
511 # force update of the cached socket path in lib/i3test
512 # as soon as i3 has started
513 $cv->cb(sub { get_socket_path(0) });
515 return $cv if $args{dont_block};
517 # blockingly wait until i3 is ready
524 use parent 'X11::XCB::Connection';
528 i3test::sync_with_i3();
530 return $self->SUPER::input_focus(@_);