tabs->spaces

This commit is contained in:
John Mertz 2023-01-06 14:41:31 -05:00
parent ecd9920a37
commit 6d33d9446f
41 changed files with 1221 additions and 1203 deletions

View File

@ -9,10 +9,10 @@ use XML::Hash::XS; # CPAN or libxml-hash-xs-perl on Debian
# Feeds that should be used if no arguments are provided # Feeds that should be used if no arguments are provided
my @default_feeds = ( my @default_feeds = (
# CBC FrontBurner # CBC FrontBurner
"https://www.cbc.ca/podcasting/includes/frontburner.xml", "https://www.cbc.ca/podcasting/includes/frontburner.xml",
# Majority Report AM Quickie # Majority Report AM Quickie
"https://feeds.fans.fm/5883fe04-e11e-4578-a018-3b93ddfb5723.xml" "https://feeds.fans.fm/5883fe04-e11e-4578-a018-3b93ddfb5723.xml"
); );
# Player command (must accept stream as STDIN) # Player command (must accept stream as STDIN)
@ -28,14 +28,14 @@ my $player = "> /tmp/fifo.mp3 & omxplayer /tmp/fifo.mp3";
# Multiple feeds can be given as CLI arguments instead # Multiple feeds can be given as CLI arguments instead
my @feeds; my @feeds;
if (scalar @ARGV) { if (scalar @ARGV) {
foreach (@ARGV) { foreach (@ARGV) {
push @feeds, $_; push @feeds, $_;
} }
} }
# Only use default feeds if no CLI feeds were given # Only use default feeds if no CLI feeds were given
unless (scalar @feeds) { unless (scalar @feeds) {
@feeds = @default_feeds; @feeds = @default_feeds;
} }
# Local function to get date pattern provided as 'pubDate' # Local function to get date pattern provided as 'pubDate'
@ -48,36 +48,36 @@ my $xml = XML::Hash::XS->new(utf8 => 0, encoding => 'utf-8');
my @playlist; my @playlist;
# Go through each feed # Go through each feed
foreach my $url (@feeds) { foreach my $url (@feeds) {
# Ensure that it's actual an XML link # Ensure that it's actual an XML link
next unless $url =~ m#^https?://.*\.xml$#; next unless $url =~ m#^https?://.*\.xml$#;
# Ensure it is fetched okay # Ensure it is fetched okay
my $raw = $ua->get("$url")->content() || next; my $raw = $ua->get("$url")->content() || next;
# Ensure it is parsed okay # Ensure it is parsed okay
my $xml_hash = $xml->xml2hash($raw) || next; my $xml_hash = $xml->xml2hash($raw) || next;
# Collect all episodes published today # Collect all episodes published today
foreach my $item (@{$xml_hash->{'channel'}->{'item'}}) { foreach my $item (@{$xml_hash->{'channel'}->{'item'}}) {
if ($item->{'pubDate'} =~ m/$today/) { if ($item->{'pubDate'} =~ m/$today/) {
# Add any found to playlist # Add any found to playlist
push @playlist, $item->{'enclosure'}->{'url'}; push @playlist, $item->{'enclosure'}->{'url'};
}
} }
}
} }
# Fetch each item and pass it to player via STDIN # Fetch each item and pass it to player via STDIN
foreach (@playlist) { foreach (@playlist) {
# Uncomment the following to print the media URL # Uncomment the following to print the media URL
print $_ . "\n"; print $_ . "\n";
system("curl -NL $_ $player"); system("curl -NL $_ $player");
} }
unlink("/tmp/fifo.mp3"); unlink("/tmp/fifo.mp3");
sub get_date sub get_date
{ {
my ($second, $minute, $hour, $day, $month, $year) = localtime(time); my ($second, $minute, $hour, $day, $month, $year) = localtime(time);
my @months = ( my @months = (
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
); );
return $day . ' ' . $months[$month] . ' ' . ($year+1900); return $day . ' ' . $months[$month] . ' ' . ($year+1900);
} }

View File

@ -13,41 +13,41 @@ my $lat_lon = fetch_lat_lon($location);
my $pid = fork; my $pid = fork;
unless ($pid) { unless ($pid) {
open(my $fh, ">", $ENV{HOME}."/.spool/gammastep.pid"); open(my $fh, ">", $ENV{HOME}."/.spool/gammastep.pid");
print $fh $$; print $fh $$;
close($fh); close($fh);
open($fh, ">", $ENV{HOME}."/.spool/gammastep.status"); open($fh, ">", $ENV{HOME}."/.spool/gammastep.status");
print $fh 1; print $fh 1;
close($fh); close($fh);
open STDIN, '/dev/null'; open STDIN, '/dev/null';
open STDOUT, '>>/dev/null'; open STDOUT, '>>/dev/null';
open STDERR, '>>/dev/null'; open STDERR, '>>/dev/null';
if (! -e "/run/.containerenv" && ! -e "/.dockerenv" ) { if (! -e "/run/.containerenv" && ! -e "/.dockerenv" ) {
exec "exec /bin/distrobox-enter -n debian12 -- gammastep -l $lat_lon -b 0.7:0.3"; exec "exec /bin/distrobox-enter -n debian12 -- gammastep -l $lat_lon -b 0.7:0.3";
} else { } else {
exec "exec gammastep -l $lat_lon -b 0.7:0.3"; exec "exec gammastep -l $lat_lon -b 0.7:0.3";
} }
} }
sub fetch_lat_lon sub fetch_lat_lon
{ {
my ($location) = shift; my ($location) = shift;
my $ua = LWP::UserAgent->new(); my $ua = LWP::UserAgent->new();
my $json = JSON::XS->new(); my $json = JSON::XS->new();
my $raw = $ua->get($location)->content(); my $raw = $ua->get($location)->content();
if (defined $raw) { if (defined $raw) {
my $decoded = $json->decode($raw); my $decoded = $json->decode($raw);
if (defined $decoded->{lat} && defined $decoded->{lon}) { if (defined $decoded->{lat} && defined $decoded->{lon}) {
return "$decoded->{lat}:$decoded->{lon}"; return "$decoded->{lat}:$decoded->{lon}";
}
} }
sleep 5; }
return fetch_lat_lon($ua, $json, $location); sleep 5;
return fetch_lat_lon($ua, $json, $location);
} }
exit; exit;

View File

@ -6,8 +6,8 @@ echo "Available Distrobox sessions, with matching gnome-terminal profiles, are:"
echo "" echo ""
distrobox list | grep -v 'IMAGE' | cut -d '|' -f 2 distrobox list | grep -v 'IMAGE' | cut -d '|' -f 2
for i in 10 9 8 7 6 5 4 3 2 1; do for i in 10 9 8 7 6 5 4 3 2 1; do
printf "\rExitting in $i ..." printf "\rExitting in $i ..."
sleep 1 sleep 1
done done
echo "" echo ""
exit exit

View File

@ -4,25 +4,25 @@ LAYOUT=`cat ~/.config/screenlayout/i3.current`
MIDDLE="eDP-1" MIDDLE="eDP-1"
if [[ $LAYOUT == 'home' ]]; then if [[ $LAYOUT == 'home' ]]; then
RIGHT="DP-2-2" RIGHT="DP-2-2"
LEFT="DP-2-1" LEFT="DP-2-1"
elif [[ $LAYOUT == 'work' ]]; then elif [[ $LAYOUT == 'work' ]]; then
RIGHT="DP-2-2" RIGHT="DP-2-2"
LEFT="DP-2-1" LEFT="DP-2-1"
elif [[ $LAYOUT == '3' ]]; then elif [[ $LAYOUT == '3' ]]; then
MIDDLE="DP-2-2" MIDDLE="DP-2-2"
LEFT="DP-2-1" LEFT="DP-2-1"
RIGHT="eDP-1" RIGHT="eDP-1"
else else
echo "No external displays connected" echo "No external displays connected"
fi fi
if [[ $1 == 'right' ]]; then if [[ $1 == 'right' ]]; then
i3 move workspace to output $RIGHT i3 move workspace to output $RIGHT
elif [[ $1 == 'middle' ]]; then elif [[ $1 == 'middle' ]]; then
i3 move workspace to output $MIDDLE i3 move workspace to output $MIDDLE
elif [[ $1 == 'left' ]]; then elif [[ $1 == 'left' ]]; then
i3 move workspace to output $LEFT i3 move workspace to output $LEFT
else else
echo "Invalid direction. Requires either 'up', 'left', or 'middle'" echo "Invalid direction. Requires either 'up', 'left', or 'middle'"
fi fi

View File

@ -4,7 +4,7 @@ ROFI=$(pgrep -xc rofi | cut -b 1)
echo $ROFI echo $ROFI
if [[ "$ROFI" -eq "0" ]]; then if [[ "$ROFI" -eq "0" ]]; then
rofi -config /home/jpm/.config/rofi/config.rasi -theme /home/jpm/.config/rofi/sidebar.rasi -show drun -lines 20 rofi -config /home/jpm/.config/rofi/config.rasi -theme /home/jpm/.config/rofi/sidebar.rasi -show drun -lines 20
else else
killall rofi 2&>1 /dev/null killall rofi 2&>1 /dev/null
fi fi

View File

@ -5,25 +5,25 @@
res=$(echo "Connection|John.Me.tz|MailCleaner|Disconnect|Restart" | rofi -sep "|" -dmenu -i -p 'P ' "" -columns 9 -width 45 -l 1 -config /home/jpm/.config/rofi/config.rasi -theme /home/jpm/.config/rofi/sidebar -hide-scrollbar -eh 1 -location 0 -auto-select -no-fullscreen) res=$(echo "Connection|John.Me.tz|MailCleaner|Disconnect|Restart" | rofi -sep "|" -dmenu -i -p 'P ' "" -columns 9 -width 45 -l 1 -config /home/jpm/.config/rofi/config.rasi -theme /home/jpm/.config/rofi/sidebar -hide-scrollbar -eh 1 -location 0 -auto-select -no-fullscreen)
if [ $res = "Connection" ]; then if [ $res = "Connection" ]; then
/usr/bin/uxterm -e 'sudo /usr/bin/nmtui' /usr/bin/uxterm -e 'sudo /usr/bin/nmtui'
elif [ $res = "John.Me.tz" ]; then elif [ $res = "John.Me.tz" ]; then
sudo /usr/bin/systemctl stop openvpn-client@mailcleaner sudo /usr/bin/systemctl stop openvpn-client@mailcleaner
sudo /usr/bin/systemctl restart wg-quick@wg0 sudo /usr/bin/systemctl restart wg-quick@wg0
elif [ $res = "MailCleaner" ]; then elif [ $res = "MailCleaner" ]; then
sudo /usr/bin/systemctl stop wg-quick@wg0 sudo /usr/bin/systemctl stop wg-quick@wg0
sudo /usr/bin/systemctl restart openvpn-client@mailcleaner sudo /usr/bin/systemctl restart openvpn-client@mailcleaner
elif [ $res = "Disconnect" ]; then elif [ $res = "Disconnect" ]; then
sudo /usr/bin/systemctl stop openvpn-client@mailcleaner sudo /usr/bin/systemctl stop openvpn-client@mailcleaner
sudo /usr/bin/systemctl stop wg-quick@wg0 sudo /usr/bin/systemctl stop wg-quick@wg0
elif [ $res = "Restart" ]; then elif [ $res = "Restart" ]; then
if [ "`ip addr show wg0 2> /dev/null`" != "" ]; then if [ "`ip addr show wg0 2> /dev/null`" != "" ]; then
sudo /usr/bin/systemctl restart wg-quick@wg0 sudo /usr/bin/systemctl restart wg-quick@wg0
fi fi
if [ "`ip addr show tun0 2> /dev/null`" != "" ]; then if [ "`ip addr show tun0 2> /dev/null`" != "" ]; then
sudo /usr/bin/systemctl restart openvpn-client@mailcleaner sudo /usr/bin/systemctl restart openvpn-client@mailcleaner
fi fi
else else
exit exit
fi fi
# Waybar sometimes doesn't update with the VPN IP, for whatever reason. Restart it. # Waybar sometimes doesn't update with the VPN IP, for whatever reason. Restart it.

View File

@ -1,7 +1,7 @@
#!/bin/bash #!/bin/bash
INPUT="$(rofi -dmenu -i -p 'Kodi:' "" -columns 1 -rows 7 -width 32 -l 1 \ INPUT="$(rofi -dmenu -i -p 'Kodi:' "" -columns 1 -rows 7 -width 32 -l 1 \
-theme /home/jpm/.config/rofi/sidebar.rasi -hide-scrollbar -eh 1 -location \ -theme /home/jpm/.config/rofi/sidebar.rasi -hide-scrollbar -eh 1 -location \
0 -padding 12 -opacity 100)" 0 -padding 12 -opacity 100)"
/home/jpm/scripts/send-to-kodi.sh $INPUT 2>&1 /dev/null /home/jpm/scripts/send-to-kodi.sh $INPUT 2>&1 /dev/null

View File

@ -10,32 +10,32 @@ rofi -sep "|" -dmenu -i -p 'P ' "" -columns 1 -rows 1 -width 45 -l 1 -config \
echo $res > /home/jpm/.last_ssh_shortcut echo $res > /home/jpm/.last_ssh_shortcut
if [ $res = "john.me.tz" ]; then if [ $res = "john.me.tz" ]; then
/usr/bin/urxvt -e /bin/bash -c '/home/jpm/scripts/sshs w' /usr/bin/urxvt -e /bin/bash -c '/home/jpm/scripts/sshs w'
elif [ $res = "root@john.me.tz" ]; then elif [ $res = "root@john.me.tz" ]; then
/usr/bin/urxvt -e /bin/bash -c '/home/jpm/scripts/sshs r' /usr/bin/urxvt -e /bin/bash -c '/home/jpm/scripts/sshs r'
elif [ $res = "shb.ng" ]; then elif [ $res = "shb.ng" ]; then
/usr/bin/urxvt -e /bin/bash -c '/home/jpm/scripts/sshs s' /usr/bin/urxvt -e /bin/bash -c '/home/jpm/scripts/sshs s'
elif [ $res = "kipary.fastnet.ch" ]; then elif [ $res = "kipary.fastnet.ch" ]; then
/usr/bin/urxvt -e /bin/bash -c '/home/jpm/scripts/sshs d' /usr/bin/urxvt -e /bin/bash -c '/home/jpm/scripts/sshs d'
elif [ $res = "camera.lan.john.me.tz" ]; then elif [ $res = "camera.lan.john.me.tz" ]; then
/usr/bin/urxvt -e /bin/bash -c '/home/jpm/scripts/sshs c' /usr/bin/urxvt -e /bin/bash -c '/home/jpm/scripts/sshs c'
elif [ $res = "hud.lan.john.me.tz" ]; then elif [ $res = "hud.lan.john.me.tz" ]; then
/usr/bin/urxvt -e /bin/bash -c '/home/jpm/scripts/sshs h' /usr/bin/urxvt -e /bin/bash -c '/home/jpm/scripts/sshs h'
elif [ $res = "media.lan.john.me.tz" ]; then elif [ $res = "media.lan.john.me.tz" ]; then
/usr/bin/urxvt -e /bin/bash -c '/home/jpm/scripts/sshs m' /usr/bin/urxvt -e /bin/bash -c '/home/jpm/scripts/sshs m'
elif [ $res = "programmer.lan.john.me.tz" ]; then elif [ $res = "programmer.lan.john.me.tz" ]; then
/usr/bin/urxvt -e /bin/bash -c '/home/jpm/scripts/sshs p' /usr/bin/urxvt -e /bin/bash -c '/home/jpm/scripts/sshs p'
elif [ $res = "t470s.lan.john.me.tz" ]; then elif [ $res = "t470s.lan.john.me.tz" ]; then
/usr/bin/urxvt -e /bin/bash -c '/home/jpm/scripts/sshs l' /usr/bin/urxvt -e /bin/bash -c '/home/jpm/scripts/sshs l'
elif [ $res = "therm.lan.john.me.tz" ]; then elif [ $res = "therm.lan.john.me.tz" ]; then
/usr/bin/urxvt -e /bin/bash -c '/home/jpm/scripts/sshs t' /usr/bin/urxvt -e /bin/bash -c '/home/jpm/scripts/sshs t'
elif [ $res = "vm.lan.john.me.tz" ]; then elif [ $res = "vm.lan.john.me.tz" ]; then
/usr/bin/urxvt -e /bin/bash -c '/home/jpm/scripts/sshs v' /usr/bin/urxvt -e /bin/bash -c '/home/jpm/scripts/sshs v'
elif [ $res = "light.lan.john.me.tz" ]; then elif [ $res = "light.lan.john.me.tz" ]; then
/usr/bin/urxvt -e /bin/bash -c '/home/jpm/scripts/sshs light' /usr/bin/urxvt -e /bin/bash -c '/home/jpm/scripts/sshs light'
elif [ $res = "mac.lan.john.me.tz" ]; then elif [ $res = "mac.lan.john.me.tz" ]; then
/usr/bin/gvncviewer 192.168.2.10 >> /home/jpm/macos /usr/bin/gvncviewer 192.168.2.10 >> /home/jpm/macos
elif [ $res = "AndroidUSB" ]; then elif [ $res = "AndroidUSB" ]; then
/usr/bin/scrcpy /usr/bin/scrcpy
fi fi
exit 0 exit 0

View File

@ -4,13 +4,13 @@
res=$(echo "Rotate 0 (Normal)|Rotate 90 (Keyboard right)|Rotate 180 (Upside-down)|Rotate 270 (Keyborad left)" | rofi -sep "|" -dmenu -i -p 'P ' "" -columns 9 -width 45 -l 1 -config /home/jpm/.config/rofi/config.rasi -theme /home/jpm/.config/rofi/sidebar.rasi -hide-scrollbar -eh 1 -location 0 -auto-select -no-fullscreen) res=$(echo "Rotate 0 (Normal)|Rotate 90 (Keyboard right)|Rotate 180 (Upside-down)|Rotate 270 (Keyborad left)" | rofi -sep "|" -dmenu -i -p 'P ' "" -columns 9 -width 45 -l 1 -config /home/jpm/.config/rofi/config.rasi -theme /home/jpm/.config/rofi/sidebar.rasi -hide-scrollbar -eh 1 -location 0 -auto-select -no-fullscreen)
if [[ $res == "Rotate 0 (Normal)" ]]; then if [[ $res == "Rotate 0 (Normal)" ]]; then
swaymsg output eDP-1 transform 0 swaymsg output eDP-1 transform 0
elif [[ $res == "Rotate 90 (Keyboard right)" ]]; then elif [[ $res == "Rotate 90 (Keyboard right)" ]]; then
swaymsg output eDP-1 transform 90 swaymsg output eDP-1 transform 90
elif [[ $res == "Rotate 180 (Upside-down)" ]]; then elif [[ $res == "Rotate 180 (Upside-down)" ]]; then
swaymsg output eDP-1 transform 180 swaymsg output eDP-1 transform 180
elif [[ $res == "Rotate 270 (Keyboard left)" ]]; then elif [[ $res == "Rotate 270 (Keyboard left)" ]]; then
swaymsg output eDP-1 transform 270 swaymsg output eDP-1 transform 270
else else
exit exit
fi fi

View File

@ -3,10 +3,10 @@
RUNNING=$(pgrep yubioath-deskto) RUNNING=$(pgrep yubioath-deskto)
if [ "$RUNNING" ]; then if [ "$RUNNING" ]; then
kill $RUNNING kill $RUNNING
sudo systemctl stop pcscd.socket sudo systemctl stop pcscd.socket
sudo systemctl restart pcscd.service sudo systemctl restart pcscd.service
sudo systemctl start pcscd.socket sudo systemctl start pcscd.socket
fi fi
QT_QPA_PLATFORMTHEME=qt5ct QT_QPA_PLATFORM=wayland QT_PLUGIN_PATH=/usr/lib/qt/plugins /usr/bin/yubioath-desktop & QT_QPA_PLATFORMTHEME=qt5ct QT_QPA_PLATFORM=wayland QT_PLUGIN_PATH=/usr/lib/qt/plugins /usr/bin/yubioath-desktop &

View File

@ -9,10 +9,10 @@ sed -e 's/^\([0-9]*\)\t*\(.*\)/\2 \1/' |
rofi -dmenu -config ~/.config/rofi/sidebar.rasi | { rofi -dmenu -config ~/.config/rofi/sidebar.rasi | {
read -r read -r
id=`echo $REPLY | rev | cut -d' ' -f1 | rev` id=`echo $REPLY | rev | cut -d' ' -f1 | rev`
swaymsg "[con_id=$id]" focus swaymsg "[con_id=$id]" focus
} }

View File

@ -12,74 +12,74 @@ SUSPEND_TIMEOUT=3600 # one hour
function usage() function usage()
{ {
echo "usage: $0 <option> echo "usage: $0 <option>
start - Initialize 'swayidle' script. This should be declared in Sway config. start - Initialize 'swayidle' script. This should be declared in Sway config.
stop - Kill 'swayidle' script. Consider idle-inhibitor instead. stop - Kill 'swayidle' script. Consider idle-inhibitor instead.
fade - First idle action. Fades all windows to show background. fade - First idle action. Fades all windows to show background.
unfade - Restore opacity for faded windows. unfade - Restore opacity for faded windows.
dim - Reduce display brightness to minimum. dim - Reduce display brightness to minimum.
undim - Restore brightness to level prior to 'dim'. undim - Restore brightness to level prior to 'dim'.
lock - Mark as inactive and start 'swaylock'. lock - Mark as inactive and start 'swaylock'.
unlock - (Run upon unlock) Mark as active again. unlock - (Run upon unlock) Mark as active again.
sleep - Disable displays, but continue background processes. sleep - Disable displays, but continue background processes.
wake - Re-enable displays. wake - Re-enable displays.
hibernate - Hibernate. hibernate - Hibernate.
help - This message." help - This message."
exit exit
} }
if [ -z $1 ]; then if [ -z $1 ]; then
echo "Missing argument" echo "Missing argument"
usage usage
elif [ $1 == "-h" ] || [ $1 == "--help" ] || [ $1 == "help" ]; then elif [ $1 == "-h" ] || [ $1 == "--help" ] || [ $1 == "help" ]; then
usage usage
elif [ $1 == "start" ]; then elif [ $1 == "start" ]; then
swayidle -w \ swayidle -w \
timeout $FADE_TIMEOUT "$0 fade" \ timeout $FADE_TIMEOUT "$0 fade" \
resume "$0 unfade" \ resume "$0 unfade" \
timeout $DIM_TIMEOUT "$0 dim" \ timeout $DIM_TIMEOUT "$0 dim" \
resume "$0 undim" \ resume "$0 undim" \
timeout $LOCK_TIMEOUT "$0 lock" \ timeout $LOCK_TIMEOUT "$0 lock" \
resume "$0 unlock" \ resume "$0 unlock" \
timeout $DPMS_TIMEOUT "$0 sleep" \ timeout $DPMS_TIMEOUT "$0 sleep" \
resume "$0 wake" \ resume "$0 wake" \
timeout $SUSPEND_TIMEOUT "$0 hibernate" timeout $SUSPEND_TIMEOUT "$0 hibernate"
elif [ $1 == "stop" ]; then elif [ $1 == "stop" ]; then
pkill swayidle pkill swayidle
elif [ $1 == "fade" ]; then elif [ $1 == "fade" ]; then
if [ ! -e $HOME/.spool/sway-hidden ]; then if [ ! -e $HOME/.spool/sway-hidden ]; then
kill -USR2 `cat $HOME/.spool/sway-transparency` kill -USR2 `cat $HOME/.spool/sway-transparency`
fi fi
elif [ $1 == "unfade" ]; then elif [ $1 == "unfade" ]; then
if [ -e $HOME/.spool/sway-hidden ]; then if [ -e $HOME/.spool/sway-hidden ]; then
kill -USR2 `cat $HOME/.spool/sway-transparency` kill -USR2 `cat $HOME/.spool/sway-transparency`
fi fi
elif [ $1 == "dim" ]; then elif [ $1 == "dim" ]; then
echo $($HOME/scripts/thinkpad/blc.pl %) > $BLFILE echo $($HOME/scripts/thinkpad/blc.pl %) > $BLFILE
$HOME/scripts/thinkpad/blc.pl = 1 &>- $HOME/scripts/thinkpad/blc.pl = 1 &>-
elif [ $1 == "undim" ]; then elif [ $1 == "undim" ]; then
$HOME/scripts/thinkpad/blc.pl = `cat $BLFILE` &>- $HOME/scripts/thinkpad/blc.pl = `cat $BLFILE` &>-
elif [ $1 == "lock" ]; then elif [ $1 == "lock" ]; then
# Change nick to AFK # Change nick to AFK
#ssh jpm@john.me.tz -i /home/jpm/.ssh/no_pass -t \ #ssh jpm@john.me.tz -i /home/jpm/.ssh/no_pass -t \
#'screen -S irssi -X stuff "/nick jpmAFK^M"' #'screen -S irssi -X stuff "/nick jpmAFK^M"'
: :
elif [ $1 == "unlock" ]; then elif [ $1 == "unlock" ]; then
# Change nick to AFK # Change nick to AFK
#ssh jpm@john.me.tz -i /home/jpm/.ssh/no_pass -t \ #ssh jpm@john.me.tz -i /home/jpm/.ssh/no_pass -t \
#'screen -S irssi -X stuff "/nick jpm^M"' #'screen -S irssi -X stuff "/nick jpm^M"'
: :
elif [ $1 == "sleep" ]; then elif [ $1 == "sleep" ]; then
for i in `cat $OPFILE`; do swaymsg "output $i dpms off"; done for i in `cat $OPFILE`; do swaymsg "output $i dpms off"; done
elif [ $1 == "wake" ]; then elif [ $1 == "wake" ]; then
/home/jpm/scripts/sway/displays.pl /home/jpm/scripts/sway/displays.pl
elif [ $1 == "hibernate" ]; then elif [ $1 == "hibernate" ]; then
if [ -e $NOHIBERNATE ]; then if [ -e $NOHIBERNATE ]; then
:: ::
else else
sudo systemctl start hibernate.target sudo systemctl start hibernate.target
fi fi
else else
echo "Invalid argument: $1" echo "Invalid argument: $1"
usage usage
fi fi

View File

@ -11,15 +11,15 @@ my $now = sprintf("%.0f",($start->[0]*1000) + ($start->[1]/1000));
my $end = $now + 30000; my $end = $now + 30000;
while ($now < $end) { while ($now < $end) {
my $remaining = ($end - $now); my $remaining = ($end - $now);
my $notification = Gtk2::Notify::new('Idle', sprintf("%.0f",($remaining/1000)), '', "status_lock"); my $notification = Gtk2::Notify::new('Idle', sprintf("%.0f",($remaining/1000)), '', "status_lock");
$notification->set_hint_string('x-canonical-private-synchronous','idle'); $notification->set_hint_string('x-canonical-private-synchronous','idle');
$notification->set_urgency('NOTIFY_URGENCY_LOW'); $notification->set_urgency('NOTIFY_URGENCY_LOW');
$notification->set_hint_int32('value',($remaining/300)); $notification->set_hint_int32('value',($remaining/300));
$notification->set_timeout(150); $notification->set_timeout(150);
$notification->show(); $notification->show();
usleep(100); usleep(100);
$now = utime( undef, undef ); $now = utime( undef, undef );
$start = [gettimeofday]; $start = [gettimeofday];
$now = sprintf("%.0f",($start->[0]*1000) + ($start->[1]/1000)); $now = sprintf("%.0f",($start->[0]*1000) + ($start->[1]/1000));
} }

View File

@ -1,5 +1,5 @@
#!/bin/bash #!/bin/bash
for i in `seq 0 30`; do for i in `seq 0 30`; do
notify-send -a 'swayidle' -t 999 "Sleeping" $(expr 30 - $i); sleep 1 notify-send -a 'swayidle' -t 999 "Sleeping" $(expr 30 - $i); sleep 1
done done

View File

@ -19,63 +19,63 @@ my $root = $json->decode($raw);
my $display = $root->{focus}->[0]; my $display = $root->{focus}->[0];
my ($workspace, $term_id, $term_ws); my ($workspace, $term_id, $term_ws);
foreach my $d (@{$root->{nodes}}) { foreach my $d (@{$root->{nodes}}) {
# If both the current workspace and terminal have been found # If both the current workspace and terminal have been found
# nothing else to look for # nothing else to look for
if (defined($workspace) && defined($term_id)) { if (defined($workspace) && defined($term_id)) {
last;
# If the display from this iteration of the loop is in focus
# look for the active workspace
} elsif ($d->{id} eq $display) {
foreach my $w (@{$d->{nodes}}) {
# Again, if both found, skip
if (defined($workspace) && defined($term_id)) {
last; last;
# If the display from this iteration of the loop is in focus # Otherwise if the current workspace is active, mark it
# look for the active workspace } elsif ($w->{id} eq $d->{focus}->[0]) {
} elsif ($d->{id} eq $display) { $workspace = $w->{name};
foreach my $w (@{$d->{nodes}}) { }
# Again, if both found, skip # In any case, look for the terminal app
if (defined($workspace) && defined($term_id)) { foreach my $n (@{$w->{floating_nodes}}) {
last; if ($n->{name} eq $term) {
# Otherwise if the current workspace is active, mark it $term_id = $n->{id};
} elsif ($w->{id} eq $d->{focus}->[0]) { $term_ws = $w->{name};
$workspace = $w->{name}; last;
}
# In any case, look for the terminal app
foreach my $n (@{$w->{floating_nodes}}) {
if ($n->{name} eq $term) {
$term_id = $n->{id};
$term_ws = $w->{name};
last;
}
}
}
# All other displays only need to be quickly searched for the term_id
} else {
foreach my $w (@{$d->{nodes}}) {
if (defined($term_id)) {
last;
}
foreach my $n (@{$w->{floating_nodes}}) {
if ($n->{name} eq $term) {
$term_id = $n->{id};
$term_ws = $w->{name};
last;
}
}
} }
}
} }
# All other displays only need to be quickly searched for the term_id
} else {
foreach my $w (@{$d->{nodes}}) {
if (defined($term_id)) {
last;
}
foreach my $n (@{$w->{floating_nodes}}) {
if ($n->{name} eq $term) {
$term_id = $n->{id};
$term_ws = $w->{name};
last;
}
}
}
}
} }
print "Active workspace = $workspace\n" print "Active workspace = $workspace\n"
. "Terminal ID = $term_id\n" . "Terminal ID = $term_id\n"
. "Terminal WS = $term_ws\n"; . "Terminal WS = $term_ws\n";
# If there is no terminal found, spawn one # If there is no terminal found, spawn one
if (!defined($term_id)) { if (!defined($term_id)) {
print "No term running, starting one\n"; print "No term running, starting one\n";
exec $term exec $term
# If the current workspace is known and terminal isn't on it, bring and focus # If the current workspace is known and terminal isn't on it, bring and focus
} elsif ($workspace != $term_ws) { } elsif ($workspace != $term_ws) {
print "Term not on current workspace, bringing it\n"; print "Term not on current workspace, bringing it\n";
`swaymsg "[con_id=$term_id]" move workspace $workspace`; `swaymsg "[con_id=$term_id]" move workspace $workspace`;
`swaymsg "[con_id=$term_id]" focus`; `swaymsg "[con_id=$term_id]" focus`;
`swaymsg "[con_id=$term_id]" sticky enable`; `swaymsg "[con_id=$term_id]" sticky enable`;
# Otherwise hide it from whereever it is # Otherwise hide it from whereever it is
} else { } else {
print "Term is on current workspace or lost, moving to $hidden\n"; print "Term is on current workspace or lost, moving to $hidden\n";
`swaymsg "[con_id=$term_id]" sticky disable`; `swaymsg "[con_id=$term_id]" sticky disable`;
`swaymsg "[con_id=$term_id]" move workspace $hidden`; `swaymsg "[con_id=$term_id]" move workspace $hidden`;
} }

View File

@ -4,45 +4,45 @@
# Determine if Sway or i3 # Determine if Sway or i3
if [ -z ${SWAYSOCK+x} ]; then if [ -z ${SWAYSOCK+x} ]; then
WM="i3" WM="i3"
else else
WM="sway" WM="sway"
fi fi
if [[ $WM == 'i3' ]]; then if [[ $WM == 'i3' ]]; then
res=$(printf "⚿ Lock|↩ Logout|↻ Reload i3|↹ Restart i3|↯ Hibernate|🡙 Reboot|⏻ Shutdown" | rofi -sep "|" -dmenu -i -p 'Power: ' "" -columns 1 -rows 7 -width 32 -l 1 -theme /home/jpm/.config/rofi/sidebar.rasi -hide-scrollbar -eh 1 -location 0 -padding 12 -opacity 100 -auto-select -no-fullscreen) res=$(printf "⚿ Lock|↩ Logout|↻ Reload i3|↹ Restart i3|↯ Hibernate|🡙 Reboot|⏻ Shutdown" | rofi -sep "|" -dmenu -i -p 'Power: ' "" -columns 1 -rows 7 -width 32 -l 1 -theme /home/jpm/.config/rofi/sidebar.rasi -hide-scrollbar -eh 1 -location 0 -padding 12 -opacity 100 -auto-select -no-fullscreen)
else else
res=$(printf "⚿ Lock\n🖵 Toggle Displays\n⚿ Yubico Authenticator\n↻ Reload Sway\n↻ Reload Waybar\n↩ Logout\n↯ Hibernate\n🡙 Reboot\n⏻ Shutdown" | wofi -I -s $HOME/.dotfiles/wofi/style.css -c $HOME/.dotfiles/wofi/sidebar --show dmenu res=$(printf "⚿ Lock\n🖵 Toggle Displays\n⚿ Yubico Authenticator\n↻ Reload Sway\n↻ Reload Waybar\n↩ Logout\n↯ Hibernate\n🡙 Reboot\n⏻ Shutdown" | wofi -I -s $HOME/.dotfiles/wofi/style.css -c $HOME/.dotfiles/wofi/sidebar --show dmenu
) )
fi fi
if [ "$res" == "⚿ Lock" ]; then if [ "$res" == "⚿ Lock" ]; then
${WM}lock -c 000000 ${WM}lock -c 000000
elif [ "$res" == "↩ Logout" ]; then elif [ "$res" == "↩ Logout" ]; then
# Prevent auto-login # Prevent auto-login
rm /home/jpm/.config/last_login_gui rm /home/jpm/.config/last_login_gui
${WM} exit ${WM} exit
elif [ "$res" == "🖵 Toggle Displays" ]; then elif [ "$res" == "🖵 Toggle Displays" ]; then
/home/jpm/scripts/sway/toggle_outputs.sh /home/jpm/scripts/sway/toggle_outputs.sh
elif [ "$res" == "⚿ Yubico Authenticator" ]; then elif [ "$res" == "⚿ Yubico Authenticator" ]; then
/home/jpm/scripts/rofi/rofi-yubioath.sh /home/jpm/scripts/rofi/rofi-yubioath.sh
elif [ "$res" == "↻ Reload i3" ]; then elif [ "$res" == "↻ Reload i3" ]; then
i3 reload i3 reload
elif [ "$res" == "↹ Restart i3" ]; then elif [ "$res" == "↹ Restart i3" ]; then
i3 restart i3 restart
elif [ "$res" == "↻ Reload Sway" ]; then elif [ "$res" == "↻ Reload Sway" ]; then
sway reload sway reload
/home/jpm/scripts/sway/displays.pl /home/jpm/scripts/sway/displays.pl
elif [ "$res" == "↻ Reload Waybar" ]; then elif [ "$res" == "↻ Reload Waybar" ]; then
# Need to integrate with sway/displays.pl for alternative outputs # Need to integrate with sway/displays.pl for alternative outputs
/home/jpm/scripts/sway/displays.pl -w /home/jpm/scripts/sway/displays.pl -w
elif [ "$res" == "🡙 Reboot" ]; then elif [ "$res" == "🡙 Reboot" ]; then
rm $SSH_AUTH_SOCK rm $SSH_AUTH_SOCK
sudo systemctl reboot -i sudo systemctl reboot -i
elif [ "$res" == "⏻ Shutdown" ]; then elif [ "$res" == "⏻ Shutdown" ]; then
rm $SSH_AUTH_SOCK rm $SSH_AUTH_SOCK
sudo systemctl poweroff -i sudo systemctl poweroff -i
elif [ "$res" == "↯ Hibernate" ]; then elif [ "$res" == "↯ Hibernate" ]; then
sudo systemctl hibernate -i sudo systemctl hibernate -i
fi fi
exit 0 exit 0

View File

@ -3,7 +3,7 @@
PID=`cat /tmp/$USER-wallpaper.pid` PID=`cat /tmp/$USER-wallpaper.pid`
if [ $PID ]; then if [ $PID ]; then
kill -SIGUSR1 $PID kill -SIGUSR1 $PID
else else
systemctl --user restart wallpapers.service systemctl --user restart wallpapers.service
fi fi

View File

@ -3,9 +3,9 @@
CURRENT=`cat /home/jpm/.config/last_display` CURRENT=`cat /home/jpm/.config/last_display`
if [ "$CURRENT" == "detached" ]; then if [ "$CURRENT" == "detached" ]; then
/home/jpm/scripts/sway/displays.pl TV /home/jpm/scripts/sway/displays.pl TV
else else
/home/jpm/scripts/sway/displays.pl detached /home/jpm/scripts/sway/displays.pl detached
fi fi
pkill mako pkill mako
mako & mako &

View File

@ -12,368 +12,314 @@ use lib "$ENV{HOME}/perl5/lib/perl5";
$ENV{PWD} = '/tmp' unless (defined($ENV{PWD})); $ENV{PWD} = '/tmp' unless (defined($ENV{PWD}));
use constant ERROR => { use constant ERROR => {
LOG_EMERG => 8, LOG_EMERG => 8,
LOG_ALERT => 7, LOG_ALERT => 7,
LOG_CRIT => 6, LOG_CRIT => 6,
LOG_ERR => 5, LOG_ERR => 5,
LOG_WARNING => 4, LOG_WARNING => 4,
LOG_NOTICE => 3, LOG_NOTICE => 3,
LOG_INFO => 2, LOG_INFO => 2,
LOG_DEBUG => 1 LOG_DEBUG => 1
}; };
our @e; our @e;
sub usage() sub usage()
{ {
my $self = shift; my $self = shift;
print("$0 [output(s)] [-d|--daemon]\n print("$0 [output(s)] [-d|--daemon]\n
Sets a wallpaper by cropping an appropriate sized section of a larger image.\n Sets a wallpaper by cropping an appropriate sized section of a larger image.\n
All arguments other than the below are assumed to be output names, as defined All arguments other than the below are assumed to be output names, as defined
in my sway/displays.pl script. If no outputs are provided, all available that in my sway/displays.pl script. If no outputs are provided, all available that
are currently enabled will be set.\n are currently enabled will be set.\n
--path=<path> Path to wallpaper directory. --path=<path> Path to wallpaper directory.
-p <path> Default: $ENV{HOME}/wallpapers\n -p <path> Default: $ENV{HOME}/wallpapers\n
--daemon=N Configures the wallpaper to be periodically rotated for all --daemon=N Configures the wallpaper to be periodically rotated for all
-d N of the given outputs. N indicates the number of seconds between -d N of the given outputs. N indicates the number of seconds between
each rotation, if provided (default: 300).\n each rotation, if provided (default: 300).\n
--nocrop Don't crop a selection from the image. Instead, pass the whole --nocrop Don't crop a selection from the image. Instead, pass the whole
-n image to swaybg and let it handle the scaling\n -n image to swaybg and let it handle the scaling\n
--verbose=N Define minimum log level. Counting from 1: LOG_DEBUG, LOG_INFO, --verbose=N Define minimum log level. Counting from 1: LOG_DEBUG, LOG_INFO,
-v N LOG_NOTICE, LOG_WARNING, LOG_ERR, LOG_CRIT, LOG_ALERT, LOG_EMERG -v N LOG_NOTICE, LOG_WARNING, LOG_ERR, LOG_CRIT, LOG_ALERT, LOG_EMERG
Default: 5; If provided without a value for N then all (1). Default: 5; If provided without a value for N then all (1).
--recursive=N Enumerate images recursively through directories in the path. --recursive=N Enumerate images recursively through directories in the path.
-r N N indicates the directory depth, unlimited if no N is provided. -r N N indicates the directory depth, unlimited if no N is provided.
--help This menu --help This menu
-h\n -h\n
You can send SIGUSR1 to force the daemon to reload immediately. Rotation timer You can send SIGUSR1 to force the daemon to reload immediately. Rotation timer
will be reset.\n"); will be reset.\n");
exit(0); exit(0);
} }
sub new sub new
{ {
my ($class, %args) = @_; my ($class, %args) = @_;
use AnyEvent::Sway; use AnyEvent::Sway;
$args{ipc} = AnyEvent::Sway->new(); $args{ipc} = AnyEvent::Sway->new();
use Image::Magick; use Image::Magick;
$args{im} = Image::Magick->new(); $args{im} = Image::Magick->new();
$args{error} = (); $args{error} = ();
$args{pidfile} = "/tmp/$ENV{USER}-wallpaper.pid"; $args{pidfile} = "/tmp/$ENV{USER}-wallpaper.pid";
return bless { %args }; return bless { %args };
} }
my $wp = new("Wallpapers");
if (-e $wp->{pidfile}) {
if (-r $wp->{pidfile}) {
if (open(my $fh, '<', $wp->{pidfile})) {
my $pid = <$fh>;
chomp($pid);
use Proc::ProcessTable;
my $pt = Proc::ProcessTable->new();
foreach my $p ( @{ $pt->table() } ) {
if ($p->{pid} eq $pid) {
my $name = $0;
$name =~ s/$ENV{PWD}//;
if ($p->{'cmndline'} =~ m#$name#) {
$wp->do_log("LOG_CRIT", "Another process is already running with PID: $pid (running and listed in $wp->{pidfile})");
# Die locally because do_log will remove pidfile that this iteration does not belong to
exit(1);
} else {
$wp->do_log("LOG_CRIT", "Found matching $pid with different cmdline: $p->{cmndline} (not $0)",1);
# PID in pidfile doesn't look like it is another wallpaper
unlink($wp->{pidfile});
last;
}
return $p->{'pid'};
}
}
} else {
$wp->do_log("LOG_CRIT", "Pidfile $wp->{pidfile} exists, but cannot be opened. Assuming it is running already.");
# Die locally because do_log will remove pidfile that this iteration does not belong to
exit(1);
}
} else {
$wp->do_log("LOG_CRIT", "Pidfile $wp->{pidfile} exists, but is not readable. Assuming it is running already.");
# Die locally because do_log will remove pidfile that this iteration does not belong to
exit(1);
}
}
# SIGUSR reset the timer, force immediate reload, continue looping
$SIG{USR1} = sub {
alarm 0;
$wp->do_log("LOG_INFO", "Reloading due to SIGUSR1");
};
# SIGTERM reset the timer, clean pid, and allow for the main loop to finish run
$SIG{TERM} = sub {
$wp->do_log("LOG_INFO", "Going down clean due to SIGTERM");
clean($wp);
$wp->{daemon} = 0;
};
# SIGKILL clean pid then exit immediately
$SIG{KILL} = sub {
$wp->do_log("LOG_INFO", "Hard kill with SIGKILL, attempting to remove pidfile");
clean($wp);
exit(0);
};
# simply returns the array of hashes provided by swaymsg # simply returns the array of hashes provided by swaymsg
sub get_outputs sub get_outputs
{ {
my $self = shift; my $self = shift;
my $o = $self->{ipc}->get_outputs->recv() || $self->do_log('LOG_WARNING',"Failed to query 'get_outputs'"); my $o = $self->{ipc}->get_outputs->recv() || $self->do_log('LOG_WARNING',"Failed to query 'get_outputs'");
die "No outputs detected.\n" unless (scalar(@$o) > 0); die "No outputs detected.\n" unless (scalar(@$o) > 0);
return $o; return $o;
} }
# returns the same as above but with the 'name' as a hash key for easier lookup # returns the same as above but with the 'name' as a hash key for easier lookup
sub get_active sub get_active
{ {
my $self = shift; my $self = shift;
if (defined($self->{outputs}) && scalar($self->{outputs})) { if (defined($self->{outputs}) && scalar($self->{outputs})) {
my %active = (); my %active = ();
foreach my $o (@{$self->{outputs}}) { foreach my $o (@{$self->{outputs}}) {
my $name; my $name;
my %details; my %details;
next unless ($o->{active}); next unless ($o->{active});
$active{$o->{name}} = (); $active{$o->{name}} = ();
foreach (keys(%$o)) { foreach (keys(%$o)) {
$active{$o->{name}}->{$_} = $o->{$_} unless ($_ eq 'name'); $active{$o->{name}}->{$_} = $o->{$_} unless ($_ eq 'name');
} }
}
$self->do_log('LOG_WARNING',"No outputs detected.") unless (scalar(keys(%active)));
return \%active;
} else {
print "You haven't initialized get_outputs";
$self->do_log('LOG_WARNING',"Output list not defined yet. Try 'get_outputs()' first");
return \{};
} }
$self->do_log('LOG_WARNING',"No outputs detected.") unless (scalar(keys(%active)));
return \%active;
} else {
print "You haven't initialized get_outputs";
$self->do_log('LOG_WARNING',"Output list not defined yet. Try 'get_outputs()' first");
return \{};
}
} }
sub clean sub clean
{ {
my $self = shift; my $self = shift;
if (-e $self->{pidfile}) { if (-e $self->{pidfile}) {
open (my $fh, '<', $self->{pidfile}); open (my $fh, '<', $self->{pidfile});
my $p = <$fh>; my $p = <$fh>;
close($fh); close($fh);
chomp $p; chomp $p;
kill($p); kill($p);
unlink($self->{pidfile}); unlink($self->{pidfile});
} }
} }
sub dig_dirs sub dig_dirs
{ {
my $self = shift; my $self = shift;
my $paths_ref = shift; my $paths_ref = shift;
my $path = shift; my $path = shift;
my $depth = shift || 0; my $depth = shift || 0;
unless (-e $path) { unless (-e $path) {
return(undef); return(undef);
} }
if ($path =~ m/\/\.\.?$/) {
return;
}
foreach (glob("$path/*"), glob("$path/.*")) {
if ($path =~ m/\/\.\.?$/) { if ($path =~ m/\/\.\.?$/) {
return; next();
} } elsif (-l $_) {
foreach (glob("$path/*"), glob("$path/.*")) { push(@$paths_ref, $_);
if ($path =~ m/\/\.\.?$/) { } elsif (-d $_ && ($self->{recursive} == '-1' || $depth < $self->{recursive})) {
next(); $self->dig_dirs($paths_ref,$_,$depth+1);
} elsif (-l $_) { } else {
push(@$paths_ref, $_); push(@$paths_ref, $_);
} elsif (-d $_ && ($self->{recursive} == '-1' || $depth < $self->{recursive})) {
$self->dig_dirs($paths_ref,$_,$depth+1);
} else {
push(@$paths_ref, $_);
}
} }
}
} }
sub choose_image sub choose_image
{ {
my $self = shift; my $self = shift;
my @i; my @i;
my $depth = 0; my $depth = 0;
my @w; my @w;
$self->dig_dirs(\@w,$self->{path}); $self->dig_dirs(\@w,$self->{path});
return undef unless (scalar(@w)); return undef unless (scalar(@w));
$self->do_log("LOG_DEBUG", "Found ".scalar(@w)." files in $self->{path} up to depth $self->{recursive}"); $self->do_log("LOG_DEBUG", "Found ".scalar(@w)." files in $self->{path} up to depth $self->{recursive}");
foreach (@w) { foreach (@w) {
if (-d $_) { if (-d $_) {
$self->do_log("LOG_DEBUG", "Ignoring sub-directory $_"); $self->do_log("LOG_DEBUG", "Ignoring sub-directory $_");
next; next;
}
if ($_ =~ m/\.(png|jpg)$/) {
push(@i,$_);
}
} }
if ($_ =~ m/\.(png|jpg)$/) {
push(@i,$_);
}
}
return $i[rand(scalar(@i))] || return undef; return $i[rand(scalar(@i))] || return undef;
} }
sub crop sub crop
{ {
my $self = shift; my $self = shift;
my $image = shift; my $image = shift;
my $ow = shift; my $ow = shift;
my $oh = shift; my $oh = shift;
my $cropped = $image; my $cropped = $image;
$cropped =~ s#^.*/([^/]*)\.([^\.]+)$#$self->{'path'}$1-cropped.$2#; $cropped =~ s#^.*/([^/]*)\.([^\.]+)$#$self->{'path'}$1-cropped.$2#;
#$image = "/tmp/Pharma-out.png.jpg"; #$image = "/tmp/Pharma-out.png.jpg";
use Image::Magick; use Image::Magick;
my $im = Image::Magick->new(); my $im = Image::Magick->new();
die "$image is not readable" unless (-r $image); die "$image is not readable" unless (-r $image);
my $ret = $im->Read($image); my $ret = $im->Read($image);
return 0 if ($ret); return 0 if ($ret);
my ($iw, $ih) = $im->Get("columns", "rows"); my ($iw, $ih) = $im->Get("columns", "rows");
$self->do_log("LOG_DEBUG", "Image has dimensions ${iw}x${ih}"); $self->do_log("LOG_DEBUG", "Image has dimensions ${iw}x${ih}");
# Return full size if it is smaller in either dimension then the output # Return full size if it is smaller in either dimension then the output
if ($iw <= $ow || $ih <= $oh) { if ($iw <= $ow || $ih <= $oh) {
$self->do_log("LOG_DEBUG", "Not cropping because ${iw}x${ih} is smaller or equal to the output (${ow}x${oh}) in at least 1 dimension."); $self->do_log("LOG_DEBUG", "Not cropping because ${iw}x${ih} is smaller or equal to the output (${ow}x${oh}) in at least 1 dimension.");
return undef; return undef;
} }
my ($x, $y); my ($x, $y);
$x = int(rand($iw-$ow)); $x = int(rand($iw-$ow));
$y = int(rand($ih-$oh)); $y = int(rand($ih-$oh));
my $err = $im->Crop(geometry=>"${ow}x${oh}+${x}+${y}"); my $err = $im->Crop(geometry=>"${ow}x${oh}+${x}+${y}");
die "$err" if ($err); die "$err" if ($err);
$err = $im->Write($cropped); $err = $im->Write($cropped);
die "$err" if ($err); die "$err" if ($err);
return $cropped if ( -e $cropped ); return $cropped if ( -e $cropped );
} }
sub set_background sub set_background
{ {
my $self = shift; my $self = shift;
my $target = shift || return "No target or image provided"; my $target = shift || return "No target or image provided";
my $cropped = shift || return "No image provided"; my $cropped = shift || return "No image provided";
# TODO get fallback from javascript # TODO get fallback from javascript
my $cmd = "output $target background $cropped fill #000000"; my $cmd = "output $target background $cropped fill #000000";
$self->do_log("LOG_DEBUG", "Running $cmd\n"); $self->do_log("LOG_DEBUG", "Running $cmd\n");
my $ret = $self->{ipc}->message(0,$cmd)->recv; my $ret = $self->{ipc}->message(0,$cmd)->recv;
if ($ret->[0]->{success}) { if ($ret->[0]->{success}) {
$self->do_log("LOG_DEBUG", "Success!"); $self->do_log("LOG_DEBUG", "Success!");
return undef; return undef;
} }
return "Failed to run Sway IPC command '$cmd'"; return "Failed to run Sway IPC command '$cmd'";
} }
sub do_log sub do_log
{ {
my $self = shift; my $self = shift;
my $level = shift; my $level = shift;
my $msg = shift; my $msg = shift;
my $die = shift || 0; my $die = shift || 0;
my $min = $self->{verbose} || 5; my $min = $self->{verbose} || 5;
# Journald is borked. Just don't bother logging # Journald is borked. Just don't bother logging
return 0; return 0;
if ($self->{daemon}) { if ($self->{daemon}) {
use Log::Journald qw(send); #use Log::Journald qw(send);
send( #send(
PRIORITY => ERROR->{$level}, #PRIORITY => ERROR->{$level},
MESSAGE => $msg, #MESSAGE => $msg,
PERL_PACKAGE => 'Sway Wallpapers' #PERL_PACKAGE => 'Sway Wallpapers'
) || warn "Could not send log ($level $msg): $!"; #) || warn "Could not send log ($level $msg): $!";
if ($die) {
$msg = '(FATAL) ' . $msg;
exit(1);
}
} else {
if (ERROR->{$level} >= $min) {
printf("%11s %s\n", $level, $msg);
}
}
if ($die) { if ($die) {
$self->clean(); $msg = '(FATAL) ' . $msg;
exit(1); exit(1);
} }
} else {
if (ERROR->{$level} >= $min) {
printf("%11s %s\n", $level, $msg);
}
}
if ($die) {
$self->clean();
exit(1);
}
} }
sub run sub run
{ {
my $self = shift; my $self = shift;
$self->do_log("LOG_DEBUG", "Fetching outputs from IPC"); $self->do_log("LOG_DEBUG", "Fetching outputs from IPC");
$self->{outputs} = $self->get_outputs(); $self->{outputs} = $self->get_outputs();
# Local copy of targets so that it will re-check active every time # Local copy of targets so that it will re-check active every time
my @t = @{$self->{targets}} if (scalar(@{$self->{targets}})); print "Changing $_\n" foreach(@{$self->{targets}});
$self->do_log("LOG_DEBUG", "Removing inactive ouputs"); my @t = @{$self->{targets}} if (scalar(@{$self->{targets}}));
my $active = $self->get_active(); $self->do_log("LOG_DEBUG", "Removing inactive ouputs");
# If specific targets were not defined, use all active my $active = $self->get_active();
unless (scalar(@t)) { # If specific targets were not defined, use all active
@t = keys(%$active); unless (scalar(@t)) {
push(@{$self->{error}}, "No target outputs") unless (scalar(@t)); @t = keys(%$active);
push(@{$self->{error}}, "No target outputs") unless (scalar(@t));
}
$self->do_log("LOG_DEBUG", "Looping desired ouputs");
foreach my $target (@t) {
print $target."\n";
$self->do_log("LOG_DEBUG", "Ensuring that desired output is active");
unless (defined($active->{$target})) {
$self->do_log('LOG_DEBUG', "Target $target is not an active output");
next;
} }
$self->do_log("LOG_DEBUG", "Looping desired ouputs"); $self->do_log("LOG_DEBUG", "Selecting image for $target");
foreach my $target (@t) { my $image = $self->choose_image();
$self->do_log("LOG_DEBUG", "Ensuring that desired output is active"); if (defined($image)) {
unless (defined($active->{$target})) { $self->do_log('LOG_DEBUG', "Selected $image");
$self->do_log('LOG_DEBUG', "Target $target is not an active output"); if ( -r "$image" ) {
next; my $cropped;
} if ($self->{crop}) {
$self->do_log("LOG_DEBUG", "Selecting image for $target"); $self->do_log('LOG_DEBUG',"Cropping image for '$target' using '$image'");
my $image = $self->choose_image(); $cropped = $self->crop(
if (defined($image)) { $image,
$self->do_log('LOG_DEBUG', "Selected $image"); $active->{$target}->{rect}->{width},
if ( -r "$image" ) { $active->{$target}->{rect}->{height}
my $cropped; );
if ($self->{crop}) { if ($cropped) {
$self->do_log('LOG_DEBUG',"Cropping image for '$target' using '$image'"); } else {
$cropped = $self->crop( # Create a tmp copy since it will be deleted later
$image, # If PWD is the wallpaper path, make the tmp in /tmp
$active->{$target}->{rect}->{width}, if ($self->{path} eq $ENV{PWD}) {
$active->{$target}->{rect}->{height} $cropped = $image;
); $cropped =~ s%$ENV{PWD}%/tmp%;
if ($cropped) { # Else make the tmp in PWD
} else {
# Create a tmp copy since it will be deleted later
# If PWD is the wallpaper path, make the tmp in /tmp
if ($self->{path} eq $ENV{PWD}) {
$cropped = $image;
$cropped =~ s%$ENV{PWD}%/tmp%;
# Else make the tmp in PWD
} else {
$cropped = '/'.$image;
$cropped =~ s%.*/([^/+])%$ENV{PWD}/$1%;
}
$self->do_log('LOG_DEBUG',"Creating copy of original: $cropped");
File::Copy::copy($image,$cropped) || $self->do_log('LOG_WARNING',"Failed to copy to $cropped: $!");
}
} else {
$self->do_log('LOG_DEBUG', "Cropping is disabled");
$cropped = $image;
}
$self->set_background($target,$cropped);
if ($self->{crop}) {
# Give swaybg a second, otherwise the file will be missing before it ends
sleep(1);
$self->do_log('LOG_DEBUG', "Deleting $cropped");
unlink($cropped) || $self->do_log("LOG_WARNING", "Failed to delete $cropped after setting: $!");
}
} else { } else {
$self->do_log("LOG_WARNING", "Failed to read $image"); $cropped = '/'.$image;
$cropped =~ s%.*/([^/+])%$ENV{PWD}/$1%;
} }
$self->do_log('LOG_DEBUG',"Creating copy of original: $cropped");
File::Copy::copy($image,$cropped) || $self->do_log('LOG_WARNING',"Failed to copy to $cropped: $!");
}
} else { } else {
$self->do_log("LOG_WARNING", "Failed to select image from $self->{path}"); $self->do_log('LOG_DEBUG', "Cropping is disabled");
$cropped = $image;
} }
$self->set_background($target,$cropped);
if ($self->{crop}) {
# Give swaybg a second, otherwise the file will be missing before it ends
sleep(1);
$self->do_log('LOG_DEBUG', "Deleting $cropped");
unlink($cropped) || $self->do_log("LOG_WARNING", "Failed to delete $cropped after setting: $!");
}
} else {
$self->do_log("LOG_WARNING", "Failed to read $image");
}
} else {
$self->do_log("LOG_WARNING", "Failed to select image from $self->{path}");
} }
}
} }
################################################################################ ################################################################################
# Collect arguments # Collect arguments
################################################################################ ################################################################################
my $wp = new("Wallpapers");
my @targets; my @targets;
my $daemon; my $daemon;
my $delay; my $delay;
@ -381,51 +327,92 @@ my $crop;
my $path; my $path;
my $verbose; my $verbose;
my $recursive = 0; my $recursive = 0;
while (my $arg = shift(@ARGV)) { while (my $arg = shift(@ARGV)) {
if ($arg eq '-h' || $arg eq '--help') { if ($arg eq '-h' || $arg eq '--help') {
$wp->usage(); $wp->usage();
} elsif ($arg =~ m/^\-\-path=?(.+)$/) { } elsif ($arg =~ m/^\-\-path=?(.+)$/) {
die "Redundant argument '$arg'. Wallpaper path already set.\n" if ($path); die "Redundant argument '$arg'. Wallpaper path already set.\n" if ($path);
$path = $1; $path = $1;
} elsif ($arg eq '-p') { } elsif ($arg eq '-p') {
die "Redundant argument '$arg'. Wallpaper path already set.\n" if ($path); die "Redundant argument '$arg'. Wallpaper path already set.\n" if ($path);
$path = shift(@ARGV); $path = shift(@ARGV);
} elsif ($arg =~ m/^\-\-daemon=?(.+)?$/) { } elsif ($arg =~ m/^\-\-daemon=?(.+)?$/) {
die "Redundant argument '$arg'. Daemon mode already set.\n" if ($daemon); die "Redundant argument '$arg'. Daemon mode already set.\n" if ($daemon);
$delay = $1 || 300; $delay = $1 || 300;
$daemon = 1; $daemon = 1;
} elsif ($arg eq '-d') { } elsif ($arg eq '-d') {
die "Redundant argument '$arg'. Daemon mode already set.\n" if ($daemon); die "Redundant argument '$arg'. Daemon mode already set.\n" if ($daemon);
if (scalar(@ARGV) && $ARGV[0] =~ m/^\d+$/) { if (scalar(@ARGV) && $ARGV[0] =~ m/^\d+$/) {
$delay = shift(@ARGV); $delay = shift(@ARGV);
}
$daemon = 1;
} elsif ($arg eq '--nocrop' || $arg eq '-n') {
die "Redundant argument '$arg'. No-crop already set.\n" if (defined($crop));
$crop = 0;
} elsif ($arg =~ m/^\-\-verbose=?(.+)?$/) {
die "Redundant argument '$arg'. Verbosity already set.\n" if ($verbose);
$verbose = $1 || 1;
} elsif ($arg eq '-v') {
die "Redundant argument '$arg'. Verbosity already set.\n" if ($verbose);
if (scalar(@ARGV) && $ARGV[0] =~ m/^\d$/) {
$verbose = shift(@ARGV);
}
} elsif ($arg =~ m/^\-\-recursive=?(.+)?$/) {
die "Redundant argument '$arg'. Recursive search already set.\n" unless ($recursive == 0);
$recursive = $1 || -1;
} elsif ($arg eq '-r') {
die "Redundant argument '$arg'. Recursive search already set.\n" unless ($recursive == 0);
if (scalar(@ARGV) && $ARGV[0] =~ m/^\d+$/) {
$recursive = shift(@ARGV);
} else {
$recursive = -1;
}
} elsif ($arg =~ m/^-/) {
die "Unrecognized argument: $arg\n";
} else {
push(@targets,$arg);
} }
$daemon = 1;
} elsif ($arg eq '--nocrop' || $arg eq '-n') {
die "Redundant argument '$arg'. No-crop already set.\n" if (defined($crop));
$crop = 0;
} elsif ($arg =~ m/^\-\-verbose=?(.+)?$/) {
die "Redundant argument '$arg'. Verbosity already set.\n" if ($verbose);
$verbose = $1 || 1;
} elsif ($arg eq '-v') {
die "Redundant argument '$arg'. Verbosity already set.\n" if ($verbose);
if (scalar(@ARGV) && $ARGV[0] =~ m/^\d$/) {
$verbose = shift(@ARGV);
}
} elsif ($arg =~ m/^\-\-recursive=?(.+)?$/) {
die "Redundant argument '$arg'. Recursive search already set.\n" unless ($recursive == 0);
$recursive = $1 || -1;
} elsif ($arg eq '-r') {
die "Redundant argument '$arg'. Recursive search already set.\n" unless ($recursive == 0);
if (scalar(@ARGV) && $ARGV[0] =~ m/^\d+$/) {
$recursive = shift(@ARGV);
} else {
$recursive = -1;
}
} elsif ($arg =~ m/^-/) {
die "Unrecognized argument: $arg\n";
} else {
print "Adding $arg to targets\n";
push(@targets,$arg);
print "Setting $_\n" foreach(@targets);
$wp->{targets} = \@targets || undef;
print "Set $_\n" foreach(@{$wp->{targets}});
}
}
if (-e $wp->{pidfile}) {
if (-r $wp->{pidfile}) {
if (open(my $fh, '<', $wp->{pidfile})) {
my $pid = <$fh>;
chomp($pid);
use Proc::ProcessTable;
my $pt = Proc::ProcessTable->new();
foreach my $p ( @{ $pt->table() } ) {
if ($p->{pid} eq $pid) {
my $name = $0;
$name =~ s/$ENV{PWD}//;
if ($p->{'cmndline'} =~ m#$name#) {
$wp->do_log("LOG_CRIT", "Another process is already running with PID: $pid (running and listed in $wp->{pidfile})");
# Die locally because do_log will remove pidfile that this iteration does not belong to
exit(1);
} else {
$wp->do_log("LOG_CRIT", "Found matching $pid with different cmdline: $p->{cmndline} (not $0)",1);
# PID in pidfile doesn't look like it is another wallpaper
unlink($wp->{pidfile});
last;
}
return $p->{'pid'};
}
}
} else {
$wp->do_log("LOG_CRIT", "Pidfile $wp->{pidfile} exists, but cannot be opened. Assuming it is running already.");
# Die locally because do_log will remove pidfile that this iteration does not belong to
exit(1);
}
} else {
$wp->do_log("LOG_CRIT", "Pidfile $wp->{pidfile} exists, but is not readable. Assuming it is running already.");
# Die locally because do_log will remove pidfile that this iteration does not belong to
exit(1);
}
} }
################################################################################ ################################################################################
@ -438,7 +425,6 @@ die "Invalid wallpaper path '$path'. Not a directory." if (defined($path) && !-d
die "Invalid verbosity level: '$verbose'\n" if (defined($verbose) && $verbose !~ m/^[1-8]$/); die "Invalid verbosity level: '$verbose'\n" if (defined($verbose) && $verbose !~ m/^[1-8]$/);
$wp->do_log("LOG_DEBUG", "Configuring object"); $wp->do_log("LOG_DEBUG", "Configuring object");
$wp->{targets} = \@targets || undef;
$wp->{daemon} = $daemon || 0; $wp->{daemon} = $daemon || 0;
$wp->{path} = $path || "$ENV{HOME}/wallpapers"; $wp->{path} = $path || "$ENV{HOME}/wallpapers";
$wp->{crop} = $crop || 1; $wp->{crop} = $crop || 1;
@ -452,23 +438,23 @@ $wp->{error} = [];
################################################################################ ################################################################################
if ($wp->{daemon}) { if ($wp->{daemon}) {
$wp->do_log("LOG_DEBUG", "Forking daemon"); $wp->do_log("LOG_DEBUG", "Forking daemon");
my $p = fork(); my $p = fork();
if ($p) { if ($p) {
$wp->do_log("LOG_DEBUG", "Writing PID ($p) to pidfile ($wp->{pidfile})"); $wp->do_log("LOG_DEBUG", "Writing PID ($p) to pidfile ($wp->{pidfile})");
if (open(my $fh, ">", $wp->{pidfile})) { if (open(my $fh, ">", $wp->{pidfile})) {
print $fh "$p" || die "Failed to write pid ($p) to pidfile ".$wp->{pidfile}; print $fh "$p" || die "Failed to write pid ($p) to pidfile ".$wp->{pidfile};
close($fh); close($fh);
} else { } else {
print "Failed to open pidfile ".$wp->{pidfile}.": $!\n"; print "Failed to open pidfile ".$wp->{pidfile}.": $!\n";
}
# Short delay necessary for SystemD to find PID
sleep(1);
exit(0);
} }
$wp->do_log("LOG_DEBUG", "Daemon running"); # Short delay necessary for SystemD to find PID
setpgrp(0, 0); sleep(1);
umask 0; exit(0);
}
$wp->do_log("LOG_DEBUG", "Daemon running");
setpgrp(0, 0);
umask 0;
} }
################################################################################ ################################################################################
@ -477,22 +463,46 @@ if ($wp->{daemon}) {
my $first = 1; my $first = 1;
do { do {
$wp->do_log("LOG_INFO", "Reloading wallpaper") unless ($first); $wp->do_log("LOG_INFO", "Reloading wallpaper") unless ($first);
$wp->run(); $wp->run();
if ($wp->{daemon}) { if ($wp->{daemon}) {
my $normal = "reload wallpaper"; my $normal = "reload wallpaper";
eval { eval {
$SIG{ALRM} = sub { return "$normal" }; $SIG{ALRM} = sub { return "$normal" };
alarm $wp->{delay}; alarm $wp->{delay};
POSIX::pause(); POSIX::pause();
alarm 0; alarm 0;
}; };
$wp->do_log("LOG_WARNING", "Reload failed: $@") if ($@ && $@ !~ quotemeta($normal)); $wp->do_log("LOG_WARNING", "Reload failed: $@") if ($@ && $@ !~ quotemeta($normal));
} }
$first = 0 if ($first); $first = 0 if ($first);
} while ($wp->{daemon}); } while ($wp->{daemon});
# If we made it to here, it was not daemonized. Output errors and exit # If we made it to here, it was not daemonized. Output errors and exit
$wp->do_log("LOG_DEBUG", "Finishing") unless ($wp->{daemon}); $wp->do_log("LOG_DEBUG", "Finishing") unless ($wp->{daemon});
################################################################################
# Signals
################################################################################
# SIGUSR reset the timer, force immediate reload, continue looping
$SIG{USR1} = sub {
alarm 0;
$wp->do_log("LOG_INFO", "Reloading due to SIGUSR1");
};
# SIGTERM reset the timer, clean pid, and allow for the main loop to finish run
$SIG{TERM} = sub {
$wp->do_log("LOG_INFO", "Going down clean due to SIGTERM");
clean($wp);
$wp->{daemon} = 0;
};
# SIGKILL clean pid then exit immediately
$SIG{KILL} = sub {
$wp->do_log("LOG_INFO", "Hard kill with SIGKILL, attempting to remove pidfile");
clean($wp);
exit(0);
};
exit(0); exit(0);

View File

@ -3,7 +3,7 @@
use strict; use strict;
use warnings; use warnings;
our $debug = 1; # For testing, will output configuration and errors if true our $debug = 1; # For testing, will output configuration and errors if true
use AnyEvent::Sway; use AnyEvent::Sway;
our $s = AnyEvent::Sway->new(); our $s = AnyEvent::Sway->new();
@ -13,37 +13,37 @@ die "No outputs detected.\n" unless (scalar(@$o) > 1);
sub usage() sub usage()
{ {
print("$0 [value] [-p|--plus] [-m|--minus] [-a x|--attribute=x] [-d N|--delay=N] print("$0 [value] [-p|--plus] [-m|--minus] [-a x|--attribute=x] [-d N|--delay=N]
Fade the opacity of one or more windows via the Sway IPC interface.\n Fade the opacity of one or more windows via the Sway IPC interface.\n
value The target opacity or offset between 0 (full transparency) and 1 value The target opacity or offset between 0 (full transparency) and 1
(fully opaque). Change will be made in increments of 0.01 with a (fully opaque). Change will be made in increments of 0.01 with a
delay between each.\n delay between each.\n
--attribute=x Attribute of window(s) to fade. --attribute=x Attribute of window(s) to fade.
-a x Default: [title="*"]\n -a x Default: [title="*"]\n
--plus Increases opacity by increment instead of setting it directly --plus Increases opacity by increment instead of setting it directly
-p to that increment.\n -p to that increment.\n
--minus Decreases opacity by increment instead of setting it directly --minus Decreases opacity by increment instead of setting it directly
-m to that increment.\n -m to that increment.\n
--delay=N Change the delay in ms between each percentage point change in --delay=N Change the delay in ms between each percentage point change in
-d N opacity. Default: 20\n -d N opacity. Default: 20\n
--help This menu --help This menu
-h\n"); -h\n");
exit(0); exit(0);
} }
sub set_opacity sub set_opacity
{ {
my $attribute = shift || return "No target or image provided"; my $attribute = shift || return "No target or image provided";
my $target = shift || return "No image provided"; my $target = shift || return "No image provided";
# TODO get fallback from javascript # TODO get fallback from javascript
my $cmd = "output $attribute opacity $target"; my $cmd = "output $attribute opacity $target";
print "Running $cmd\n"; print "Running $cmd\n";
my $ret = $s->message(0,$cmd)->recv; my $ret = $s->message(0,$cmd)->recv;
if ($ret->[0]->{success}) { if ($ret->[0]->{success}) {
print "Success!\n"; print "Success!\n";
return undef; return undef;
} }
return "Failed to run Sway IPC command '$cmd'"; return "Failed to run Sway IPC command '$cmd'";
} }
my @targets; my @targets;
@ -53,123 +53,123 @@ my $crop = 1;
my $path; my $path;
while (my $arg = shift(@ARGV)) { while (my $arg = shift(@ARGV)) {
if ($arg eq '-h' || $arg eq '--help') { if ($arg eq '-h' || $arg eq '--help') {
usage(); usage();
} elsif ($arg =~ m/^\-\-path=?(.+)$/) { } elsif ($arg =~ m/^\-\-path=?(.+)$/) {
die "Redundant argument '$arg'. Wallpaper path already set.\n" if ($path); die "Redundant argument '$arg'. Wallpaper path already set.\n" if ($path);
$path = $1; $path = $1;
} elsif ($arg eq '-p') { } elsif ($arg eq '-p') {
die "Redundant argument '$arg'. Wallpaper path already set.\n" if ($path); die "Redundant argument '$arg'. Wallpaper path already set.\n" if ($path);
$path = shift(@ARGV); $path = shift(@ARGV);
} elsif ($arg =~ m/^\-\-daemon=?(.+)$/) { } elsif ($arg =~ m/^\-\-daemon=?(.+)$/) {
die "Redundant argument '$arg'. Daemon mode already set.\n" if ($daemon); die "Redundant argument '$arg'. Daemon mode already set.\n" if ($daemon);
$delay = $1; $delay = $1;
$daemon = 1; $daemon = 1;
} elsif ($arg eq '-d') { } elsif ($arg eq '-d') {
die "Redundant argument '$arg'. Daemon mode already set.\n" if ($daemon); die "Redundant argument '$arg'. Daemon mode already set.\n" if ($daemon);
if ($ARGV[0] =~ m/^\d+$/) { if ($ARGV[0] =~ m/^\d+$/) {
$delay = shift(@ARGV); $delay = shift(@ARGV);
} }
$daemon = 1; $daemon = 1;
} elsif ($arg eq '--nocrop' || $arg eq '-') { } elsif ($arg eq '--nocrop' || $arg eq '-') {
die "Redundant argument '$arg'. No-crop already set.\n" unless ($crop); die "Redundant argument '$arg'. No-crop already set.\n" unless ($crop);
} else { } else {
push(@targets,$arg); push(@targets,$arg);
} }
} }
die "Invalid rotation delay: $delay" unless ($delay =~ m/^\d+$/); die "Invalid rotation delay: $delay" unless ($delay =~ m/^\d+$/);
if ($path) { if ($path) {
die "Invalid wallpaper path '$path'. Not a directory." unless (-d $path); die "Invalid wallpaper path '$path'. Not a directory." unless (-d $path);
} else { } else {
$path = "$ENV{HOME}/wallpapers"; $path = "$ENV{HOME}/wallpapers";
} }
if (scalar(@targets)) { if (scalar(@targets)) {
my @kept; my @kept;
foreach my $t (@targets) { foreach my $t (@targets) {
my $hit = 0; my $hit = 0;
foreach (@$o) { foreach (@$o) {
if ($_->{name} eq $t) { if ($_->{name} eq $t) {
push(@kept, $t); push(@kept, $t);
$hit++; $hit++;
last; last;
} }
} }
print STDERR "Requested output '$t' not found\n" unless ($hit); print STDERR "Requested output '$t' not found\n" unless ($hit);
} }
die "None of the requested outputs are active" unless (scalar(@kept)); die "None of the requested outputs are active" unless (scalar(@kept));
@targets = @kept; @targets = @kept;
} }
if ($daemon) { if ($daemon) {
my $p = fork(); my $p = fork();
if ($p) { if ($p) {
print "Daemonized as PID: $p\n"; print "Daemonized as PID: $p\n";
exit(0); exit(0);
} }
} }
if ($debug) { if ($debug) {
print "Initial configuration:\n"; print "Initial configuration:\n";
print " Targets: ( " . ( join(" ",@targets) || "All active" ) . " )\n"; print " Targets: ( " . ( join(" ",@targets) || "All active" ) . " )\n";
print " Daemon: $daemon\n"; print " Daemon: $daemon\n";
print " Path: $path\n"; print " Path: $path\n";
} }
my @e; my @e;
do { do {
my @err; my @err;
# Local copy of targets so that it will re-check active every time # Local copy of targets so that it will re-check active every time
my @t = @targets; my @t = @targets;
unless (scalar(@t)) { unless (scalar(@t)) {
@t = get_active(); @t = get_active();
push(@err, "No target outputs") unless (scalar(@t)); push(@err, "No target outputs") unless (scalar(@t));
} }
foreach my $a (@t) { foreach my $a (@t) {
my $image = choose_image($path); my $image = choose_image($path);
if (defined($image)) { if (defined($image)) {
if ( -r "$image" ) { if ( -r "$image" ) {
print "selected $image\n"; print "selected $image\n";
my $cropped; my $cropped;
if ($crop) { if ($crop) {
if ($debug) { if ($debug) {
print "Cropping image for '$a' using '$image'\n"; print "Cropping image for '$a' using '$image'\n";
} }
my ($ow, $oh) = get_size($a); my ($ow, $oh) = get_size($a);
$cropped = crop($image, $ow, $oh); $cropped = crop($image, $ow, $oh);
unless ($cropped) { unless ($cropped) {
push(@err, "Failed to generate cropped image") unless ($cropped); push(@err, "Failed to generate cropped image") unless ($cropped);
next; next;
} }
} else { } else {
$cropped = $image; $cropped = $image;
} }
my $e = set_background($a,$cropped); my $e = set_background($a,$cropped);
push(@err, $e) if (defined($e)); push(@err, $e) if (defined($e));
if ($crop) { if ($crop) {
print "Deleting $cropped\n"; print "Deleting $cropped\n";
#unlink($cropped) || push(@err, "Failed to delete $cropped after setting: $!"); #unlink($cropped) || push(@err, "Failed to delete $cropped after setting: $!");
} }
} else { } else {
push(@err, "$a: Unable to read image $image"); push(@err, "$a: Unable to read image $image");
} }
} else { } else {
push(@err, "$a: Unable to select image from $path"); push(@err, "$a: Unable to select image from $path");
} }
} }
if ($debug && $daemon) { if ($debug && $daemon) {
print STDERR join("\n",@err); print STDERR join("\n",@err);
sleep($delay); sleep($delay);
} else { } else {
@e = @err; @e = @err;
} }
} while ($daemon); } while ($daemon);
if (scalar(@e)) { if (scalar(@e)) {
die "Failure while not running as daemon:\n" . die "Failure while not running as daemon:\n" .
join("\n",@e); join("\n",@e);
} }
exit(0); exit(0);

View File

@ -9,65 +9,65 @@ our $sleepfile = "$ENV{HOME}/.spool/kbd_sleep";
sub readFile sub readFile
{ {
my $file = shift; my $file = shift;
my $ret; my $ret;
if (open(my $fh, '<', $file)) { if (open(my $fh, '<', $file)) {
$ret = readline($fh); $ret = readline($fh);
chomp $ret; chomp $ret;
close($fh); close($fh);
} else { } else {
die "Failed to read $file: $?\n"; die "Failed to read $file: $?\n";
} }
return $ret; return $ret;
} }
sub writeFile sub writeFile
{ {
my ($file, $value) = @_; my ($file, $value) = @_;
if (open(my $fh, '>', $file)) { if (open(my $fh, '>', $file)) {
print $fh $value; print $fh $value;
close($fh); close($fh);
} else { } else {
die "Failed to write $current\n"; die "Failed to write $current\n";
} }
} }
sub sleepFile sub sleepFile
{ {
my $now = readFile($current); my $now = readFile($current);
writeFile($sleepfile,$now); writeFile($sleepfile,$now);
writeFile($current,0); writeFile($current,0);
} }
sub restoreFile sub restoreFile
{ {
unless (-e $sleepfile) { unless (-e $sleepfile) {
die "Missing '$sleepfile'. Must not have slept prior to restore.\n" die "Missing '$sleepfile'. Must not have slept prior to restore.\n"
} }
my $value = readFile($sleepfile); my $value = readFile($sleepfile);
writeFile($current,$value); writeFile($current,$value);
unlink($sleepfile); unlink($sleepfile);
} }
sub rotateFile sub rotateFile
{ {
my $max = readFile($maxfile); my $max = readFile($maxfile);
my $now = readFile($current); my $now = readFile($current);
my $new = (($now+1) % ($max+1)); my $new = (($now+1) % ($max+1));
writeFile($current,$new); writeFile($current,$new);
} }
if (defined($ARGV[0])) { if (defined($ARGV[0])) {
if ($ARGV[0] eq 'sleep') { if ($ARGV[0] eq 'sleep') {
sleepFile(); sleepFile();
exit(0); exit(0);
} elsif ($ARGV[0] eq 'restore') { } elsif ($ARGV[0] eq 'restore') {
restoreFile(); restoreFile();
exit(0); exit(0);
} elsif ($ARGV[0] ne 'rotate') { } elsif ($ARGV[0] ne 'rotate') {
die "Invalid mode '".$ARGV[0]."'. 'rotate', 'sleep', or 'restore'\n"; die "Invalid mode '".$ARGV[0]."'. 'rotate', 'sleep', or 'restore'\n";
} }
} }
rotateFile(); rotateFile();

View File

@ -4,160 +4,170 @@ my $output;
my ($bar, $pretty) = (0, 0); my ($bar, $pretty) = (0, 0);
if ( defined($ARGV[0]) && $ARGV[0] ne '-b' && $ARGV[0] ne '--bar' && $ARGV[0] ne '-p' && $ARGV[0] ne '--pretty' ) { if ( defined($ARGV[0]) && $ARGV[0] ne '-b' && $ARGV[0] ne '--bar' && $ARGV[0] ne '-p' && $ARGV[0] ne '--pretty' ) {
print' print'
pow.pl - Power Status Script pow.pl - Power Status Script
Usage: pow.pl Usage: pow.pl
Prints information about all power devices as JSON. Prints information about all power devices as JSON.
-p --pretty Display as human-readable -p --pretty Display as human-readable
-b --bar Waybar simplified output -b --bar Waybar simplified output
-h --help Display help. This is the only option. -h --help Display help. This is the only option.
'; ';
exit(); exit();
} elsif ($ARGV[0] eq '-b' || $ARGV[0] eq '--bar') { } elsif ($ARGV[0] eq '-b' || $ARGV[0] eq '--bar') {
$bar = 1; $bar = 1;
} elsif ($ARGV[0] eq '-p' || $ARGV[0] eq '--pretty') { } elsif ($ARGV[0] eq '-p' || $ARGV[0] eq '--pretty') {
$pretty = 1; $pretty = 1;
} }
my %battery_total = ( my %battery_total = (
'current' => 0, 'current' => 0,
'max' => 0, 'max' => 0,
'percentage' => 0 'percentage' => 0
); );
my @devices = <"/sys/class/power_supply/*">; my @devices = <"/sys/class/power_supply/*">;
unless (scalar(@devices)) {
print('{"AC":{"Type":"AC","Status":"Plugged-In"}}');
exit();
}
my $nobat = 1;
$output .= "{"; $output .= "{";
foreach (@devices) { foreach (@devices) {
my $path = $_; my $path = $_;
my $name = $_; my $name = $_;
$name =~ s/.*\///; $name =~ s/.*\///;
$output .= '"' . $name . '":{'; $output .= '"' . $name . '":{';
open(my $t,'<',"$_/type"); open(my $t,'<',"$_/type");
my $type = <$t>; my $type = <$t>;
chomp $type; chomp $type;
close $t; close $t;
$output .= '"Type":"' . $type . '"'; $output .= '"Type":"' . $type . '"';
if ($name =~ /BAT[0-9]+/) { if ($name =~ /BAT[0-9]+/) {
open(my $s,'<',"$_/status"); $nobat = 0;
my $status = <$s>; open(my $s,'<',"$_/status");
chomp $status; my $status = <$s>;
$output .= ',"Status":"' . $status . '"'; chomp $status;
$output .= ',"Status":"' . $status . '"';
} else {
open(my $s,'<',"$_/online");
my $status = <$s>;
chomp $status;
if ($status) {
$status = "Plugged-In";
} else { } else {
open(my $s,'<',"$_/online"); $status = "Unplugged";
my $status = <$s>;
chomp $status;
if ($status) {
$status = "Plugged-In";
} else {
$status = "Unplugged";
}
$output .= ',"Status":"' . $status . '"';
} }
close $s; $output .= ',"Status":"' . $status . '"';
if ($name =~ /BAT[0-9]+/) { }
open(my $m,'<',"$_/energy_full"); close $s;
my $max = <$m>; if ($name =~ /BAT[0-9]+/) {
close $m; open(my $m,'<',"$_/energy_full");
chomp $max; my $max = <$m>;
$battery_total{'max'} += $max; close $m;
open(my $c,'<',"$_/energy_now"); chomp $max;
my $current = <$c>; $battery_total{'max'} += $max;
chomp $current; open(my $c,'<',"$_/energy_now");
#$current =~ s/\n//; my $current = <$c>;
$battery_total{'current'} += $current; chomp $current;
close $c; #$current =~ s/\n//;
$output .= ',"Current":"' $battery_total{'current'} += $current;
. $current close $c;
. '","Max":"' $output .= ',"Current":"'
. $max . $current
. '","Percentage":"' . '","Max":"'
. int($current/$max*100) . $max
. '"'; . '","Percentage":"'
} . int($current/$max*100)
$output .= "},"; . '"';
}
$output .= "},";
}
unless ($nobat) {
print('{"AC":{"Type":"AC","Status":"Plugged-In"}}');
exit();
} }
$battery_total{'percentage'} = sprintf("%0d", $battery_total{'percentage'} = sprintf("%0d",
$battery_total{'current'} / $battery_total{'max'} * 100 $battery_total{'current'} / $battery_total{'max'} * 100
); );
$output .= '"Total":{"Current":"' $output .= '"Total":{"Current":"'
. $battery_total{'current'} . $battery_total{'current'}
. '","Max":"' . '","Max":"'
. $battery_total{'max'} . $battery_total{'max'}
. '","Percentage":"' . '","Percentage":"'
. $battery_total{'percentage'} . $battery_total{'percentage'}
. '"}}'; . '"}}';
if ($bar) { if ($bar) {
use JSON::XS; use JSON::XS;
my $json = JSON::XS->new(); my $json = JSON::XS->new();
my $powref = $json->decode($output); my $powref = $json->decode($output);
my $class = 'discharging'; my $class = 'discharging';
$output = ''; $output = '';
if ($powref->{AC}->{Status} eq "Plugged-In") { if ($powref->{AC}->{Status} eq "Plugged-In") {
$class = 'charging'; $class = 'charging';
$output .= ""; $output .= "";
} elsif ($powref->{Total}->{Percentage} <= 10) { } elsif ($powref->{Total}->{Percentage} <= 10) {
$class = 'critical'; $class = 'critical';
$output .= ""; $output .= "";
} elsif ($powref->{Total}->{Percentage} <= 35) { } elsif ($powref->{Total}->{Percentage} <= 35) {
$class = 'low'; $class = 'low';
$output .= ""; $output .= "";
} elsif ($powref->{Total}->{Percentage} <= 60) { } elsif ($powref->{Total}->{Percentage} <= 60) {
$output .= ""; $output .= "";
} elsif ($powref->{Total}->{Percentage} <= 85) { } elsif ($powref->{Total}->{Percentage} <= 85) {
$output .= ""; $output .= "";
} else { } else {
$output .= ""; $output .= "";
} }
$output = '{' $output = '{'
. '"text":"' . $output . '\u200a' . $powref->{Total}->{Percentage} . '%",' . '"text":"' . $output . '\u200a' . $powref->{Total}->{Percentage} . '%",'
. '"icon":"' . $output . '",' . '"icon":"' . $output . '",'
. '"percentage":"' . $powref->{Total}->{Percentage} . '",' . '"percentage":"' . $powref->{Total}->{Percentage} . '",'
. '"tooltip":"' . $class . '",' . '"tooltip":"' . $class . '",'
. '"class":"' . $class . '"' . '"class":"' . $class . '"'
. '}'; . '}';
} elsif ($pretty) { } elsif ($pretty) {
use JSON::XS; use JSON::XS;
my $json = JSON::XS->new(); my $json = JSON::XS->new();
my $powref = $json->decode($output); my $powref = $json->decode($output);
my $total = ''; my $total = '';
$output = "Device Status Percentage\n"; $output = "Device Status Percentage\n";
foreach my $device (keys %{$powref}) { foreach my $device (keys %{$powref}) {
my $status; my $status;
if ($powref->{$device}->{Status} eq "Plugged-In") { if ($powref->{$device}->{Status} eq "Plugged-In") {
$status = ""; $status = "";
} elsif (!defined($powref->{$device}->{Percentage}) || $powref->{$device}->{Percentage} == 0) { } elsif (!defined($powref->{$device}->{Percentage}) || $powref->{$device}->{Percentage} == 0) {
$status = " "; $status = " ";
} elsif ($powref->{$device}->{Percentage} <= 10) { } elsif ($powref->{$device}->{Percentage} <= 10) {
$status = " " . $powref->{$device}->{'Percentage'} . "%"; $status = " " . $powref->{$device}->{'Percentage'} . "%";
} elsif ($powref->{$device}->{Percentage} <= 35) { } elsif ($powref->{$device}->{Percentage} <= 35) {
$status = " " . $powref->{$device}->{'Percentage'} . "%"; $status = " " . $powref->{$device}->{'Percentage'} . "%";
} elsif ($powref->{$device}->{Percentage} <= 60) { } elsif ($powref->{$device}->{Percentage} <= 60) {
$status = " " . $powref->{$device}->{'Percentage'} . "%"; $status = " " . $powref->{$device}->{'Percentage'} . "%";
} elsif ($powref->{$device}->{Percentage} <= 85) { } elsif ($powref->{$device}->{Percentage} <= 85) {
$status = " " . $powref->{$device}->{'Percentage'} . "%"; $status = " " . $powref->{$device}->{'Percentage'} . "%";
} else { } else {
$status = " " . $powref->{$device}->{'Percentage'} . "%"; $status = " " . $powref->{$device}->{'Percentage'} . "%";
} }
if ($device eq 'Total') { if ($device eq 'Total') {
$total .= sprintf("%-24s %-12s", $device, $status); $total .= sprintf("%-24s %-12s", $device, $status);
} else { } else {
#$output .= sprintf("%".length($powref->{$device->{'Type'}})."s (%".length($powref->{$device->{'Type'}})."s): %3d\%\n", $device, $device->{'Type'}, $device->{'Percentage'}); #$output .= sprintf("%".length($powref->{$device->{'Type'}})."s (%".length($powref->{$device->{'Type'}})."s): %3d\%\n", $device, $device->{'Type'}, $device->{'Percentage'});
my $name = ' ('.$powref->{$device}->{'Type'}.')'; my $name = ' ('.$powref->{$device}->{'Type'}.')';
if ((length($device)+length($name)) >= 24) { if ((length($device)+length($name)) >= 24) {
$name = substr($device, 0, (21-length($name))) . '...' . $name; $name = substr($device, 0, (21-length($name))) . '...' . $name;
} else { } else {
$name = substr(($device.$name), 0, 24); $name = substr(($device.$name), 0, 24);
} }
$output .= sprintf("%-24s %-12s %-12s\n", $name, $powref->{$device}->{Status}, $status); $output .= sprintf("%-24s %-12s %-12s\n", $name, $powref->{$device}->{Status}, $status);
} }
} }
$output .= $total; $output .= $total;
} }
print $output . "\n"; print $output . "\n";

View File

@ -3,8 +3,8 @@ Description=Give ownership of backlight to %I
[Service] [Service]
ExecStart=chown %i:%i \ ExecStart=chown %i:%i \
/sys/class/backlight/intel_backlight/brightness \ /sys/class/backlight/intel_backlight/brightness \
/sys/class/leds/tpacpi::kbd_backlight/brightness /sys/class/leds/tpacpi::kbd_backlight/brightness
[Install] [Install]
WantedBy=multi-user.target WantedBy=multi-user.target

View File

@ -12,51 +12,51 @@ my $working = "/tmp/firefox.new";
# Download link as provided by https://www.mozilla.org/$lang/firefox/developer/ # Download link as provided by https://www.mozilla.org/$lang/firefox/developer/
my $url = 'https://download.mozilla.org/?product=firefox-devedition-latest-ssl' my $url = 'https://download.mozilla.org/?product=firefox-devedition-latest-ssl'
. '&os=linux64&lang='.$lang; . '&os=linux64&lang='.$lang;
# Ensure that we can unzip # Ensure that we can unzip
unless (which("bunzip2")) { unless (which("bunzip2")) {
die "Requires bunzip2. Try:\n" die "Requires bunzip2. Try:\n"
. "sudo apt install zutils or your distro's equivalent\n"; . "sudo apt install zutils or your distro's equivalent\n";
} }
# Only understood argument is to not bother verifying the package # Only understood argument is to not bother verifying the package
my ($download_key, $verify) = (0,1); my ($download_key, $verify) = (0,1);
if (defined $ARGV[0]) { if (defined $ARGV[0]) {
if ($ARGV[0] eq '--no-verify') { if ($ARGV[0] eq '--no-verify') {
$verify = 0; $verify = 0;
} else { } else {
die "Didn't understand argument $ARGV[0]\n"; die "Didn't understand argument $ARGV[0]\n";
} }
} }
# If verification is to be done, make sure we have the key # If verification is to be done, make sure we have the key
unless ($verify) { unless ($verify) {
print "Checking for Mozilla GPG key in keyring...\n"; print "Checking for Mozilla GPG key in keyring...\n";
system("gpg --list-keys release\@mozillla.com 2>&1 > /dev/null"); system("gpg --list-keys release\@mozillla.com 2>&1 > /dev/null");
if ($?) { if ($?) {
my $YN = prompt (-in => *STDIN, "You don't currently have " my $YN = prompt (-in => *STDIN, "You don't currently have "
. "Mozilla's GPG key in your keyring.\n" . "Mozilla's GPG key in your keyring.\n"
. "Would you like to install it? If not, installation " . "Would you like to install it? If not, installation "
. "will not be verified. [y/N]: ", . "will not be verified. [y/N]: ",
-single -single
); );
if ($YN eq 'y' || $YN eq 'Y') { if ($YN eq 'y' || $YN eq 'Y') {
$download_key = 1; $download_key = 1;
} else { } else {
$verify = 0; $verify = 0;
}
} }
}
} }
# If a previous download still exists remove it # If a previous download still exists remove it
if ( -e $working ) { if ( -e $working ) {
system("rm -rf $working"); system("rm -rf $working");
if ($?) { if ($?) {
die "Working directory " die "Working directory "
. $working . $working
. "already exists and failed to remove: $!\n"; . "already exists and failed to remove: $!\n";
} }
} }
# Get version currently installed # Get version currently installed
@ -75,13 +75,13 @@ my ($location, $version);
# This redirect will have the version id, so we can use that to determine if a # This redirect will have the version id, so we can use that to determine if a
# new version actually exists # new version actually exists
if ($head->{'_msg'}) { if ($head->{'_msg'}) {
$version = $location = $head->{'_previous'}->{'_headers'}->{'location'}; $version = $location = $head->{'_previous'}->{'_headers'}->{'location'};
$version =~ s/^.*\-([^\-]*)\.tar\.bz2$/$1/; $version =~ s/^.*\-([^\-]*)\.tar\.bz2$/$1/;
if ($version eq $current) { if ($version eq $current) {
die "Current ($current) is the same as New ($version)\n"; die "Current ($current) is the same as New ($version)\n";
} }
} else { } else {
print "unable to find new download\n"; print "unable to find new download\n";
} }
mkdir($working) || die "Couldn't make $working: $!\n"; mkdir($working) || die "Couldn't make $working: $!\n";
@ -90,105 +90,105 @@ mkdir($working) || die "Couldn't make $working: $!\n";
print "Fetching package $location...\n"; print "Fetching package $location...\n";
$mech->get($location); $mech->get($location);
$mech->save_content( $working."/firefox-".$version.".tar.bz2", $mech->save_content( $working."/firefox-".$version.".tar.bz2",
binmode => ':raw', binmode => ':raw',
decoded_by_headers => 1 decoded_by_headers => 1
); );
# If verification is required, get signature as well # If verification is required, get signature as well
if ($verify) { if ($verify) {
$location .= '.asc'; $location .= '.asc';
print "Fetching GPG signature $location...\n"; print "Fetching GPG signature $location...\n";
$mech->get($location); $mech->get($location);
$mech->save_content( $working."/firefox-".$version.".tar.bz2.asc", $mech->save_content( $working."/firefox-".$version.".tar.bz2.asc",
binmode => ':raw', binmode => ':raw',
decoded_by_headers => 1 decoded_by_headers => 1
); );
} }
# If key still needs to be fetched, get it # If key still needs to be fetched, get it
if ($download_key) { if ($download_key) {
$location =~ s/linux-x86_64.*$/KEY/; $location =~ s/linux-x86_64.*$/KEY/;
print "Fetching GPG key $location...\n"; print "Fetching GPG key $location...\n";
$mech->get($location); $mech->get($location);
$mech->save_content( $working."/mozilla.pgp", $mech->save_content( $working."/mozilla.pgp",
binmode => ':raw', binmode => ':raw',
decoded_by_headers => 1 decoded_by_headers => 1
); );
# And install it # And install it
print "Installing Mozilla GPG key in keyring...\n"; print "Installing Mozilla GPG key in keyring...\n";
system("gpg --import $working/mozilla.pgp 2>&1 > /dev/null"); system("gpg --import $working/mozilla.pgp 2>&1 > /dev/null");
if ($?) { if ($?) {
die "Warning: failed to import key. Cannot verify integrity.\n" die "Warning: failed to import key. Cannot verify integrity.\n"
. "Downloaded to " . "Downloaded to "
. $working . $working
. ". You can check and install it to " . ". You can check and install it to "
. $install . $install
. "manually: " . "manually: "
. $! . $!
. "\n"; . "\n";
} }
unlink("$working/mozilla.pgp"); unlink("$working/mozilla.pgp");
} }
# Verify the package # Verify the package
if ($verify) { if ($verify) {
print "Verifying download with Mozilla GPG key...\n"; print "Verifying download with Mozilla GPG key...\n";
system("gpg --verify $working/firefox-$version.tar.bz2.asc"); system("gpg --verify $working/firefox-$version.tar.bz2.asc");
if ($?) { if ($?) {
die "Warning: failed to verify download. Signing failed.\n" die "Warning: failed to verify download. Signing failed.\n"
. "Downloaded to " . "Downloaded to "
. $working . $working
. ". You can check and install it to " . ". You can check and install it to "
. $install . $install
. " manually: " . " manually: "
. $! . $!
. "\n"; . "\n";
} }
} }
# Uncompress # Uncompress
print "Uncompressing download with bunzip2...\n"; print "Uncompressing download with bunzip2...\n";
system("bunzip2 $working/firefox-$version.tar.bz2"); system("bunzip2 $working/firefox-$version.tar.bz2");
if ($?) { if ($?) {
die "Failed to uncompress: $!\n"; die "Failed to uncompress: $!\n";
} }
# Extract # Extract
print "Extracting from TAR archive...\n"; print "Extracting from TAR archive...\n";
system("tar -xf $working/firefox-$version.tar -C $working"); system("tar -xf $working/firefox-$version.tar -C $working");
if ($?) { if ($?) {
die "Failed to extract: $!\n"; die "Failed to extract: $!\n";
} }
# Bin the old backup # Bin the old backup
if (-e "$install/.firefox.old") { if (-e "$install/.firefox.old") {
print "Removing previous backup folder...\n"; print "Removing previous backup folder...\n";
system("rm -rf $install/.firefox.old"); system("rm -rf $install/.firefox.old");
if ($?) { if ($?) {
die "Failed to remove: $!\n"; die "Failed to remove: $!\n";
} }
} }
# Move current to old # Move current to old
print "Backing up currently installed version (" print "Backing up currently installed version ("
. $current . $current
. ") to " . ") to "
. $install . $install
. "/.firefox.old...\n"; . "/.firefox.old...\n";
system("mv $install/firefox $install/.firefox.old"); system("mv $install/firefox $install/.firefox.old");
if ($?) { if ($?) {
die "Failed to move: $!\n"; die "Failed to move: $!\n";
} }
# Move new to current # Move new to current
print "Moving new version to $install for final installation...\n"; print "Moving new version to $install for final installation...\n";
system("mv $working/firefox $install/"); system("mv $working/firefox $install/");
if ($?) { if ($?) {
die "Failed to move: $!\n"; die "Failed to move: $!\n";
} }
# Hurray! # Hurray!
print "Installation of version " print "Installation of version "
. $version . $version
. " complete. You should restart firefox whenever it is convenient.\n"; . " complete. You should restart firefox whenever it is convenient.\n";
exit(); exit();

View File

@ -8,21 +8,21 @@ int main(int argc, char*argv[])
{ {
int pid; int pid;
if (argc <= 1) { if (argc <= 1) {
printf("No PID given\n"); printf("No PID given\n");
return(1); return(1);
} else if (argc > 2) { } else if (argc > 2) {
printf("Too many arguments\n"); printf("Too many arguments\n");
return(1); return(1);
} else { } else {
long val; long val;
char *next; char *next;
val = strtol(argv[1], &next, 10); val = strtol(argv[1], &next, 10);
if ((next == argv[1]) || (*next != '\0')) { if ((next == argv[1]) || (*next != '\0')) {
printf("Argument '%s' is not a number\n", argv[1]); printf("Argument '%s' is not a number\n", argv[1]);
return(1); return(1);
} else { } else {
pid = val; pid = val;
} }
} }
kill(pid, SIGUSR1); kill(pid, SIGUSR1);
return(0); return(0);

View File

@ -2,31 +2,31 @@
ARG=$1 ARG=$1
if [[ $ARG == '' ]]; then if [[ $ARG == '' ]]; then
ARG="toggle" ARG="toggle"
fi fi
if [[ $ARG == 'toggle' ]]; then if [[ $ARG == 'toggle' ]]; then
if [[ -e '/home/jpm/.config/waybar/.hidden' ]]; then if [[ -e '/home/jpm/.config/waybar/.hidden' ]]; then
rm '/home/jpm/.config/waybar/.hidden'; rm '/home/jpm/.config/waybar/.hidden';
else else
touch '/home/jpm/.config/waybar/.hidden'; touch '/home/jpm/.config/waybar/.hidden';
fi fi
elif [[ $ARG == 'hide' ]]; then elif [[ $ARG == 'hide' ]]; then
if [[ ! -e '/home/jpm/.config/waybar/.hidden' ]]; then if [[ ! -e '/home/jpm/.config/waybar/.hidden' ]]; then
touch '/home/jpm/.config/waybar/.hidden'; touch '/home/jpm/.config/waybar/.hidden';
else else
echo 'Already hidden. You may need to use the "invert" option if action is reversed'; echo 'Already hidden. You may need to use the "invert" option if action is reversed';
exit; exit;
fi fi
elif [[ $ARG == 'show' ]]; then elif [[ $ARG == 'show' ]]; then
if [[ -e '/home/jpm/.config/waybar/.hidden' ]]; then if [[ -e '/home/jpm/.config/waybar/.hidden' ]]; then
rm '/home/jpm/.config/waybar/.hidden'; rm '/home/jpm/.config/waybar/.hidden';
else else
echo 'Already shown. You may need to use the "invert" option if action is reversed'; echo 'Already shown. You may need to use the "invert" option if action is reversed';
exit; exit;
fi fi
elif [[ $ARG != 'invert' ]]; then elif [[ $ARG != 'invert' ]]; then
echo "Invalid argument"; echo "Invalid argument";
fi fi
/home/jpm/scripts/waybar/toggle `pgrep waybar` /home/jpm/scripts/waybar/toggle `pgrep waybar`

View File

@ -3,7 +3,7 @@
RUNNING=$(pgrep pavucontrol) RUNNING=$(pgrep pavucontrol)
if [ "$RUNNING" ]; then if [ "$RUNNING" ]; then
kill $RUNNING 2&>1 /dev/null kill $RUNNING 2&>1 /dev/null
else else
/usr/bin/pavucontrol /usr/bin/pavucontrol
fi fi

View File

@ -1,7 +1,7 @@
#!/bin/bash #!/bin/bash
if [ "$(pgrep -c htop)" -gt 0 ]; then if [ "$(pgrep -c htop)" -gt 0 ]; then
pkill htop pkill htop
else else
/usr/bin/uxterm -e htop /usr/bin/uxterm -e htop
fi fi

View File

@ -1,36 +1,36 @@
#!/bin/bash #!/bin/bash
if [ "$1" == 'bar' ]; then if [ "$1" == 'bar' ]; then
if [ ! -e ${HOME}/.spool/apt-upgradeable ]; then if [ ! -e ${HOME}/.spool/apt-upgradeable ]; then
sudo apt update >/dev/null 2>/dev/null sudo apt update >/dev/null 2>/dev/null
COUNT=`apt list --upgradable 2> /dev/null | wc -l` COUNT=`apt list --upgradable 2> /dev/null | wc -l`
let COUNT-- let COUNT--
echo $COUNT > /home/jpm/.spool/apt-upgradeable echo $COUNT > /home/jpm/.spool/apt-upgradeable
else else
COUNT=`cat ${HOME}/.spool/apt-upgradeable` COUNT=`cat ${HOME}/.spool/apt-upgradeable`
fi fi
if [ $COUNT -eq 0 ]; then if [ $COUNT -eq 0 ]; then
echo '{"text": "🗹", "tooltip": "Up-to-date", "class": "up-to-date"}' echo '{"text": "🗹", "tooltip": "Up-to-date", "class": "up-to-date"}'
else else
echo '{"text": "⭳'$COUNT'", "tooltip": "'$COUNT' updates available (click to download)", "class": "updateable"}' echo '{"text": "⭳'$COUNT'", "tooltip": "'$COUNT' updates available (click to download)", "class": "updateable"}'
fi fi
elif [ "$SUDO_USER" != '' ]; then elif [ "$SUDO_USER" != '' ]; then
echo "Don't run with sudo. Run normally, but with a sudoer user" echo "Don't run with sudo. Run normally, but with a sudoer user"
elif [ $UID -eq 0 ]; then elif [ $UID -eq 0 ]; then
echo "Don't run as root. Run normally, but with a sudoer user" echo "Don't run as root. Run normally, but with a sudoer user"
elif [ "$1" == 'upgrade' ]; then elif [ "$1" == 'upgrade' ]; then
/usr/bin/uxterm -e "sudo apt-get update && sudo apt-get full-upgrade -y && sudo apt-get autoremove -y && sudo apt-get clean -y && exit" /usr/bin/uxterm -e "sudo apt-get update && sudo apt-get full-upgrade -y && sudo apt-get autoremove -y && sudo apt-get clean -y && exit"
COUNT=`apt list --upgradable 2> /dev/null | wc -l` COUNT=`apt list --upgradable 2> /dev/null | wc -l`
let COUNT-- let COUNT--
echo $COUNT > /home/jpm/.spool/apt-upgradeable echo $COUNT > /home/jpm/.spool/apt-upgradeable
if [ -e /var/run/reboot-required ]; then if [ -e /var/run/reboot-required ]; then
grep -B1 -A4 upgrade /var/log/apt/history.log | tail -n 6 | swaynag --config=${HOME}/.dotfiles/sway/swaynag --edge=bottom --message="New packages require restart" --button="Restart Now" "sudo systemctl reboot" --dismiss-button="Later" --detailed-message --detailed-button "Show/Hide Upgrade Details" grep -B1 -A4 upgrade /var/log/apt/history.log | tail -n 6 | swaynag --config=${HOME}/.dotfiles/sway/swaynag --edge=bottom --message="New packages require restart" --button="Restart Now" "sudo systemctl reboot" --dismiss-button="Later" --detailed-message --detailed-button "Show/Hide Upgrade Details"
fi fi
elif [ "$1" == 'update' ]; then elif [ "$1" == 'update' ]; then
sudo apt update >/dev/null 2>/dev/null sudo apt update >/dev/null 2>/dev/null
COUNT=`apt list --upgradable 2> /dev/null | wc -l` COUNT=`apt list --upgradable 2> /dev/null | wc -l`
let COUNT-- let COUNT--
echo $COUNT > /home/jpm/.spool/apt-upgradeable echo $COUNT > /home/jpm/.spool/apt-upgradeable
else else
echo "Missing argument: update, upgrade, bar" echo "Missing argument: update, upgrade, bar"
fi fi

View File

@ -1,7 +1,7 @@
#!/bin/bash #!/bin/bash
notify-send -t 0 Disks \ notify-send -t 0 Disks \
"$(lsblk -o NAME,SIZE,FSUSE%,MOUNTPOINT | grep -vP '^loop' | \ "$(lsblk -o NAME,SIZE,FSUSE%,MOUNTPOINT | grep -vP '^loop' | \
sed 's/MOUNTPOINT/MOUNT/' | sed -e 's/│ └─/+---/' | \ sed 's/MOUNTPOINT/MOUNT/' | sed -e 's/│ └─/+---/' | \
sed -e 's/ └─/+---/' | sed -e 's/├─/+-/' | sed -e 's/└─/+-/' | \ sed -e 's/ └─/+---/' | sed -e 's/├─/+-/' | sed -e 's/└─/+-/' | \
awk {'printf "%-20s %-7s %- 6s %-7s\n", $1, $2, $3, $4'})" awk {'printf "%-20s %-7s %- 6s %-7s\n", $1, $2, $3, $4'})"

View File

@ -2,37 +2,37 @@
COUNT=0 COUNT=0
function count() { function count() {
RESULTS="`rpm-ostree upgrade --check 2> /dev/null | grep Diff: | sed 's/.*\([0-9][0-9]*\).*/\1/'`" RESULTS="`rpm-ostree upgrade --check 2> /dev/null | grep Diff: | sed 's/.*\([0-9][0-9]*\).*/\1/'`"
COUNT=0 COUNT=0
for i in $RESULTS; do for i in $RESULTS; do
i=`echo $i | sed 's/;//'` i=`echo $i | sed 's/;//'`
let COUNT=$COUNT+$i let COUNT=$COUNT+$i
done done
} }
if [ "$1" == 'bar' ]; then if [ "$1" == 'bar' ]; then
if [ ! -e ${HOME}/.spool/ostree-upgradeable ]; then if [ ! -e ${HOME}/.spool/ostree-upgradeable ]; then
count count
echo $COUNT > /home/jpm/.spool/ostree-upgradeable echo $COUNT > /home/jpm/.spool/ostree-upgradeable
else else
COUNT=`cat ${HOME}/.spool/ostree-upgradeable` COUNT=`cat ${HOME}/.spool/ostree-upgradeable`
fi fi
if [ $COUNT -eq 0 ]; then if [ $COUNT -eq 0 ]; then
echo '{"text": "🗹", "tooltip": "Up-to-date", "class": "up-to-date"}' echo '{"text": "🗹", "tooltip": "Up-to-date", "class": "up-to-date"}'
else else
echo '{"text": "⭳'$COUNT'", "tooltip": "'$COUNT' updates available (click to download)", "class": "updateable"}' echo '{"text": "⭳'$COUNT'", "tooltip": "'$COUNT' updates available (click to download)", "class": "updateable"}'
fi fi
elif [ "$SUDO_USER" != '' ]; then elif [ "$SUDO_USER" != '' ]; then
echo "Don't run with sudo. Run normally, but with a sudoer user" echo "Don't run with sudo. Run normally, but with a sudoer user"
elif [ $UID -eq 0 ]; then elif [ $UID -eq 0 ]; then
echo "Don't run as root. Run normally, but with a sudoer user" echo "Don't run as root. Run normally, but with a sudoer user"
elif [ "$1" == 'upgrade' ]; then elif [ "$1" == 'upgrade' ]; then
/usr/bin/uxterm -e "rpm-ostree upgrade" /usr/bin/uxterm -e "rpm-ostree upgrade"
count count
echo $COUNT > /home/jpm/.spool/ostree-upgradeable echo $COUNT > /home/jpm/.spool/ostree-upgradeable
elif [ "$1" == 'update' ]; then elif [ "$1" == 'update' ]; then
count count
echo $COUNT > /home/jpm/.spool/ostree-upgradeable echo $COUNT > /home/jpm/.spool/ostree-upgradeable
else else
echo "Missing argument: update, upgrade, bar" echo "Missing argument: update, upgrade, bar"
fi fi

View File

@ -1,60 +1,66 @@
#!/bin/bash #!/bin/bash
PID=$(pgrep gammastep) PID=$(pgrep gammastep)
RUNNING=`cat $HOME/.spool/gammastep.status` RUNNING=0
if [ -e $HOME/.spool/gammastep.status ]; then
RUNNING=`cat $HOME/.spool/gammastep.status`
fi
ACTION=$1 ACTION=$1
if [[ "$1" == '' ]]; then if [[ "$1" == '' ]]; then
ACTION='bar' ACTION='bar'
fi fi
if [[ $ACTION == 'bar' ]]; then if [[ $ACTION == 'bar' ]]; then
: :
elif [[ $ACTION == 'toggle' ]]; then elif [[ $ACTION == 'toggle' ]]; then
if [ "$PID" ]; then if [ "$PID" ]; then
kill -SIGUSR1 $PID kill -SIGUSR1 $PID
else else
echo 'Gammastep is not running' echo 'Gammastep is not running'
fi fi
elif [[ $ACTION == 'start' ]]; then elif [[ $ACTION == 'start' ]]; then
if [ "$PID" ]; then if [ "$PID" ]; then
echo 'Gammastep is already running' echo 'Gammastep is already running'
else else
$HOME/scripts/sway/gammastep.pl $HOME/scripts/sway/gammastep.pl
fi fi
elif [[ $ACTION == 'stop' ]]; then elif [[ $ACTION == 'stop' ]]; then
if [ "$PID" ]; then if [ "$PID" ]; then
kill $PID kill $PID
else else
echo 'Gammastep is not running' echo 'Gammastep is not running'
fi fi
elif [[ $ACTION == 'enable' ]]; then elif [[ $ACTION == 'enable' ]]; then
if [ $PID ]; then if [ $PID ]; then
if [ $RUNNING ]; then if [ $RUNNING ]; then
echo 'Already enabled' echo 'Already enabled'
else
kill -SIGUSR1 $PID
fi
else else
echo 'Gammastep is not running' kill -SIGUSR1 $PID
fi fi
else
echo 'Gammastep is not running'
fi
elif [[ $ACTION == 'disable' ]]; then elif [[ $ACTION == 'disable' ]]; then
if [ $PID ]; then if [ $PID ]; then
if [ $RUNNING ]; then if [ $RUNNING ]; then
kill -SIGUSR1 $PID kill -SIGUSR1 $PID
else
echo 'Already disabled'
fi
else else
echo 'Gammastep in not running' echo 'Already disabled'
fi fi
else
echo 'Gammastep in not running'
fi
else else
echo "Invalid argument '$ACTION'. Use 'bar', 'toggle', 'start', 'stop', 'enable', 'disable'." echo "Invalid argument '$ACTION'. Use 'bar', 'toggle', 'start', 'stop', 'enable', 'disable'."
fi fi
RUNNING=`cat $HOME/.spool/gammastep.status` RUNNING=0
if [ "$RUNNING" ]; then if [ -e $HOME/.spool/gammastep.status ]; then
echo '{"text":"ɣ","icon":"ɣ","tooltip":"Disable Gammastep","class":"enabled"}' RUNNING=`cat $HOME/.spool/gammastep.status`
else fi
echo '{"text":"ɣ","icon":"ɣ","tooltip":"Enable Gammastep","class":"disabled"}' if [ "$RUNNING" ]; then
echo '{"text":"ɣ","icon":"ɣ","tooltip":"Disable Gammastep","class":"enabled"}'
else
echo '{"text":"ɣ","icon":"ɣ","tooltip":"Enable Gammastep","class":"disabled"}'
fi fi

View File

@ -2,23 +2,23 @@
FILE="$HOME/.spool/hibernate_inhibitor" FILE="$HOME/.spool/hibernate_inhibitor"
if [ -e $FILE ]; then if [ -e $FILE ]; then
INHIBITED=1 INHIBITED=1
else else
INHIBITED=0 INHIBITED=0
fi fi
if [ -z $1 ] || [[ "$1" == "bar" ]]; then if [ -z $1 ] || [[ "$1" == "bar" ]]; then
if [[ $INHIBITED == 1 ]]; then if [[ $INHIBITED == 1 ]]; then
echo '{"text":"☕","icon":"☕","tooltip":"Allow hibernation","class":"enabled"}' echo '{"text":"☕","icon":"☕","tooltip":"Allow hibernation","class":"enabled"}'
else else
echo '{"text":"💤","icon":"💤","tooltip":"Prevent hibernation","class":"disabled"}' echo '{"text":"💤","icon":"💤","tooltip":"Prevent hibernation","class":"disabled"}'
fi fi
elif [[ "$1" == "toggle" ]]; then elif [[ "$1" == "toggle" ]]; then
if [[ $INHIBITED == "1" ]]; then if [[ $INHIBITED == "1" ]]; then
rm $FILE rm $FILE
else else
touch $FILE touch $FILE
fi fi
else else
echo "Invalid argumuent $1" echo "Invalid argumuent $1"
fi fi

View File

@ -2,9 +2,9 @@
FILE=/home/jpm/.spool/onscreen-keyboard FILE=/home/jpm/.spool/onscreen-keyboard
if [ -f $FILE ]; then if [ -f $FILE ]; then
rm $FILE rm $FILE
busctl call --user sm.puri.OSK0 /sm/puri/OSK0 sm.puri.OSK0 SetVisible b false busctl call --user sm.puri.OSK0 /sm/puri/OSK0 sm.puri.OSK0 SetVisible b false
else else
touch $FILE touch $FILE
busctl call --user sm.puri.OSK0 /sm/puri/OSK0 sm.puri.OSK0 SetVisible b true busctl call --user sm.puri.OSK0 /sm/puri/OSK0 sm.puri.OSK0 SetVisible b true
fi fi

View File

@ -1,5 +1,5 @@
#!/bin/bash #!/bin/bash
notify-send -t 0 'Memory Usage' "`free -h | \ notify-send -t 0 'Memory Usage' "`free -h | \
awk '{printf(\"%6s %6s %6s %6s\n\", $1, $2, $3, $4)}' | \ awk '{printf(\"%6s %6s %6s %6s\n\", $1, $2, $3, $4)}' | \
sed -r 's/(.*) shared$/ \1/'`" sed -r 's/(.*) shared$/ \1/'`"

View File

@ -3,8 +3,8 @@
RUNNING=$(pgrep ncmpcpp) RUNNING=$(pgrep ncmpcpp)
if [ "$RUNNING" ]; then if [ "$RUNNING" ]; then
kill $RUNNING 2&>1 /dev/null kill $RUNNING 2&>1 /dev/null
else else
echo "starting" echo "starting"
/usr/bin/xterm -e /usr/bin/ncmpcpp /usr/bin/xterm -e /usr/bin/ncmpcpp
fi fi

View File

@ -3,7 +3,7 @@
RUNNING=$(pgrep todotxt-machine) RUNNING=$(pgrep todotxt-machine)
if [ "$RUNNING" ]; then if [ "$RUNNING" ]; then
kill $RUNNING 2&>1 /dev/null kill $RUNNING 2&>1 /dev/null
else else
/usr/bin/xterm -e "/home/jpm/.local/bin/todotxt-machine /home/jpm/nextcloud/phone/todo.txt" /usr/bin/xterm -e "/home/jpm/.local/bin/todotxt-machine /home/jpm/nextcloud/phone/todo.txt"
fi fi

View File

@ -5,29 +5,29 @@ use warnings;
my $cmd = 'bar'; my $cmd = 'bar';
if (defined($ARGV[0])) { if (defined($ARGV[0])) {
$cmd = $ARGV[0]; $cmd = $ARGV[0];
} }
my $url = "https://john.me.tz/weather/weather.json"; my $url = "https://john.me.tz/weather/weather.json";
my %icons = ( my %icons = (
'01d' => "☀", '01d' => "☀",
'01n' => "☾", '01n' => "☾",
'02d' => "☁", '02d' => "☁",
'02n' => "☁", '02n' => "☁",
'03d' => "☁", '03d' => "☁",
'03n' => "☁", '03n' => "☁",
'04d' => "☁", '04d' => "☁",
'04n' => "☁", '04n' => "☁",
'10d' => "🌧", '10d' => "🌧",
'10n' => "🌧", '10n' => "🌧",
); );
use LWP::UserAgent; use LWP::UserAgent;
my $ua = LWP::UserAgent->new(); my $ua = LWP::UserAgent->new();
my $ret = $ua->get($url); my $ret = $ua->get($url);
unless (defined($ret->{_rc}) && $ret->{_rc} == 200) { unless (defined($ret->{_rc}) && $ret->{_rc} == 200) {
die "Failed to fetch $url"; die "Failed to fetch $url";
} }
use JSON::XS; use JSON::XS;
@ -36,12 +36,12 @@ my $json = JSON::XS->new();
my $ref = $json->decode($ret->{_content}); my $ref = $json->decode($ret->{_content});
if ($cmd eq 'bar') { if ($cmd eq 'bar') {
my $temp = $ref->{current}->{temp} - 273.15; my $temp = $ref->{current}->{temp} - 273.15;
my $icon = $ref->{current}->{weather}->[0]->{icon}; my $icon = $ref->{current}->{weather}->[0]->{icon};
printf("<span font='Anonymous Pro 18'>%s</span>%.1f%s", $icons{$icon}, ${temp}, "°C"); printf("<span font='Anonymous Pro 18'>%s</span>%.1f%s", $icons{$icon}, ${temp}, "°C");
} elsif ($cmd eq 'notify') { } elsif ($cmd eq 'notify') {
`notify-send weather TODO`; `notify-send weather TODO`;
} else { } else {
die "Invalid command\n"; die "Invalid command\n";
} }

View File

@ -1,22 +1,14 @@
#!/bin/bash #!/bin/bash
swaymsg -t get_tree | swaymsg -t get_tree |
jq -r '.nodes[].nodes[] | if .nodes then [recurse(.nodes[])] else [] end + .floating_nodes | .[] | select(.nodes==[]) | if .app_id then ((.app_id | tostring) + " -- " + .name) else .name end' | jq -r '.nodes[].nodes[] | if .nodes then [recurse(.nodes[])] else [] end + .floating_nodes | .[] | select(.nodes==[]) | if .app_id then ((.app_id | tostring) + " -- " + .name) else .name end' |
grep -v __i3_scratch | grep -v __i3_scratch |
sed -e 's/^.*\-\- \(.*\)$/\1/' | sed -e 's/^.*\-\- \(.*\)$/\1/' |
sed -e 's/^\(.*\) [—-] .*$/\1/'| sed -e 's/^\(.*\) [—-] .*$/\1/'|
sed -e 's/^\([0-9]*\)\t*\(.*\)/\2 \1/' | sed -e 's/^\([0-9]*\)\t*\(.*\)/\2 \1/' |
<<<<<<< HEAD wofi -s $HOME/.dotfiles/wofi/style.css -c \
wofi -s $HOME/.dotfiles/wofi/style.css -c \ $HOME/.dotfiles/wofi/sidebar -d | {
$HOME/.dotfiles/wofi/sidebar -d | { read -r
read -r id=`echo $REPLY | rev | cut -d' ' -f1 | rev`
id=`echo $REPLY | rev | cut -d' ' -f1 | rev` swaymsg "[con_id=$id]" focus
swaymsg "[con_id=$id]" focus }
} echo $id $REPLY
echo $id $REPLY
=======
wofi -I -s /home/jpm/.dotfiles/wofi/style.css -c \
$HOME/.dotfiles/wofi/sidebar --show dmenu | {
read -r id name
swaymsg "[con_id=$id]" focus
}
>>>>>>> master

View File

@ -4,7 +4,7 @@ WOFI=$(pgrep -xc wofi | cut -b 1)
echo $WOFI echo $WOFI
if [[ "$WOFI" -eq "0" ]]; then if [[ "$WOFI" -eq "0" ]]; then
wofi -s /home/jpm/.dotfiles/wofi/style.css -c $HOME/.dotfiles/wofi/sidebar --show drun -I wofi -s /home/jpm/.dotfiles/wofi/style.css -c $HOME/.dotfiles/wofi/sidebar --show drun -I
else else
killall wofi 2&>1 /dev/null killall wofi 2&>1 /dev/null
fi fi

View File

@ -10,11 +10,11 @@ DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
FIELDS=SSID,SECURITY FIELDS=SSID,SECURITY
if [ -r "$DIR/config" ]; then if [ -r "$DIR/config" ]; then
source "$DIR/config" source "$DIR/config"
elif [ -r "$HOME/.dotfiles/wofi/wifi" ]; then elif [ -r "$HOME/.dotfiles/wofi/wifi" ]; then
source "$HOME/.dotfiles/wofi/wifi" source "$HOME/.dotfiles/wofi/wifi"
else else
echo "WARNING: config file not found! Using default values." echo "WARNING: config file not found! Using default values."
fi fi
LIST=$(nmcli --fields "$FIELDS" device wifi list | sed '/^--/d') LIST=$(nmcli --fields "$FIELDS" device wifi list | sed '/^--/d')
@ -26,13 +26,13 @@ CONSTATE=$(nmcli -fields WIFI g)
CURRSSID=$(LANGUAGE=C nmcli -t -f active,ssid dev wifi | awk -F: '$1 ~ /^yes/ {print $2}') CURRSSID=$(LANGUAGE=C nmcli -t -f active,ssid dev wifi | awk -F: '$1 ~ /^yes/ {print $2}')
if [[ ! -z $CURRSSID ]]; then if [[ ! -z $CURRSSID ]]; then
HIGHLINE=$(echo "$(echo "$LIST" | awk -F "[ ]{2,}" '{print $1}' | grep -Fxn -m 1 "$CURRSSID" | awk -F ":" '{print $1}') + 1" | bc ) HIGHLINE=$(echo "$(echo "$LIST" | awk -F "[ ]{2,}" '{print $1}' | grep -Fxn -m 1 "$CURRSSID" | awk -F ":" '{print $1}') + 1" | bc )
fi fi
if [[ "$CONSTATE" =~ "enabled" ]]; then if [[ "$CONSTATE" =~ "enabled" ]]; then
TOGGLE="toggle off" TOGGLE="toggle off"
elif [[ "$CONSTATE" =~ "disabled" ]]; then elif [[ "$CONSTATE" =~ "disabled" ]]; then
TOGGLE="toggle on" TOGGLE="toggle on"
fi fi
CHENTRY=$(echo -e "$TOGGLE\nmanual\n$LIST" | uniq -u | wofi -s $HOME/.dotfiles/wofi/style.css -i -d --prompt "Wi-Fi SSID: " -c $HOME/.dotfiles/wofi/sidebar) CHENTRY=$(echo -e "$TOGGLE\nmanual\n$LIST" | uniq -u | wofi -s $HOME/.dotfiles/wofi/style.css -i -d --prompt "Wi-Fi SSID: " -c $HOME/.dotfiles/wofi/sidebar)
@ -45,42 +45,42 @@ CHSSID=$(echo "$CHENTRY" | sed 's/\s\{2,\}/\|/g' | awk -F "|" '{print $1}')
# If the user inputs "manual" as their SSID in the start window, it will bring them to this screen # If the user inputs "manual" as their SSID in the start window, it will bring them to this screen
if [ "$CHENTRY" = "manual" ] ; then if [ "$CHENTRY" = "manual" ] ; then
# Manual entry of the SSID and password (if appplicable) # Manual entry of the SSID and password (if appplicable)
MSSID=$(echo "enter the SSID of the network (SSID,password)" | wofi -s $HOME/.dotfiles/wofi/style.css -d "Manual Entry: " -c $HOME/.dotfiles/wofi/sidebar) MSSID=$(echo "enter the SSID of the network (SSID,password)" | wofi -s $HOME/.dotfiles/wofi/style.css -d "Manual Entry: " -c $HOME/.dotfiles/wofi/sidebar)
# Separating the password from the entered string # Separating the password from the entered string
MPASS=$(echo "$MSSID" | awk -F "," '{print $2}') MPASS=$(echo "$MSSID" | awk -F "," '{print $2}')
#echo "$MSSID" #echo "$MSSID"
#echo "$MPASS" #echo "$MPASS"
# If the user entered a manual password, then use the password nmcli command # If the user entered a manual password, then use the password nmcli command
if [ "$MPASS" = "" ]; then if [ "$MPASS" = "" ]; then
nmcli dev wifi con "$MSSID" nmcli dev wifi con "$MSSID"
else else
nmcli dev wifi con "$MSSID" password "$MPASS" nmcli dev wifi con "$MSSID" password "$MPASS"
fi fi
elif [ "$CHENTRY" = "toggle on" ]; then elif [ "$CHENTRY" = "toggle on" ]; then
nmcli radio wifi on nmcli radio wifi on
elif [ "$CHENTRY" = "toggle off" ]; then elif [ "$CHENTRY" = "toggle off" ]; then
nmcli radio wifi off nmcli radio wifi off
else else
# If the connection is already in use, then this will still be able to get the SSID # If the connection is already in use, then this will still be able to get the SSID
if [ "$CHSSID" = "*" ]; then if [ "$CHSSID" = "*" ]; then
CHSSID=$(echo "$CHENTRY" | sed 's/\s\{2,\}/\|/g' | awk -F "|" '{print $3}') CHSSID=$(echo "$CHENTRY" | sed 's/\s\{2,\}/\|/g' | awk -F "|" '{print $3}')
fi fi
# Parses the list of preconfigured connections to see if it already contains the chosen SSID. This speeds up the connection process # Parses the list of preconfigured connections to see if it already contains the chosen SSID. This speeds up the connection process
if [[ $(echo "$KNOWNCON" | grep "$CHSSID") = "$CHSSID" ]]; then if [[ $(echo "$KNOWNCON" | grep "$CHSSID") = "$CHSSID" ]]; then
nmcli con up "$CHSSID" nmcli con up "$CHSSID"
else else
if [[ "$CHENTRY" =~ "WPA2" ]] || [[ "$CHENTRY" =~ "WEP" ]]; then if [[ "$CHENTRY" =~ "WPA2" ]] || [[ "$CHENTRY" =~ "WEP" ]]; then
WIFIPASS=$(echo "if connection is stored, hit enter" | wofi -s $HOME/.dotfiles/wofi/style.css -P -d --prompt "password" -c $HOME/.dotfiles/wofi/sidebar) WIFIPASS=$(echo "if connection is stored, hit enter" | wofi -s $HOME/.dotfiles/wofi/style.css -P -d --prompt "password" -c $HOME/.dotfiles/wofi/sidebar)
fi fi
nmcli dev wifi con "$CHSSID" password "$WIFIPASS" nmcli dev wifi con "$CHSSID" password "$WIFIPASS"
fi fi
fi fi