Friday, September 7, 2007

Perl Module Browser in Perl/tk

I was interested in using Tk to develop some GUI application. As I was playing with Perl/tk I realised that there was no GUI based application for me to browse perl module installations on the system, so I decided to build one and try out Perl/tk widgets as well. I found the initial code on the web and modified it to suit my purpose.


#!/usr/bin/env perl
use strict;
use Tk;
use Tk::HList;
use Tk::BrowseEntry;
use Tk::Dialog;
use ExtUtils::Packlist;
use ExtUtils::Installed;

my $mw = MainWindow->new;
my $inst = ExtUtils::Installed->new();
my $dropdown;
my @modules;
my $dropdown_default_msg = "-- Choose a Module --";

# Mainwindow: sizex/y, positionx/y
$mw->geometry("600x300+100+120");
my $top = $mw->Frame()->pack(-anchor=>'n', -expand=>'yes', -fill=>'both');
my $bottom = $mw->Frame()->pack(-anchor=>'n');
# Default value
&create_datagrid($top, $bottom, $inst);
MainLoop;

sub create_datagrid {
my $mother = $_[0];
my $bottom = $_[1];
my $inst = $_[2];

# Create dropdown to choose module
my $dropdown_value;
$dropdown = $mother->BrowseEntry(
-label => "Choose Module",
-variable => \$dropdown_value,
# populate the dropdown list
-listcmd => sub {
if($#modules != 0 ) {
$dropdown->delete(0, $#modules);
}
@modules = sort($inst->modules());
foreach (@modules) {
$dropdown->insert('end', $_);
}
}
)->pack(-anchor=>'n');

my $grid = $mother->Scrolled(
'HList',
-columns => 1,
-scrollbars => 'osoe',
-width => 40,
-height => 10,
-background => 'white',
)->pack(-anchor=>'n', -expand=>'yes', -fill=>'both');
# Set the initial value for the dropdown
$dropdown_value = $dropdown_default_msg;

# Configure dropdown what to do when sth is selected
$dropdown->configure(
# What to do when an entry is selected
-browsecmd => sub {
my @values = sort($inst->files($dropdown_value));
$grid->delete('all'); # delete currently displayed values
my $i = 1;
foreach(@values) {
$grid->add($i);
$grid->itemCreate($i++, 0, -text => $_);
}
$grid->add($i);
$grid->itemCreate($i, 0,
-text => $inst->packlist($dropdown_value)->packlist_file()
);
},
);

my $delete_button = $bottom->Button(-text=>'Delete',
-command => sub {
my @button_text = ("Cancel", "Continue >>");
if($dropdown_value ne $dropdown_default_msg) {
my $confirm = $mw->Dialog(-title => "Delete $dropdown_value?",
-text => "This action shall remove $dropdown_value from the filesystem",
-default_button => $button_text[0],
-buttons => \@button_text);
my $value = $confirm->Show();
if($value eq $button_text[1]) {
foreach(sort($inst->files($dropdown_value))) {
unlink $_;
}
unlink $inst->packlist($dropdown_value)->packlist_file();
$dropdown_value = $dropdown_default_msg;
$grid->delete('all');
undef $inst;
$inst = ExtUtils::Installed->new(); }
}
}
)->grid(-column => 0, -row => 0);
my $exit_button = $bottom->Button(-text=>'Exit',
-command=> sub {exit;},
)->grid(-column => 1, -row => 0);
}


No comments: