summaryrefslogtreecommitdiff
path: root/perl5/Local/Desktop/WMIPC.pm
blob: effa7797de79b095d49e2c784cab76f6139b07dd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package Local::Desktop::WMIPC;
use 5.036;

# Copyright (C) 2024 Sean Whitton
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

use IO::Socket::UNIX;
use parent "IO::Socket::UNIX";
use Exporter "import";
use overload "<>" => sub { shift->recv };
use JSON;
use Encode "encode";

our @EXPORT_OK = ();

sub new ($class, $socket = $ENV{SWAYSOCK} || $ENV{I3SOCK}) {
    bless IO::Socket::UNIX->new(Type => SOCK_STREAM, Peer => $socket)
      => $class;
}

sub send ($self, $type, $payload = "") {
    $payload = encode "UTF-8", $payload;
    my $head = pack "A6ll", "i3-ipc", length $payload, $type;
    $self->SUPER::send($head.$payload);
    return $self->recv;
}

sub recv ($self) {
    my $buf;
    $self->SUPER::recv($buf, 14);
    length $buf or die "WMIPC socket EOF";
    my $len = (unpack "A6ll", $buf)[1];
    $self->SUPER::recv($buf, $len);
    return decode_json $buf;
}

sub subscribe ($self, @event_types) {
    my $reply = $self->send(2, encode_json \@event_types);
    $reply->{success} or die "WMIPC subscription failed";
}

sub cmd ($self, @cmds) { $self->send(0, join "; ", @cmds) }

sub get_tree { shift->send(4) }
sub get_workspaces { shift->send(1) }

sub send_tick ($self, $payload = "") { $self->send(10, $payload) }

1;