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