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.12';
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";
50 =head2 $i3 = i3([ $path ]);
52 Creates a new C<AnyEvent::I3> object and returns it.
54 C<path> is an optional path of the UNIX socket to connect to. It is strongly
55 advised to NOT specify this unless you're absolutely sure you need it.
56 C<AnyEvent::I3> will automatically figure it out by querying the running i3
57 instance on the current DISPLAY which is almost always what you want.
59 =head1 SUBROUTINES/METHODS
63 use Exporter qw(import);
68 use constant TYPE_COMMAND => 0;
69 use constant TYPE_GET_WORKSPACES => 1;
70 use constant TYPE_SUBSCRIBE => 2;
71 use constant TYPE_GET_OUTPUTS => 3;
72 use constant TYPE_GET_TREE => 4;
73 use constant TYPE_GET_MARKS => 5;
74 use constant TYPE_GET_BAR_CONFIG => 6;
76 our %EXPORT_TAGS = ( 'all' => [
77 qw(i3 TYPE_COMMAND TYPE_GET_WORKSPACES TYPE_SUBSCRIBE TYPE_GET_OUTPUTS
78 TYPE_GET_TREE TYPE_GET_MARKS TYPE_GET_BAR_CONFIG)
81 our @EXPORT_OK = ( @{ $EXPORT_TAGS{all} } );
85 # TODO: auto-generate this from the header file? (i3/ipc.h)
86 my $event_mask = (1 << 31);
88 workspace => ($event_mask | 0),
89 output => ($event_mask | 1),
97 =head2 $i3 = AnyEvent::I3->new([ $path ])
99 Creates a new C<AnyEvent::I3> object and returns it.
101 C<path> is an optional path of the UNIX socket to connect to. It is strongly
102 advised to NOT specify this unless you're absolutely sure you need it.
103 C<AnyEvent::I3> will automatically figure it out by querying the running i3
104 instance on the current DISPLAY which is almost always what you want.
108 my ($class, $path) = @_;
111 my $path_tainted = tainted($ENV{PATH});
112 # This effectively circumvents taint mode checking for $ENV{PATH}. We
113 # do this because users might specify PATH explicitly to call i3 in a
114 # custom location (think ~/.bin/).
115 (local $ENV{PATH}) = ($ENV{PATH} =~ /(.*)/);
117 # In taint mode, we also need to remove all relative directories from
118 # PATH (like . or ../bin). We only do this in taint mode and warn the
119 # user, since this might break a real-world use case for some people.
121 my @dirs = split /:/, $ENV{PATH};
122 my @filtered = grep !/^\./, @dirs;
123 if (scalar @dirs != scalar @filtered) {
124 $ENV{PATH} = join ':', @filtered;
125 warn qq|Removed relative directories from PATH because you | .
126 qq|are running Perl with taint mode enabled. Remove -T | .
127 qq|to be able to use relative directories in PATH. | .
128 qq|New PATH is "$ENV{PATH}"|;
131 # Otherwise the qx() operator wont work:
132 delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};
133 chomp($path = qx(i3 --get-socketpath));
134 # Circumventing taint mode again: the socket can be anywhere on the
135 # system and that’s okay.
136 if ($path =~ /^([^\0]+)$/) {
139 warn "Asking i3 for the socket path failed. Is DISPLAY set and is i3 in your PATH?";
143 # This is the old default path (v3.*). This fallback line can be removed in
144 # a year from now. -- Michael, 2012-07-09
145 $path ||= '~/.i3/ipc.sock';
147 # Check if we need to resolve ~
149 # We use getpwuid() instead of $ENV{HOME} because the latter is tainted
150 # and thus produces warnings when running tests with perl -T
151 my $home = (getpwuid($<))[7];
152 die "Could not get home directory" unless $home and -d $home;
153 $path =~ s/~/$home/g;
156 bless { path => $path } => $class;
161 Establishes the connection to i3. Returns an C<AnyEvent::CondVar> which will
162 be triggered with a boolean (true if the connection was established) as soon as
163 the connection has been established.
165 if ($i3->connect->recv) {
166 say "Connected to i3";
172 my $cv = AnyEvent->condvar;
174 tcp_connect "unix/", $self->{path}, sub {
177 return $cv->send(0) unless $fh;
179 $self->{ipchdl} = AnyEvent::Handle->new(
181 on_read => sub { my ($hdl) = @_; $self->_data_available($hdl) },
183 my ($hdl, $fatal, $msg) = @_;
184 delete $self->{ipchdl};
187 my $cb = $self->{callbacks};
189 # Trigger all one-time callbacks with undef
190 for my $type (keys %{$cb}) {
191 next if ($type & $event_mask) == $event_mask;
196 # Trigger _error callback, if set
197 my $type = $events{_error};
198 return unless defined($cb->{$type});
199 $cb->{$type}->($msg);
209 sub _data_available {
210 my ($self, $hdl) = @_;
213 chunk => length($magic) + 4 + 4,
216 # Unpack message length and read the payload
217 my ($len, $type) = unpack("LL", substr($header, length($magic)));
220 sub { $self->_handle_i3_message($type, $_[1]) }
226 sub _handle_i3_message {
227 my ($self, $type, $payload) = @_;
229 return unless defined($self->{callbacks}->{$type});
231 my $cb = $self->{callbacks}->{$type};
232 $cb->(decode_json $payload);
234 return if ($type & $event_mask) == $event_mask;
236 # If this was a one-time callback, we delete it
237 # (when connection is lost, all one-time callbacks get triggered)
238 delete $self->{callbacks}->{$type};
241 =head2 $i3->subscribe(\%callbacks)
243 Subscribes to the given event types. This function awaits a hashref with the
244 key being the name of the event and the value being a callback.
247 workspace => sub { say "Workspaces changed" }
250 if ($i3->subscribe(\%callbacks)->recv->{success})
251 say "Successfully subscribed";
254 The special callback with name C<_error> is called when the connection to i3
255 is killed (because of a crash, exit or restart of i3 most likely). You can
256 use it to print an appropriate message and exit cleanly or to try to reconnect.
261 say "I am sorry. I am so sorry: $msg";
266 $i3->subscribe(\%callbacks)->recv;
270 my ($self, $callbacks) = @_;
272 # Register callbacks for each message type
273 for my $key (keys %{$callbacks}) {
274 my $type = $events{$key};
275 $self->{callbacks}->{$type} = $callbacks->{$key};
278 $self->message(TYPE_SUBSCRIBE, [ keys %{$callbacks} ])
281 =head2 $i3->message($type, $content)
283 Sends a message of the specified C<type> to i3, possibly containing the data
284 structure C<content> (or C<content>, encoded as utf8, if C<content> is a
285 scalar), if specified.
287 my $reply = $i3->message(TYPE_COMMAND, "reload")->recv;
288 if ($reply->{success}) {
289 say "Configuration successfully reloaded";
294 my ($self, $type, $content) = @_;
296 die "No message type specified" unless defined($type);
298 die "No connection to i3" unless defined($self->{ipchdl});
302 if (not ref($content)) {
303 # Convert from Perl’s internal encoding to UTF8 octets
304 $payload = encode_utf8($content);
306 $payload = encode_json $content;
309 my $message = $magic . pack("LL", length($payload), $type) . $payload;
310 $self->{ipchdl}->push_write($message);
312 my $cv = AnyEvent->condvar;
314 # We don’t preserve the old callback as it makes no sense to
315 # have a callback on message reply types (only on events)
316 $self->{callbacks}->{$type} =
320 undef $self->{callbacks}->{$type};
328 These methods intend to make your scripts as beautiful as possible. All of
329 them automatically establish a connection to i3 blockingly (if it does not
334 sub _ensure_connection {
337 return if defined($self->{ipchdl});
339 $self->connect->recv or die "Unable to connect to i3 (socket path " . $self->{path} . ")";
342 =head2 get_workspaces
344 Gets the current workspaces from i3.
346 my $ws = i3->get_workspaces->recv;
353 $self->_ensure_connection;
355 $self->message(TYPE_GET_WORKSPACES)
360 Gets the current outputs from i3.
362 my $outs = i3->get_outputs->recv;
369 $self->_ensure_connection;
371 $self->message(TYPE_GET_OUTPUTS)
376 Gets the layout tree from i3 (>= v4.0).
378 my $tree = i3->get_tree->recv;
385 $self->_ensure_connection;
387 $self->message(TYPE_GET_TREE)
392 Gets all the window identifier marks from i3 (>= v4.1).
394 my $marks = i3->get_marks->recv;
401 $self->_ensure_connection;
403 $self->message(TYPE_GET_MARKS)
406 =head2 get_bar_config
408 Gets the bar configuration for the specific bar id from i3 (>= v4.1).
410 my $config = i3->get_bar_config($id)->recv;
415 my ($self, $id) = @_;
417 $self->_ensure_connection;
419 $self->message(TYPE_GET_BAR_CONFIG, $id)
422 =head2 command($content)
424 Makes i3 execute the given command
426 my $reply = i3->command("reload")->recv;
427 die "command failed" unless $reply->{success};
431 my ($self, $content) = @_;
433 $self->_ensure_connection;
435 $self->message(TYPE_COMMAND, $content)
440 Michael Stapelberg, C<< <michael at i3wm.org> >>
444 Please report any bugs or feature requests to C<bug-anyevent-i3 at
445 rt.cpan.org>, or through the web interface at
446 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=AnyEvent-I3>. I will be
447 notified, and then you'll automatically be notified of progress on your bug as
452 You can find documentation for this module with the perldoc command.
456 You can also look for information at:
460 =item * RT: CPAN's request tracker
462 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=AnyEvent-I3>
464 =item * The i3 window manager website
471 =head1 ACKNOWLEDGEMENTS
474 =head1 LICENSE AND COPYRIGHT
476 Copyright 2010-2012 Michael Stapelberg.
478 This program is free software; you can redistribute it and/or modify it
479 under the terms of either: the GNU General Public License as published
480 by the Free Software Foundation; or the Artistic License.
482 See http://dev.perl.org/licenses/ for more information.
487 1; # End of AnyEvent::I3