1

i3status-anyevent: add ability to reload config, relaxed json parser

This commit is contained in:
Sergei Fedosov
2021-02-18 19:08:41 +03:00
parent 949ce2f0c7
commit 20789b2a2c
2 changed files with 486 additions and 290 deletions

View File

@@ -1,72 +1,148 @@
[ # Enable "plugin" 1, disable "plugin" 0
{ {
"full_text" : "u", # Load Average
"name" : "urxvt", "la" : 1,
"cmd" : "urxvtc" # Memory stats
"mem" : 1,
# Just clock
"clock": 1,
# Battery
"battery": 1,
# 0-th core temperature
"cpu_temp": 1,
# Caps Lock staus
"capslock": 1,
# Application Buttons
"app_buttons": 1,
# OpenVPN status. Note that directive status in openvpn.conf should point to
# state file and update its timestamp at least as frequent as mtime_threshold in seconds
"vpn": {
"enabled": 0,
"statusfile" : "/tmp/openvpn-status.stat",
"mtime_threshold": 10,
# Also we can tcp-ping some service inside vpn network to ensure that connection is not stoned
"tcp_check" : {
"enabled": 0,
"host": "somehost.com",
"port": "443",
"timeout" : 3
}
},
# Buttons :)
"apps": [
{
"full_text" : " X ",
"name" : "kill_fbpanel",
"cmd" : "killall -9 fbpanel",
"color": "#aa0000",
"border": "#adadad",
"separator": false,
"separator_block_width": 2
}, },
{ {
"full_text" : "l", "full_text" : " Term ",
"name" : "lxterm", "name" : "lilyterm",
"cmd" : "lxterminal" "cmd" : "lilyterm",
"color" : "#666666",
"border": "#adadad",
"separator": false,
"separator_block_width": 2
}, },
{ {
"full_text" : "f", "full_text" : " Ff ",
"name" : "firefox", "name" : "firefox",
"cmd" : "firefox" "cmd" : "firefox",
"color" : "#ffa500",
"border": "#adadad",
"separator": false,
"separator_block_width": 2
}, },
{ {
"full_text" : "v", "full_text" : " V ",
"name" : "vivaldi", "name" : "vivaldi",
"cmd" : "vivaldi" "cmd" : "vivaldi",
"color" : "#ffa500",
"border": "#adadad",
"separator": false,
"separator_block_width": 2
}, },
{ {
"full_text" : "c", "full_text" : " Chr ",
"name" : "chromium", "name" : "chrome",
"cmd" : "chromium" "cmd" : "chrome",
"color" : "#ffa500",
"border": "#adadad",
"separator": false,
"separator_block_width": 2
}, },
{ {
"full_text" : "o", "full_text" : " O ",
"name" : "opera", "name" : "opera",
"cmd" : "opera" "cmd" : "opera",
"color" : "#ffa500",
"border": "#adadad",
"separator": false,
"separator_block_width": 2
}, },
{ {
"full_text" : "t", "full_text" : " @ ",
"name" : "thunderbird", "name" : "thunderbird",
"cmd" : "thunderbird" "cmd" : "thunderbird",
"color" : "#006994",
"border": "#adadad",
"separator": false,
"separator_block_width": 2
}, },
{ {
"full_text" : "t", "full_text" : " Tg ",
"name" : "telegram", "name" : "telegram",
"cmd" : "Telegram" "cmd" : "Telegram",
"color" : "#5a8850",
"border": "#adadad",
"separator": false,
"separator_block_width": 2
}, },
{ {
"full_text" : "i", "full_text" : " M ",
"name" : "icq", "name" : "myteam",
"cmd" : "icq" "cmd" : "myteam",
"color" : "#5a8850",
"border": "#adadad",
"separator": false,
"separator_block_width": 2
}, },
{ {
"full_text" : "s", "full_text" : " S ",
"name" : "slack", "name" : "slack",
"cmd" : "slack" "cmd" : "slack",
"color" : "#5a8850",
"border": "#adadad",
"separator": false,
"separator_block_width": 2
}, },
{ {
"full_text" : "z", "full_text" : " Txt ",
"name" : "zim",
"cmd" : "zim"
},
{
"full_text" : "m",
"name" : "mousepad", "name" : "mousepad",
"cmd" : "mousepad" "cmd" : "mousepad",
"border": "#adadad",
"separator": false,
"separator_block_width": 2
}, },
{ {
"full_text" : "c", "full_text" : " VSC ",
"name" : "code", "name" : "code",
"cmd" : "code" "cmd" : "code",
"border": "#adadad",
"separator": false,
"separator_block_width": 2
}, },
{ {
"full_text" : "k", "full_text" : " K ",
"name" : "keepassxc", "name" : "keepassxc",
"cmd" : "keepassxc" "cmd" : "keepassxc",
"color" : "#7ec850",
"border": "#adadad"
} }
] ]
}

View File

@@ -16,20 +16,30 @@ use utf8;
use open qw (:std :utf8); use open qw (:std :utf8);
use Fcntl qw (:seek); use Fcntl qw (:seek);
use AnyEvent; use AnyEvent;
#use Linux::Inotify2;
use JSON::XS; use JSON::XS;
use Net::DBus; use Net::DBus;
use Encode; use Encode;
use IO::Socket qw (AF_INET SOCK_STREAM SHUT_WR);
sub add_events ();
sub spawn (@); sub spawn (@);
sub find_caps_led (); sub find_caps_led ();
sub to_hours ($); sub to_hours ($);
sub readconf (); sub readconf ();
my $CONF = readconf (); my $CONF = readconf ();
my $done = AnyEvent->condvar;
# event pool
my @EP;
# reload config and re-apply it on SIGHUP
$SIG{HUP} = sub {
$CONF = readconf ();
$#EP = -1;
add_events ();
};
# note that /proc and sys does not generate events via inotify()
#my @files = qw( /proc/meminfo /proc/loadavg /tmp/boom /sys/class/net/wlan0/operstate );
my @month = ('Янв', 'Фев', 'Мар', 'Апр', 'Май', 'Июн', 'Июл', 'Авг', 'Сен', 'Окт', 'Ноя', 'Дек'); my @month = ('Янв', 'Фев', 'Мар', 'Апр', 'Май', 'Июн', 'Июл', 'Авг', 'Сен', 'Окт', 'Ноя', 'Дек');
my @week_day = ('Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'); my @week_day = ('Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб');
@@ -46,18 +56,17 @@ my $meminfo = '';
my $cputemp = ''; my $cputemp = '';
my $caps_state = ''; my $caps_state = '';
my $charge = ''; my $charge = '';
my $tcp_check = 0;
my $file_check = 0;
my $file_check_mtime = 0;
my $output_string; my $output_string;
my $old_output_string = ''; my $old_output_string = '';
my $STDIN_FIRST_LINE_DROPPED = 0; my $STDIN_FIRST_LINE_DROPPED = 0;
#my $inotify = Linux::Inotify2->new or die "Can't create inotify object: $!";
my $done = AnyEvent->condvar;
my $CAPS_LED_PATH = find_caps_led (); my $CAPS_LED_PATH = find_caps_led ();
# prep dee-boos connection # for fetching battery stats via dee-boos :)
my $bus = Net::DBus->system; my $properties;
my $upower = $bus->get_service ('org.freedesktop.UPower');
my $properties = $upower->get_object ('/org/freedesktop/UPower/devices/battery_BAT0', 'org.freedesktop.DBus.Properties');
# capture click events and do not override sigstop and sigcont numbers # capture click events and do not override sigstop and sigcont numbers
syswrite STDOUT, << 'EOJSON'; syswrite STDOUT, << 'EOJSON';
@@ -65,37 +74,90 @@ syswrite STDOUT, << 'EOJSON';
[ [], [ [],
EOJSON EOJSON
#foreach my $file (@files) { add_events ();
# $inotify->watch ( warn "events added";
# $file, $done->recv ();
# IN_MODIFY, exit 0;
#
# sub {
# my $e = shift; sub add_events () {
## if ($e->IN_MODIFY) { # prep dee-boos connection
# print "$file modified\n"; if ($CONF->{battery}) {
# } unless (defined $properties) {
# } # we should not install more than one connection to dbus,
# ); # but we can not break connection gracefully (via Net::DBus) once we make one
#} my $bus = Net::DBus->system;
my $upower = $bus->get_service ('org.freedesktop.UPower');
$properties = $upower->get_object ('/org/freedesktop/UPower/devices/battery_BAT0', 'org.freedesktop.DBus.Properties');
}
}
# Register callbacks/event handlers # Register callbacks/event handlers
# Actually print messages there # Actually print messages there
my $watch_stdout = AnyEvent->timer ( push @EP, AnyEvent->timer (
after => 1, # sleep 1 second after => 1, # sleep 1 second
interval => 0.3, # then invoke every 1 second interval => 0.3, # then invoke every 1 second
cb => sub { # the callback to invoke cb => sub { # the callback to invoke
my $OUTPUT; my $OUTPUT;
@{$OUTPUT} = @{$CONF};
push @{$OUTPUT}, { "color" => "#3e78fd", "full_text" => $caps_state }; if ($CONF->{app_buttons}) {
@{$OUTPUT} = @{$CONF->{apps}};
}
if ($CONF->{capslock}) {
unless ($caps_state) {
push @{$OUTPUT}, { "color" => "#3e78fd", "background" => "#edeceb", border => "#edeceb", "full_text" => "caps", "markup" => "pango"};
} else {
push @{$OUTPUT}, { "background" => "#3e78fd", "color" => "#edeceb", border => "#edeceb", "full_text" => "caps", "markup" => "pango"};
}
}
if ($CONF->{cpu_temp}) {
push @{$OUTPUT}, { "color" => "#3e78fd", "full_text" => $cputemp }; push @{$OUTPUT}, { "color" => "#3e78fd", "full_text" => $cputemp };
}
if ($CONF->{mem}) {
push @{$OUTPUT}, { "color" => "#3e78fd", "full_text" => $meminfo }; push @{$OUTPUT}, { "color" => "#3e78fd", "full_text" => $meminfo };
}
if ($CONF->{la}) {
push @{$OUTPUT}, { "color" => "#3e78fd", "full_text" => "LA: $la" }; push @{$OUTPUT}, { "color" => "#3e78fd", "full_text" => "LA: $la" };
}
my $vpn_str = 'VPN:';
if ($CONF->{vpn}->{enabled}) {
if ($file_check) {
$vpn_str .= '⍋';
} else {
$vpn_str .= '⍒';
}
}
if ($CONF->{vpn}->{tcp_check}->{enabled}) {
if ($CONF->{vpn}->{enabled}) {
$vpn_str .= ':';
}
if ($tcp_check) {
$vpn_str .= '✔';
} else {
$vpn_str .= '✘';
}
}
if ($CONF->{vpn}->{tcp_check}->{enabled} || $CONF->{vpn}->{enabled}) {
push @{$OUTPUT}, { "color" => "#3e78fd", "full_text" => $vpn_str };
}
if ($CONF->{battery}) {
push @{$OUTPUT}, { "color" => "#3e78fd", "full_text" => $charge }; push @{$OUTPUT}, { "color" => "#3e78fd", "full_text" => $charge };
push @{$OUTPUT}, { "color" => "#3e78fd", "full_text" => $wallclock }; }
if ($CONF->{clock}) {
push @{$OUTPUT}, { "color" => "#000000", "full_text" => "<big>$wallclock</big>", "markup" => "pango"};
}
$output_string = eval { encode_json ($OUTPUT) }; $output_string = eval { encode_json ($OUTPUT) };
@@ -114,7 +176,7 @@ my $watch_stdout = AnyEvent->timer (
# read STDIN # read STDIN
my $watch_stdin = AnyEvent->io ( push @EP, AnyEvent->io (
fh => \*STDIN, fh => \*STDIN,
poll => 'r', poll => 'r',
cb => sub { cb => sub {
@@ -134,8 +196,16 @@ my $watch_stdin = AnyEvent->io (
my $j = eval { decode_json ($msg) }; my $j = eval { decode_json ($msg) };
if (defined $j) { if (defined $j) {
foreach (@{$CONF}) { foreach (@{$CONF->{apps}}) {
if ((defined $_->{name}) && ($j->{name} eq $_->{name})) { unless (defined $_->{name}) {
next;
}
unless (defined $j->{name}) {
next;
}
if ($j->{name} eq $_->{name}) {
spawn ($_->{cmd}); spawn ($_->{cmd});
last; last;
} }
@@ -146,7 +216,8 @@ my $watch_stdin = AnyEvent->io (
); );
# poll caps lock status, on one of my laptop there is no led for this :( # poll caps lock status, on one of my laptop there is no led for this :(
my $watch_caps_led = AnyEvent->timer ( if ($CONF->{capslock}) {
push @EP, AnyEvent->timer (
after => 0, # first invoke ASAP after => 0, # first invoke ASAP
interval => 0.3, # then invoke every 0.3 seconds interval => 0.3, # then invoke every 0.3 seconds
cb => sub { # the callback to invoke cb => sub { # the callback to invoke
@@ -168,24 +239,18 @@ my $watch_caps_led = AnyEvent->timer (
$caps_state = 2; $caps_state = 2;
} }
if ($caps_state eq '2') { if ($caps_state ne '2') {
$caps_state = '? caps';
} else {
$caps_state = eval { readline ($CAPSHANDLE) }; $caps_state = eval { readline ($CAPSHANDLE) };
seek $CAPSHANDLE, SEEK_SET, 0; seek $CAPSHANDLE, SEEK_SET, 0;
chomp $caps_state; chomp $caps_state;
if ($caps_state eq '1') {
$caps_state = '☒ caps';
} else {
$caps_state = '☐ caps';
}
} }
} }
); );
}
# poll clock by timer # poll clock by timer
my $watch_clock = AnyEvent->timer ( if ($CONF->{clock}) {
push @EP, AnyEvent->timer (
after => 0, # first invoke ASAP after => 0, # first invoke ASAP
interval => 1, # then invoke every 1 second interval => 1, # then invoke every 1 second
cb => sub { # the callback to invoke cb => sub { # the callback to invoke
@@ -195,11 +260,12 @@ my $watch_clock = AnyEvent->timer (
$wallclock = sprintf ' %s, %s %s %s %02s:%02s ', $week_day[$wday], $mday, $month[$mon], $year, $hour, $min; $wallclock = sprintf ' %s, %s %s %s %02s:%02s ', $week_day[$wday], $mday, $month[$mon], $year, $hour, $min;
} }
); );
}
# poll battery status via dbus # poll battery status via dbus
# but it is possible to fetch this status via upower directly # but it is possible to fetch this status via upower directly
my $watch_battery = AnyEvent->timer ( if ($CONF->{battery}) {
push @EP, AnyEvent->timer (
after => 0, # first invoke ASAP after => 0, # first invoke ASAP
interval => 10, # then invoke every 10 seconds interval => 10, # then invoke every 10 seconds
cb => sub { # the callback to invoke cb => sub { # the callback to invoke
@@ -229,15 +295,16 @@ my $watch_battery = AnyEvent->timer (
$charge = sprintf '⚡ %s%% %s %s', $capacity, $state, $time; $charge = sprintf '⚡ %s%% %s %s', $capacity, $state, $time;
} }
); );
}
# put all fast accessable stats in one callback # put all fast accessable stats in one callback
my $watch_stats = AnyEvent->timer ( push @EP, AnyEvent->timer (
after => 0, # first invoke ASAP after => 0, # first invoke ASAP
interval => 3, # then invoke every 3 second interval => 3, # then invoke every 3 second
cb => sub { # the callback to invoke cb => sub { # the callback to invoke
# Fetch Load Average # Fetch Load Average
if ($CONF->{la}) {
if (defined $LAHANDLE) { if (defined $LAHANDLE) {
if (tell ($LAHANDLE) == -1) { if (tell ($LAHANDLE) == -1) {
open $LAHANDLE, '<', '/proc/loadavg'; open $LAHANDLE, '<', '/proc/loadavg';
@@ -249,8 +316,10 @@ my $watch_stats = AnyEvent->timer (
$la = readline ($LAHANDLE); $la = readline ($LAHANDLE);
seek $LAHANDLE, SEEK_SET, 0; seek $LAHANDLE, SEEK_SET, 0;
$la = (split / /ms, $la, 2)[0]; $la = (split / /ms, $la, 2)[0];
}
# populate memory statistics # populate memory statistics
if ($CONF->{mem}) {
if (defined $MEMINFOHANDLE) { if (defined $MEMINFOHANDLE) {
if (tell ($MEMINFOHANDLE) == -1) { if (tell ($MEMINFOHANDLE) == -1) {
open $MEMINFOHANDLE, '<', '/proc/meminfo'; open $MEMINFOHANDLE, '<', '/proc/meminfo';
@@ -267,17 +336,23 @@ my $watch_stats = AnyEvent->timer (
seek $MEMINFOHANDLE, SEEK_SET, 0; seek $MEMINFOHANDLE, SEEK_SET, 0;
@mem = map { substr $_, 0, -4 } @mem; @mem = map { substr $_, 0, -4 } @mem;
my $memtotal = (split /\s+/xms, $mem[0])[1];
my $memavail = (split /\s+/xms, $mem[2])[1]; my $memavail = (split /\s+/xms, $mem[2])[1];
my $swaptotal = (split /\s+/xms, $mem[14])[1]; my $swaptotal = (split /\s+/xms, $mem[14])[1];
my $swapfree = (split /\s+/xms, $mem[15])[1]; my $swapfree = (split /\s+/xms, $mem[15])[1];
my $shmem = (split /\s+/xms, $mem[20])[1];
my $memused = int (($memtotal - $memavail) / ($memtotal / 100));
$meminfo = sprintf ( $meminfo = sprintf (
'mem/sw: %s/%s M', 'M:%d%% SHM:%dM SW:%dM',
int ($memavail / 1024), $memused,
int ($shmem / 1024),
int (($swaptotal - $swapfree) / 1024) int (($swaptotal - $swapfree) / 1024)
); );
}
# populate cpu temperature info # populate cpu temperature info
if ($CONF->{cpu_temp}) {
my $hwmon = 1; my $hwmon = 1;
if (defined $CPUTEMPHANDLE) { if (defined $CPUTEMPHANDLE) {
@@ -306,18 +381,60 @@ my $watch_stats = AnyEvent->timer (
$cputemp = sprintf('%s°', $cputemp); $cputemp = sprintf('%s°', $cputemp);
} }
}
}, },
); );
# Try to tcp connect to server
if ($CONF->{vpn}->{tcp_check}->{enabled}) {
push @EP, AnyEvent->timer (
after => 0, # first invoke ASAP
interval => 5, # then invoke every 5 seconds
cb => sub { # the callback to invoke
if (
my $sock = IO::Socket->new (
Domain => AF_INET,
proto => 'tcp',
PeerHost => $CONF->{vpn}->{tcp_check}->{host},
PeerPort => $CONF->{vpn}->{tcp_check}->{port},
Type => SOCK_STREAM,
Timeout => $CONF->{vpn}->{tcp_check}->{timeout}
)
) {
$sock->shutdown (SHUT_WR);
$sock->close ();
$tcp_check = 1;
} else {
$tcp_check = 0;
}
}
);
}
# This callback for inotify stuff # check file mtime
#my $watch_file_event = AnyEvent->idle ( if ($CONF->{vpn}->{enabled}) {
# cb => sub { push @EP, AnyEvent->timer (
# $inotify->poll; after => 0, # first invoke ASAP
# } interval => 3, # then invoke every 3 seconds
#); cb => sub { # the callback to invoke
my $mtime = (stat $CONF->{vpn}->{statusfile}) [8];
$done->recv(); if (defined $mtime) {
if (($mtime - $file_check_mtime) < $CONF->{vpn}->{mtime_threshold}) {
$file_check = 1;
} else {
$file_check = 0;
}
$file_check_mtime = $mtime;
} else {
$mtime = 0;
$file_check = 0;
}
}
);
}
}
sub spawn (@) { sub spawn (@) {
my @args = @_; my @args = @_;
@@ -330,9 +447,12 @@ sub spawn (@) {
# Child, we need to exec() given prog with args # Child, we need to exec() given prog with args
# it seems that at least vscode creashes if we close stdio handles # it seems that at least vscode creashes if we close stdio handles
open STDOUT, ">", '/dev/null'; close STDOUT;
open STDERR, ">", '/dev/null'; close STDERR;
open STDIN, '<', '/dev/null'; close STDIN;
# open STDOUT, '>', '/dev/null';
# open STDERR, '>', '/dev/null';
# open STDIN, '<', '/dev/null';
$pid = fork (); $pid = fork ();
if ($pid) { # Parent if ($pid) { # Parent
@@ -341,10 +461,10 @@ sub spawn (@) {
} elsif ($pid == 0) { # Child } elsif ($pid == 0) { # Child
my $prg = shift (@args); my $prg = shift (@args);
# weird situation, silently quit here :) # weird situation, silently quit here :)
exit 0 unless(defined($prg)); exit 0 unless (defined $prg);
if (@args > 0) { if (@args > 0) {
exec $prg @args; exec $prg, @args;
} else { } else {
exec $prg; exec $prg;
} }
@@ -406,7 +526,7 @@ sub readconf () {
die "Unable to read $file: read $readlen, but stat() reports that file is $len bytes\n"; die "Unable to read $file: read $readlen, but stat() reports that file is $len bytes\n";
} }
my $config = eval { decode_json ($data) }; my $config = eval { JSON::XS->new->utf8->relaxed->decode ($data) };
if ($@) { if ($@) {
die "Unable to decode $file: $@\n"; die "Unable to decode $file: $@\n";