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