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