2 # vim:ts=4:sw=4:expandtab
11 use Scalar::Util qw(tainted);
15 AnyEvent::I3 - communicate with the i3 window manager
19 our $VERSION = '0.16';
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.
31 use AnyEvent::I3 qw(:all);
35 $i3->connect->recv or die "Error connecting";
36 say "Connected to i3";
38 my $workspaces = $i3->message(TYPE_GET_WORKSPACES)->recv;
39 say "Currently, you use " . @{$workspaces} . " workspaces";
41 ...or, using the sugar methods:
45 my $workspaces = i3->get_workspaces->recv;
46 say "Currently, you use " . @{$workspaces} . " workspaces";
48 A somewhat more involved example which dumps the i3 layout tree whenever there
57 $i3->connect->recv or die "Error connecting to i3";
61 $i3->get_tree->cb(sub {
63 say "tree: " . Dumper($tree);
66 })->recv->{success} or die "Error subscribing to events";
72 =head2 $i3 = i3([ $path ]);
74 Creates a new C<AnyEvent::I3> object and returns it.
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.
81 =head1 SUBROUTINES/METHODS
85 use Exporter qw(import);
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;
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)
104 our @EXPORT_OK = ( @{ $EXPORT_TAGS{all} } );
106 my $magic = "i3-ipc";
108 # TODO: auto-generate this from the header file? (i3/ipc.h)
109 my $event_mask = (1 << 31);
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 _error => 0xFFFFFFFF,
121 AnyEvent::I3->new(@_)
124 # Calls i3, even when running in taint mode.
128 my $path_tainted = tainted($ENV{PATH});
129 # This effectively circumvents taint mode checking for $ENV{PATH}. We
130 # do this because users might specify PATH explicitly to call i3 in a
131 # custom location (think ~/.bin/).
132 (local $ENV{PATH}) = ($ENV{PATH} =~ /(.*)/);
134 # In taint mode, we also need to remove all relative directories from
135 # PATH (like . or ../bin). We only do this in taint mode and warn the
136 # user, since this might break a real-world use case for some people.
138 my @dirs = split /:/, $ENV{PATH};
139 my @filtered = grep !/^\./, @dirs;
140 if (scalar @dirs != scalar @filtered) {
141 $ENV{PATH} = join ':', @filtered;
142 warn qq|Removed relative directories from PATH because you | .
143 qq|are running Perl with taint mode enabled. Remove -T | .
144 qq|to be able to use relative directories in PATH. | .
145 qq|New PATH is "$ENV{PATH}"|;
148 # Otherwise the qx() operator wont work:
149 delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};
150 chomp(my $result = qx(i3 $args));
151 # Circumventing taint mode again: the socket can be anywhere on the
152 # system and that’s okay.
153 if ($result =~ /^([^\0]+)$/) {
157 warn "Calling i3 $args failed. Is DISPLAY set and is i3 in your PATH?";
161 =head2 $i3 = AnyEvent::I3->new([ $path ])
163 Creates a new C<AnyEvent::I3> object and returns it.
165 C<path> is an optional path of the UNIX socket to connect to. It is strongly
166 advised to NOT specify this unless you're absolutely sure you need it.
167 C<AnyEvent::I3> will automatically figure it out by querying the running i3
168 instance on the current DISPLAY which is almost always what you want.
172 my ($class, $path) = @_;
174 $path = _call_i3('--get-socketpath') unless $path;
176 # This is the old default path (v3.*). This fallback line can be removed in
177 # a year from now. -- Michael, 2012-07-09
178 $path ||= '~/.i3/ipc.sock';
180 # Check if we need to resolve ~
182 # We use getpwuid() instead of $ENV{HOME} because the latter is tainted
183 # and thus produces warnings when running tests with perl -T
184 my $home = (getpwuid($<))[7];
185 die "Could not get home directory" unless $home and -d $home;
186 $path =~ s/~/$home/g;
189 bless { path => $path } => $class;
194 Establishes the connection to i3. Returns an C<AnyEvent::CondVar> which will
195 be triggered with a boolean (true if the connection was established) as soon as
196 the connection has been established.
198 if ($i3->connect->recv) {
199 say "Connected to i3";
205 my $cv = AnyEvent->condvar;
207 tcp_connect "unix/", $self->{path}, sub {
210 return $cv->send(0) unless $fh;
212 $self->{ipchdl} = AnyEvent::Handle->new(
214 on_read => sub { my ($hdl) = @_; $self->_data_available($hdl) },
216 my ($hdl, $fatal, $msg) = @_;
217 delete $self->{ipchdl};
220 my $cb = $self->{callbacks};
222 # Trigger all one-time callbacks with undef
223 for my $type (keys %{$cb}) {
224 next if ($type & $event_mask) == $event_mask;
229 # Trigger _error callback, if set
230 my $type = $events{_error};
231 return unless defined($cb->{$type});
232 $cb->{$type}->($msg);
242 sub _data_available {
243 my ($self, $hdl) = @_;
246 chunk => length($magic) + 4 + 4,
249 # Unpack message length and read the payload
250 my ($len, $type) = unpack("LL", substr($header, length($magic)));
253 sub { $self->_handle_i3_message($type, $_[1]) }
259 sub _handle_i3_message {
260 my ($self, $type, $payload) = @_;
262 return unless defined($self->{callbacks}->{$type});
264 my $cb = $self->{callbacks}->{$type};
265 $cb->(decode_json $payload);
267 return if ($type & $event_mask) == $event_mask;
269 # If this was a one-time callback, we delete it
270 # (when connection is lost, all one-time callbacks get triggered)
271 delete $self->{callbacks}->{$type};
274 =head2 $i3->subscribe(\%callbacks)
276 Subscribes to the given event types. This function awaits a hashref with the
277 key being the name of the event and the value being a callback.
280 workspace => sub { say "Workspaces changed" }
283 if ($i3->subscribe(\%callbacks)->recv->{success}) {
284 say "Successfully subscribed";
287 The special callback with name C<_error> is called when the connection to i3
288 is killed (because of a crash, exit or restart of i3 most likely). You can
289 use it to print an appropriate message and exit cleanly or to try to reconnect.
294 say "I am sorry. I am so sorry: $msg";
299 $i3->subscribe(\%callbacks)->recv;
303 my ($self, $callbacks) = @_;
305 # Register callbacks for each message type
306 for my $key (keys %{$callbacks}) {
307 my $type = $events{$key};
308 $self->{callbacks}->{$type} = $callbacks->{$key};
311 $self->message(TYPE_SUBSCRIBE, [ keys %{$callbacks} ])
314 =head2 $i3->message($type, $content)
316 Sends a message of the specified C<type> to i3, possibly containing the data
317 structure C<content> (or C<content>, encoded as utf8, if C<content> is a
318 scalar), if specified.
320 my $reply = $i3->message(TYPE_COMMAND, "reload")->recv;
321 if ($reply->{success}) {
322 say "Configuration successfully reloaded";
327 my ($self, $type, $content) = @_;
329 die "No message type specified" unless defined($type);
331 die "No connection to i3" unless defined($self->{ipchdl});
335 if (not ref($content)) {
336 # Convert from Perl’s internal encoding to UTF8 octets
337 $payload = encode_utf8($content);
339 $payload = encode_json $content;
342 my $message = $magic . pack("LL", length($payload), $type) . $payload;
343 $self->{ipchdl}->push_write($message);
345 my $cv = AnyEvent->condvar;
347 # We don’t preserve the old callback as it makes no sense to
348 # have a callback on message reply types (only on events)
349 $self->{callbacks}->{$type} =
353 undef $self->{callbacks}->{$type};
361 These methods intend to make your scripts as beautiful as possible. All of
362 them automatically establish a connection to i3 blockingly (if it does not
367 sub _ensure_connection {
370 return if defined($self->{ipchdl});
372 $self->connect->recv or die "Unable to connect to i3 (socket path " . $self->{path} . ")";
375 =head2 get_workspaces
377 Gets the current workspaces from i3.
379 my $ws = i3->get_workspaces->recv;
386 $self->_ensure_connection;
388 $self->message(TYPE_GET_WORKSPACES)
393 Gets the current outputs from i3.
395 my $outs = i3->get_outputs->recv;
402 $self->_ensure_connection;
404 $self->message(TYPE_GET_OUTPUTS)
409 Gets the layout tree from i3 (>= v4.0).
411 my $tree = i3->get_tree->recv;
418 $self->_ensure_connection;
420 $self->message(TYPE_GET_TREE)
425 Gets all the window identifier marks from i3 (>= v4.1).
427 my $marks = i3->get_marks->recv;
434 $self->_ensure_connection;
436 $self->message(TYPE_GET_MARKS)
439 =head2 get_bar_config
441 Gets the bar configuration for the specific bar id from i3 (>= v4.1).
443 my $config = i3->get_bar_config($id)->recv;
448 my ($self, $id) = @_;
450 $self->_ensure_connection;
452 $self->message(TYPE_GET_BAR_CONFIG, $id)
457 Gets the i3 version via IPC, with a fall-back that parses the output of i3
458 --version (for i3 < v4.3).
460 my $version = i3->get_version()->recv;
461 say "major: " . $version->{major} . ", minor = " . $version->{minor};
467 $self->_ensure_connection;
469 my $cv = AnyEvent->condvar;
471 my $version_cv = $self->message(TYPE_GET_VERSION);
473 $timeout = AnyEvent->timer(
476 warn "Falling back to i3 --version since the running i3 doesn’t support GET_VERSION yet.";
477 my $version = _call_i3('--version');
478 $version =~ s/^i3 version //;
480 my ($major, $minor) = ($version =~ /^([0-9]+)\.([0-9]+)/);
481 if ($version =~ /^[0-9]+\.[0-9]+\.([0-9]+)/) {
484 # Strip everything from the © sign on.
485 $version =~ s/ ©.*$//g;
487 major => int($major),
488 minor => int($minor),
489 patch => int($patch),
490 human_readable => $version,
495 $version_cv->cb(sub {
497 $cv->send($version_cv->recv);
503 =head2 command($content)
505 Makes i3 execute the given command
507 my $reply = i3->command("reload")->recv;
508 die "command failed" unless $reply->{success};
512 my ($self, $content) = @_;
514 $self->_ensure_connection;
516 $self->message(TYPE_COMMAND, $content)
521 Michael Stapelberg, C<< <michael at i3wm.org> >>
525 Please report any bugs or feature requests to C<bug-anyevent-i3 at
526 rt.cpan.org>, or through the web interface at
527 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=AnyEvent-I3>. I will be
528 notified, and then you'll automatically be notified of progress on your bug as
533 You can find documentation for this module with the perldoc command.
537 You can also look for information at:
541 =item * RT: CPAN's request tracker
543 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=AnyEvent-I3>
545 =item * The i3 window manager website
552 =head1 ACKNOWLEDGEMENTS
555 =head1 LICENSE AND COPYRIGHT
557 Copyright 2010-2012 Michael Stapelberg.
559 This program is free software; you can redistribute it and/or modify it
560 under the terms of either: the GNU General Public License as published
561 by the Free Software Foundation; or the Artistic License.
563 See http://dev.perl.org/licenses/ for more information.
568 1; # End of AnyEvent::I3