Debian Codegraph @

AnyEvent-I3/lib/AnyEvent/I3.pm

raw
1 package AnyEvent::I3;
2 # vim:ts=4:sw=4:expandtab
3
4 use strict;
5 use warnings;
6 use JSON::XS;
7 use AnyEvent::Handle;
8 use AnyEvent::Socket;
9 use AnyEvent;
10 use Encode;
11 use Carp;
12
13 =head1 NAME
14
15 AnyEvent::I3 - communicate with the i3 window manager
16
17 =cut
18
19 our $VERSION = '0.19';
20
21 =head1 VERSION
22
23 Version 0.19
24
25 =head1 SYNOPSIS
26
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.
30
31 use AnyEvent::I3 qw(:all);
32
33 my $i3 = i3();
34
35 $i3->connect->recv or die "Error connecting";
36 say "Connected to i3";
37
38 my $workspaces = $i3->message(TYPE_GET_WORKSPACES)->recv;
39 say "Currently, you use " . @{$workspaces} . " workspaces";
40
41 ...or, using the sugar methods:
42
43 use AnyEvent::I3;
44
45 my $workspaces = i3->get_workspaces->recv;
46 say "Currently, you use " . @{$workspaces} . " workspaces";
47
48 A somewhat more involved example which dumps the i3 layout tree whenever there
49 is a workspace event:
50
51 use Data::Dumper;
52 use AnyEvent;
53 use AnyEvent::I3;
54
55 my $i3 = i3();
56
57 $i3->connect->recv or die "Error connecting to i3";
58
59 $i3->subscribe({
60 workspace => sub {
61 $i3->get_tree->cb(sub {
62 my ($tree) = @_;
63 say "tree: " . Dumper($tree);
64 });
65 }
66 })->recv->{success} or die "Error subscribing to events";
67
68 AE::cv->recv
69
70 =head1 EXPORT
71
72 =head2 $i3 = i3([ $path ]);
73
74 Creates a new C<AnyEvent::I3> object and returns it.
75
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.
80
81 =head1 SUBROUTINES/METHODS
82
83 =cut
84
85 use Exporter qw(import);
86 use base 'Exporter';
87
88 our @EXPORT = qw(i3);
89
90 use constant TYPE_RUN_COMMAND => 0;
91 use constant TYPE_COMMAND => 0;
92 use constant TYPE_GET_WORKSPACES => 1;
93 use constant TYPE_SUBSCRIBE => 2;
94 use constant TYPE_GET_OUTPUTS => 3;
95 use constant TYPE_GET_TREE => 4;
96 use constant TYPE_GET_MARKS => 5;
97 use constant TYPE_GET_BAR_CONFIG => 6;
98 use constant TYPE_GET_VERSION => 7;
99 use constant TYPE_GET_BINDING_MODES => 8;
100 use constant TYPE_GET_CONFIG => 9;
101 use constant TYPE_SEND_TICK => 10;
102 use constant TYPE_SYNC => 11;
103 use constant TYPE_GET_BINDING_STATE => 12;
104
105 our %EXPORT_TAGS = ( 'all' => [
106 qw(i3 TYPE_RUN_COMMAND TYPE_COMMAND TYPE_GET_WORKSPACES TYPE_SUBSCRIBE TYPE_GET_OUTPUTS
107 TYPE_GET_TREE TYPE_GET_MARKS TYPE_GET_BAR_CONFIG TYPE_GET_VERSION
108 TYPE_GET_BINDING_MODES TYPE_GET_CONFIG TYPE_SEND_TICK TYPE_SYNC
109 TYPE_GET_BINDING_STATE)
110 ] );
111
112 our @EXPORT_OK = ( @{ $EXPORT_TAGS{all} } );
113
114 my $magic = "i3-ipc";
115
116 # TODO: auto-generate this from the header file? (i3/ipc.h)
117 my $event_mask = (1 << 31);
118 my %events = (
119 workspace => ($event_mask | 0),
120 output => ($event_mask | 1),
121 mode => ($event_mask | 2),
122 window => ($event_mask | 3),
123 barconfig_update => ($event_mask | 4),
124 binding => ($event_mask | 5),
125 shutdown => ($event_mask | 6),
126 tick => ($event_mask | 7),
127 _error => 0xFFFFFFFF,
128 );
129
130 sub i3 {
131 AnyEvent::I3->new(@_)
132 }
133
134 sub _call_i3 {
135 my ($args) = @_;
136
137 chomp(my $result = qx(i3 $args));
138 if ($result =~ /^([^\0]+)$/) {
139 return $1;
140 }
141
142 warn "Calling i3 $args failed. Is DISPLAY set and is i3 in your PATH?";
143 return undef;
144 }
145
146 =head2 $i3 = AnyEvent::I3->new([ $path ])
147
148 Creates a new C<AnyEvent::I3> object and returns it.
149
150 C<path> is an optional path of the UNIX socket to connect to. It is strongly
151 advised to NOT specify this unless you're absolutely sure you need it.
152 C<AnyEvent::I3> will automatically figure it out by querying the running i3
153 instance on the current DISPLAY which is almost always what you want.
154
155 =cut
156 sub new {
157 my ($class, $path) = @_;
158
159 # We have I3SOCK now
160 $path ||= $ENV{I3SOCK};
161 $path ||= _call_i3('--get-socketpath');
162
163 # Check if we need to resolve ~
164 if ($path =~ /~/) {
165 my $home = $ENV{HOME};
166 confess "Could not get home directory" unless $home and -d $home;
167 $path =~ s/~/$home/g;
168 }
169
170 if(!-S $path) {
171 die "$path is not a socket", $/;
172 }
173
174 bless { path => $path } => $class;
175 }
176
177 =head2 $i3->connect
178
179 Establishes the connection to i3. Returns an C<AnyEvent::CondVar> which will
180 be triggered with a boolean (true if the connection was established) as soon as
181 the connection has been established.
182
183 if ($i3->connect->recv) {
184 say "Connected to i3";
185 }
186
187 =cut
188 sub connect {
189 my ($self) = @_;
190 my $cv = AnyEvent->condvar;
191
192 tcp_connect "unix/", $self->{path}, sub {
193 my ($fh) = @_;
194
195 return $cv->send(0) unless $fh;
196
197 $self->{ipchdl} = AnyEvent::Handle->new(
198 fh => $fh,
199 on_read => sub { my ($hdl) = @_; $self->_data_available($hdl) },
200 on_error => sub {
201 my ($hdl, $fatal, $msg) = @_;
202 delete $self->{ipchdl};
203 $hdl->destroy;
204
205 my $cb = $self->{callbacks};
206
207 # Trigger all one-time callbacks with undef
208 for my $type (keys %{$cb}) {
209 next if ($type & $event_mask) == $event_mask;
210 $cb->{$type}->();
211 delete $cb->{$type};
212 }
213
214 # Trigger _error callback, if set
215 my $type = $events{_error};
216 return unless defined($cb->{$type});
217 $cb->{$type}->($msg);
218 }
219 );
220
221 $cv->send(1)
222 };
223
224 $cv
225 }
226
227 sub _data_available {
228 my ($self, $hdl) = @_;
229
230 $hdl->unshift_read(
231 chunk => length($magic) + 4 + 4,
232 sub {
233 my $header = $_[1];
234 # Unpack message length and read the payload
235 my ($len, $type) = unpack("LL", substr($header, length($magic)));
236 $hdl->unshift_read(
237 chunk => $len,
238 sub { $self->_handle_i3_message($type, $_[1]) }
239 );
240 }
241 );
242 }
243
244 sub _handle_i3_message {
245 my ($self, $type, $payload) = @_;
246
247 return unless defined($self->{callbacks}->{$type});
248
249 my $cb = $self->{callbacks}->{$type};
250 $cb->(decode_json $payload);
251
252 return if ($type & $event_mask) == $event_mask;
253
254 # If this was a one-time callback, we delete it
255 # (when connection is lost, all one-time callbacks get triggered)
256 delete $self->{callbacks}->{$type};
257 }
258
259 =head2 $i3->subscribe(\%callbacks)
260
261 Subscribes to the given event types. This function awaits a hashref with the
262 key being the name of the event and the value being a callback.
263
264 my %callbacks = (
265 workspace => sub { say "Workspaces changed" }
266 );
267
268 if ($i3->subscribe(\%callbacks)->recv->{success}) {
269 say "Successfully subscribed";
270 }
271
272 The special callback with name C<_error> is called when the connection to i3
273 is killed (because of a crash, exit or restart of i3 most likely). You can
274 use it to print an appropriate message and exit cleanly or to try to reconnect.
275
276 my %callbacks = (
277 _error => sub {
278 my ($msg) = @_;
279 say "I am sorry. I am so sorry: $msg";
280 exit 1;
281 }
282 );
283
284 $i3->subscribe(\%callbacks)->recv;
285
286 =cut
287 sub subscribe {
288 my ($self, $callbacks) = @_;
289
290 # Register callbacks for each message type
291 for my $key (keys %{$callbacks}) {
292 if (!exists $events{$key}) {
293 warn "Could not subscribe to event type '$key'." .
294 " Supported events are " . join(" ", sort keys %events), $/;
295 next;
296 }
297 my $type = $events{$key};
298 $self->{callbacks}->{$type} = $callbacks->{$key};
299 }
300
301 $self->message(TYPE_SUBSCRIBE, [ keys %{$callbacks} ])
302 }
303
304 =head2 $i3->message($type, $content)
305
306 Sends a message of the specified C<type> to i3, possibly containing the data
307 structure C<content> (or C<content>, encoded as utf8, if C<content> is a
308 scalar), if specified.
309
310 my $reply = $i3->message(TYPE_RUN_COMMAND, "reload")->recv;
311 if ($reply->{success}) {
312 say "Configuration successfully reloaded";
313 }
314
315 =cut
316 sub message {
317 my ($self, $type, $content) = @_;
318
319 confess "No message type specified" unless defined($type);
320
321 confess "No connection to i3" unless defined($self->{ipchdl});
322
323 my $payload = "";
324 if ($content) {
325 if (not ref($content)) {
326 # Convert from Perl’s internal encoding to UTF8 octets
327 $payload = encode_utf8($content);
328 } else {
329 $payload = encode_json $content;
330 }
331 }
332 my $message = $magic . pack("LL", length($payload), $type) . $payload;
333 $self->{ipchdl}->push_write($message);
334
335 my $cv = AnyEvent->condvar;
336
337 # We don’t preserve the old callback as it makes no sense to
338 # have a callback on message reply types (only on events)
339 $self->{callbacks}->{$type} =
340 sub {
341 my ($reply) = @_;
342 $cv->send($reply);
343 undef $self->{callbacks}->{$type};
344 };
345
346 $cv
347 }
348
349 =head1 SUGAR METHODS
350
351 These methods intend to make your scripts as beautiful as possible. All of
352 them automatically establish a connection to i3 blockingly (if it does not
353 already exist).
354
355 =cut
356
357 sub _ensure_connection {
358 my ($self) = @_;
359
360 return if defined($self->{ipchdl});
361
362 $self->connect->recv or confess "Unable to connect to i3 (socket path " . $self->{path} . ")";
363 }
364
365 =head2 get_workspaces
366
367 Gets the current workspaces from i3.
368
369 my $ws = i3->get_workspaces->recv;
370 say Dumper($ws);
371
372 =cut
373 sub get_workspaces {
374 my ($self) = @_;
375
376 $self->_ensure_connection;
377
378 $self->message(TYPE_GET_WORKSPACES)
379 }
380
381 =head2 get_outputs
382
383 Gets the current outputs from i3.
384
385 my $outs = i3->get_outputs->recv;
386 say Dumper($outs);
387
388 =cut
389 sub get_outputs {
390 my ($self) = @_;
391
392 $self->_ensure_connection;
393
394 $self->message(TYPE_GET_OUTPUTS)
395 }
396
397 =head2 get_tree
398
399 Gets the layout tree from i3 (>= v4.0).
400
401 my $tree = i3->get_tree->recv;
402 say Dumper($tree);
403
404 =cut
405 sub get_tree {
406 my ($self) = @_;
407
408 $self->_ensure_connection;
409
410 $self->message(TYPE_GET_TREE)
411 }
412
413 =head2 get_marks
414
415 Gets all the window identifier marks from i3 (>= v4.1).
416
417 my $marks = i3->get_marks->recv;
418 say Dumper($marks);
419
420 =cut
421 sub get_marks {
422 my ($self) = @_;
423
424 $self->_ensure_connection;
425
426 $self->message(TYPE_GET_MARKS)
427 }
428
429 =head2 get_bar_config
430
431 Gets the bar configuration for the specific bar id from i3 (>= v4.1).
432
433 my $config = i3->get_bar_config($id)->recv;
434 say Dumper($config);
435
436 =cut
437 sub get_bar_config {
438 my ($self, $id) = @_;
439
440 $self->_ensure_connection;
441
442 $self->message(TYPE_GET_BAR_CONFIG, $id)
443 }
444
445 =head2 get_version
446
447 Gets the i3 version via IPC, with a fall-back that parses the output of i3
448 --version (for i3 < v4.3).
449
450 my $version = i3->get_version()->recv;
451 say "major: " . $version->{major} . ", minor = " . $version->{minor};
452
453 =cut
454 sub get_version {
455 my ($self) = @_;
456
457 $self->_ensure_connection;
458
459 my $cv = AnyEvent->condvar;
460
461 my $version_cv = $self->message(TYPE_GET_VERSION);
462 my $timeout;
463 $timeout = AnyEvent->timer(
464 after => 1,
465 cb => sub {
466 warn "Falling back to i3 --version since the running i3 doesn’t support GET_VERSION yet.";
467 my $version = _call_i3('--version');
468 $version =~ s/^i3 version //;
469 my $patch = 0;
470 my ($major, $minor) = ($version =~ /^([0-9]+)\.([0-9]+)/);
471 if ($version =~ /^[0-9]+\.[0-9]+\.([0-9]+)/) {
472 $patch = $1;
473 }
474 # Strip everything from the © sign on.
475 $version =~ s/ ©.*$//g;
476 $cv->send({
477 major => int($major),
478 minor => int($minor),
479 patch => int($patch),
480 human_readable => $version,
481 });
482 undef $timeout;
483 },
484 );
485 $version_cv->cb(sub {
486 undef $timeout;
487 $cv->send($version_cv->recv);
488 });
489
490 return $cv;
491 }
492
493 =head2 get_config
494
495 Gets the raw last read config from i3. Requires i3 >= 4.14
496
497 =cut
498 sub get_config {
499 my ($self) = @_;
500
501 $self->_ensure_connection;
502
503 $self->message(TYPE_GET_CONFIG);
504 }
505
506 =head2 send_tick
507
508 Sends a tick event. Requires i3 >= 4.15
509
510 =cut
511 sub send_tick {
512 my ($self, $payload) = @_;
513
514 $self->_ensure_connection;
515
516 $self->message(TYPE_SEND_TICK, $payload);
517 }
518
519 =head2 sync
520
521 Sends an i3 sync event. Requires i3 >= 4.16
522
523 =cut
524 sub sync {
525 my ($self, $payload) = @_;
526
527 $self->_ensure_connection;
528
529 $self->message(TYPE_SYNC, $payload);
530 }
531
532 =head2 command($content)
533
534 Makes i3 execute the given command
535
536 my $reply = i3->command("reload")->recv;
537 die "command failed" unless $reply->{success};
538
539 =cut
540 sub command {
541 my ($self, $content) = @_;
542
543 $self->_ensure_connection;
544
545 $self->message(TYPE_RUN_COMMAND, $content)
546 }
547
548 =head1 AUTHOR
549
550 Michael Stapelberg, C<< <michael at i3wm.org> >>
551
552 =head1 BUGS
553
554 Please report any bugs or feature requests to C<bug-anyevent-i3 at
555 rt.cpan.org>, or through the web interface at
556 L<https://rt.cpan.org/NoAuth/ReportBug.html?Queue=AnyEvent-I3>. I will be
557 notified, and then you'll automatically be notified of progress on your bug as
558 I make changes.
559
560 =head1 SUPPORT
561
562 You can find documentation for this module with the perldoc command.
563
564 perldoc AnyEvent::I3
565
566 You can also look for information at:
567
568 =over 2
569
570 =item * RT: CPAN's request tracker
571
572 L<https://rt.cpan.org/NoAuth/Bugs.html?Dist=AnyEvent-I3>
573
574 =item * The i3 window manager website
575
576 L<https://i3wm.org>
577
578 =back
579
580
581 =head1 ACKNOWLEDGEMENTS
582
583
584 =head1 LICENSE AND COPYRIGHT
585
586 Copyright 2010-2012 Michael Stapelberg.
587
588 This program is free software; you can redistribute it and/or modify it
589 under the terms of either: the GNU General Public License as published
590 by the Free Software Foundation; or the Artistic License.
591
592 See https://dev.perl.org/licenses/ for more information.
593
594
595 =cut
596
597 1; # End of AnyEvent::I3