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