#!/usr/bin/perl

use strict;
use warnings;
use Gtk2 -init;
use Gtk2::Notify -init, "fdpowermon";

my $icon;
my $theme;
my %themes;
my $fnormal = 0;
my @warnings = (10, 5, 1);
my $dir = "charging";
my $lastwarning = 100;

=head1 NAME

fdpowermon - add a battery level icon to a freedesktop.org-compliant system tray

=head1 SYNOPSIS

fdpowermon

=head1 DESCRIPTION

This program allows one to display a "battery level" icon in any
freedesktop.org-compliant status area. It can be themed through either a
plain-text configuration file (F</etc/fdpowermon/theme.cfg> or
F<$HOME/.config/fdpowermon/theme.cfg>), or through a short perl script
(F</etc/fdpowermon/theme.pl> or F<$HOME/.config/fdpowermon/theme.pl>).

The former is easier, as it doesn't require any scripting; and indeed
the default configuration is an example of such a plain-text theme.
However, the latter allows for more flexibility, as one can define
callbacks that should be run when the battery level reaches a certain
threshold.

Themes, whether perl themes or plain-text themes, are built through
'steps', which are defined in a single line. In a plain-text config
file, such a line looks like this:

 discharging = 2:missing.png:low.png, 10:low.png, 100:full.png

This defines three steps. The highest step shows "full.png" when the
battery level is between 11% and 100% (inclusive); the second step shows
"low.png" when the battery level is between 3% and 10% (inclusive); and
the third step will alternate between "missing.png" and "low.png" on
three-second intervals, when the battery is between 0% and 2%.

Since the line starts with "discharging", these steps are used when the
system is running on battery power. A similar line of steps could be
defined for when the battery is charging:

 charging = 0:empty-charging.png, 10:low-charging.png, 100: full-charging.png

this will show "empty-charging.png" when the battery is at 0% (exactly),
"low-charging.png" between 1% and 10% (inclusive), and "full-charging.png"
at 11% and above.

Note that ordering is significant: steps should be defined from low to
high.

To complete the theme configuration, we must add a few more items:

 [mytheme]
 steps = 3
 dir = /home/wouter/.fdpowermon/mytheme-icons
 charging = 0:empty-charging.png, 10:low-charging.png, 100: full-charging.png
 discharging = 2:missing.png:low.png, 10:low.png, 100:full.png

This defines a theme called "mytheme" which has three steps, and will
look for images in the directory
"/home/wouter/.fdpowermon/mytheme-icons". It is not possible to define a theme
which has a different number of steps for the charging phase than it does for
the discharging phase; if you want that, just define (an) extra step(s) for the
phase that you would like to have less steps, which has the same icon as the
step above or below.

Note that ordering is significant here, too; the "steps" line should
appear before any "charging" or "discharging" lines (this was not the
case in fdpowermon 1.7 or below).

If more than one theme is configured, fdpowermon will, by default, use
the last theme defined in the per-user configuration, or (if no per-user
configuration file exists) the last theme defined in the system-wide
configuration.

Perl theme config files can use fdpowermon::theme::make_default to
change the default theme.

=head1 PERL API

=cut

package fdpowermon::theme;

=head2 new

Create a new fdpowermon theme. Returns a blessed reference; e.g.,

my $theme = new fdpowermon::theme;
=cut

sub new {
	my $self = {};
	bless $self;
}

=head2 $theme->set_stepcount($count)

Set the number of steps in the theme. Note that an fdpowermon theme must
have an equal number of steps in both the "charging" and the
"discharging" direction.

Should be called before calling set_charging, set_discharging, or
parse_step.
=cut

sub set_stepcount($$) {
	my $self = shift;
	my $steps = shift;
	$self->{steps} = $steps;
}

=head2 $theme->set_dir($dir)

Set the base directory used for icon file names.
=cut

sub set_dir($$) {
	my $self = shift;
	my $dir = shift;
	$self->{dir} = $dir;
}

=head2 $theme->set_charging(\@elements)

Set the icons that should be shown when the battery is charging. The
argument should be created by way of the parse_step method.
=cut

sub set_charging($\@) {
	my $self = shift;
	my $charge_steps = shift;
	if($self->{steps} != scalar(@$charge_steps)) {
		die "array must have " . $self->{steps} . " elements but has " . scalar(@$charge_steps) . " instead";
	}
	$self->{charging} = $charge_steps;
}

=head2 $theme->set_discharging(\@elements)

Set the icons that should be shown when the battery is discharging. The
argument should be created by way of the parse_step method.
=cut

sub set_discharging($\@) {
	my $self = shift;
	my $discharge_steps = shift;
	if($self->{steps} != scalar(@$discharge_steps)) {
		die "array must have " . $self->{steps} . " elements but has " . scalar(@$discharge_steps) . " instead";
	}
	$self->{discharging} = $discharge_steps;
}

=head2 $theme->parse_step($defs)

Parses the given string into something that can be passed on to
set_charging or set_discharging. The definitions should be in the steps
format, described above, without the leading C< charging = > or
C< discharging = >.

While this method returns an arrayref that can be inspected and
(probably) modified, themes that want to be forward-compatible should
treat it as an opaque data structure.
=cut

sub parse_step($$) {
	my $self = shift;
	my $defs = shift;
	my $num = $self->{steps};
	my @sdefs = split /,/,$defs,$num;
	my $curmin = 0;
	my @retval;
	my $curval;

	foreach my $def (@sdefs) {
		my @def = split /:/,$def;
		$curval = {};
		$curval->{min} = $curmin;
		$curval->{max} = $def[0];
		$curval->{icon} = $def[1];
		if (defined($def[2])) {
			$curval->{iconf} = $def[2];
			$curval->{flash} = 1;
		}
		$curmin = $curval->{max} + 1;
		push @retval, $curval;
	}
	return \@retval;
}

=head2 $theme->set_event($step, \&callback, 'd')

Update the theme so the sub 'callback' is executed when we're discharging
and we reach $step for the first time. To set an event when charging
instead, pass a 'c' as the third argument.

Note that the steps are arrays, and are therefore 0-based; the lowest-numbered
items are the lowest-level steps.

When the event triggers, the callback routine will be passed two
arguments: the first is the current battery level (in percent); the
second is a number denoting whether the battery is currently charging
(1) or discharging (0). In case the parsing of the ACPI command fails,
however, the second argument may be undef; you should prepare for this
possibility. Note that fdpowermon itself handles that case by assuming
the battery is charging; you may or may not wish to do the same.
=cut

sub set_event($$$$) {
	my $self = shift;
	my $step = shift;
	my $event = shift;
	my $dir = shift;

	my $stepset;
	
	if($dir eq 'c') {
		$stepset = $self->{charging};
	} elsif($dir eq 'd') {
		$stepset = $self->{discharging};
	} else {
		die "unknown direction '" . $dir . "' passed to set_event";
	}
	$stepset->[$step]->{event} = $event;
}

=head2 $theme->register($name)

Registers a theme under a given name. If a theme already exists under
that name, it is replaced.

=cut

sub register($$) {
	my $self = shift;
	my $name = shift;

	$themes{$name} = $self;
}

=head2 make_default($name)

Makes a theme with a given name be the default theme.

=cut

sub make_default($) {
	my $name = shift;

	$theme = $name;
}

=head2 get_theme($name)

Looks up a theme with the given name; e.g.,

 my $theme = fdpowermon::theme::get_theme("default");

=cut

sub get_theme($) {
	my $name = shift;

	return $themes{$name};
}

package main;

sub checklevels {
	my %lastevent;
	my @batstates;
	my $flevel = 0;
	my $bat;
	my $state;
	my $level;
	my $remaining;
	my $step;
	my $acpi_output;
	my $found = 0;
	my $charging = 1;
	open my $acpi, "acpi -b |";
	while ($acpi_output = <$acpi>) {
		chomp $acpi_output;
		if ($acpi_output =~ /^Battery (\d): ((Dis)?[Cc]harging|Unknown|Full), ((\d)+)%(, ([\d:]*))?/) {
			$bat = $1;
			$state = $2;
			$level = $4;
			if (defined($6)) {
				$remaining = $7;
			}
			$found = 1;
			last;
		}
	}
	return 1 if !$found;
	$flevel = ($flevel*$bat + $level) / ($bat+1);
	if($state =~ /Discharging/) {
		$step = $themes{$theme}->{discharging};
		$charging = 0;
	} elsif($state =~/Charging/) {
		$step = $themes{$theme}->{charging};
		$charging = 1;
	} elsif($state =~/Full/) {
		$step = $themes{$theme}->{charging};
		$charging = 1;
	} else {
		$step = $themes{$theme}->{charging};
	}
	my $ifile = undef;
	my $s_item;
	my $s_item_s;
	foreach $s_item (@$step) {
		if ($flevel >= $s_item->{min} && $flevel <= $s_item->{max}) {
			$ifile = $themes{$theme}->{dir} . "/" . $s_item->{icon};
			$s_item_s = $s_item;
			last;
		}
	}
	$s_item = $s_item_s;
	if(defined($ifile)) {
		if($s_item->{flash}) {
			if(defined $s_item->{iconf}) {
				if($fnormal) {
					$ifile = $themes{$theme}->{dir} . "/" . $s_item->{iconf};
				}
				$fnormal = 1 - $fnormal;
			}
		}
	}
	if(defined($s_item->{event})) {
		my $sub = $s_item->{event};
		if (!defined($lastevent{dir}) || $lastevent{dir} != $charging && $lastevent{level} != $s_item->{min}) {
			&$sub($flevel, $charging);
			$lastevent{dir} = $charging;
			$lastevent{level} = $s_item->{min};
		}
	}
	$icon->set_tooltip_text($acpi_output);
	if(defined($ifile)) {
		$icon->set_from_file($ifile);
		$icon->set_visible(1);
	} else {
		$icon->set_visible(1);
	}
	if($charging) {
		$lastwarning = 100;
	}
	foreach my $wlevel(@warnings) {
		next if $charging;
		next if $wlevel >= $lastwarning;
		if($flevel <= $wlevel) {
			warning($flevel);
			$lastwarning=$flevel;
		}
	}
	return 1;
}

sub parse_themefile($) {
	my $themefile = shift;
	open my $themecfg, "<$themefile";
	my $line;
	my $curtheme;
	my $curtheme_name;
	while($line = <$themecfg>) {
		chomp $line;
		if($line=~ /\[([\S]*)\]/) {
			if(defined($curtheme_name)) {
				$curtheme->register($curtheme_name);
			}
			$curtheme = new fdpowermon::theme;
			$curtheme->set_dir("/usr/share/fdpowermon");
			$curtheme_name = $1;
		} elsif($line=~ /steps\s*=\s*(\d+)/) {
			$curtheme->set_stepcount($1);
		} elsif($line=~ /discharging\s*=\s*(.*)$/) {
			$curtheme->set_discharging($curtheme->parse_step($1));
		} elsif($line=~ /charging\s*=\s*(.*)$/) {
			$curtheme->set_charging($curtheme->parse_step($1));
		} elsif($line=~ /dir\s*=\s*(.*)$/) {
			$curtheme->set_dir($1);
		}
	}
	$curtheme->register($curtheme_name);
	return $curtheme_name;
}

sub parse_themes {
	my $curtheme;
	fdpowermon::theme::make_default(parse_themefile("/etc/fdpowermon/theme.cfg"));
	if(-f "/etc/fdpowermon/theme.pl") {
		require "/etc/fdpowermon/theme.pl";
	}
	my $userdir = $ENV{HOME} . "/.config/fdpowermon";
	if(-f "$userdir/theme.cfg") {
		fdpowermon::theme::make_default(parse_themefile("$userdir/theme.cfg"));
	}
	if(-f "$userdir/theme.pl") {
		require "$userdir/theme.pl";
	}
}

sub warning ($) {
	my $level = shift;
	#my $dialog = Gtk2::MessageDialog->new(undef, 'destroy-with-parent', 'warning', 'ok', "Warning: battery level low (now at %s%%)", $level);
	#$dialog->run;
	#$dialog->destroy;
	my $notif = Gtk2::Notify->new("battery status", "Warning: battery level low (now at " . $level . "%)", undef);
	$notif->show;
}

$icon = Gtk2::StatusIcon->new();
parse_themes;
checklevels();
Glib::Timeout->add_seconds(3, \&checklevels);
Gtk2->main();
