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 my $tester = Test::Builder->new();
51 my $_cached_socket_path = undef;
52 my $_sync_window = undef;
53 my $tmp_socket_path = undef;
60 return $window_count++;
69 # testcases which start i3 manually should always call exit_gracefully
70 # on their own. Let’s see, whether they really did.
71 if (! $i3_autostart) {
72 return unless $i3_pid;
74 $tester->ok(undef, 'testcase called exit_gracefully()');
77 # don't trigger SIGCHLD handler
80 # From perldoc -v '$?':
81 # Inside an "END" subroutine $? contains the value
82 # that is going to be given to "exit()".
84 # Since waitpid sets $?, we need to localize it,
85 # otherwise TAP would be misinterpreted our return status
88 # When measuring code coverage, try to exit i3 cleanly (otherwise, .gcda
89 # files are not written)
90 if ($ENV{COVERAGE} || $ENV{VALGRIND}) {
91 exit_gracefully($i3_pid, "/tmp/nested-$ENV{DISPLAY}");
95 or $tester->BAIL_OUT("could not kill i3");
102 my ($class, %args) = @_;
105 $i3_autostart = delete($args{i3_autostart}) // 1;
107 my $cv = launch_with_config('-default', dont_block => 1)
110 my $test_more_args = '';
111 $test_more_args = join(' ', 'qw(', %args, ')') if keys %args;
115 use Test::More $test_more_args;
118 use Time::HiRes qw(sleep);
120 $tester->BAIL_OUT("$@") if $@;
121 feature->import(":5.10");
125 $x ||= i3test::X11->new;
126 $cv->recv if $i3_autostart;
129 goto \&Exporter::import;
133 # Waits for the next event and calls the given callback for every event to
134 # determine if this is the event we are waiting for.
136 # Can be used to wait until a window is mapped, until a ClientMessage is
139 # wait_for_event $x, 0.25, sub { $_[0]->{response_type} == MAP_NOTIFY };
142 my ($timeout, $cb) = @_;
148 # unfortunately, there is no constant for this
151 my $guard = AE::io $x->get_file_descriptor, $ae_read, sub {
152 while (defined(my $event = $x->poll_for_event)) {
160 # Trigger timeout after $timeout seconds (can be fractional)
161 my $t = AE::timer $timeout, 0, sub { warn "timeout ($timeout secs)"; $cv->send(0) };
163 my $result = $cv->recv;
169 # thin wrapper around wait_for_event which waits for MAP_NOTIFY
170 # make sure to include 'structure_notify' in the window’s event_mask attribute
173 my $id = (blessed($win) && $win->isa('X11::XCB::Window')) ? $win->id : $win;
174 wait_for_event 2, sub {
175 $_[0]->{response_type} == MAP_NOTIFY and $_[0]->{window} == $id
179 # Wrapper around wait_for_event which waits for UNMAP_NOTIFY. Also calls
180 # sync_with_i3 to make sure i3 also picked up and processed the UnmapNotify
184 # my $id = (blessed($win) && $win->isa('X11::XCB::Window')) ? $win->id : $win;
185 wait_for_event 2, sub {
186 $_[0]->{response_type} == UNMAP_NOTIFY # and $_[0]->{window} == $id
192 # Opens a new window (see X11::XCB::Window), maps it, waits until it got mapped
193 # and synchronizes with i3.
195 # set dont_map to a true value to avoid mapping
197 # if you want to change aspects of your window before it would be mapped,
198 # set before_map to a coderef. $window gets passed as $_ and as first argument.
200 # if you set both dont_map and before_map, the coderef will be called nevertheless
204 # class => WINDOW_CLASS_INPUT_OUTPUT
205 # rect => [ 0, 0, 30, 30 ]
206 # background_color => '#c0c0c0'
207 # event_mask => [ 'structure_notify' ]
208 # name => 'Window <n>'
211 my %args = @_ == 1 ? %{$_[0]} : @_;
213 my $dont_map = delete $args{dont_map};
214 my $before_map = delete $args{before_map};
216 $args{class} //= WINDOW_CLASS_INPUT_OUTPUT;
217 $args{rect} //= [ 0, 0, 30, 30 ];
218 $args{background_color} //= '#c0c0c0';
219 $args{event_mask} //= [ 'structure_notify' ];
220 $args{name} //= 'Window ' . counter_window();
222 my $window = $x->root->create_child(%args);
225 # TODO: investigate why _create is not needed
227 $before_map->($window) for $window;
230 return $window if $dont_map;
233 wait_for_map($window);
237 # Thin wrapper around open_window which sets window_type to
238 # _NET_WM_WINDOW_TYPE_UTILITY to make the window floating.
239 sub open_floating_window {
240 my %args = @_ == 1 ? %{$_[0]} : @_;
242 $args{window_type} = $x->atom(name => '_NET_WM_WINDOW_TYPE_UTILITY');
244 return open_window(\%args);
250 my $reply = $i3->command('open')->recv;
251 return $reply->[0]->{id};
254 sub get_workspace_names {
255 my $i3 = i3(get_socket_path());
256 my $tree = $i3->get_tree->recv;
257 my @outputs = @{$tree->{nodes}};
259 for my $output (@outputs) {
260 next if $output->{name} eq '__i3';
261 # get the first CT_CON of each output
262 my $content = first { $_->{type} == 2 } @{$output->{nodes}};
263 @cons = (@cons, @{$content->{nodes}});
265 [ map { $_->{name} } @cons ]
268 sub get_unused_workspace {
269 my @names = get_workspace_names();
271 do { $tmp = tmpnam() } while ($tmp ~~ @names);
275 =head2 fresh_workspace(...)
277 Switches to an unused workspace and returns the name of that workspace.
279 Optionally switches to the specified output first.
281 my $ws = fresh_workspace;
283 # Get a fresh workspace on the second output.
284 my $ws = fresh_workspace(output => 1);
287 sub fresh_workspace {
289 if (exists($args{output})) {
290 my $i3 = i3(get_socket_path());
291 my $tree = $i3->get_tree->recv;
292 my $output = first { $_->{name} eq "fake-$args{output}" }
294 die "BUG: Could not find output $args{output}" unless defined($output);
295 # Get the focused workspace on that output and switch to it.
296 my $content = first { $_->{type} == 2 } @{$output->{nodes}};
297 my $focused = $content->{focus}->[0];
298 my $workspace = first { $_->{id} == $focused } @{$content->{nodes}};
299 $workspace = $workspace->{name};
300 cmd("workspace $workspace");
303 my $unused = get_unused_workspace;
304 cmd("workspace $unused");
310 my $i3 = i3(get_socket_path());
311 my $tree = $i3->get_tree->recv;
313 my @outputs = @{$tree->{nodes}};
315 for my $output (@outputs) {
316 # get the first CT_CON of each output
317 my $content = first { $_->{type} == 2 } @{$output->{nodes}};
318 @workspaces = (@workspaces, @{$content->{nodes}});
321 # as there can only be one workspace with this name, we can safely
322 # return the first entry
323 return first { $_->{name} eq $name } @workspaces;
327 # returns the content (== tree, starting from the node of a workspace)
328 # of a workspace. If called in array context, also includes the focus
329 # stack of the workspace
333 my $con = get_ws($name);
334 return wantarray ? ($con->{nodes}, $con->{focus}) : $con->{nodes};
339 my $con = get_ws($ws);
341 my @focused = @{$con->{focus}};
343 while (@focused > 0) {
345 last unless defined($con->{focus});
346 @focused = @{$con->{focus}};
347 my @cons = grep { $_->{id} == $lf } (@{$con->{nodes}}, @{$con->{'floating_nodes'}});
354 sub get_dock_clients {
357 my $tree = i3(get_socket_path())->get_tree->recv;
358 my @outputs = @{$tree->{nodes}};
359 # Children of all dockareas
361 for my $output (@outputs) {
362 if (!defined($which)) {
363 @docked = (@docked, map { @{$_->{nodes}} }
364 grep { $_->{type} == 5 }
365 @{$output->{nodes}});
366 } elsif ($which eq 'top') {
367 my $first = first { $_->{type} == 5 } @{$output->{nodes}};
368 @docked = (@docked, @{$first->{nodes}}) if defined($first);
369 } elsif ($which eq 'bottom') {
370 my @matching = grep { $_->{type} == 5 } @{$output->{nodes}};
371 my $last = $matching[-1];
372 @docked = (@docked, @{$last->{nodes}}) if defined($last);
379 i3(get_socket_path())->command(@_)->recv
382 sub workspace_exists {
384 ($name ~~ @{get_workspace_names()})
389 Returns the name of the currently focused workspace.
393 my $i3 = i3(get_socket_path());
394 my $tree = $i3->get_tree->recv;
395 my $focused = $tree->{focus}->[0];
396 my $output = first { $_->{id} == $focused } @{$tree->{nodes}};
397 my $content = first { $_->{type} == 2 } @{$output->{nodes}};
398 my $first = first { $_->{fullscreen_mode} == 1 } @{$content->{nodes}};
399 return $first->{name}
403 # Sends an I3_SYNC ClientMessage with a random value to the root window.
404 # i3 will reply with the same value, but, due to the order of events it
405 # processes, only after all other events are done.
407 # This can be used to ensure the results of a cmd 'focus left' are pushed to
408 # X11 and that $x->input_focus returns the correct value afterwards.
410 # See also docs/testsuite for a long explanation
413 my %args = @_ == 1 ? %{$_[0]} : @_;
415 # Since we need a (mapped) window for receiving a ClientMessage, we create
416 # one on the first call of sync_with_i3. It will be re-used in all
418 if (!exists($args{window_id}) &&
419 (!defined($_sync_window) || exists($args{no_cache}))) {
420 $_sync_window = open_window(
421 rect => [ -15, -15, 10, 10 ],
422 override_redirect => 1,
426 my $window_id = delete $args{window_id};
427 $window_id //= $_sync_window->id;
429 my $root = $x->get_root_window();
430 # Generate a random number to identify this particular ClientMessage.
431 my $myrnd = int(rand(255)) + 1;
433 # Generate a ClientMessage, see xcb_client_message_t
434 my $msg = pack "CCSLLLLLLL",
435 CLIENT_MESSAGE, # response_type
438 $root, # destination window
439 $x->atom(name => 'I3_SYNC')->id,
441 $window_id, # data[0]: our own window id
442 $myrnd, # data[1]: a random value to identify the request
447 # Send it to the root window -- since i3 uses the SubstructureRedirect
448 # event mask, it will get the ClientMessage.
449 $x->send_event(0, $root, EVENT_MASK_SUBSTRUCTURE_REDIRECT, $msg);
451 # now wait until the reply is here
452 return wait_for_event 2, sub {
455 return 0 unless $event->{response_type} == 161;
457 my ($win, $rnd) = unpack "LL", $event->{data};
458 return ($rnd == $myrnd);
463 my $tree = i3(get_socket_path())->get_tree->recv;
464 my @nodes = @{$tree->{nodes}};
465 my $ok = (@nodes > 0);
466 $tester->ok($ok, 'i3 still lives');
470 # Tries to exit i3 gracefully (with the 'exit' cmd) or kills the PID if that fails
471 sub exit_gracefully {
472 my ($pid, $socketpath) = @_;
473 $socketpath ||= get_socket_path();
477 say "Exiting i3 cleanly...";
478 i3($socketpath)->command('exit')->recv;
484 or $tester->BAIL_OUT("could not kill i3");
487 if ($socketpath =~ m,^/tmp/i3-test-socket-,) {
495 # Gets the socket path from the I3_SOCKET_PATH atom stored on the X11 root window
496 sub get_socket_path {
500 if ($cache && defined($_cached_socket_path)) {
501 return $_cached_socket_path;
504 my $atom = $x->atom(name => 'I3_SOCKET_PATH');
505 my $cookie = $x->get_property(0, $x->get_root_window(), $atom->id, GET_PROPERTY_TYPE_ANY, 0, 256);
506 my $reply = $x->get_property_reply($cookie->{sequence});
507 my $socketpath = $reply->{value};
508 if ($socketpath eq "/tmp/nested-$ENV{DISPLAY}") {
509 $socketpath .= '-activation';
511 $_cached_socket_path = $socketpath;
516 # launches a new i3 process with the given string as configuration file.
517 # useful for tests which test specific config file directives.
518 sub launch_with_config {
519 my ($config, %args) = @_;
521 $tmp_socket_path = "/tmp/nested-$ENV{DISPLAY}";
523 $args{dont_create_temp_dir} //= 0;
525 my ($fh, $tmpfile) = tempfile("i3-cfg-for-$ENV{TESTNAME}-XXXXX", UNLINK => 1);
527 if ($config ne '-default') {
530 open(my $conf_fh, '<', './i3-test.config')
531 or $tester->BAIL_OUT("could not open default config: $!");
533 say $fh scalar <$conf_fh>;
536 say $fh "ipc-socket $tmp_socket_path"
537 unless $args{dont_add_socket_path};
541 my $cv = AnyEvent->condvar;
542 $i3_pid = activate_i3(
543 unix_socket_path => "$tmp_socket_path-activation",
544 display => $ENV{DISPLAY},
545 configfile => $tmpfile,
546 outdir => $ENV{OUTDIR},
547 testname => $ENV{TESTNAME},
548 valgrind => $ENV{VALGRIND},
549 strace => $ENV{STRACE},
550 restart => $ENV{RESTART},
552 dont_create_temp_dir => $args{dont_create_temp_dir},
555 # force update of the cached socket path in lib/i3test
556 # as soon as i3 has started
557 $cv->cb(sub { get_socket_path(0) });
559 return $cv if $args{dont_block};
561 # blockingly wait until i3 is ready
567 # compares two floats and return true if they differ less
572 return abs($a - $b) < 1e-6;
576 use parent 'X11::XCB::Connection';
580 i3test::sync_with_i3();
582 return $self->SUPER::input_focus(@_);