]> git.sur5r.net Git - i3/i3/blob - testcases/lib/i3test.pm
testcases: let i3test.pm export $x, adapt testcases
[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 ($x, $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     my ($x) = @_;
126     wait_for_event $x, 2, sub { $_[0]->{response_type} == MAP_NOTIFY };
127 }
128
129 # Wrapper around wait_for_event which waits for UNMAP_NOTIFY. Also calls
130 # sync_with_i3 to make sure i3 also picked up and processed the UnmapNotify
131 # event.
132 sub wait_for_unmap {
133     my ($x) = @_;
134     wait_for_event $x, 2, sub { $_[0]->{response_type} == UNMAP_NOTIFY };
135     sync_with_i3($x);
136 }
137
138 #
139 # Opens a new window (see X11::XCB::Window), maps it, waits until it got mapped
140 # and synchronizes with i3.
141 #
142 # set dont_map to a true value to avoid mapping
143 #
144 # default values:
145 #     class => WINDOW_CLASS_INPUT_OUTPUT
146 #     rect => [ 0, 0, 30, 30 ]
147 #     background_color => '#c0c0c0'
148 #     event_mask => [ 'structure_notify' ]
149 #     name => 'Window <n>'
150 #
151 sub open_window {
152     my ($x, $args) = @_;
153     my %args = ($args ? %$args : ());
154
155     my $dont_map = delete $args{dont_map};
156
157     $args{class} //= WINDOW_CLASS_INPUT_OUTPUT;
158     $args{rect} //= [ 0, 0, 30, 30 ];
159     $args{background_color} //= '#c0c0c0';
160     $args{event_mask} //= [ 'structure_notify' ];
161     $args{name} //= 'Window ' . counter_window();
162
163     my $window = $x->root->create_child(%args);
164
165     return $window if $dont_map;
166
167     $window->map;
168     wait_for_map($x);
169     # We sync with i3 here to make sure $x->input_focus is updated.
170     sync_with_i3($x);
171     return $window;
172 }
173
174 # Thin wrapper around open_window which sets window_type to
175 # _NET_WM_WINDOW_TYPE_UTILITY to make the window floating.
176 sub open_floating_window {
177     my ($x, $args) = @_;
178     my %args = ($args ? %$args : ());
179
180     $args{window_type} = $x->atom(name => '_NET_WM_WINDOW_TYPE_UTILITY');
181
182     return open_window($x, \%args);
183 }
184
185 sub open_empty_con {
186     my ($i3) = @_;
187
188     my $reply = $i3->command('open')->recv;
189     return $reply->{id};
190 }
191
192 sub get_workspace_names {
193     my $i3 = i3(get_socket_path());
194     my $tree = $i3->get_tree->recv;
195     my @outputs = @{$tree->{nodes}};
196     my @cons;
197     for my $output (@outputs) {
198         # get the first CT_CON of each output
199         my $content = first { $_->{type} == 2 } @{$output->{nodes}};
200         @cons = (@cons, @{$content->{nodes}});
201     }
202     [ map { $_->{name} } @cons ]
203 }
204
205 sub get_unused_workspace {
206     my @names = get_workspace_names();
207     my $tmp;
208     do { $tmp = tmpnam() } while ($tmp ~~ @names);
209     $tmp
210 }
211
212 sub fresh_workspace {
213     my $unused = get_unused_workspace;
214     cmd("workspace $unused");
215     $unused
216 }
217
218 sub get_ws {
219     my ($name) = @_;
220     my $i3 = i3(get_socket_path());
221     my $tree = $i3->get_tree->recv;
222
223     my @outputs = @{$tree->{nodes}};
224     my @workspaces;
225     for my $output (@outputs) {
226         # get the first CT_CON of each output
227         my $content = first { $_->{type} == 2 } @{$output->{nodes}};
228         @workspaces = (@workspaces, @{$content->{nodes}});
229     }
230
231     # as there can only be one workspace with this name, we can safely
232     # return the first entry
233     return first { $_->{name} eq $name } @workspaces;
234 }
235
236 #
237 # returns the content (== tree, starting from the node of a workspace)
238 # of a workspace. If called in array context, also includes the focus
239 # stack of the workspace
240 #
241 sub get_ws_content {
242     my ($name) = @_;
243     my $con = get_ws($name);
244     return wantarray ? ($con->{nodes}, $con->{focus}) : $con->{nodes};
245 }
246
247 sub get_focused {
248     my ($ws) = @_;
249     my $con = get_ws($ws);
250
251     my @focused = @{$con->{focus}};
252     my $lf;
253     while (@focused > 0) {
254         $lf = $focused[0];
255         last unless defined($con->{focus});
256         @focused = @{$con->{focus}};
257         my @cons = grep { $_->{id} == $lf } (@{$con->{nodes}}, @{$con->{'floating_nodes'}});
258         $con = $cons[0];
259     }
260
261     return $lf;
262 }
263
264 sub get_dock_clients {
265     my $which = shift;
266
267     my $tree = i3(get_socket_path())->get_tree->recv;
268     my @outputs = @{$tree->{nodes}};
269     # Children of all dockareas
270     my @docked;
271     for my $output (@outputs) {
272         if (!defined($which)) {
273             @docked = (@docked, map { @{$_->{nodes}} }
274                                 grep { $_->{type} == 5 }
275                                 @{$output->{nodes}});
276         } elsif ($which eq 'top') {
277             my $first = first { $_->{type} == 5 } @{$output->{nodes}};
278             @docked = (@docked, @{$first->{nodes}});
279         } elsif ($which eq 'bottom') {
280             my @matching = grep { $_->{type} == 5 } @{$output->{nodes}};
281             my $last = $matching[-1];
282             @docked = (@docked, @{$last->{nodes}});
283         }
284     }
285     return @docked;
286 }
287
288 sub cmd {
289     i3(get_socket_path())->command(@_)->recv
290 }
291
292 sub workspace_exists {
293     my ($name) = @_;
294     ($name ~~ @{get_workspace_names()})
295 }
296
297 sub focused_ws {
298     my $i3 = i3(get_socket_path());
299     my $tree = $i3->get_tree->recv;
300     my @outputs = @{$tree->{nodes}};
301     my @cons;
302     for my $output (@outputs) {
303         # get the first CT_CON of each output
304         my $content = first { $_->{type} == 2 } @{$output->{nodes}};
305         my $first = first { $_->{fullscreen_mode} == 1 } @{$content->{nodes}};
306         return $first->{name}
307     }
308 }
309
310 #
311 # Sends an I3_SYNC ClientMessage with a random value to the root window.
312 # i3 will reply with the same value, but, due to the order of events it
313 # processes, only after all other events are done.
314 #
315 # This can be used to ensure the results of a cmd 'focus left' are pushed to
316 # X11 and that $x->input_focus returns the correct value afterwards.
317 #
318 # See also docs/testsuite for a long explanation
319 #
320 sub sync_with_i3 {
321     my ($x) = @_;
322
323     # Since we need a (mapped) window for receiving a ClientMessage, we create
324     # one on the first call of sync_with_i3. It will be re-used in all
325     # subsequent calls.
326     if (!defined($_sync_window)) {
327         $_sync_window = $x->root->create_child(
328             class => WINDOW_CLASS_INPUT_OUTPUT,
329             rect => X11::XCB::Rect->new(x => -15, y => -15, width => 10, height => 10 ),
330             override_redirect => 1,
331             background_color => '#ff0000',
332             event_mask => [ 'structure_notify' ],
333         );
334
335         $_sync_window->map;
336
337         wait_for_event $x, 2, sub { $_[0]->{response_type} == MAP_NOTIFY };
338     }
339
340     my $root = $x->get_root_window();
341     # Generate a random number to identify this particular ClientMessage.
342     my $myrnd = int(rand(255)) + 1;
343
344     # Generate a ClientMessage, see xcb_client_message_t
345     my $msg = pack "CCSLLLLLLL",
346          CLIENT_MESSAGE, # response_type
347          32,     # format
348          0,      # sequence
349          $root,  # destination window
350          $x->atom(name => 'I3_SYNC')->id,
351
352          $_sync_window->id,    # data[0]: our own window id
353          $myrnd, # data[1]: a random value to identify the request
354          0,
355          0,
356          0;
357
358     # Send it to the root window -- since i3 uses the SubstructureRedirect
359     # event mask, it will get the ClientMessage.
360     $x->send_event(0, $root, EVENT_MASK_SUBSTRUCTURE_REDIRECT, $msg);
361
362     # now wait until the reply is here
363     return wait_for_event $x, 2, sub {
364         my ($event) = @_;
365         # TODO: const
366         return 0 unless $event->{response_type} == 161;
367
368         my ($win, $rnd) = unpack "LL", $event->{data};
369         return ($rnd == $myrnd);
370     };
371 }
372
373 sub does_i3_live {
374     my $tree = i3(get_socket_path())->get_tree->recv;
375     my @nodes = @{$tree->{nodes}};
376     my $ok = (@nodes > 0);
377     $tester->ok($ok, 'i3 still lives');
378     return $ok;
379 }
380
381 # Tries to exit i3 gracefully (with the 'exit' cmd) or kills the PID if that fails
382 sub exit_gracefully {
383     my ($pid, $socketpath) = @_;
384     $socketpath ||= get_socket_path();
385
386     my $exited = 0;
387     eval {
388         say "Exiting i3 cleanly...";
389         i3($socketpath)->command('exit')->recv;
390         $exited = 1;
391     };
392
393     if (!$exited) {
394         kill(9, $pid) or die "could not kill i3";
395     }
396
397     if ($socketpath =~ m,^/tmp/i3-test-socket-,) {
398         unlink($socketpath);
399     }
400 }
401
402 # Gets the socket path from the I3_SOCKET_PATH atom stored on the X11 root window
403 sub get_socket_path {
404     my ($cache) = @_;
405     $cache ||= 1;
406
407     if ($cache && defined($_cached_socket_path)) {
408         return $_cached_socket_path;
409     }
410
411     my $atom = $x->atom(name => 'I3_SOCKET_PATH');
412     my $cookie = $x->get_property(0, $x->get_root_window(), $atom->id, GET_PROPERTY_TYPE_ANY, 0, 256);
413     my $reply = $x->get_property_reply($cookie->{sequence});
414     my $socketpath = $reply->{value};
415     $_cached_socket_path = $socketpath;
416     return $socketpath;
417 }
418
419 #
420 # launches a new i3 process with the given string as configuration file.
421 # useful for tests which test specific config file directives.
422 #
423 # be sure to use !NO_I3_INSTANCE! somewhere in the file to signal
424 # complete-run.pl that it should not create an instance of i3
425 #
426 sub launch_with_config {
427     my ($config, $dont_add_socket_path) = @_;
428
429     $dont_add_socket_path //= 0;
430
431     if (!defined($tmp_socket_path)) {
432         $tmp_socket_path = File::Temp::tempnam('/tmp', 'i3-test-socket-');
433     }
434
435     my ($fh, $tmpfile) = tempfile('/tmp/i3-test-config-XXXXX', UNLINK => 1);
436     say $fh $config;
437     say $fh "ipc-socket $tmp_socket_path" unless $dont_add_socket_path;
438     close($fh);
439
440     my $cv = AnyEvent->condvar;
441     my $pid = activate_i3(
442         unix_socket_path => "$tmp_socket_path-activation",
443         display => $ENV{DISPLAY},
444         configfile => $tmpfile,
445         outdir => $ENV{OUTDIR},
446         testname => $ENV{TESTNAME},
447         valgrind => $ENV{VALGRIND},
448         strace => $ENV{STRACE},
449         cv => $cv,
450     );
451
452     # blockingly wait until i3 is ready
453     $cv->recv;
454
455     # force update of the cached socket path in lib/i3test
456     get_socket_path(0);
457
458     return $pid;
459 }
460
461 package i3test::X11;
462 use parent 'X11::XCB::Connection';
463
464 sub input_focus {
465     my $self = shift;
466     i3test::sync_with_i3($self);
467
468     return $self->SUPER::input_focus(@_);
469 }
470
471 1