File Coverage

blib/lib/AnyEvent/I3.pm
Criterion Covered Total %
statement 83 176 47.1
branch 7 36 19.4
condition 2 5 40.0
subroutine 23 39 58.9
pod 12 12 100.0
total 127 268 47.3


line stmt bran cond sub pod time code
1             package AnyEvent::I3;
2             # vim:ts=4:sw=4:expandtab
3              
4 3     3   39699 use strict;
  3         4  
  3         69  
5 3     3   8 use warnings;
  3         3  
  3         59  
6 3     3   1601 use JSON::XS;
  3         15901  
  3         133  
7 3     3   1767 use AnyEvent::Handle;
  3         55865  
  3         94  
8 3     3   1444 use AnyEvent::Socket;
  3         30318  
  3         246  
9 3     3   16 use AnyEvent;
  3         3  
  3         55  
10 3     3   1440 use Encode;
  3         21850  
  3         170  
11 3     3   15 use Scalar::Util qw(tainted);
  3         3  
  3         218  
12              
13             =head1 NAME
14              
15             AnyEvent::I3 - communicate with the i3 window manager
16              
17             =cut
18              
19             our $VERSION = '0.17';
20              
21             =head1 VERSION
22              
23             Version 0.17
24              
25             =head1 SYNOPSIS
26              
27             This module connects to the i3 window manager using the UNIX socket based
28             IPC interface it provides (if enabled in the configuration file). You can
29             then subscribe to events or send messages and receive their replies.
30              
31             use AnyEvent::I3 qw(:all);
32              
33             my $i3 = i3();
34              
35             $i3->connect->recv or die "Error connecting";
36             say "Connected to i3";
37              
38             my $workspaces = $i3->message(TYPE_GET_WORKSPACES)->recv;
39             say "Currently, you use " . @{$workspaces} . " workspaces";
40              
41             ...or, using the sugar methods:
42              
43             use AnyEvent::I3;
44              
45             my $workspaces = i3->get_workspaces->recv;
46             say "Currently, you use " . @{$workspaces} . " workspaces";
47              
48             A somewhat more involved example which dumps the i3 layout tree whenever there
49             is a workspace event:
50              
51             use Data::Dumper;
52             use AnyEvent;
53             use AnyEvent::I3;
54              
55             my $i3 = i3();
56              
57             $i3->connect->recv or die "Error connecting to i3";
58              
59             $i3->subscribe({
60             workspace => sub {
61             $i3->get_tree->cb(sub {
62             my ($tree) = @_;
63             say "tree: " . Dumper($tree);
64             });
65             }
66             })->recv->{success} or die "Error subscribing to events";
67              
68             AE::cv->recv
69              
70             =head1 EXPORT
71              
72             =head2 $i3 = i3([ $path ]);
73              
74             Creates a new C object and returns it.
75              
76             C is an optional path of the UNIX socket to connect to. It is strongly
77             advised to NOT specify this unless you're absolutely sure you need it.
78             C will automatically figure it out by querying the running i3
79             instance on the current DISPLAY which is almost always what you want.
80              
81             =head1 SUBROUTINES/METHODS
82              
83             =cut
84              
85 3     3   10 use Exporter qw(import);
  3         3  
  3         56  
86 3     3   23 use base 'Exporter';
  3         2  
  3         196  
87              
88             our @EXPORT = qw(i3);
89              
90 3     3   11 use constant TYPE_COMMAND => 0;
  3         3  
  3         119  
91 3     3   10 use constant TYPE_GET_WORKSPACES => 1;
  3         3  
  3         115  
92 3     3   12 use constant TYPE_SUBSCRIBE => 2;
  3         3  
  3         99  
93 3     3   17 use constant TYPE_GET_OUTPUTS => 3;
  3         3  
  3         90  
94 3     3   10 use constant TYPE_GET_TREE => 4;
  3         3  
  3         123  
95 3     3   9 use constant TYPE_GET_MARKS => 5;
  3         4  
  3         96  
96 3     3   9 use constant TYPE_GET_BAR_CONFIG => 6;
  3         3  
  3         95  
97 3     3   9 use constant TYPE_GET_VERSION => 7;
  3         2  
  3         4128  
98              
99             our %EXPORT_TAGS = ( 'all' => [
100             qw(i3 TYPE_COMMAND TYPE_GET_WORKSPACES TYPE_SUBSCRIBE TYPE_GET_OUTPUTS
101             TYPE_GET_TREE TYPE_GET_MARKS TYPE_GET_BAR_CONFIG TYPE_GET_VERSION)
102             ] );
103              
104             our @EXPORT_OK = ( @{ $EXPORT_TAGS{all} } );
105              
106             my $magic = "i3-ipc";
107              
108             # TODO: auto-generate this from the header file? (i3/ipc.h)
109             my $event_mask = (1 << 31);
110             my %events = (
111             workspace => ($event_mask | 0),
112             output => ($event_mask | 1),
113             mode => ($event_mask | 2),
114             window => ($event_mask | 3),
115             barconfig_update => ($event_mask | 4),
116             binding => ($event_mask | 5),
117             shutdown => ($event_mask | 6),
118             _error => 0xFFFFFFFF,
119             );
120              
121             sub i3 {
122 2     2 1 18 AnyEvent::I3->new(@_)
123             }
124              
125             # Calls i3, even when running in taint mode.
126             sub _call_i3 {
127 2     2   4 my ($args) = @_;
128              
129 2         16 my $path_tainted = tainted($ENV{PATH});
130             # This effectively circumvents taint mode checking for $ENV{PATH}. We
131             # do this because users might specify PATH explicitly to call i3 in a
132             # custom location (think ~/.bin/).
133 2         108 (local $ENV{PATH}) = ($ENV{PATH} =~ /(.*)/);
134              
135             # In taint mode, we also need to remove all relative directories from
136             # PATH (like . or ../bin). We only do this in taint mode and warn the
137             # user, since this might break a real-world use case for some people.
138 2 50       9 if ($path_tainted) {
139 2         20 my @dirs = split /:/, $ENV{PATH};
140 2         17 my @filtered = grep !/^\./, @dirs;
141 2 50       10 if (scalar @dirs != scalar @filtered) {
142 2         75 $ENV{PATH} = join ':', @filtered;
143 2         88 warn qq|Removed relative directories from PATH because you | .
144             qq|are running Perl with taint mode enabled. Remove -T | .
145             qq|to be able to use relative directories in PATH. | .
146             qq|New PATH is "$ENV{PATH}"|;
147             }
148             }
149             # Otherwise the qx() operator wont work:
150 2         21 delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};
151 2         2974 chomp(my $result = qx(i3 $args));
152             # Circumventing taint mode again: the socket can be anywhere on the
153             # system and that’s okay.
154 2 50       36 if ($result =~ /^([^\0]+)$/) {
155 0         0 return $1;
156             }
157              
158 2         17 warn "Calling i3 $args failed. Is DISPLAY set and is i3 in your PATH?";
159 2         109 return undef;
160             }
161              
162             =head2 $i3 = AnyEvent::I3->new([ $path ])
163              
164             Creates a new C object and returns it.
165              
166             C is an optional path of the UNIX socket to connect to. It is strongly
167             advised to NOT specify this unless you're absolutely sure you need it.
168             C will automatically figure it out by querying the running i3
169             instance on the current DISPLAY which is almost always what you want.
170              
171             =cut
172             sub new {
173 2     2 1 3 my ($class, $path) = @_;
174              
175 2 50       8 $path = _call_i3('--get-socketpath') unless $path;
176              
177             # This is the old default path (v3.*). This fallback line can be removed in
178             # a year from now. -- Michael, 2012-07-09
179 2   50     25 $path ||= '~/.i3/ipc.sock';
180              
181             # Check if we need to resolve ~
182 2 50       13 if ($path =~ /~/) {
183             # We use getpwuid() instead of $ENV{HOME} because the latter is tainted
184             # and thus produces warnings when running tests with perl -T
185 2         1118 my $home = (getpwuid($<))[7];
186 2 50 33     39 die "Could not get home directory" unless $home and -d $home;
187 2         13 $path =~ s/~/$home/g;
188             }
189              
190 2         23 bless { path => $path } => $class;
191             }
192              
193             =head2 $i3->connect
194              
195             Establishes the connection to i3. Returns an C which will
196             be triggered with a boolean (true if the connection was established) as soon as
197             the connection has been established.
198              
199             if ($i3->connect->recv) {
200             say "Connected to i3";
201             }
202              
203             =cut
204             sub connect {
205 2     2 1 6576 my ($self) = @_;
206 2         37 my $cv = AnyEvent->condvar;
207              
208             tcp_connect "unix/", $self->{path}, sub {
209 2     2   2302 my ($fh) = @_;
210              
211 2 50       23 return $cv->send(0) unless $fh;
212              
213             $self->{ipchdl} = AnyEvent::Handle->new(
214             fh => $fh,
215 0         0 on_read => sub { my ($hdl) = @_; $self->_data_available($hdl) },
  0         0  
216             on_error => sub {
217 0         0 my ($hdl, $fatal, $msg) = @_;
218 0         0 delete $self->{ipchdl};
219 0         0 $hdl->destroy;
220              
221 0         0 my $cb = $self->{callbacks};
222              
223             # Trigger all one-time callbacks with undef
224 0         0 for my $type (keys %{$cb}) {
  0         0  
225 0 0       0 next if ($type & $event_mask) == $event_mask;
226 0         0 $cb->{$type}->();
227 0         0 delete $cb->{$type};
228             }
229              
230             # Trigger _error callback, if set
231 0         0 my $type = $events{_error};
232 0 0       0 return unless defined($cb->{$type});
233 0         0 $cb->{$type}->($msg);
234             }
235 0         0 );
236              
237 0         0 $cv->send(1)
238 2         39 };
239              
240 2         292 $cv
241             }
242              
243             sub _data_available {
244 0     0     my ($self, $hdl) = @_;
245              
246             $hdl->unshift_read(
247             chunk => length($magic) + 4 + 4,
248             sub {
249 0     0     my $header = $_[1];
250             # Unpack message length and read the payload
251 0           my ($len, $type) = unpack("LL", substr($header, length($magic)));
252             $hdl->unshift_read(
253             chunk => $len,
254 0           sub { $self->_handle_i3_message($type, $_[1]) }
255 0           );
256             }
257 0           );
258             }
259              
260             sub _handle_i3_message {
261 0     0     my ($self, $type, $payload) = @_;
262              
263 0 0         return unless defined($self->{callbacks}->{$type});
264              
265 0           my $cb = $self->{callbacks}->{$type};
266 0           $cb->(decode_json $payload);
267              
268 0 0         return if ($type & $event_mask) == $event_mask;
269              
270             # If this was a one-time callback, we delete it
271             # (when connection is lost, all one-time callbacks get triggered)
272 0           delete $self->{callbacks}->{$type};
273             }
274              
275             =head2 $i3->subscribe(\%callbacks)
276              
277             Subscribes to the given event types. This function awaits a hashref with the
278             key being the name of the event and the value being a callback.
279              
280             my %callbacks = (
281             workspace => sub { say "Workspaces changed" }
282             );
283              
284             if ($i3->subscribe(\%callbacks)->recv->{success}) {
285             say "Successfully subscribed";
286             }
287              
288             The special callback with name C<_error> is called when the connection to i3
289             is killed (because of a crash, exit or restart of i3 most likely). You can
290             use it to print an appropriate message and exit cleanly or to try to reconnect.
291              
292             my %callbacks = (
293             _error => sub {
294             my ($msg) = @_;
295             say "I am sorry. I am so sorry: $msg";
296             exit 1;
297             }
298             );
299              
300             $i3->subscribe(\%callbacks)->recv;
301              
302             =cut
303             sub subscribe {
304 0     0 1   my ($self, $callbacks) = @_;
305              
306             # Register callbacks for each message type
307 0           for my $key (keys %{$callbacks}) {
  0            
308 0           my $type = $events{$key};
309 0           $self->{callbacks}->{$type} = $callbacks->{$key};
310             }
311              
312 0           $self->message(TYPE_SUBSCRIBE, [ keys %{$callbacks} ])
  0            
313             }
314              
315             =head2 $i3->message($type, $content)
316              
317             Sends a message of the specified C to i3, possibly containing the data
318             structure C (or C, encoded as utf8, if C is a
319             scalar), if specified.
320              
321             my $reply = $i3->message(TYPE_COMMAND, "reload")->recv;
322             if ($reply->{success}) {
323             say "Configuration successfully reloaded";
324             }
325              
326             =cut
327             sub message {
328 0     0 1   my ($self, $type, $content) = @_;
329              
330 0 0         die "No message type specified" unless defined($type);
331              
332 0 0         die "No connection to i3" unless defined($self->{ipchdl});
333              
334 0           my $payload = "";
335 0 0         if ($content) {
336 0 0         if (not ref($content)) {
337             # Convert from Perl’s internal encoding to UTF8 octets
338 0           $payload = encode_utf8($content);
339             } else {
340 0           $payload = encode_json $content;
341             }
342             }
343 0           my $message = $magic . pack("LL", length($payload), $type) . $payload;
344 0           $self->{ipchdl}->push_write($message);
345              
346 0           my $cv = AnyEvent->condvar;
347              
348             # We don’t preserve the old callback as it makes no sense to
349             # have a callback on message reply types (only on events)
350             $self->{callbacks}->{$type} =
351             sub {
352 0     0     my ($reply) = @_;
353 0           $cv->send($reply);
354 0           undef $self->{callbacks}->{$type};
355 0           };
356              
357 0           $cv
358             }
359              
360             =head1 SUGAR METHODS
361              
362             These methods intend to make your scripts as beautiful as possible. All of
363             them automatically establish a connection to i3 blockingly (if it does not
364             already exist).
365              
366             =cut
367              
368             sub _ensure_connection {
369 0     0     my ($self) = @_;
370              
371 0 0         return if defined($self->{ipchdl});
372              
373 0 0         $self->connect->recv or die "Unable to connect to i3 (socket path " . $self->{path} . ")";
374             }
375              
376             =head2 get_workspaces
377              
378             Gets the current workspaces from i3.
379              
380             my $ws = i3->get_workspaces->recv;
381             say Dumper($ws);
382              
383             =cut
384             sub get_workspaces {
385 0     0 1   my ($self) = @_;
386              
387 0           $self->_ensure_connection;
388              
389 0           $self->message(TYPE_GET_WORKSPACES)
390             }
391              
392             =head2 get_outputs
393              
394             Gets the current outputs from i3.
395              
396             my $outs = i3->get_outputs->recv;
397             say Dumper($outs);
398              
399             =cut
400             sub get_outputs {
401 0     0 1   my ($self) = @_;
402              
403 0           $self->_ensure_connection;
404              
405 0           $self->message(TYPE_GET_OUTPUTS)
406             }
407              
408             =head2 get_tree
409              
410             Gets the layout tree from i3 (>= v4.0).
411              
412             my $tree = i3->get_tree->recv;
413             say Dumper($tree);
414              
415             =cut
416             sub get_tree {
417 0     0 1   my ($self) = @_;
418              
419 0           $self->_ensure_connection;
420              
421 0           $self->message(TYPE_GET_TREE)
422             }
423              
424             =head2 get_marks
425              
426             Gets all the window identifier marks from i3 (>= v4.1).
427              
428             my $marks = i3->get_marks->recv;
429             say Dumper($marks);
430              
431             =cut
432             sub get_marks {
433 0     0 1   my ($self) = @_;
434              
435 0           $self->_ensure_connection;
436              
437 0           $self->message(TYPE_GET_MARKS)
438             }
439              
440             =head2 get_bar_config
441              
442             Gets the bar configuration for the specific bar id from i3 (>= v4.1).
443              
444             my $config = i3->get_bar_config($id)->recv;
445             say Dumper($config);
446              
447             =cut
448             sub get_bar_config {
449 0     0 1   my ($self, $id) = @_;
450              
451 0           $self->_ensure_connection;
452              
453 0           $self->message(TYPE_GET_BAR_CONFIG, $id)
454             }
455              
456             =head2 get_version
457              
458             Gets the i3 version via IPC, with a fall-back that parses the output of i3
459             --version (for i3 < v4.3).
460              
461             my $version = i3->get_version()->recv;
462             say "major: " . $version->{major} . ", minor = " . $version->{minor};
463              
464             =cut
465             sub get_version {
466 0     0 1   my ($self) = @_;
467              
468 0           $self->_ensure_connection;
469              
470 0           my $cv = AnyEvent->condvar;
471              
472 0           my $version_cv = $self->message(TYPE_GET_VERSION);
473 0           my $timeout;
474             $timeout = AnyEvent->timer(
475             after => 1,
476             cb => sub {
477 0     0     warn "Falling back to i3 --version since the running i3 doesn’t support GET_VERSION yet.";
478 0           my $version = _call_i3('--version');
479 0           $version =~ s/^i3 version //;
480 0           my $patch = 0;
481 0           my ($major, $minor) = ($version =~ /^([0-9]+)\.([0-9]+)/);
482 0 0         if ($version =~ /^[0-9]+\.[0-9]+\.([0-9]+)/) {
483 0           $patch = $1;
484             }
485             # Strip everything from the © sign on.
486 0           $version =~ s/ ©.*$//g;
487 0           $cv->send({
488             major => int($major),
489             minor => int($minor),
490             patch => int($patch),
491             human_readable => $version,
492             });
493 0           undef $timeout;
494             },
495 0           );
496             $version_cv->cb(sub {
497 0     0     undef $timeout;
498 0           $cv->send($version_cv->recv);
499 0           });
500              
501 0           return $cv;
502             }
503              
504             =head2 command($content)
505              
506             Makes i3 execute the given command
507              
508             my $reply = i3->command("reload")->recv;
509             die "command failed" unless $reply->{success};
510              
511             =cut
512             sub command {
513 0     0 1   my ($self, $content) = @_;
514              
515 0           $self->_ensure_connection;
516              
517 0           $self->message(TYPE_COMMAND, $content)
518             }
519              
520             =head1 AUTHOR
521              
522             Michael Stapelberg, C<< >>
523              
524             =head1 BUGS
525              
526             Please report any bugs or feature requests to C
527             rt.cpan.org>, or through the web interface at
528             L. I will be
529             notified, and then you'll automatically be notified of progress on your bug as
530             I make changes.
531              
532             =head1 SUPPORT
533              
534             You can find documentation for this module with the perldoc command.
535              
536             perldoc AnyEvent::I3
537              
538             You can also look for information at:
539              
540             =over 2
541              
542             =item * RT: CPAN's request tracker
543              
544             L
545              
546             =item * The i3 window manager website
547              
548             L
549              
550             =back
551              
552              
553             =head1 ACKNOWLEDGEMENTS
554              
555              
556             =head1 LICENSE AND COPYRIGHT
557              
558             Copyright 2010-2012 Michael Stapelberg.
559              
560             This program is free software; you can redistribute it and/or modify it
561             under the terms of either: the GNU General Public License as published
562             by the Free Software Foundation; or the Artistic License.
563              
564             See http://dev.perl.org/licenses/ for more information.
565              
566              
567             =cut
568              
569             1; # End of AnyEvent::I3