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