#!/usr/bin/perl

use strict;
use warnings;
use Gtk3 -init;
use Glib::Object::Introspection;

my $icon;
my $theme;
my %themes;
my $fnormal = 0;
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<$XDG_CONFIG_DIR/fdpowermon/theme.cfg>), or through a short perl script
(F</etc/fdpowermon/theme.pl> or F<$XDG_CONFIG_DIR/fdpowermon/theme.pl>).
If $XDG_CONFIG_DIR is not set, $HOME/.config is used as a default.

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 @warnings

The @fdpowermon::theme::warnings array can be used to specify at which levels
fdpowermon should issue a standard warning. The default is (10, 5, 1), which
means to issue a warning at a level of 10%, 5%, and 1%. Note that if the
battery runs flat at a particularly fast pace, the level may have reduced even
further than that before the warning is issued; also, fdpowermon will issue a
warning immediately when power is removed from the machine and the power is
below the first level.

To make fdpowermon always issue a warning when power is removed, set
this to something like (100, 10, 5, 1). To make fdpowermon issue
warnings at 20%, 10%, and 5%, set this to (20, 10, 5).

Note that it is not possible to change the text of the warning. If you
want that, see the fdpowermon::theme::warning sub, and use an event.

=cut

our @warnings = (10, 5, 1);

=head2 $use_notify

The variable $fdpowermon::theme::use_notify can be used to decide whether
to use a libnotify message (if set to a nonzero value), or a dialog
window (if set to a value which evaluates to zero).

The default is to use libnotify if the libnotify Glib introspection data
is installed, or a dialog box if not. Because dialog boxes can steal the
focus and therefore wreak havoc with the user's work, using libnotify is
strongly recommended by the author.

Note that if you set the variable to nonzero explicitly, then the test
whether or not the Glib introspection data is installed will be ignored.
Make sure it's available in that case!

=cut

our $use_notify = 1;

eval {
	Glib::Object::Introspection->setup(
			basename => "Notify",
			version => 0.7,
			package => "Fdpowermon::Notify",
			);
};
if($@) {
	$use_notify = 0;
} else {
	Fdpowermon::Notify->init();
}

=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;
		if(!defined($def[1])) {
			warning("unparseable entry '$def' in config file: missing colon");
			next;
		}
		$curval->{max} = $def[0];
		$curval->{icon} = $def[1];
		if (defined($def[2])) {
			$curval->{iconf} = $def[2];
			$curval->{flash} = 1;
		}
		$curmin = $curval->{max};
		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};
}

=head2 warning($message)

Produce a warning, either using libnotify, or using a dialog box:

 fdpowermon::theme::warning($message);

See the documentation on $fdpowermon::theme::use_notify above for
details on which implementation is chosen.

=cut

sub warning ($) {
	my $message = shift;
	if($use_notify) {
		my $notif = Fdpowermon::Notify::Notification->new("battery status", "Warning: " . $message, "");
		eval {
			$notif->show;
		};
		if ($@) {
			# Something went wrong trying to show a notification
			# message. Fall back to using a dialog box instead.
			$use_notify = 0;
			return;
		};
	}
	if(!$use_notify) {
		my $dialog = Gtk3::MessageDialog->new(undef, 'destroy-with-parent', 'warning', 'ok', "Warning: " . $message);
		$dialog->run;
		$dialog->destroy;
	}
}

=head1 EXAMPLES

For a full .cfg theme example, look above.

To construct the same theme fully from perl, you'd do something like this:

 my $theme = new fdpowermon::theme;
 $theme->set_stepcount(3);
 $theme->set_dir("/home/wouter/.fdpowermon/mytheme-icons");
 $theme->set_charging($theme->parse_step("0:empty-charging.png, 10:low-charging.png, 100: full-charging.png"));
 $theme->set_discharging($theme->parse_step("2:missing.png:low.png, 10:low.png, 100:full.png"));

(note, as a perl theme, this would go in theme.pl, not theme.cfg; see
above for possible locations for perl themes)

However, unless you want to build the theme dynamically, doing it this
way is not recommended. Instead, you would build the theme from a .cfg
file, and possibly modify it from perl. Let's say you wish to add an
event to suspend the system when the power gets low; in that case, you'd
do something like this:

 sub suspend {
	system("sudo pm-suspend");
 }

 my $theme = fdpowermon::theme::get_theme("mytheme");
 $theme->set_event(0, \&suspend, 'd');

This would call the 'suspend' sub when the battery is discharging and we
reach the lowest step (in the above example, that would be when the
battery reaches 10%; you might want to do that somewhat later). This
'suspend' sub simply calls the "pm-suspend" program, with sudo, to
suspend the system.

=cut

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 $title_text = "";
	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:]*))?/) {
			$title_text .= ($found ? "\n" : "") . $acpi_output;
			$bat = $1;
			$state = $2;
			$level = $4;
			if (defined($6)) {
				$remaining = $7;
			}
			$found = 1;
			$flevel = ($flevel*$bat + $level) / ($bat+1);
		}
	}
	return 1 if !$found;
	if($bat > 0) {
		$title_text .= "\nCombined: $flevel%";
	}
	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($title_text);
	if(defined($ifile)) {
		$icon->set_from_file($ifile);
		$icon->set_visible(1);
	} else {
		$icon->set_from_stock("gtk-discard");
		$icon->set_visible(1);
	}
	if($charging) {
		$lastwarning = 100;
	}
	foreach my $wlevel(@fdpowermon::theme::warnings) {
		next if $charging;
		next if $wlevel >= $lastwarning;
		if($flevel <= $wlevel) {
                	fdpowermon::theme::warning("battery level low (now at " . $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);
		} elsif($line=~ /^\s*[#;]/) {
			# comment in theme file
			next;
		} else {
			fdpowermon::theme::warning("unparseable line in configuration file: $line");
		}
	}
	$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;
	if(exists($ENV{XDG_CONFIG_DIR})) {
		$userdir = $ENV{XDG_CONFIG_DIR} . "/fdpowermon";
	} elsif(exists($ENV{HOME})) {
		$userdir = $ENV{HOME} . "/.config/fdpowermon";
	} else {
		die 'Need $HOME or $XDG_CONFIG_DIR to be set!';
	}
	if(-f "$userdir/theme.cfg") {
		fdpowermon::theme::make_default(parse_themefile("$userdir/theme.cfg"));
	}
	if(-f "$userdir/theme.pl") {
		require "$userdir/theme.pl";
	}
}

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