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);
49 my $tester = Test::Builder->new();
50 my $_cached_socket_path = undef;
51 my $_sync_window = undef;
52 my $tmp_socket_path = undef;
59 return $window_count++;
68 # testcases which start i3 manually should always call exit_gracefully
69 # on their own. Let’s see, whether they really did.
70 if (! $i3_autostart) {
71 return unless $i3_pid;
73 $tester->ok(undef, 'testcase called exit_gracefully()');
76 # don't trigger SIGCHLD handler
79 # From perldoc -v '$?':
80 # Inside an "END" subroutine $? contains the value
81 # that is going to be given to "exit()".
83 # Since waitpid sets $?, we need to localize it,
84 # otherwise TAP would be misinterpreted our return status
87 # When measuring code coverage, try to exit i3 cleanly (otherwise, .gcda
88 # files are not written)
89 if ($ENV{COVERAGE} || $ENV{VALGRIND}) {
90 exit_gracefully($i3_pid, "/tmp/nested-$ENV{DISPLAY}");
94 or $tester->BAIL_OUT("could not kill i3");
101 my ($class, %args) = @_;
104 $i3_autostart = delete($args{i3_autostart}) // 1;
106 my $cv = launch_with_config('-default', dont_block => 1)
109 my $test_more_args = '';
110 $test_more_args = join(' ', 'qw(', %args, ')') if keys %args;
114 use Test::More $test_more_args;
117 use Time::HiRes qw(sleep);
119 $tester->BAIL_OUT("$@") if $@;
120 feature->import(":5.10");
124 $x ||= i3test::X11->new;
125 $cv->recv if $i3_autostart;
128 goto \&Exporter::import;
132 # Waits for the next event and calls the given callback for every event to
133 # determine if this is the event we are waiting for.
135 # Can be used to wait until a window is mapped, until a ClientMessage is
138 # wait_for_event $x, 0.25, sub { $_[0]->{response_type} == MAP_NOTIFY };
141 my ($timeout, $cb) = @_;
147 # unfortunately, there is no constant for this
150 my $guard = AE::io $x->get_file_descriptor, $ae_read, sub {
151 while (defined(my $event = $x->poll_for_event)) {
159 # Trigger timeout after $timeout seconds (can be fractional)
160 my $t = AE::timer $timeout, 0, sub { warn "timeout ($timeout secs)"; $cv->send(0) };
162 my $result = $cv->recv;
168 # thin wrapper around wait_for_event which waits for MAP_NOTIFY
169 # make sure to include 'structure_notify' in the window’s event_mask attribute
172 my $id = (blessed($win) && $win->isa('X11::XCB::Window')) ? $win->id : $win;
173 wait_for_event 2, sub {
174 $_[0]->{response_type} == MAP_NOTIFY and $_[0]->{window} == $id
178 # Wrapper around wait_for_event which waits for UNMAP_NOTIFY. Also calls
179 # sync_with_i3 to make sure i3 also picked up and processed the UnmapNotify
183 # my $id = (blessed($win) && $win->isa('X11::XCB::Window')) ? $win->id : $win;
184 wait_for_event 2, sub {
185 $_[0]->{response_type} == UNMAP_NOTIFY # and $_[0]->{window} == $id
191 # Opens a new window (see X11::XCB::Window), maps it, waits until it got mapped
192 # and synchronizes with i3.
194 # set dont_map to a true value to avoid mapping
196 # if you want to change aspects of your window before it would be mapped,
197 # set before_map to a coderef. $window gets passed as $_ and as first argument.
199 # if you set both dont_map and before_map, the coderef will be called nevertheless
203 # class => WINDOW_CLASS_INPUT_OUTPUT
204 # rect => [ 0, 0, 30, 30 ]
205 # background_color => '#c0c0c0'
206 # event_mask => [ 'structure_notify' ]
207 # name => 'Window <n>'
210 my %args = @_ == 1 ? %{$_[0]} : @_;
212 my $dont_map = delete $args{dont_map};
213 my $before_map = delete $args{before_map};
215 $args{class} //= WINDOW_CLASS_INPUT_OUTPUT;
216 $args{rect} //= [ 0, 0, 30, 30 ];
217 $args{background_color} //= '#c0c0c0';
218 $args{event_mask} //= [ 'structure_notify' ];
219 $args{name} //= 'Window ' . counter_window();
221 my $window = $x->root->create_child(%args);
224 # TODO: investigate why _create is not needed
226 $before_map->($window) for $window;
229 return $window if $dont_map;
232 wait_for_map($window);
236 # Thin wrapper around open_window which sets window_type to
237 # _NET_WM_WINDOW_TYPE_UTILITY to make the window floating.
238 sub open_floating_window {
239 my %args = @_ == 1 ? %{$_[0]} : @_;
241 $args{window_type} = $x->atom(name => '_NET_WM_WINDOW_TYPE_UTILITY');
243 return open_window(\%args);
249 my $reply = $i3->command('open')->recv;
253 sub get_workspace_names {
254 my $i3 = i3(get_socket_path());
255 my $tree = $i3->get_tree->recv;
256 my @outputs = @{$tree->{nodes}};
258 for my $output (@outputs) {
259 next if $output->{name} eq '__i3';
260 # get the first CT_CON of each output
261 my $content = first { $_->{type} == 2 } @{$output->{nodes}};
262 @cons = (@cons, @{$content->{nodes}});
264 [ map { $_->{name} } @cons ]
267 sub get_unused_workspace {
268 my @names = get_workspace_names();
270 do { $tmp = tmpnam() } while ($tmp ~~ @names);
274 sub fresh_workspace {
275 my $unused = get_unused_workspace;
276 cmd("workspace $unused");
282 my $i3 = i3(get_socket_path());
283 my $tree = $i3->get_tree->recv;
285 my @outputs = @{$tree->{nodes}};
287 for my $output (@outputs) {
288 # get the first CT_CON of each output
289 my $content = first { $_->{type} == 2 } @{$output->{nodes}};
290 @workspaces = (@workspaces, @{$content->{nodes}});
293 # as there can only be one workspace with this name, we can safely
294 # return the first entry
295 return first { $_->{name} eq $name } @workspaces;
299 # returns the content (== tree, starting from the node of a workspace)
300 # of a workspace. If called in array context, also includes the focus
301 # stack of the workspace
305 my $con = get_ws($name);
306 return wantarray ? ($con->{nodes}, $con->{focus}) : $con->{nodes};
311 my $con = get_ws($ws);
313 my @focused = @{$con->{focus}};
315 while (@focused > 0) {
317 last unless defined($con->{focus});
318 @focused = @{$con->{focus}};
319 my @cons = grep { $_->{id} == $lf } (@{$con->{nodes}}, @{$con->{'floating_nodes'}});
326 sub get_dock_clients {
329 my $tree = i3(get_socket_path())->get_tree->recv;
330 my @outputs = @{$tree->{nodes}};
331 # Children of all dockareas
333 for my $output (@outputs) {
334 if (!defined($which)) {
335 @docked = (@docked, map { @{$_->{nodes}} }
336 grep { $_->{type} == 5 }
337 @{$output->{nodes}});
338 } elsif ($which eq 'top') {
339 my $first = first { $_->{type} == 5 } @{$output->{nodes}};
340 @docked = (@docked, @{$first->{nodes}}) if defined($first);
341 } elsif ($which eq 'bottom') {
342 my @matching = grep { $_->{type} == 5 } @{$output->{nodes}};
343 my $last = $matching[-1];
344 @docked = (@docked, @{$last->{nodes}}) if defined($last);
351 i3(get_socket_path())->command(@_)->recv
354 sub workspace_exists {
356 ($name ~~ @{get_workspace_names()})
360 my $i3 = i3(get_socket_path());
361 my $tree = $i3->get_tree->recv;
362 my @outputs = @{$tree->{nodes}};
364 for my $output (@outputs) {
365 next if $output->{name} eq '__i3';
366 # get the first CT_CON of each output
367 my $content = first { $_->{type} == 2 } @{$output->{nodes}};
368 my $first = first { $_->{fullscreen_mode} == 1 } @{$content->{nodes}};
369 return $first->{name}
374 # Sends an I3_SYNC ClientMessage with a random value to the root window.
375 # i3 will reply with the same value, but, due to the order of events it
376 # processes, only after all other events are done.
378 # This can be used to ensure the results of a cmd 'focus left' are pushed to
379 # X11 and that $x->input_focus returns the correct value afterwards.
381 # See also docs/testsuite for a long explanation
384 # Since we need a (mapped) window for receiving a ClientMessage, we create
385 # one on the first call of sync_with_i3. It will be re-used in all
387 if (!defined($_sync_window)) {
388 $_sync_window = open_window(
389 rect => [ -15, -15, 10, 10 ],
390 override_redirect => 1,
394 my $root = $x->get_root_window();
395 # Generate a random number to identify this particular ClientMessage.
396 my $myrnd = int(rand(255)) + 1;
398 # Generate a ClientMessage, see xcb_client_message_t
399 my $msg = pack "CCSLLLLLLL",
400 CLIENT_MESSAGE, # response_type
403 $root, # destination window
404 $x->atom(name => 'I3_SYNC')->id,
406 $_sync_window->id, # data[0]: our own window id
407 $myrnd, # data[1]: a random value to identify the request
412 # Send it to the root window -- since i3 uses the SubstructureRedirect
413 # event mask, it will get the ClientMessage.
414 $x->send_event(0, $root, EVENT_MASK_SUBSTRUCTURE_REDIRECT, $msg);
416 # now wait until the reply is here
417 return wait_for_event 2, sub {
420 return 0 unless $event->{response_type} == 161;
422 my ($win, $rnd) = unpack "LL", $event->{data};
423 return ($rnd == $myrnd);
428 my $tree = i3(get_socket_path())->get_tree->recv;
429 my @nodes = @{$tree->{nodes}};
430 my $ok = (@nodes > 0);
431 $tester->ok($ok, 'i3 still lives');
435 # Tries to exit i3 gracefully (with the 'exit' cmd) or kills the PID if that fails
436 sub exit_gracefully {
437 my ($pid, $socketpath) = @_;
438 $socketpath ||= get_socket_path();
442 say "Exiting i3 cleanly...";
443 i3($socketpath)->command('exit')->recv;
449 or $tester->BAIL_OUT("could not kill i3");
452 if ($socketpath =~ m,^/tmp/i3-test-socket-,) {
460 # Gets the socket path from the I3_SOCKET_PATH atom stored on the X11 root window
461 sub get_socket_path {
465 if ($cache && defined($_cached_socket_path)) {
466 return $_cached_socket_path;
469 my $atom = $x->atom(name => 'I3_SOCKET_PATH');
470 my $cookie = $x->get_property(0, $x->get_root_window(), $atom->id, GET_PROPERTY_TYPE_ANY, 0, 256);
471 my $reply = $x->get_property_reply($cookie->{sequence});
472 my $socketpath = $reply->{value};
473 $_cached_socket_path = $socketpath;
478 # launches a new i3 process with the given string as configuration file.
479 # useful for tests which test specific config file directives.
480 sub launch_with_config {
481 my ($config, %args) = @_;
483 $tmp_socket_path = "/tmp/nested-$ENV{DISPLAY}";
485 my ($fh, $tmpfile) = tempfile("i3-cfg-for-$ENV{TESTNAME}-XXXXX", UNLINK => 1);
487 if ($config ne '-default') {
490 open(my $conf_fh, '<', './i3-test.config')
491 or $tester->BAIL_OUT("could not open default config: $!");
493 say $fh scalar <$conf_fh>;
496 say $fh "ipc-socket $tmp_socket_path"
497 unless $args{dont_add_socket_path};
501 my $cv = AnyEvent->condvar;
502 $i3_pid = activate_i3(
503 unix_socket_path => "$tmp_socket_path-activation",
504 display => $ENV{DISPLAY},
505 configfile => $tmpfile,
506 outdir => $ENV{OUTDIR},
507 testname => $ENV{TESTNAME},
508 valgrind => $ENV{VALGRIND},
509 strace => $ENV{STRACE},
510 restart => $ENV{RESTART},
514 # force update of the cached socket path in lib/i3test
515 # as soon as i3 has started
516 $cv->cb(sub { get_socket_path(0) });
518 return $cv if $args{dont_block};
520 # blockingly wait until i3 is ready
527 use parent 'X11::XCB::Connection';
531 i3test::sync_with_i3();
533 return $self->SUPER::input_focus(@_);