I made a small program to display a X::Osd bar displaying my volume
percentage (on GNU/Linux box). It works, but I'd like to have any suggestions or
corrections about it (i'm not confident about my skills i suppose).
So, here is how it works:
1) Have a named pipe defined at $OSD_VOLUME environmental variable.
2) Run the program in the background.
3) When echoing 'up', 'down' or 'toggle' in the named pipe, it raises,
lowers or toggles mute state using amixer program.
I have the following questions:
1) Is the code OK? (I mean is there anything I should avoid or add?)
2) Is there a better solution to make a perl program and a shell script
and/or window manager communicate? (I really didn't love that named
pipe solution, but I didn't know of anything else)
Enough words, here is the code:
#!/usr/bin/perl
use strict;
use warnings;
# extra modules
use X::Osd;
# create osd bar (two output lines)
my $osd = X::Osd->new(2);
# osd bar properties
$osd->set_font("-*-terminus-bold-*-*-*-18-*-*-*-*-*-*-*");
$osd->set_shadow_offset(1);
$osd->set_pos(XOSD_bottom);
$osd->set_align(XOSD_center);
$osd->set_horizontal_offset(0);
$osd->set_vertical_offset(30);
$osd->set_timeout(5);
# locate (and if missing create) named pipe
my $fifo_file = (defined $ENV{OSD_VOLUME}) ? $ENV{OSD_VOLUME} :
glob("~/.osd-volume.fifo");
unless (-p $fifo_file) {
# delete non-named pipe file (risky)
unlink $fifo_file or die "cannot remove $fifo_file: $!";
# create the named pipe
require POSIX;
POSIX::mkfifo($fifo_file, 0600) or die "cannot mkfifo $fifo_file: $!";
}
# open named pipe
open(FIFO, "+<", $fifo_file) or die "cannot open $fifo_file: $!";
# constantly read from it
my $vol;
while (chomp(my $fifo_line = <FIFO>)) {
if ($fifo_line eq 'up') {
$vol = '3%+';
} elsif ($fifo_line eq 'down') {
$vol = '3%-';
} elsif ($fifo_line eq 'toggle') {
$vol = 'toggle';
} else {
die "invalid input: $fifo_line";
}
# set new volume value and read the output
my $amixer = `amixer sset Master,0 $vol` or die "error: $!";
# get new volume value
$vol = $1 if ($amixer =~ m/(\d{1,3})(?:%)/);
# change output color if volume is muted
if ($amixer =~ m/\[off\]/) {
$osd->set_colour("#DD0000");
} else {
$osd->set_colour("#1E90FF");
}
# print volume bar
$osd->string(0, 'Master Volume:'.$vol.'%');
$osd->percentage(1, $vol);
}
# close pipe and exit (with error)
# (impossible to get here)
close(FIFO);
exit(0);
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/