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