]> git.sur5r.net Git - i3/i3/blob - testcases/lib/i3test.pm.in
i3test: blockingly wait for events
[i3/i3] / testcases / lib / i3test.pm.in
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 lib qw(@abs_top_srcdir@/AnyEvent-I3/blib/lib);
11 use AnyEvent::I3;
12 use List::Util qw(first);
13 use Time::HiRes qw(sleep);
14 use Cwd qw(abs_path);
15 use Scalar::Util qw(blessed);
16 use SocketActivation;
17 use i3test::Util qw(slurp);
18
19 use v5.10;
20
21 # preload
22 use Test::More ();
23 use Data::Dumper ();
24
25 use Exporter ();
26 our @EXPORT = qw(
27     get_workspace_names
28     get_unused_workspace
29     fresh_workspace
30     get_ws_content
31     get_ws
32     get_focused
33     open_empty_con
34     open_window
35     open_floating_window
36     get_dock_clients
37     cmd
38     sync_with_i3
39     exit_gracefully
40     workspace_exists
41     focused_ws
42     get_socket_path
43     launch_with_config
44     get_i3_log
45     wait_for_event
46     wait_for_map
47     wait_for_unmap
48     $x
49     kill_all_windows
50     events_for
51     listen_for_binding
52 );
53
54 =head1 NAME
55
56 i3test - Testcase setup module
57
58 =encoding utf-8
59
60 =head1 SYNOPSIS
61
62   use i3test;
63
64   my $ws = fresh_workspace;
65   is_num_children($ws, 0, 'no containers on this workspace yet');
66   cmd 'open';
67   is_num_children($ws, 1, 'one container after "open"');
68
69   done_testing;
70
71 =head1 DESCRIPTION
72
73 This module is used in every i3 testcase and takes care of automatically
74 starting i3 before any test instructions run. It also saves you typing of lots
75 of boilerplate in every test file.
76
77
78 i3test automatically "use"s C<Test::More>, C<Data::Dumper>, C<AnyEvent::I3>,
79 C<Time::HiRes>’s C<sleep> and C<i3test::Test> so that all of them are available
80 to you in your testcase.
81
82 See also C<i3test::Test> (L<https://build.i3wm.org/docs/lib-i3test-test.html>)
83 which provides additional test instructions (like C<ok> or C<is>).
84
85 =cut
86
87 my $tester = Test::Builder->new();
88 my $_cached_socket_path = undef;
89 my $_sync_window = undef;
90 my $tmp_socket_path = undef;
91
92 our $x;
93
94 BEGIN {
95     my $window_count = 0;
96     sub counter_window {
97         return $window_count++;
98     }
99 }
100
101 my $i3_pid;
102 my $i3_autostart;
103
104 END {
105     # Skip the remaining cleanup for testcases which set i3_autostart => 0:
106     return if !defined($i3_pid) && !$i3_autostart;
107
108     # don't trigger SIGCHLD handler
109     local $SIG{CHLD};
110
111     # From perldoc -v '$?':
112     # Inside an "END" subroutine $? contains the value
113     # that is going to be given to "exit()".
114     #
115     # Since waitpid sets $?, we need to localize it,
116     # otherwise TAP would be misinterpreted our return status
117     local $?;
118
119     # When measuring code coverage, try to exit i3 cleanly (otherwise, .gcda
120     # files are not written)
121     if ($ENV{COVERAGE} || $ENV{VALGRIND}) {
122         exit_gracefully($i3_pid, "/tmp/nested-$ENV{DISPLAY}");
123
124     } else {
125         kill(-9, $i3_pid)
126             or $tester->BAIL_OUT("could not kill i3");
127
128         waitpid $i3_pid, 0;
129     }
130 }
131
132 sub import {
133     my ($class, %args) = @_;
134     my $pkg = caller;
135
136     $x ||= i3test::X11->new;
137     # set the pointer to a predictable position in case a previous test has
138     # disturbed it
139     $x->warp_pointer(
140         0, # src_window (None)
141         $x->get_root_window(), # dst_window (None)
142         0, # src_x
143         0, # src_y
144         0, # src_width
145         0, # src_height
146         0, # dst_x
147         0); # dst_y
148     # Synchronize with X11 to ensure the pointer has been warped before i3
149     # starts up.
150     $x->get_input_focus_reply($x->get_input_focus()->{sequence});
151
152     $i3_autostart = delete($args{i3_autostart}) // 1;
153     my $i3_config = delete($args{i3_config}) // '-default';
154
155     my $cv = launch_with_config($i3_config, dont_block => 1)
156         if $i3_autostart;
157
158     my $test_more_args = '';
159     $test_more_args = join(' ', 'qw(', %args, ')') if keys %args;
160     local $@;
161     eval << "__";
162 package $pkg;
163 use Test::More $test_more_args;
164 use Data::Dumper;
165 use AnyEvent::I3;
166 use Time::HiRes qw(sleep);
167 use i3test::Test;
168 __
169     $tester->BAIL_OUT("$@") if $@;
170     feature->import(":5.10");
171     strict->import;
172     warnings->import;
173
174     $cv->recv if $i3_autostart;
175
176     @_ = ($class);
177     goto \&Exporter::import;
178 }
179
180 =head1 EXPORT
181
182 =head2 wait_for_event($timeout, $callback)
183
184 Waits for the next event and calls the given callback for every event to
185 determine if this is the event we are waiting for.
186
187 Can be used to wait until a window is mapped, until a ClientMessage is
188 received, etc.
189
190   wait_for_event 0.25, sub { $_[0]->{response_type} == MAP_NOTIFY };
191
192 =cut
193 sub wait_for_event {
194     my ($timeout, $cb) = @_;
195
196     $x->flush;
197
198     while (defined(my $event = $x->wait_for_event)) {
199         return 1 if $cb->($event);
200     }
201 }
202
203 =head2 wait_for_map($window)
204
205 Thin wrapper around wait_for_event which waits for MAP_NOTIFY.
206 Make sure to include 'structure_notify' in the window’s event_mask attribute.
207
208 This function is called by C<open_window>, so in most cases, you don’t need to
209 call it on your own. If you need special setup of the window before mapping,
210 you might have to map it on your own and use this function:
211
212   my $window = open_window(dont_map => 1);
213   # Do something special with the window first
214   # …
215
216   # Now map it and wait until it’s been mapped
217   $window->map;
218   wait_for_map($window);
219
220 =cut
221 sub wait_for_map {
222     my ($win) = @_;
223     my $id = (blessed($win) && $win->isa('X11::XCB::Window')) ? $win->id : $win;
224     wait_for_event 4, sub {
225         $_[0]->{response_type} == MAP_NOTIFY and $_[0]->{window} == $id
226     };
227 }
228
229 =head2 wait_for_unmap($window)
230
231 Wrapper around C<wait_for_event> which waits for UNMAP_NOTIFY. Also calls
232 C<sync_with_i3> to make sure i3 also picked up and processed the UnmapNotify
233 event.
234
235   my $ws = fresh_workspace;
236   my $window = open_window;
237   is_num_children($ws, 1, 'one window on workspace');
238   $window->unmap;
239   wait_for_unmap;
240   is_num_children($ws, 0, 'no more windows on this workspace');
241
242 =cut
243 sub wait_for_unmap {
244     my ($win) = @_;
245     # my $id = (blessed($win) && $win->isa('X11::XCB::Window')) ? $win->id : $win;
246     wait_for_event 4, sub {
247         $_[0]->{response_type} == UNMAP_NOTIFY # and $_[0]->{window} == $id
248     };
249     sync_with_i3();
250 }
251
252 =head2 open_window([ $args ])
253
254 Opens a new window (see C<X11::XCB::Window>), maps it, waits until it got mapped
255 and synchronizes with i3.
256
257 The following arguments can be passed:
258
259 =over 4
260
261 =item class
262
263 The X11 window class (e.g. WINDOW_CLASS_INPUT_OUTPUT), not to be confused with
264 the WM_CLASS!
265
266 =item rect
267
268 An arrayref with 4 members specifying the initial geometry (position and size)
269 of the window, e.g. C<< [ 0, 100, 70, 50 ] >> for a window appearing at x=0, y=100
270 with width=70 and height=50.
271
272 Note that this is entirely irrelevant for tiling windows.
273
274 =item background_color
275
276 The background pixel color of the window, formatted as "#rrggbb", like HTML
277 color codes (e.g. #c0c0c0). This is useful to tell windows apart when actually
278 watching the testcases.
279
280 =item event_mask
281
282 An arrayref containing strings which describe the X11 event mask we use for that
283 window. The default is C<< [ 'structure_notify' ] >>.
284
285 =item name
286
287 The window’s C<_NET_WM_NAME> (UTF-8 window title). By default, this is "Window
288 n" with n being replaced by a counter to keep windows apart.
289
290 =item dont_map
291
292 Set to a true value to avoid mapping the window (making it visible).
293
294 =item before_map
295
296 A coderef which is called before the window is mapped (unless C<dont_map> is
297 true). The freshly created C<$window> is passed as C<$_> and as the first
298 argument.
299
300 =back
301
302 The default values are equivalent to this call:
303
304   open_window(
305     class => WINDOW_CLASS_INPUT_OUTPUT
306     rect => [ 0, 0, 30, 30 ]
307     background_color => '#c0c0c0'
308     event_mask => [ 'structure_notify' ]
309     name => 'Window <n>'
310   );
311
312 Usually, though, calls are simpler:
313
314   my $top_window = open_window;
315
316 To identify the resulting window object in i3 commands, use the id property:
317
318   my $top_window = open_window;
319   cmd '[id="' . $top_window->id . '"] kill';
320
321 =cut
322 sub open_window {
323     my %args = @_ == 1 ? %{$_[0]} : @_;
324
325     my $dont_map = delete $args{dont_map};
326     my $before_map = delete $args{before_map};
327
328     $args{class} //= WINDOW_CLASS_INPUT_OUTPUT;
329     $args{rect} //= [ 0, 0, 30, 30 ];
330     $args{background_color} //= '#c0c0c0';
331     $args{event_mask} //= [ 'structure_notify' ];
332     $args{name} //= 'Window ' . counter_window();
333
334     my $window = $x->root->create_child(%args);
335     $window->add_hint('input');
336
337     if ($before_map) {
338         # TODO: investigate why _create is not needed
339         $window->_create;
340         $before_map->($window) for $window;
341     }
342
343     return $window if $dont_map;
344
345     $window->map;
346     wait_for_map($window);
347
348     # MapWindow is sent before i3 even starts rendering: the window is placed at
349     # temporary off-screen coordinates first, and x_push_changes() sends further
350     # X11 requests to set focus etc. Hence, we sync with i3 before continuing.
351     sync_with_i3();
352
353     return $window;
354 }
355
356 =head2 open_floating_window([ $args ])
357
358 Thin wrapper around open_window which sets window_type to
359 C<_NET_WM_WINDOW_TYPE_UTILITY> to make the window floating.
360
361 The arguments are the same as those of C<open_window>.
362
363 =cut
364 sub open_floating_window {
365     my %args = @_ == 1 ? %{$_[0]} : @_;
366
367     $args{window_type} = $x->atom(name => '_NET_WM_WINDOW_TYPE_UTILITY');
368
369     return open_window(\%args);
370 }
371
372 sub open_empty_con {
373     my ($i3) = @_;
374
375     my $reply = $i3->command('open')->recv;
376     return $reply->[0]->{id};
377 }
378
379 =head2 get_workspace_names()
380
381 Returns an arrayref containing the name of every workspace (regardless of its
382 output) which currently exists.
383
384   my $workspace_names = get_workspace_names;
385   is(scalar @$workspace_names, 3, 'three workspaces exist currently');
386
387 =cut
388 sub get_workspace_names {
389     my $i3 = i3(get_socket_path());
390     my $tree = $i3->get_tree->recv;
391     my @outputs = @{$tree->{nodes}};
392     my @cons;
393     for my $output (@outputs) {
394         next if $output->{name} eq '__i3';
395         # get the first CT_CON of each output
396         my $content = first { $_->{type} eq 'con' } @{$output->{nodes}};
397         @cons = (@cons, @{$content->{nodes}});
398     }
399     [ map { $_->{name} } @cons ]
400 }
401
402 =head2 get_unused_workspace
403
404 Returns a workspace name which has not yet been used. See also
405 C<fresh_workspace> which directly switches to an unused workspace.
406
407   my $ws = get_unused_workspace;
408   cmd "workspace $ws";
409
410 =cut
411 sub get_unused_workspace {
412     my @names = get_workspace_names();
413     my $tmp;
414     do { $tmp = tmpnam() } while ((scalar grep { $_ eq $tmp } @names) > 0);
415     $tmp
416 }
417
418 =head2 fresh_workspace([ $args ])
419
420 Switches to an unused workspace and returns the name of that workspace.
421
422 Optionally switches to the specified output first.
423
424     my $ws = fresh_workspace;
425
426     # Get a fresh workspace on the second output.
427     my $ws = fresh_workspace(output => 1);
428
429 =cut
430 sub fresh_workspace {
431     my %args = @_;
432     if (exists($args{output})) {
433         my $i3 = i3(get_socket_path());
434         my $tree = $i3->get_tree->recv;
435         my $output = first { $_->{name} eq "fake-$args{output}" }
436                         @{$tree->{nodes}};
437         die "BUG: Could not find output $args{output}" unless defined($output);
438         # Get the focused workspace on that output and switch to it.
439         my $content = first { $_->{type} eq 'con' } @{$output->{nodes}};
440         my $focused = $content->{focus}->[0];
441         my $workspace = first { $_->{id} == $focused } @{$content->{nodes}};
442         $workspace = $workspace->{name};
443         cmd("workspace $workspace");
444     }
445
446     my $unused = get_unused_workspace;
447     cmd("workspace $unused");
448     $unused
449 }
450
451 =head2 get_ws($workspace)
452
453 Returns the container (from the i3 layout tree) which represents C<$workspace>.
454
455   my $ws = fresh_workspace;
456   my $ws_con = get_ws($ws);
457   ok(!$ws_con->{urgent}, 'fresh workspace not marked urgent');
458
459 Here is an example which counts the number of urgent containers recursively,
460 starting from the workspace container:
461
462   sub count_urgent {
463       my ($con) = @_;
464
465       my @children = (@{$con->{nodes}}, @{$con->{floating_nodes}});
466       my $urgent = grep { $_->{urgent} } @children;
467       $urgent += count_urgent($_) for @children;
468       return $urgent;
469   }
470   my $urgent = count_urgent(get_ws($ws));
471   is($urgent, 3, "three urgent windows on workspace $ws");
472
473
474 =cut
475 sub get_ws {
476     my ($name) = @_;
477     my $i3 = i3(get_socket_path());
478     my $tree = $i3->get_tree->recv;
479
480     my @outputs = @{$tree->{nodes}};
481     my @workspaces;
482     for my $output (@outputs) {
483         # get the first CT_CON of each output
484         my $content = first { $_->{type} eq 'con' } @{$output->{nodes}};
485         @workspaces = (@workspaces, @{$content->{nodes}});
486     }
487
488     # as there can only be one workspace with this name, we can safely
489     # return the first entry
490     return first { $_->{name} eq $name } @workspaces;
491 }
492
493 =head2 get_ws_content($workspace)
494
495 Returns the content (== tree, starting from the node of a workspace)
496 of a workspace. If called in array context, also includes the focus
497 stack of the workspace.
498
499   my $nodes = get_ws_content($ws);
500   is(scalar @$nodes, 4, 'there are four containers at workspace-level');
501
502 Or, in array context:
503
504   my $window = open_window;
505   my ($nodes, $focus) = get_ws_content($ws);
506   is($focus->[0], $window->id, 'newly opened window focused');
507
508 Note that this function does not do recursion for you! It only returns the
509 containers B<on workspace level>. If you want to work with all containers (even
510 nested ones) on a workspace, you have to use recursion:
511
512   # NB: This function does not count floating windows
513   sub count_urgent {
514       my ($nodes) = @_;
515
516       my $urgent = 0;
517       for my $con (@$nodes) {
518           $urgent++ if $con->{urgent};
519           $urgent += count_urgent($con->{nodes});
520       }
521
522       return $urgent;
523   }
524   my $nodes = get_ws_content($ws);
525   my $urgent = count_urgent($nodes);
526   is($urgent, 3, "three urgent windows on workspace $ws");
527
528 If you also want to deal with floating windows, you have to use C<get_ws>
529 instead and access C<< ->{nodes} >> and C<< ->{floating_nodes} >> on your own.
530
531 =cut
532 sub get_ws_content {
533     my ($name) = @_;
534     my $con = get_ws($name);
535     return wantarray ? ($con->{nodes}, $con->{focus}) : $con->{nodes};
536 }
537
538 =head2 get_focused($workspace)
539
540 Returns the container ID of the currently focused container on C<$workspace>.
541
542 Note that the container ID is B<not> the X11 window ID, so comparing the result
543 of C<get_focused> with a window's C<< ->{id} >> property does B<not> work.
544
545   my $ws = fresh_workspace;
546   my $first_window = open_window;
547   my $first_id = get_focused();
548
549   my $second_window = open_window;
550   my $second_id = get_focused();
551
552   cmd 'focus left';
553
554   is(get_focused($ws), $first_id, 'second window focused');
555
556 =cut
557 sub get_focused {
558     my ($ws) = @_;
559     my $con = get_ws($ws);
560
561     my @focused = @{$con->{focus}};
562     my $lf;
563     while (@focused > 0) {
564         $lf = $focused[0];
565         last unless defined($con->{focus});
566         @focused = @{$con->{focus}};
567         my @cons = grep { $_->{id} == $lf } (@{$con->{nodes}}, @{$con->{'floating_nodes'}});
568         $con = $cons[0];
569     }
570
571     return $lf;
572 }
573
574 =head2 get_dock_clients([ $dockarea ])
575
576 Returns an array of all dock containers in C<$dockarea> (one of "top" or
577 "bottom"). If C<$dockarea> is not specified, returns an array of all dock
578 containers in any dockarea.
579
580   my @docked = get_dock_clients;
581   is(scalar @docked, 0, 'no dock clients yet');
582
583 =cut
584 sub get_dock_clients {
585     my $which = shift;
586
587     my $tree = i3(get_socket_path())->get_tree->recv;
588     my @outputs = @{$tree->{nodes}};
589     # Children of all dockareas
590     my @docked;
591     for my $output (@outputs) {
592         if (!defined($which)) {
593             @docked = (@docked, map { @{$_->{nodes}} }
594                                 grep { $_->{type} eq 'dockarea' }
595                                 @{$output->{nodes}});
596         } elsif ($which eq 'top') {
597             my $first = first { $_->{type} eq 'dockarea' } @{$output->{nodes}};
598             @docked = (@docked, @{$first->{nodes}}) if defined($first);
599         } elsif ($which eq 'bottom') {
600             my @matching = grep { $_->{type} eq 'dockarea' } @{$output->{nodes}};
601             my $last = $matching[-1];
602             @docked = (@docked, @{$last->{nodes}}) if defined($last);
603         }
604     }
605     return @docked;
606 }
607
608 =head2 cmd($command)
609
610 Sends the specified command to i3 and returns the output.
611
612   my $ws = unused_workspace;
613   cmd "workspace $ws";
614   cmd 'focus right';
615
616 =cut
617 sub cmd {
618     i3(get_socket_path())->command(@_)->recv
619 }
620
621 =head2 workspace_exists($workspace)
622
623 Returns true if C<$workspace> is the name of an existing workspace.
624
625   my $old_ws = focused_ws;
626   # switch away from where we currently are
627   fresh_workspace;
628
629   ok(workspace_exists($old_ws), 'old workspace still exists');
630
631 =cut
632 sub workspace_exists {
633     my ($name) = @_;
634     (scalar grep { $_ eq $name } @{get_workspace_names()}) > 0;
635 }
636
637 =head2 focused_ws
638
639 Returns the name of the currently focused workspace.
640
641   my $ws = focused_ws;
642   is($ws, '1', 'i3 starts on workspace 1');
643
644 =cut
645 sub focused_ws {
646     my $i3 = i3(get_socket_path());
647     my $tree = $i3->get_tree->recv;
648     my $focused = $tree->{focus}->[0];
649     my $output = first { $_->{id} == $focused } @{$tree->{nodes}};
650     my $content = first { $_->{type} eq 'con' } @{$output->{nodes}};
651     my $first = first { $_->{fullscreen_mode} == 1 } @{$content->{nodes}};
652     return $first->{name}
653 }
654
655 =head2 sync_with_i3([ $args ])
656
657 Sends an I3_SYNC ClientMessage with a random value to the root window.
658 i3 will reply with the same value, but, due to the order of events it
659 processes, only after all other events are done.
660
661 This can be used to ensure the results of a cmd 'focus left' are pushed to
662 X11 and that C<< $x->input_focus >> returns the correct value afterwards.
663
664 See also L<https://build.i3wm.org/docs/testsuite.html> for a longer explanation.
665
666   my $window = open_window;
667   $window->add_hint('urgency');
668   # Ensure i3 picked up the change
669   sync_with_i3;
670
671 The only time when you need to use the C<no_cache> argument is when you just
672 killed your own X11 connection:
673
674   cmd 'kill client';
675   # We need to re-establish the X11 connection which we just killed :).
676   $x = i3test::X11->new;
677   sync_with_i3(no_cache => 1);
678
679 =cut
680 sub sync_with_i3 {
681     my %args = @_ == 1 ? %{$_[0]} : @_;
682
683     # Since we need a (mapped) window for receiving a ClientMessage, we create
684     # one on the first call of sync_with_i3. It will be re-used in all
685     # subsequent calls.
686     if (!exists($args{window_id}) &&
687         (!defined($_sync_window) || exists($args{no_cache}))) {
688         $_sync_window = open_window(
689             rect => [ -15, -15, 10, 10 ],
690             override_redirect => 1,
691             dont_map => 1,
692         );
693     }
694
695     my $window_id = delete $args{window_id};
696     $window_id //= $_sync_window->id;
697
698     my $root = $x->get_root_window();
699     # Generate a random number to identify this particular ClientMessage.
700     my $myrnd = int(rand(255)) + 1;
701
702     # Generate a ClientMessage, see xcb_client_message_t
703     my $msg = pack "CCSLLLLLLL",
704          CLIENT_MESSAGE, # response_type
705          32,     # format
706          0,      # sequence
707          $root,  # destination window
708          $x->atom(name => 'I3_SYNC')->id,
709
710          $window_id,    # data[0]: our own window id
711          $myrnd, # data[1]: a random value to identify the request
712          0,
713          0,
714          0;
715
716     # Send it to the root window -- since i3 uses the SubstructureRedirect
717     # event mask, it will get the ClientMessage.
718     $x->send_event(0, $root, EVENT_MASK_SUBSTRUCTURE_REDIRECT, $msg);
719
720     return $myrnd if $args{dont_wait_for_event};
721
722     # now wait until the reply is here
723     return wait_for_event 4, sub {
724         my ($event) = @_;
725         # TODO: const
726         return 0 unless $event->{response_type} == 161;
727
728         my ($win, $rnd) = unpack "LL", $event->{data};
729         return ($rnd == $myrnd);
730     };
731 }
732
733 =head2 exit_gracefully($pid, [ $socketpath ])
734
735 Tries to exit i3 gracefully (with the 'exit' cmd) or kills the PID if that fails.
736
737 If C<$socketpath> is not specified, C<get_socket_path()> will be called.
738
739 You only need to use this function if you have launched i3 on your own with
740 C<launch_with_config>. Otherwise, it will be automatically called when the
741 testcase ends.
742
743   use i3test i3_autostart => 0;
744   my $pid = launch_with_config($config);
745   # …
746   exit_gracefully($pid);
747
748 =cut
749 sub exit_gracefully {
750     my ($pid, $socketpath) = @_;
751     $socketpath ||= get_socket_path();
752
753     my $exited = 0;
754     eval {
755         say "Exiting i3 cleanly...";
756         i3($socketpath)->command('exit')->recv;
757         $exited = 1;
758     };
759
760     if (!$exited) {
761         kill(9, $pid)
762             or $tester->BAIL_OUT("could not kill i3");
763     }
764
765     if ($socketpath =~ m,^/tmp/i3-test-socket-,) {
766         unlink($socketpath);
767     }
768
769     waitpid $pid, 0;
770     undef $i3_pid;
771 }
772
773 =head2 get_socket_path([ $cache ])
774
775 Gets the socket path from the C<I3_SOCKET_PATH> atom stored on the X11 root
776 window. After the first call, this function will return a cached version of the
777 socket path unless you specify a false value for C<$cache>.
778
779   my $i3 = i3(get_socket_path());
780   $i3->command('nop test example')->recv;
781
782 To avoid caching:
783
784   my $i3 = i3(get_socket_path(0));
785
786 =cut
787 sub get_socket_path {
788     my ($cache) = @_;
789     $cache //= 1;
790
791     if ($cache && defined($_cached_socket_path)) {
792         return $_cached_socket_path;
793     }
794     my $socketpath = i3test::Util::get_socket_path($x);
795     $_cached_socket_path = $socketpath;
796     return $socketpath;
797 }
798
799 =head2 launch_with_config($config, [ $args ])
800
801 Launches a new i3 process with C<$config> as configuration file. Useful for
802 tests which test specific config file directives.
803
804   use i3test i3_autostart => 0;
805
806   my $config = <<EOT;
807   # i3 config file (v4)
808   for_window [class="borderless"] border none
809   for_window [title="special borderless title"] border none
810   EOT
811
812   my $pid = launch_with_config($config);
813
814   # …
815
816   exit_gracefully($pid);
817
818 =cut
819 sub launch_with_config {
820     my ($config, %args) = @_;
821
822     $tmp_socket_path = "/tmp/nested-$ENV{DISPLAY}";
823
824     $args{dont_create_temp_dir} //= 0;
825     $args{validate_config} //= 0;
826
827     my ($fh, $tmpfile) = tempfile("i3-cfg-for-$ENV{TESTNAME}-XXXXX", UNLINK => 1);
828
829     say $fh "ipc-socket $tmp_socket_path"
830         unless $args{dont_add_socket_path};
831
832     if ($config ne '-default') {
833         print $fh $config;
834     } else {
835         open(my $conf_fh, '<', '@abs_top_srcdir@/testcases/i3-test.config')
836             or $tester->BAIL_OUT("could not open default config: $!");
837         local $/;
838         say $fh scalar <$conf_fh>;
839     }
840
841     close($fh);
842
843     my $cv = AnyEvent->condvar;
844     $i3_pid = activate_i3(
845         unix_socket_path => "$tmp_socket_path-activation",
846         display => $ENV{DISPLAY},
847         configfile => $tmpfile,
848         outdir => $ENV{OUTDIR},
849         testname => $ENV{TESTNAME},
850         valgrind => $ENV{VALGRIND},
851         strace => $ENV{STRACE},
852         xtrace => $ENV{XTRACE},
853         restart => $ENV{RESTART},
854         cv => $cv,
855         dont_create_temp_dir => $args{dont_create_temp_dir},
856         validate_config => $args{validate_config},
857         inject_randr15 => $args{inject_randr15},
858         inject_randr15_outputinfo => $args{inject_randr15_outputinfo},
859     );
860
861     # If we called i3 with -C, we wait for it to exit and then return as
862     # there's nothing else we need to do.
863     if ($args{validate_config}) {
864         $cv->recv;
865         waitpid $i3_pid, 0;
866
867         # We need this since exit_gracefully will not be called in this case.
868         undef $i3_pid;
869
870         return ${^CHILD_ERROR_NATIVE};
871     }
872
873     # force update of the cached socket path in lib/i3test
874     # as soon as i3 has started
875     $cv->cb(sub { get_socket_path(0) });
876
877     return $cv if $args{dont_block};
878
879     # blockingly wait until i3 is ready
880     $cv->recv;
881
882     return $i3_pid;
883 }
884
885 =head2 get_i3_log
886
887 Returns the content of the log file for the current test.
888
889 =cut
890 sub get_i3_log {
891     my $logfile = "$ENV{OUTDIR}/i3-log-for-$ENV{TESTNAME}";
892     return slurp($logfile);
893 }
894
895 =head2 kill_all_windows
896
897 Kills all windows to clean up between tests.
898
899 =cut
900 sub kill_all_windows {
901     # Sync in case not all windows are managed by i3 just yet.
902     sync_with_i3;
903     cmd '[title=".*"] kill';
904 }
905
906 =head2 events_for($subscribecb, [ $rettype ], [ $eventcbs ])
907
908 Helper function which returns an array containing all events of type $rettype
909 which were generated by i3 while $subscribecb was running.
910
911 Set $eventcbs to subscribe to multiple event types and/or perform your own event
912 aggregation.
913
914 =cut
915 sub events_for {
916     my ($subscribecb, $rettype, $eventcbs) = @_;
917
918     my @events;
919     $eventcbs //= {};
920     if (defined($rettype)) {
921         $eventcbs->{$rettype} = sub { push @events, shift };
922     }
923     my $subscribed = AnyEvent->condvar;
924     my $flushed = AnyEvent->condvar;
925     $eventcbs->{tick} = sub {
926         my ($event) = @_;
927         if ($event->{first}) {
928             $subscribed->send($event);
929         } else {
930             $flushed->send($event);
931         }
932     };
933     my $i3 = i3(get_socket_path(0));
934     $i3->connect->recv;
935     $i3->subscribe($eventcbs)->recv;
936     $subscribed->recv;
937     # Subscription established, run the callback.
938     $subscribecb->();
939     # Now generate a tick event, which we know we’ll receive (and at which point
940     # all other events have been received).
941     my $nonce = int(rand(255)) + 1;
942     $i3->send_tick($nonce);
943
944     my $tick = $flushed->recv;
945     $tester->is_eq($tick->{payload}, $nonce, 'tick nonce received');
946     return @events;
947 }
948
949 =head2 listen_for_binding($cb)
950
951 Helper function to evaluate whether sending KeyPress/KeyRelease events via XTEST
952 triggers an i3 key binding or not. Expects key bindings to be configured in the
953 form “bindsym <binding> nop <binding>”, e.g.  “bindsym Mod4+Return nop
954 Mod4+Return”.
955
956   is(listen_for_binding(
957       sub {
958           xtest_key_press(133); # Super_L
959           xtest_key_press(36); # Return
960           xtest_key_release(36); # Return
961           xtest_key_release(133); # Super_L
962           xtest_sync_with_i3;
963       },
964       ),
965      'Mod4+Return',
966      'triggered the "Mod4+Return" keybinding');
967
968 =cut
969
970 sub listen_for_binding {
971     my ($cb) = @_;
972     my $triggered = AnyEvent->condvar;
973     my @events = events_for(
974         $cb,
975         'binding');
976
977     $tester->is_eq(scalar @events, 1, 'Received precisely one event');
978     $tester->is_eq($events[0]->{change}, 'run', 'change is "run"');
979     # We look at the command (which is “nop <binding>”) because that is easier
980     # than re-assembling the string representation of $event->{binding}.
981     my $command = $events[0]->{binding}->{command};
982     $command =~ s/^nop //g;
983     return $command;
984 }
985
986 =head1 AUTHOR
987
988 Michael Stapelberg <michael@i3wm.org>
989
990 =cut
991
992 package i3test::X11;
993 use parent 'X11::XCB::Connection';
994
995 sub input_focus {
996     my $self = shift;
997     i3test::sync_with_i3();
998
999     return $self->SUPER::input_focus(@_);
1000 }
1001
1002 1