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