File: fdpowermon

package info (click to toggle)
fdpowermon 1.19
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, sid
  • size: 148 kB
  • sloc: perl: 297; makefile: 6
file content (573 lines) | stat: -rwxr-xr-x 15,987 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
#!/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($@) {
	print "no notify because setup failed: $@\n";
	$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] + 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;
	my $mah_cur = 0;
	my $mah_max = 0;
	open my $acpi, "acpi -bi |";
	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;
		}
		if ($acpi_output =~ /^Battery (\d): design capacity (\d+) mAh, last full capacity (\d+) mAh/) {
			$bat = $1;
			my $lastfull = $3;
			$mah_max += $lastfull;
			$mah_cur += $lastfull * $level / 100;
			$flevel = $mah_cur / $mah_max * 100;
		}
	}
	return 1 if !$found;
	if($bat > 0) {
		$title_text .= "\nCombined: " . sprintf("%.2f%%", $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(0);
	}
	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 " . sprintf("%.2f%%)", $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;
		} elsif($line=~/^\s*$/) {
			# empty line, skip
			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();