When a program needs to run in the background, but still give the user a visual indication on events, the system tray area is ideal for this.
This lesson will show you how to utilize the system tray on Linux.
We will look at a sample program which will toggle the icon in the system tray. It will also use Gtk2::NotificationBubble
to show a message on each toggle. When we enter the mouse pointer into the Gtk2::TrayIcon
area, the toggling will quit and a final message appear. If you click on the Gtk2::TrayIcon
, the program quits.
This is a very simple program, heavy commented, so further explanation will duplicate comments already present inside the program. You are advised to read the man pages for additional data.
The |
Table 22-1. Gtk2
object classes used
Gtk2 Class Name |
---|
Gtk2::TrayIcon |
Gtk2::NotificationBubble |
Gtk2::EventBox |
Gtk2::Image |
The program can be found here: 'gtk2_tray.pl'
1 #! /usr/bin/perl -w 2 use strict; 3 #external modules, needs to be separately loaded 4 use Gtk2::TrayIcon; 5 use Gtk2::NotificationBubble; 6 7 use Gtk2 -init; 8 use Glib qw/TRUE FALSE/; 9 10 my $flag = 1; 11 my $event_number; 12 my $bubble; 13 14 my $icon= Gtk2::TrayIcon->new("test"); 15 16 my $eventbox = Gtk2::EventBox->new; 17 my $img= Gtk2::Image->new_from_file("./pix/1.png"); 18 $eventbox->add($img); 19 20 #attach a callback which will stop the flashing 21 #of the message as soon as we enter the the 22 #tray icon 23 $eventbox->signal_connect( 24 'enter-notify-event' => sub { 25 #Remove the toggle action 26 Glib::Source->remove ($event_number); 27 $bubble->set( 28 'Sorry...', #Heading 29 undef, #icon (Gtk2::Image) 30 'For being so persistent ;-)', #message 31 ); 32 $bubble->show(-1); #to keep it forever set it to < 0 33 } 34 ); 35 36 #if the user click on the tray icon, we quit the program 37 $eventbox->signal_connect('button-press-event' => sub{ Gtk2->main_quit;}); 38 39 40 #The tray icon is a container, we 41 #can add widgets to it 42 $icon->add($eventbox); 43 $icon->show_all; 44 45 #The notification bubble attaches to widgets, 46 #here we attach to the eventbox. 47 #We could attach to the tray icon to the 48 #same effect 49 $bubble = Gtk2::NotificationBubble->new; 50 $bubble->attach($eventbox); 51 52 #We record the ID in order to remove this 53 #callback later. 54 $event_number = Glib::Timeout->add ( 55 4000 => sub{ 56 57 ($flag)&&($img->set_from_file('./pix/1.png')); 58 ($flag)||($img->set_from_file('./pix/2.png')); 59 $flag = !$flag; 60 $bubble->set( 61 'Hello', #Heading 62 Gtk2::Image->new_from_file('./pix/1.png'), #icon (Gtk2::Image) 63 'Time for a Big Mac :)!', #message 64 ); 65 $bubble->show(1000); 66 return 1; 67 }); 68 69 Gtk2->main;