]> git.sur5r.net Git - i3/i3/blob - testcases/lib/i3test.pm
testcases: use global $x in wait_for_event, drop $x parameter
[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 EV;
12 use List::Util qw(first);
13 use Time::HiRes qw(sleep);
14 use Cwd qw(abs_path);
15 use SocketActivation;
16
17 use v5.10;
18
19 use Exporter ();
20 our @EXPORT = qw(
21     get_workspace_names
22     get_unused_workspace
23     fresh_workspace
24     get_ws_content
25     get_ws
26     get_focused
27     open_empty_con
28     open_window
29     open_floating_window
30     get_dock_clients
31     cmd
32     sync_with_i3
33     does_i3_live
34     exit_gracefully
35     workspace_exists
36     focused_ws
37     get_socket_path
38     launch_with_config
39     wait_for_event
40     wait_for_map
41     wait_for_unmap
42     $x
43 );
44
45 my $tester = Test::Builder->new();
46 my $_cached_socket_path = undef;
47 my $_sync_window = undef;
48 my $tmp_socket_path = undef;
49
50 our $x;
51
52 BEGIN {
53     my $window_count = 0;
54     sub counter_window {
55         return $window_count++;
56     }
57 }
58
59 sub import {
60     my $class = shift;
61     my $pkg = caller;
62
63     my $test_most_args = @_ ? "qw(@_)" : "";
64     local $@;
65     eval << "__";
66 package $pkg;
67 use Test::Most $test_most_args;
68 use Data::Dumper;
69 use AnyEvent::I3;
70 use Time::HiRes qw(sleep);
71 use Test::Deep qw(eq_deeply cmp_deeply cmp_set cmp_bag cmp_methods useclass noclass set bag subbagof superbagof subsetof supersetof superhashof subhashof bool str arraylength Isa ignore methods regexprefonly regexpmatches num regexponly scalref reftype hashkeysonly blessed array re hash regexpref hash_each shallow array_each code arrayelementsonly arraylengthonly scalarrefonly listmethods any hashkeys isa);
72 __
73     $tester->bail_out("$@") if $@;
74     feature->import(":5.10");
75     strict->import;
76     warnings->import;
77
78     $x ||= i3test::X11->new;
79     @_ = ($class);
80     goto \&Exporter::import;
81 }
82
83 #
84 # Waits for the next event and calls the given callback for every event to
85 # determine if this is the event we are waiting for.
86 #
87 # Can be used to wait until a window is mapped, until a ClientMessage is
88 # received, etc.
89 #
90 # wait_for_event $x, 0.25, sub { $_[0]->{response_type} == MAP_NOTIFY };
91 #
92 sub wait_for_event {
93     my ($timeout, $cb) = @_;
94
95     my $cv = AE::cv;
96
97     my $prep = EV::prepare sub {
98         $x->flush;
99     };
100
101     my $check = EV::check sub {
102         while (defined(my $event = $x->poll_for_event)) {
103             if ($cb->($event)) {
104                 $cv->send(1);
105                 last;
106             }
107         }
108     };
109
110     my $watcher = EV::io $x->get_file_descriptor, EV::READ, sub {
111         # do nothing, we only need this watcher so that EV picks up the events
112     };
113
114     # Trigger timeout after $timeout seconds (can be fractional)
115     my $t = AE::timer $timeout, 0, sub { warn "timeout ($timeout secs)"; $cv->send(0) };
116
117     my $result = $cv->recv;
118     undef $t;
119     return $result;
120 }
121
122 # thin wrapper around wait_for_event which waits for MAP_NOTIFY
123 # make sure to include 'structure_notify' in the window’s event_mask attribute
124 sub wait_for_map {
125     wait_for_event 2, sub { $_[0]->{response_type} == MAP_NOTIFY };
126 }
127
128 # Wrapper around wait_for_event which waits for UNMAP_NOTIFY. Also calls
129 # sync_with_i3 to make sure i3 also picked up and processed the UnmapNotify
130 # event.
131 sub wait_for_unmap {
132     wait_for_event 2, sub { $_[0]->{response_type} == UNMAP_NOTIFY };
133     sync_with_i3($x);
134 }
135
136 #
137 # Opens a new window (see X11::XCB::Window), maps it, waits until it got mapped
138 # and synchronizes with i3.
139 #
140 # set dont_map to a true value to avoid mapping
141 #
142 # default values:
143 #     class => WINDOW_CLASS_INPUT_OUTPUT
144 #     rect => [ 0, 0, 30, 30 ]
145 #     background_color => '#c0c0c0'
146 #     event_mask => [ 'structure_notify' ]
147 #     name => 'Window <n>'
148 #
149 sub open_window {
150     my ($x, $args) = @_;
151     my %args = ($args ? %$args : ());
152
153     my $dont_map = delete $args{dont_map};
154
155     $args{class} //= WINDOW_CLASS_INPUT_OUTPUT;
156     $args{rect} //= [ 0, 0, 30, 30 ];
157     $args{background_color} //= '#c0c0c0';
158     $args{event_mask} //= [ 'structure_notify' ];
159     $args{name} //= 'Window ' . counter_window();
160
161     my $window = $x->root->create_child(%args);
162
163     return $window if $dont_map;
164
165     $window->map;
166     wait_for_map($x);
167     # We sync with i3 here to make sure $x->input_focus is updated.
168     sync_with_i3($x);
169     return $window;
170 }
171
172 # Thin wrapper around open_window which sets window_type to
173 # _NET_WM_WINDOW_TYPE_UTILITY to make the window floating.
174 sub open_floating_window {
175     my ($x, $args) = @_;
176     my %args = ($args ? %$args : ());
177
178     $args{window_type} = $x->atom(name => '_NET_WM_WINDOW_TYPE_UTILITY');
179
180     return open_window($x, \%args);
181 }
182
183 sub open_empty_con {
184     my ($i3) = @_;
185
186     my $reply = $i3->command('open')->recv;
187     return $reply->{id};
188 }
189
190 sub get_workspace_names {
191     my $i3 = i3(get_socket_path());
192     my $tree = $i3->get_tree->recv;
193     my @outputs = @{$tree->{nodes}};
194     my @cons;
195     for my $output (@outputs) {
196         # get the first CT_CON of each output
197         my $content = first { $_->{type} == 2 } @{$output->{nodes}};
198         @cons = (@cons, @{$content->{nodes}});
199     }
200     [ map { $_->{name} } @cons ]
201 }
202
203 sub get_unused_workspace {
204     my @names = get_workspace_names();
205     my $tmp;
206     do { $tmp = tmpnam() } while ($tmp ~~ @names);
207     $tmp
208 }
209
210 sub fresh_workspace {
211     my $unused = get_unused_workspace;
212     cmd("workspace $unused");
213     $unused
214 }
215
216 sub get_ws {
217     my ($name) = @_;
218     my $i3 = i3(get_socket_path());
219     my $tree = $i3->get_tree->recv;
220
221     my @outputs = @{$tree->{nodes}};
222     my @workspaces;
223     for my $output (@outputs) {
224         # get the first CT_CON of each output
225         my $content = first { $_->{type} == 2 } @{$output->{nodes}};
226         @workspaces = (@workspaces, @{$content->{nodes}});
227     }
228
229     # as there can only be one workspace with this name, we can safely
230     # return the first entry
231     return first { $_->{name} eq $name } @workspaces;
232 }
233
234 #
235 # returns the content (== tree, starting from the node of a workspace)
236 # of a workspace. If called in array context, also includes the focus
237 # stack of the workspace
238 #
239 sub get_ws_content {
240     my ($name) = @_;
241     my $con = get_ws($name);
242     return wantarray ? ($con->{nodes}, $con->{focus}) : $con->{nodes};
243 }
244
245 sub get_focused {
246     my ($ws) = @_;
247     my $con = get_ws($ws);
248
249     my @focused = @{$con->{focus}};
250     my $lf;
251     while (@focused > 0) {
252         $lf = $focused[0];
253         last unless defined($con->{focus});
254         @focused = @{$con->{focus}};
255         my @cons = grep { $_->{id} == $lf } (@{$con->{nodes}}, @{$con->{'floating_nodes'}});
256         $con = $cons[0];
257     }
258
259     return $lf;
260 }
261
262 sub get_dock_clients {
263     my $which = shift;
264
265     my $tree = i3(get_socket_path())->get_tree->recv;
266     my @outputs = @{$tree->{nodes}};
267     # Children of all dockareas
268     my @docked;
269     for my $output (@outputs) {
270         if (!defined($which)) {
271             @docked = (@docked, map { @{$_->{nodes}} }
272                                 grep { $_->{type} == 5 }
273                                 @{$output->{nodes}});
274         } elsif ($which eq 'top') {
275             my $first = first { $_->{type} == 5 } @{$output->{nodes}};
276             @docked = (@docked, @{$first->{nodes}});
277         } elsif ($which eq 'bottom') {
278             my @matching = grep { $_->{type} == 5 } @{$output->{nodes}};
279             my $last = $matching[-1];
280             @docked = (@docked, @{$last->{nodes}});
281         }
282     }
283     return @docked;
284 }
285
286 sub cmd {
287     i3(get_socket_path())->command(@_)->recv
288 }
289
290 sub workspace_exists {
291     my ($name) = @_;
292     ($name ~~ @{get_workspace_names()})
293 }
294
295 sub focused_ws {
296     my $i3 = i3(get_socket_path());
297     my $tree = $i3->get_tree->recv;
298     my @outputs = @{$tree->{nodes}};
299     my @cons;
300     for my $output (@outputs) {
301         # get the first CT_CON of each output
302         my $content = first { $_->{type} == 2 } @{$output->{nodes}};
303         my $first = first { $_->{fullscreen_mode} == 1 } @{$content->{nodes}};
304         return $first->{name}
305     }
306 }
307
308 #
309 # Sends an I3_SYNC ClientMessage with a random value to the root window.
310 # i3 will reply with the same value, but, due to the order of events it
311 # processes, only after all other events are done.
312 #
313 # This can be used to ensure the results of a cmd 'focus left' are pushed to
314 # X11 and that $x->input_focus returns the correct value afterwards.
315 #
316 # See also docs/testsuite for a long explanation
317 #
318 sub sync_with_i3 {
319     my ($x) = @_;
320
321     # Since we need a (mapped) window for receiving a ClientMessage, we create
322     # one on the first call of sync_with_i3. It will be re-used in all
323     # subsequent calls.
324     if (!defined($_sync_window)) {
325         $_sync_window = $x->root->create_child(
326             class => WINDOW_CLASS_INPUT_OUTPUT,
327             rect => X11::XCB::Rect->new(x => -15, y => -15, width => 10, height => 10 ),
328             override_redirect => 1,
329             background_color => '#ff0000',
330             event_mask => [ 'structure_notify' ],
331         );
332
333         $_sync_window->map;
334
335         wait_for_event 2, sub { $_[0]->{response_type} == MAP_NOTIFY };
336     }
337
338     my $root = $x->get_root_window();
339     # Generate a random number to identify this particular ClientMessage.
340     my $myrnd = int(rand(255)) + 1;
341
342     # Generate a ClientMessage, see xcb_client_message_t
343     my $msg = pack "CCSLLLLLLL",
344          CLIENT_MESSAGE, # response_type
345          32,     # format
346          0,      # sequence
347          $root,  # destination window
348          $x->atom(name => 'I3_SYNC')->id,
349
350          $_sync_window->id,    # data[0]: our own window id
351          $myrnd, # data[1]: a random value to identify the request
352          0,
353          0,
354          0;
355
356     # Send it to the root window -- since i3 uses the SubstructureRedirect
357     # event mask, it will get the ClientMessage.
358     $x->send_event(0, $root, EVENT_MASK_SUBSTRUCTURE_REDIRECT, $msg);
359
360     # now wait until the reply is here
361     return wait_for_event 2, sub {
362         my ($event) = @_;
363         # TODO: const
364         return 0 unless $event->{response_type} == 161;
365
366         my ($win, $rnd) = unpack "LL", $event->{data};
367         return ($rnd == $myrnd);
368     };
369 }
370
371 sub does_i3_live {
372     my $tree = i3(get_socket_path())->get_tree->recv;
373     my @nodes = @{$tree->{nodes}};
374     my $ok = (@nodes > 0);
375     $tester->ok($ok, 'i3 still lives');
376     return $ok;
377 }
378
379 # Tries to exit i3 gracefully (with the 'exit' cmd) or kills the PID if that fails
380 sub exit_gracefully {
381     my ($pid, $socketpath) = @_;
382     $socketpath ||= get_socket_path();
383
384     my $exited = 0;
385     eval {
386         say "Exiting i3 cleanly...";
387         i3($socketpath)->command('exit')->recv;
388         $exited = 1;
389     };
390
391     if (!$exited) {
392         kill(9, $pid) or die "could not kill i3";
393     }
394
395     if ($socketpath =~ m,^/tmp/i3-test-socket-,) {
396         unlink($socketpath);
397     }
398 }
399
400 # Gets the socket path from the I3_SOCKET_PATH atom stored on the X11 root window
401 sub get_socket_path {
402     my ($cache) = @_;
403     $cache ||= 1;
404
405     if ($cache && defined($_cached_socket_path)) {
406         return $_cached_socket_path;
407     }
408
409     my $atom = $x->atom(name => 'I3_SOCKET_PATH');
410     my $cookie = $x->get_property(0, $x->get_root_window(), $atom->id, GET_PROPERTY_TYPE_ANY, 0, 256);
411     my $reply = $x->get_property_reply($cookie->{sequence});
412     my $socketpath = $reply->{value};
413     $_cached_socket_path = $socketpath;
414     return $socketpath;
415 }
416
417 #
418 # launches a new i3 process with the given string as configuration file.
419 # useful for tests which test specific config file directives.
420 #
421 # be sure to use !NO_I3_INSTANCE! somewhere in the file to signal
422 # complete-run.pl that it should not create an instance of i3
423 #
424 sub launch_with_config {
425     my ($config, $dont_add_socket_path) = @_;
426
427     $dont_add_socket_path //= 0;
428
429     if (!defined($tmp_socket_path)) {
430         $tmp_socket_path = File::Temp::tempnam('/tmp', 'i3-test-socket-');
431     }
432
433     my ($fh, $tmpfile) = tempfile('/tmp/i3-test-config-XXXXX', UNLINK => 1);
434     say $fh $config;
435     say $fh "ipc-socket $tmp_socket_path" unless $dont_add_socket_path;
436     close($fh);
437
438     my $cv = AnyEvent->condvar;
439     my $pid = activate_i3(
440         unix_socket_path => "$tmp_socket_path-activation",
441         display => $ENV{DISPLAY},
442         configfile => $tmpfile,
443         outdir => $ENV{OUTDIR},
444         testname => $ENV{TESTNAME},
445         valgrind => $ENV{VALGRIND},
446         strace => $ENV{STRACE},
447         cv => $cv,
448     );
449
450     # blockingly wait until i3 is ready
451     $cv->recv;
452
453     # force update of the cached socket path in lib/i3test
454     get_socket_path(0);
455
456     return $pid;
457 }
458
459 package i3test::X11;
460 use parent 'X11::XCB::Connection';
461
462 sub input_focus {
463     my $self = shift;
464     i3test::sync_with_i3($self);
465
466     return $self->SUPER::input_focus(@_);
467 }
468
469 1