2 # vim:ts=4:sw=4:expandtab
14 AnyEvent::I3 - communicate with the i3 window manager
18 our $VERSION = '0.10';
26 This module connects to the i3 window manager using the UNIX socket based
27 IPC interface it provides (if enabled in the configuration file). You can
28 then subscribe to events or send messages and receive their replies.
30 use AnyEvent::I3 qw(:all);
34 $i3->connect->recv or die "Error connecting";
35 say "Connected to i3";
37 my $workspaces = $i3->message(TYPE_GET_WORKSPACES)->recv;
38 say "Currently, you use " . @{$workspaces} . " workspaces";
40 ...or, using the sugar methods:
44 my $workspaces = i3->get_workspaces->recv;
45 say "Currently, you use " . @{$workspaces} . " workspaces";
49 =head2 $i3 = i3([ $path ]);
51 Creates a new C<AnyEvent::I3> object and returns it.
53 C<path> is an optional path of the UNIX socket to connect to. It is strongly
54 advised to NOT specify this unless you're absolutely sure you need it.
55 C<AnyEvent::I3> will automatically figure it out by querying the running i3
56 instance on the current DISPLAY which is almost always what you want.
58 =head1 SUBROUTINES/METHODS
62 use Exporter qw(import);
67 use constant TYPE_COMMAND => 0;
68 use constant TYPE_GET_WORKSPACES => 1;
69 use constant TYPE_SUBSCRIBE => 2;
70 use constant TYPE_GET_OUTPUTS => 3;
71 use constant TYPE_GET_TREE => 4;
72 use constant TYPE_GET_MARKS => 5;
73 use constant TYPE_GET_BAR_CONFIG => 6;
75 our %EXPORT_TAGS = ( 'all' => [
76 qw(i3 TYPE_COMMAND TYPE_GET_WORKSPACES TYPE_SUBSCRIBE TYPE_GET_OUTPUTS
77 TYPE_GET_TREE TYPE_GET_MARKS TYPE_GET_BAR_CONFIG)
80 our @EXPORT_OK = ( @{ $EXPORT_TAGS{all} } );
84 # TODO: auto-generate this from the header file? (i3/ipc.h)
85 my $event_mask = (1 << 31);
87 workspace => ($event_mask | 0),
88 output => ($event_mask | 1),
96 =head2 $i3 = AnyEvent::I3->new([ $path ])
98 Creates a new C<AnyEvent::I3> object and returns it.
100 C<path> is an optional path of the UNIX socket to connect to. It is strongly
101 advised to NOT specify this unless you're absolutely sure you need it.
102 C<AnyEvent::I3> will automatically figure it out by querying the running i3
103 instance on the current DISPLAY which is almost always what you want.
107 my ($class, $path) = @_;
110 # This effectively circumvents taint mode checking for $ENV{PATH}. We
111 # do this because users might specify PATH explicitly to call i3 in a
112 # custom location (think ~/.bin/).
113 my $paths = $ENV{PATH};
114 if ($paths =~ /^(.*)$/) {
117 chomp($path = qx(i3 --get-socketpath));
118 # Circumventing taint mode again: the socket can be anywhere on the
119 # system and that’s okay.
120 if ($path =~ /^([^\0]+)$/) {
123 warn "Asking i3 for the socket path failed. Is DISPLAY set and is i3 in your PATH?";
127 # This is the old default path (v3.*). This fallback line can be removed in
128 # a year from now. -- Michael, 2012-07-09
129 $path ||= '~/.i3/ipc.sock';
131 # Check if we need to resolve ~
133 # We use getpwuid() instead of $ENV{HOME} because the latter is tainted
134 # and thus produces warnings when running tests with perl -T
135 my $home = (getpwuid($<))[7];
136 die "Could not get home directory" unless $home and -d $home;
137 $path =~ s/~/$home/g;
140 bless { path => $path } => $class;
145 Establishes the connection to i3. Returns an C<AnyEvent::CondVar> which will
146 be triggered with a boolean (true if the connection was established) as soon as
147 the connection has been established.
149 if ($i3->connect->recv) {
150 say "Connected to i3";
156 my $cv = AnyEvent->condvar;
158 tcp_connect "unix/", $self->{path}, sub {
161 return $cv->send(0) unless $fh;
163 $self->{ipchdl} = AnyEvent::Handle->new(
165 on_read => sub { my ($hdl) = @_; $self->_data_available($hdl) },
167 my ($hdl, $fatal, $msg) = @_;
168 delete $self->{ipchdl};
171 my $cb = $self->{callbacks};
173 # Trigger all one-time callbacks with undef
174 for my $type (keys %{$cb}) {
175 next if ($type & $event_mask) == $event_mask;
180 # Trigger _error callback, if set
181 my $type = $events{_error};
182 return unless defined($cb->{$type});
183 $cb->{$type}->($msg);
193 sub _data_available {
194 my ($self, $hdl) = @_;
197 chunk => length($magic) + 4 + 4,
200 # Unpack message length and read the payload
201 my ($len, $type) = unpack("LL", substr($header, length($magic)));
204 sub { $self->_handle_i3_message($type, $_[1]) }
210 sub _handle_i3_message {
211 my ($self, $type, $payload) = @_;
213 return unless defined($self->{callbacks}->{$type});
215 my $cb = $self->{callbacks}->{$type};
216 $cb->(decode_json $payload);
218 return if ($type & $event_mask) == $event_mask;
220 # If this was a one-time callback, we delete it
221 # (when connection is lost, all one-time callbacks get triggered)
222 delete $self->{callbacks}->{$type};
225 =head2 $i3->subscribe(\%callbacks)
227 Subscribes to the given event types. This function awaits a hashref with the
228 key being the name of the event and the value being a callback.
231 workspace => sub { say "Workspaces changed" }
234 if ($i3->subscribe(\%callbacks)->recv->{success})
235 say "Successfully subscribed";
238 The special callback with name C<_error> is called when the connection to i3
239 is killed (because of a crash, exit or restart of i3 most likely). You can
240 use it to print an appropriate message and exit cleanly or to try to reconnect.
245 say "I am sorry. I am so sorry: $msg";
250 $i3->subscribe(\%callbacks)->recv;
254 my ($self, $callbacks) = @_;
256 # Register callbacks for each message type
257 for my $key (keys %{$callbacks}) {
258 my $type = $events{$key};
259 $self->{callbacks}->{$type} = $callbacks->{$key};
262 $self->message(TYPE_SUBSCRIBE, [ keys %{$callbacks} ])
265 =head2 $i3->message($type, $content)
267 Sends a message of the specified C<type> to i3, possibly containing the data
268 structure C<content> (or C<content>, encoded as utf8, if C<content> is a
269 scalar), if specified.
271 my $reply = $i3->message(TYPE_COMMAND, "reload")->recv;
272 if ($reply->{success}) {
273 say "Configuration successfully reloaded";
278 my ($self, $type, $content) = @_;
280 die "No message type specified" unless defined($type);
282 die "No connection to i3" unless defined($self->{ipchdl});
286 if (not ref($content)) {
287 # Convert from Perl’s internal encoding to UTF8 octets
288 $payload = encode_utf8($content);
290 $payload = encode_json $content;
293 my $message = $magic . pack("LL", length($payload), $type) . $payload;
294 $self->{ipchdl}->push_write($message);
296 my $cv = AnyEvent->condvar;
298 # We don’t preserve the old callback as it makes no sense to
299 # have a callback on message reply types (only on events)
300 $self->{callbacks}->{$type} =
304 undef $self->{callbacks}->{$type};
312 These methods intend to make your scripts as beautiful as possible. All of
313 them automatically establish a connection to i3 blockingly (if it does not
318 sub _ensure_connection {
321 return if defined($self->{ipchdl});
323 $self->connect->recv or die "Unable to connect to i3 (socket path " . $self->{path} . ")";
326 =head2 get_workspaces
328 Gets the current workspaces from i3.
330 my $ws = i3->get_workspaces->recv;
337 $self->_ensure_connection;
339 $self->message(TYPE_GET_WORKSPACES)
344 Gets the current outputs from i3.
346 my $outs = i3->get_outputs->recv;
353 $self->_ensure_connection;
355 $self->message(TYPE_GET_OUTPUTS)
360 Gets the layout tree from i3 (>= v4.0).
362 my $tree = i3->get_tree->recv;
369 $self->_ensure_connection;
371 $self->message(TYPE_GET_TREE)
376 Gets all the window identifier marks from i3 (>= v4.1).
378 my $marks = i3->get_marks->recv;
385 $self->_ensure_connection;
387 $self->message(TYPE_GET_MARKS)
390 =head2 get_bar_config
392 Gets the bar configuration for the specific bar id from i3 (>= v4.1).
394 my $config = i3->get_bar_config($id)->recv;
399 my ($self, $id) = @_;
401 $self->_ensure_connection;
403 $self->message(TYPE_GET_BAR_CONFIG, $id)
406 =head2 command($content)
408 Makes i3 execute the given command
410 my $reply = i3->command("reload")->recv;
411 die "command failed" unless $reply->{success};
415 my ($self, $content) = @_;
417 $self->_ensure_connection;
419 $self->message(TYPE_COMMAND, $content)
424 Michael Stapelberg, C<< <michael at i3wm.org> >>
428 Please report any bugs or feature requests to C<bug-anyevent-i3 at
429 rt.cpan.org>, or through the web interface at
430 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=AnyEvent-I3>. I will be
431 notified, and then you'll automatically be notified of progress on your bug as
436 You can find documentation for this module with the perldoc command.
440 You can also look for information at:
444 =item * RT: CPAN's request tracker
446 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=AnyEvent-I3>
448 =item * The i3 window manager website
455 =head1 ACKNOWLEDGEMENTS
458 =head1 LICENSE AND COPYRIGHT
460 Copyright 2010-2012 Michael Stapelberg.
462 This program is free software; you can redistribute it and/or modify it
463 under the terms of either: the GNU General Public License as published
464 by the Free Software Foundation; or the Artistic License.
466 See http://dev.perl.org/licenses/ for more information.
471 1; # End of AnyEvent::I3