]> git.sur5r.net Git - i3/i3/blob - testcases/lib/i3test.pm
Refactor the interface of commands.c
[i3/i3] / testcases / lib / i3test.pm
1 package i3test;
2 # vim:ts=4:sw=4:expandtab
3 use strict; use warnings;
4
5 use File::Temp qw(tmpnam tempfile tempdir);
6 use Test::Builder;
7 use X11::XCB::Rect;
8 use X11::XCB::Window;
9 use X11::XCB qw(:all);
10 use AnyEvent::I3;
11 use List::Util qw(first);
12 use Time::HiRes qw(sleep);
13 use Cwd qw(abs_path);
14 use Scalar::Util qw(blessed);
15 use SocketActivation;
16
17 use v5.10;
18
19 # preload
20 use Test::More ();
21 use Data::Dumper ();
22
23 use Exporter ();
24 our @EXPORT = qw(
25     get_workspace_names
26     get_unused_workspace
27     fresh_workspace
28     get_ws_content
29     get_ws
30     get_focused
31     open_empty_con
32     open_window
33     open_floating_window
34     get_dock_clients
35     cmd
36     sync_with_i3
37     does_i3_live
38     exit_gracefully
39     workspace_exists
40     focused_ws
41     get_socket_path
42     launch_with_config
43     wait_for_event
44     wait_for_map
45     wait_for_unmap
46     $x
47 );
48
49 my $tester = Test::Builder->new();
50 my $_cached_socket_path = undef;
51 my $_sync_window = undef;
52 my $tmp_socket_path = undef;
53
54 our $x;
55
56 BEGIN {
57     my $window_count = 0;
58     sub counter_window {
59         return $window_count++;
60     }
61 }
62
63 my $i3_pid;
64 my $i3_autostart;
65
66 END {
67
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;
72
73         $tester->ok(undef, 'testcase called exit_gracefully()');
74     }
75
76     # don't trigger SIGCHLD handler
77     local $SIG{CHLD};
78
79     # From perldoc -v '$?':
80     # Inside an "END" subroutine $? contains the value
81     # that is going to be given to "exit()".
82     #
83     # Since waitpid sets $?, we need to localize it,
84     # otherwise TAP would be misinterpreted our return status
85     local $?;
86
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}");
91
92     } else {
93         kill(9, $i3_pid)
94             or $tester->BAIL_OUT("could not kill i3");
95
96         waitpid $i3_pid, 0;
97     }
98 }
99
100 sub import {
101     my ($class, %args) = @_;
102     my $pkg = caller;
103
104     $i3_autostart = delete($args{i3_autostart}) // 1;
105
106     my $cv = launch_with_config('-default', dont_block => 1)
107         if $i3_autostart;
108
109     my $test_more_args = '';
110     $test_more_args = join(' ', 'qw(', %args, ')') if keys %args;
111     local $@;
112     eval << "__";
113 package $pkg;
114 use Test::More $test_more_args;
115 use Data::Dumper;
116 use AnyEvent::I3;
117 use Time::HiRes qw(sleep);
118 __
119     $tester->BAIL_OUT("$@") if $@;
120     feature->import(":5.10");
121     strict->import;
122     warnings->import;
123
124     $x ||= i3test::X11->new;
125     $cv->recv if $i3_autostart;
126
127     @_ = ($class);
128     goto \&Exporter::import;
129 }
130
131 #
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.
134 #
135 # Can be used to wait until a window is mapped, until a ClientMessage is
136 # received, etc.
137 #
138 # wait_for_event $x, 0.25, sub { $_[0]->{response_type} == MAP_NOTIFY };
139 #
140 sub wait_for_event {
141     my ($timeout, $cb) = @_;
142
143     my $cv = AE::cv;
144
145     $x->flush;
146
147     # unfortunately, there is no constant for this
148     my $ae_read = 0;
149
150     my $guard = AE::io $x->get_file_descriptor, $ae_read, sub {
151         while (defined(my $event = $x->poll_for_event)) {
152             if ($cb->($event)) {
153                 $cv->send(1);
154                 last;
155             }
156         }
157     };
158
159     # Trigger timeout after $timeout seconds (can be fractional)
160     my $t = AE::timer $timeout, 0, sub { warn "timeout ($timeout secs)"; $cv->send(0) };
161
162     my $result = $cv->recv;
163     undef $t;
164     undef $guard;
165     return $result;
166 }
167
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
170 sub wait_for_map {
171     my ($win) = @_;
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
175     };
176 }
177
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
180 # event.
181 sub wait_for_unmap {
182     my ($win) = @_;
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
186     };
187     sync_with_i3();
188 }
189
190 #
191 # Opens a new window (see X11::XCB::Window), maps it, waits until it got mapped
192 # and synchronizes with i3.
193 #
194 # set dont_map to a true value to avoid mapping
195 #
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.
198 #
199 # if you set both dont_map and before_map, the coderef will be called nevertheless
200 #
201 #
202 # default values:
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>'
208 #
209 sub open_window {
210     my %args = @_ == 1 ? %{$_[0]} : @_;
211
212     my $dont_map = delete $args{dont_map};
213     my $before_map = delete $args{before_map};
214
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();
220
221     my $window = $x->root->create_child(%args);
222
223     if ($before_map) {
224         # TODO: investigate why _create is not needed
225         $window->_create;
226         $before_map->($window) for $window;
227     }
228
229     return $window if $dont_map;
230
231     $window->map;
232     wait_for_map($window);
233     return $window;
234 }
235
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]} : @_;
240
241     $args{window_type} = $x->atom(name => '_NET_WM_WINDOW_TYPE_UTILITY');
242
243     return open_window(\%args);
244 }
245
246 sub open_empty_con {
247     my ($i3) = @_;
248
249     my $reply = $i3->command('open')->recv;
250     return $reply->[0]->{id};
251 }
252
253 sub get_workspace_names {
254     my $i3 = i3(get_socket_path());
255     my $tree = $i3->get_tree->recv;
256     my @outputs = @{$tree->{nodes}};
257     my @cons;
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}});
263     }
264     [ map { $_->{name} } @cons ]
265 }
266
267 sub get_unused_workspace {
268     my @names = get_workspace_names();
269     my $tmp;
270     do { $tmp = tmpnam() } while ($tmp ~~ @names);
271     $tmp
272 }
273
274 =head2 fresh_workspace(...)
275
276 Switches to an unused workspace and returns the name of that workspace.
277
278 Optionally switches to the specified output first.
279
280     my $ws = fresh_workspace;
281
282     # Get a fresh workspace on the second output.
283     my $ws = fresh_workspace(output => 1);
284
285 =cut
286 sub fresh_workspace {
287     my %args = @_;
288     if (exists($args{output})) {
289         my $i3 = i3(get_socket_path());
290         my $tree = $i3->get_tree->recv;
291         my $output = first { $_->{name} eq "xinerama-$args{output}" }
292                         @{$tree->{nodes}};
293         die "BUG: Could not find output $args{output}" unless defined($output);
294         # Get the focused workspace on that output and switch to it.
295         my $content = first { $_->{type} == 2 } @{$output->{nodes}};
296         my $focused = $content->{focus}->[0];
297         my $workspace = first { $_->{id} == $focused } @{$content->{nodes}};
298         $workspace = $workspace->{name};
299         cmd("workspace $workspace");
300     }
301
302     my $unused = get_unused_workspace;
303     cmd("workspace $unused");
304     $unused
305 }
306
307 sub get_ws {
308     my ($name) = @_;
309     my $i3 = i3(get_socket_path());
310     my $tree = $i3->get_tree->recv;
311
312     my @outputs = @{$tree->{nodes}};
313     my @workspaces;
314     for my $output (@outputs) {
315         # get the first CT_CON of each output
316         my $content = first { $_->{type} == 2 } @{$output->{nodes}};
317         @workspaces = (@workspaces, @{$content->{nodes}});
318     }
319
320     # as there can only be one workspace with this name, we can safely
321     # return the first entry
322     return first { $_->{name} eq $name } @workspaces;
323 }
324
325 #
326 # returns the content (== tree, starting from the node of a workspace)
327 # of a workspace. If called in array context, also includes the focus
328 # stack of the workspace
329 #
330 sub get_ws_content {
331     my ($name) = @_;
332     my $con = get_ws($name);
333     return wantarray ? ($con->{nodes}, $con->{focus}) : $con->{nodes};
334 }
335
336 sub get_focused {
337     my ($ws) = @_;
338     my $con = get_ws($ws);
339
340     my @focused = @{$con->{focus}};
341     my $lf;
342     while (@focused > 0) {
343         $lf = $focused[0];
344         last unless defined($con->{focus});
345         @focused = @{$con->{focus}};
346         my @cons = grep { $_->{id} == $lf } (@{$con->{nodes}}, @{$con->{'floating_nodes'}});
347         $con = $cons[0];
348     }
349
350     return $lf;
351 }
352
353 sub get_dock_clients {
354     my $which = shift;
355
356     my $tree = i3(get_socket_path())->get_tree->recv;
357     my @outputs = @{$tree->{nodes}};
358     # Children of all dockareas
359     my @docked;
360     for my $output (@outputs) {
361         if (!defined($which)) {
362             @docked = (@docked, map { @{$_->{nodes}} }
363                                 grep { $_->{type} == 5 }
364                                 @{$output->{nodes}});
365         } elsif ($which eq 'top') {
366             my $first = first { $_->{type} == 5 } @{$output->{nodes}};
367             @docked = (@docked, @{$first->{nodes}}) if defined($first);
368         } elsif ($which eq 'bottom') {
369             my @matching = grep { $_->{type} == 5 } @{$output->{nodes}};
370             my $last = $matching[-1];
371             @docked = (@docked, @{$last->{nodes}}) if defined($last);
372         }
373     }
374     return @docked;
375 }
376
377 sub cmd {
378     i3(get_socket_path())->command(@_)->recv
379 }
380
381 sub workspace_exists {
382     my ($name) = @_;
383     ($name ~~ @{get_workspace_names()})
384 }
385
386 =head2 focused_ws
387
388 Returns the name of the currently focused workspace.
389
390 =cut
391 sub focused_ws {
392     my $i3 = i3(get_socket_path());
393     my $tree = $i3->get_tree->recv;
394     my $focused = $tree->{focus}->[0];
395     my $output = first { $_->{id} == $focused } @{$tree->{nodes}};
396     my $content = first { $_->{type} == 2 } @{$output->{nodes}};
397     my $first = first { $_->{fullscreen_mode} == 1 } @{$content->{nodes}};
398     return $first->{name}
399 }
400
401 #
402 # Sends an I3_SYNC ClientMessage with a random value to the root window.
403 # i3 will reply with the same value, but, due to the order of events it
404 # processes, only after all other events are done.
405 #
406 # This can be used to ensure the results of a cmd 'focus left' are pushed to
407 # X11 and that $x->input_focus returns the correct value afterwards.
408 #
409 # See also docs/testsuite for a long explanation
410 #
411 sub sync_with_i3 {
412     # Since we need a (mapped) window for receiving a ClientMessage, we create
413     # one on the first call of sync_with_i3. It will be re-used in all
414     # subsequent calls.
415     if (!defined($_sync_window)) {
416         $_sync_window = open_window(
417             rect => [ -15, -15, 10, 10 ],
418             override_redirect => 1,
419         );
420     }
421
422     my $root = $x->get_root_window();
423     # Generate a random number to identify this particular ClientMessage.
424     my $myrnd = int(rand(255)) + 1;
425
426     # Generate a ClientMessage, see xcb_client_message_t
427     my $msg = pack "CCSLLLLLLL",
428          CLIENT_MESSAGE, # response_type
429          32,     # format
430          0,      # sequence
431          $root,  # destination window
432          $x->atom(name => 'I3_SYNC')->id,
433
434          $_sync_window->id,    # data[0]: our own window id
435          $myrnd, # data[1]: a random value to identify the request
436          0,
437          0,
438          0;
439
440     # Send it to the root window -- since i3 uses the SubstructureRedirect
441     # event mask, it will get the ClientMessage.
442     $x->send_event(0, $root, EVENT_MASK_SUBSTRUCTURE_REDIRECT, $msg);
443
444     # now wait until the reply is here
445     return wait_for_event 2, sub {
446         my ($event) = @_;
447         # TODO: const
448         return 0 unless $event->{response_type} == 161;
449
450         my ($win, $rnd) = unpack "LL", $event->{data};
451         return ($rnd == $myrnd);
452     };
453 }
454
455 sub does_i3_live {
456     my $tree = i3(get_socket_path())->get_tree->recv;
457     my @nodes = @{$tree->{nodes}};
458     my $ok = (@nodes > 0);
459     $tester->ok($ok, 'i3 still lives');
460     return $ok;
461 }
462
463 # Tries to exit i3 gracefully (with the 'exit' cmd) or kills the PID if that fails
464 sub exit_gracefully {
465     my ($pid, $socketpath) = @_;
466     $socketpath ||= get_socket_path();
467
468     my $exited = 0;
469     eval {
470         say "Exiting i3 cleanly...";
471         i3($socketpath)->command('exit')->recv;
472         $exited = 1;
473     };
474
475     if (!$exited) {
476         kill(9, $pid)
477             or $tester->BAIL_OUT("could not kill i3");
478     }
479
480     if ($socketpath =~ m,^/tmp/i3-test-socket-,) {
481         unlink($socketpath);
482     }
483
484     waitpid $pid, 0;
485     undef $i3_pid;
486 }
487
488 # Gets the socket path from the I3_SOCKET_PATH atom stored on the X11 root window
489 sub get_socket_path {
490     my ($cache) = @_;
491     $cache ||= 1;
492
493     if ($cache && defined($_cached_socket_path)) {
494         return $_cached_socket_path;
495     }
496
497     my $atom = $x->atom(name => 'I3_SOCKET_PATH');
498     my $cookie = $x->get_property(0, $x->get_root_window(), $atom->id, GET_PROPERTY_TYPE_ANY, 0, 256);
499     my $reply = $x->get_property_reply($cookie->{sequence});
500     my $socketpath = $reply->{value};
501     if ($socketpath eq "/tmp/nested-$ENV{DISPLAY}") {
502         $socketpath .= '-activation';
503     }
504     $_cached_socket_path = $socketpath;
505     return $socketpath;
506 }
507
508 #
509 # launches a new i3 process with the given string as configuration file.
510 # useful for tests which test specific config file directives.
511 sub launch_with_config {
512     my ($config, %args) = @_;
513
514     $tmp_socket_path = "/tmp/nested-$ENV{DISPLAY}";
515
516     $args{dont_create_temp_dir} //= 0;
517
518     my ($fh, $tmpfile) = tempfile("i3-cfg-for-$ENV{TESTNAME}-XXXXX", UNLINK => 1);
519
520     if ($config ne '-default') {
521         say $fh $config;
522     } else {
523         open(my $conf_fh, '<', './i3-test.config')
524             or $tester->BAIL_OUT("could not open default config: $!");
525         local $/;
526         say $fh scalar <$conf_fh>;
527     }
528
529     say $fh "ipc-socket $tmp_socket_path"
530         unless $args{dont_add_socket_path};
531
532     close($fh);
533
534     my $cv = AnyEvent->condvar;
535     $i3_pid = activate_i3(
536         unix_socket_path => "$tmp_socket_path-activation",
537         display => $ENV{DISPLAY},
538         configfile => $tmpfile,
539         outdir => $ENV{OUTDIR},
540         testname => $ENV{TESTNAME},
541         valgrind => $ENV{VALGRIND},
542         strace => $ENV{STRACE},
543         restart => $ENV{RESTART},
544         cv => $cv,
545         dont_create_temp_dir => $args{dont_create_temp_dir},
546     );
547
548     # force update of the cached socket path in lib/i3test
549     # as soon as i3 has started
550     $cv->cb(sub { get_socket_path(0) });
551
552     return $cv if $args{dont_block};
553
554     # blockingly wait until i3 is ready
555     $cv->recv;
556
557     return $i3_pid;
558 }
559
560 package i3test::X11;
561 use parent 'X11::XCB::Connection';
562
563 sub input_focus {
564     my $self = shift;
565     i3test::sync_with_i3();
566
567     return $self->SUPER::input_focus(@_);
568 }
569
570 1