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