2 # vim:ts=4:sw=4:expandtab
14 AnyEvent::I3 - communicate with the i3 window manager
18 our $VERSION = '0.07';
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);
32 my $i3 = i3("~/.i3/ipc.sock");
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. C<path> is the path of
52 the UNIX socket to connect to.
54 =head1 SUBROUTINES/METHODS
58 use Exporter qw(import);
63 use constant TYPE_COMMAND => 0;
64 use constant TYPE_GET_WORKSPACES => 1;
65 use constant TYPE_SUBSCRIBE => 2;
66 use constant TYPE_GET_OUTPUTS => 3;
67 use constant TYPE_GET_TREE => 4;
69 our %EXPORT_TAGS = ( 'all' => [
70 qw(i3 TYPE_COMMAND TYPE_GET_WORKSPACES TYPE_SUBSCRIBE TYPE_GET_OUTPUTS TYPE_GET_TREE)
73 our @EXPORT_OK = ( @{ $EXPORT_TAGS{all} } );
77 # TODO: auto-generate this from the header file? (i3/ipc.h)
78 my $event_mask = (1 << 31);
80 workspace => ($event_mask | 0),
81 output => ($event_mask | 1),
89 =head2 $i3 = AnyEvent::I3->new([ $path ])
91 Creates a new C<AnyEvent::I3> object and returns it. C<path> is the path of
92 the UNIX socket to connect to.
96 my ($class, $path) = @_;
98 $path ||= '~/.i3/ipc.sock';
100 # Check if we need to resolve ~
102 # We use getpwuid() instead of $ENV{HOME} because the latter is tainted
103 # and thus produces warnings when running tests with perl -T
104 my $home = (getpwuid($<))[7];
105 die "Could not get home directory" unless $home and -d $home;
106 $path =~ s/~/$home/g;
109 bless { path => $path } => $class;
114 Establishes the connection to i3. Returns an C<AnyEvent::CondVar> which will
115 be triggered with a boolean (true if the connection was established) as soon as
116 the connection has been established.
118 if ($i3->connect->recv) {
119 say "Connected to i3";
125 my $cv = AnyEvent->condvar;
127 tcp_connect "unix/", $self->{path}, sub {
130 return $cv->send(0) unless $fh;
132 $self->{ipchdl} = AnyEvent::Handle->new(
134 on_read => sub { my ($hdl) = @_; $self->_data_available($hdl) },
136 my ($hdl, $fatal, $msg) = @_;
137 delete $self->{ipchdl};
140 my $cb = $self->{callbacks};
142 # Trigger all one-time callbacks with undef
143 for my $type (keys %{$cb}) {
144 next if ($type & $event_mask) == $event_mask;
148 # Trigger _error callback, if set
149 my $type = $events{_error};
150 return unless defined($cb->{$type});
151 $cb->{$type}->($msg);
161 sub _data_available {
162 my ($self, $hdl) = @_;
165 chunk => length($magic) + 4 + 4,
168 # Unpack message length and read the payload
169 my ($len, $type) = unpack("LL", substr($header, length($magic)));
172 sub { $self->_handle_i3_message($type, $_[1]) }
178 sub _handle_i3_message {
179 my ($self, $type, $payload) = @_;
181 return unless defined($self->{callbacks}->{$type});
183 my $cb = $self->{callbacks}->{$type};
184 $cb->(decode_json $payload);
186 return if ($type & $event_mask) == $event_mask;
188 # If this was a one-time callback, we delete it
189 # (when connection is lost, all one-time callbacks get triggered)
190 delete $self->{callbacks}->{$type};
193 =head2 $i3->subscribe(\%callbacks)
195 Subscribes to the given event types. This function awaits a hashref with the
196 key being the name of the event and the value being a callback.
199 workspace => sub { say "Workspaces changed" }
202 if ($i3->subscribe(\%callbacks)->recv->{success})
203 say "Successfully subscribed";
206 The special callback with name C<_error> is called when the connection to i3
207 is killed (because of a crash, exit or restart of i3 most likely). You can
208 use it to print an appropriate message and exit cleanly or to try to reconnect.
213 say "I am sorry. I am so sorry: $msg";
218 $i3->subscribe(\%callbacks)->recv;
222 my ($self, $callbacks) = @_;
224 # Register callbacks for each message type
225 for my $key (keys %{$callbacks}) {
226 my $type = $events{$key};
227 $self->{callbacks}->{$type} = $callbacks->{$key};
230 $self->message(TYPE_SUBSCRIBE, [ keys %{$callbacks} ])
233 =head2 $i3->message($type, $content)
235 Sends a message of the specified C<type> to i3, possibly containing the data
236 structure C<content> (or C<content>, encoded as utf8, if C<content> is a
237 scalar), if specified.
239 my $reply = $i3->message(TYPE_COMMAND, "reload")->recv;
240 if ($reply->{success}) {
241 say "Configuration successfully reloaded";
246 my ($self, $type, $content) = @_;
248 die "No message type specified" unless defined($type);
250 die "No connection to i3" unless defined($self->{ipchdl});
254 if (not ref($content)) {
255 # Convert from Perl’s internal encoding to UTF8 octets
256 $payload = encode_utf8($content);
258 $payload = encode_json $content;
261 my $message = $magic . pack("LL", length($payload), $type) . $payload;
262 $self->{ipchdl}->push_write($message);
264 my $cv = AnyEvent->condvar;
266 # We don’t preserve the old callback as it makes no sense to
267 # have a callback on message reply types (only on events)
268 $self->{callbacks}->{$type} =
272 undef $self->{callbacks}->{$type};
280 These methods intend to make your scripts as beautiful as possible. All of
281 them automatically establish a connection to i3 blockingly (if it does not
286 sub _ensure_connection {
289 return if defined($self->{ipchdl});
291 $self->connect->recv or die "Unable to connect to i3"
294 =head2 get_workspaces
296 Gets the current workspaces from i3.
298 my $ws = i3->get_workspaces->recv;
305 $self->_ensure_connection;
307 $self->message(TYPE_GET_WORKSPACES)
312 Gets the current outputs from i3.
314 my $outs = i3->get_outputs->recv;
321 $self->_ensure_connection;
323 $self->message(TYPE_GET_OUTPUTS)
328 Gets the layout tree from i3 (tree branch only).
330 my $tree = i3->get_tree->recv;
337 $self->_ensure_connection;
339 $self->message(TYPE_GET_TREE)
343 =head2 command($content)
345 Makes i3 execute the given command
347 my $reply = i3->command("reload")->recv;
348 die "command failed" unless $reply->{success};
352 my ($self, $content) = @_;
354 $self->_ensure_connection;
356 $self->message(TYPE_COMMAND, $content)
361 Michael Stapelberg, C<< <michael at stapelberg.de> >>
365 Please report any bugs or feature requests to C<bug-anyevent-i3 at
366 rt.cpan.org>, or through the web interface at
367 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=AnyEvent-I3>. I will be
368 notified, and then you'll automatically be notified of progress on your bug as
373 You can find documentation for this module with the perldoc command.
377 You can also look for information at:
381 =item * RT: CPAN's request tracker
383 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=AnyEvent-I3>
385 =item * The i3 window manager website
387 L<http://i3.zekjur.net/>
392 =head1 ACKNOWLEDGEMENTS
395 =head1 LICENSE AND COPYRIGHT
397 Copyright 2010 Michael Stapelberg.
399 This program is free software; you can redistribute it and/or modify it
400 under the terms of either: the GNU General Public License as published
401 by the Free Software Foundation; or the Artistic License.
403 See http://dev.perl.org/licenses/ for more information.
408 1; # End of AnyEvent::I3