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