2 # vim:ts=4:sw=4:expandtab
14 AnyEvent::I3 - communicate with the i3 window manager
18 our $VERSION = '0.05';
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->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;
68 our %EXPORT_TAGS = ( 'all' => [
69 qw(i3 TYPE_COMMAND TYPE_GET_WORKSPACES TYPE_SUBSCRIBE TYPE_GET_OUTPUTS)
72 our @EXPORT_OK = ( @{ $EXPORT_TAGS{all} } );
76 # TODO: auto-generate this from the header file? (i3/ipc.h)
77 my $event_mask = (1 << 31);
79 workspace => ($event_mask | 0),
80 output => ($event_mask | 1),
88 =head2 $i3 = AnyEvent::I3->new([ $path ])
90 Creates a new C<AnyEvent::I3> object and returns it. C<path> is the path of
91 the UNIX socket to connect to.
95 my ($class, $path) = @_;
97 $path ||= '~/.i3/ipc.sock';
99 # Check if we need to resolve ~
101 # We use getpwuid() instead of $ENV{HOME} because the latter is tainted
102 # and thus produces warnings when running tests with perl -T
103 my $home = (getpwuid($<))[7];
104 die "Could not get home directory" unless $home and -d $home;
105 $path =~ s/~/$home/g;
108 bless { path => $path } => $class;
113 Establishes the connection to i3. Returns an C<AnyEvent::CondVar> which will
114 be triggered with a boolean (true if the connection was established) as soon as
115 the connection has been established.
117 if ($i3->connect->recv) {
118 say "Connected to i3";
124 my $cv = AnyEvent->condvar;
126 tcp_connect "unix/", $self->{path}, sub {
129 return $cv->send(0) unless $fh;
131 $self->{ipchdl} = AnyEvent::Handle->new(
133 on_read => sub { my ($hdl) = @_; $self->_data_available($hdl) },
135 my ($hdl, $fatal, $msg) = @_;
136 delete $self->{ipchdl};
139 my $cb = $self->{callbacks};
141 # Trigger all one-time callbacks with undef
142 for my $type (keys %{$cb}) {
143 next if ($type & $event_mask) == $event_mask;
147 # Trigger _error callback, if set
148 my $type = $events{_error};
149 return unless defined($cb->{$type});
150 $cb->{$type}->($msg);
160 sub _data_available {
161 my ($self, $hdl) = @_;
164 chunk => length($magic) + 4 + 4,
167 # Unpack message length and read the payload
168 my ($len, $type) = unpack("LL", substr($header, length($magic)));
171 sub { $self->_handle_i3_message($type, $_[1]) }
177 sub _handle_i3_message {
178 my ($self, $type, $payload) = @_;
180 return unless defined($self->{callbacks}->{$type});
182 my $cb = $self->{callbacks}->{$type};
183 $cb->(decode_json $payload);
185 return if ($type & $event_mask) == $event_mask;
187 # If this was a one-time callback, we delete it
188 # (when connection is lost, all one-time callbacks get triggered)
189 delete $self->{callbacks}->{$type};
192 =head2 $i3->subscribe(\%callbacks)
194 Subscribes to the given event types. This function awaits a hashref with the
195 key being the name of the event and the value being a callback.
198 workspace => sub { say "Workspaces changed" }
201 if ($i3->subscribe(\%callbacks)->recv->{success})
202 say "Successfully subscribed";
205 The special callback with name C<_error> is called when the connection to i3
206 is killed (because of a crash, exit or restart of i3 most likely). You can
207 use it to print an appropriate message and exit cleanly or to try to reconnect.
212 say "I am sorry. I am so sorry: $msg";
217 $i3->subscribe(\%callbacks)->recv;
221 my ($self, $callbacks) = @_;
223 # Register callbacks for each message type
224 for my $key (keys %{$callbacks}) {
225 my $type = $events{$key};
226 $self->{callbacks}->{$type} = $callbacks->{$key};
229 $self->message(TYPE_SUBSCRIBE, [ keys %{$callbacks} ])
232 =head2 $i3->message($type, $content)
234 Sends a message of the specified C<type> to i3, possibly containing the data
235 structure C<content> (or C<content>, encoded as utf8, if C<content> is a
236 scalar), if specified.
238 my $reply = $i3->message(TYPE_COMMAND, "reload")->recv;
239 if ($reply->{success}) {
240 say "Configuration successfully reloaded";
245 my ($self, $type, $content) = @_;
247 die "No message type specified" unless defined($type);
249 die "No connection to i3" unless defined($self->{ipchdl});
253 if (not ref($content)) {
254 # Convert from Perl’s internal encoding to UTF8 octets
255 $payload = encode_utf8($content);
257 $payload = encode_json $content;
260 my $message = $magic . pack("LL", length($payload), $type) . $payload;
261 $self->{ipchdl}->push_write($message);
263 my $cv = AnyEvent->condvar;
265 # We don’t preserve the old callback as it makes no sense to
266 # have a callback on message reply types (only on events)
267 $self->{callbacks}->{$type} =
271 undef $self->{callbacks}->{$type};
279 These methods intend to make your scripts as beautiful as possible. All of
280 them automatically establish a connection to i3 blockingly (if it does not
285 sub _ensure_connection {
288 return if defined($self->{ipchdl});
290 $self->connect->recv or die "Unable to connect to i3"
293 =head2 get_workspaces
295 Gets the current workspaces from i3.
297 my $ws = i3->get_workspaces->recv;
304 $self->_ensure_connection;
306 $self->message(TYPE_GET_WORKSPACES)
311 Gets the current outputs from i3.
313 my $outs = i3->get_outputs->recv;
320 $self->_ensure_connection;
322 $self->message(TYPE_GET_OUTPUTS)
325 =head2 command($content)
327 Makes i3 execute the given command
329 my $reply = i3->command("reload")->recv;
330 die "command failed" unless $reply->{success};
334 my ($self, $content) = @_;
336 $self->_ensure_connection;
338 $self->message(TYPE_COMMAND, $content)
343 Michael Stapelberg, C<< <michael at stapelberg.de> >>
347 Please report any bugs or feature requests to C<bug-anyevent-i3 at
348 rt.cpan.org>, or through the web interface at
349 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=AnyEvent-I3>. I will be
350 notified, and then you'll automatically be notified of progress on your bug as
355 You can find documentation for this module with the perldoc command.
359 You can also look for information at:
363 =item * RT: CPAN's request tracker
365 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=AnyEvent-I3>
367 =item * The i3 window manager website
369 L<http://i3.zekjur.net/>
374 =head1 ACKNOWLEDGEMENTS
377 =head1 LICENSE AND COPYRIGHT
379 Copyright 2010 Michael Stapelberg.
381 This program is free software; you can redistribute it and/or modify it
382 under the terms of either: the GNU General Public License as published
383 by the Free Software Foundation; or the Artistic License.
385 See http://dev.perl.org/licenses/ for more information.
390 1; # End of AnyEvent::I3