Saturday, November 15, 2008

Perl Gtk2::StatusIcon example

I had the need to add a status icon in the systray, enhancing the functionality of a web application. My needs are a little more complex than displaying a simple menu, but the problem was that you can't find many examples for scripting languages, like Perl, especially with StatusIcon.

The beautiful thing is that Gtk+ bindings try not to diverge too much from the main API, although some of them add useful extensions.

So I found this PyGtk example, converting it to Perl:
http://marcin.af.gliwice.pl/if-then-else-20070121143245.

#!/usr/bin/env perl
use strict;
use warnings;

use Gtk2 -init;

sub quit_cb {
my ($widget, $status_icon) = @_;

$status_icon->set_visible(0) if $status_icon;
Gtk2->main_quit();
}

sub popup_menu_cb {
my ($widget, $button, $time, $menu) = @_;

if ($button == 3) {
my ($x, $y, $push_in)
= Gtk2::StatusIcon::position_menu($menu, $widget);

$menu->show_all();
$menu->popup( undef, undef,
sub{return ($x,$y,0)} ,
undef, 0, $time );
}
}

sub activate_icon_cb {
my $msgBox = Gtk2::MessageDialog->new(undef,
'GTK_DIALOG_MODAL',
'GTK_MESSAGE_INFO',
'GTK_BUTTONS_OK',
"Status Icon example!");
$msgBox->run();
$msgBox->destroy();
}

my $status_icon = Gtk2::StatusIcon->new_from_stock('gtk-home');

my $menu = Gtk2::Menu->new();
my $menuItem = Gtk2::ImageMenuItem->new_from_stock("gtk-about");
$menuItem->signal_connect('activate', \&activate_icon_cb);
$menu->append($menuItem);

$menuItem = Gtk2::ImageMenuItem->new_from_stock('gtk-quit');
$menuItem->signal_connect('activate', \&quit_cb, $status_icon);
$menu->append($menuItem);

$status_icon->set_tooltip("StatusIcon test");
$status_icon->signal_connect('activate', \&activate_icon_cb);
$status_icon->signal_connect('popup-menu', \&popup_menu_cb, $menu);
$status_icon->set_visible(1);

Gtk2->main();

~

3 comments:

Anonymous said...

Great example, just what I was looking for! Thanks

Anonymous said...

Hey, thanks a million. You're right, finding decent example code for GTK2-perl is not very easy at all. This example is exactly what I needed to get status icons working.

Thanks again!

everythingido said...

Amazing! Really great example. Just what I was looking for since I learned that this is a standard Gtk2 class replacing Gtk2::TrayIcon, which doesn't have as good capabilities.