<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">#!/usr/bin/perl -w
# ###########################################################################
# dupie - pie chart representing disk usage for a directory
#
# ###########################################################################
# (c) Mark J Hewitt.  January 1997
#
# $Author: mjh $ $Date: 1998/10/06 22:36:53 $ $Revision: 1.4 $
#
# History
#
# $Log: dupie.pl,v $
# Revision 1.4  1998/10/06 22:36:53  mjh
# Oops!  Teach me to include a one line patch in with the POD!
#
# Revision 1.3  1998/10/06 22:35:30  mjh
# Added POD documentation suitable for submission to CPAN
#
# Revision 1.2  1998/10/06 21:09:32  mjh
# Added $VERSION
#
# Revision 1.1  1998/10/06 21:01:13  mjh
# Initial revision
#
# 06-Oct-1998
#  * transfer into RCS
# 28-Jul-1998 (mjh)
#  * Replaced listbox with HList directory browser
#  * Arranged for segments to be outst when selected
#  * Added .dupierc config file
#  * Improved resize behaviour
#  * Generally tidied up for perl 5.005_01
# 31-Jul-1998 (mjh)
#  * Added AutoUpdate feature
#
# ###########################################################################
#
# Todo
#
# [1]  Add current directory label above piechart (Leave this in title bar)
# [8]  Sort out resize operations for the pie
# [9]  Write pod documentation
# [12] Re-write using a piechart widget
# [13] Add a fast-select directory
# [14] Add a file viewer
#
require 5.002;
use strict;
use Getopt::Std;
use File::Basename;
use Cwd;
use Tk;
use Tk::WaitBox;
use Tk::DialogBox;
use Tk::Table;
use Tk::HList;
use Tk::ErrorDialog;

# ###########################################################################

=head1 NAME

dupie - Provides a Tk-based piechart browser to UNIX directories

=head1 SYNTAX

dupie [C&lt;-t&gt; sec] ][directory]

=head1 DESCRIPTION

Dupie has two panes: A pie chart indicating the filesystem occupancy of
elements below a directory and a hierachical list pane for navigating.
In fact, the pie segments are sensitive to mouse clicks, so the piechart
also has an active function too.  Additionally, there are four buttons.

A command line parameter determines which directory it will start at; no
parameter implies the current directory.

An optional B&lt;-t&gt; B&lt;sec&gt; parameter will cause B&lt;dupie&gt; to collect and
redraw the piechart and browser panes every B&lt;sec&gt; seconds.

=head2 Buttons

Four buttons, activated with a left mouse click are available:

=over 4

=item
B&lt;Close&gt; Closes the dupie window and exits.

=item
B&lt;Redraw&gt; Re-scans the directory and redraws the piechart and directory
browser.

=item
B&lt;Up&gt; Move the focus to the parent directory of that currently under
examination.

=item
B&lt;Details&gt; Pops up a I&lt;details&gt; dialog box for the currently selected element.
The dialog box gives all the basic information available for the file system
element (from stat(2) and provides) and provides a I&lt;Remove&gt; button to delete
the selected file or directory if required.

=back

=head2 List Browser

The right hand pane is a scrollable hierarchical list browser.  This is
the only pane that dynamically resizes if the containing frame is itself
resized.  Single left clicking on any element will select it, and the
corresponding pie segment will slip out of the piechart indicating which
it is.  Double clicking on a directory will change the focus there and
redraw both pie and browser.  Double clicking on a file will pop up the
I&lt;details&gt; dialog, from which the file may be removed if desired.

=head2 Piechart

The piechart in the left pane is composed of a cycle of rotating
colours.  These colours are configurable (see below).  Left clicking on
any segment will select the corresponding item in the browser, which
will adjust itself to bring that item into view if necessary.  Double
clicking on a segment corresponding to a directory will change the focus
to that directory and redraw the piechart and browser.  Double clicking
on a file will pop up the I&lt;details&gt; dialog box.  Right clicking will
pop up a I&lt;details&gt; box for all filesystem element, that is, it does not
change the current focus into a directory, but rather displays the
stat(2) details of it.

=head2 Configuration

The file F&lt;.dupierc&gt; in the user's home account will be eval'd by dupie
if it exists.  Note this is as big a security hole as .cshrc or .bashrc
files - they should not be writable by anyone other than the owner,
especially if that owner is root!  The following values may currently be set
in F&lt;~/.dupierc&gt;:

=over

=item
$DiskUsageCmd = 'du -ks'; # Disk usage - sum and in kB

=item
$PieRadius = 5;	    # Starting pie radius (in cm)

=item
$PieMargin = 0.5;         # Blank space left around pie (in cm)

=item
$SegOutStep = 0.075;      # Proportion of radius segments step out

=item
$IconDir = '/usr/share/images/icons/appl/desktop/file/cl';

=item
$OpenDirIcon = 'dir_open.xpm';

=item
$ClosedDirIcon = 'dir.xpm';

=item
$FileIcon = 'file.xpm';

=item
$AutoUpdate = 20;         # Automatically update after this many seconds

=item
@Colours = qw(gold red blue orange green);

=back

=head1 FILES

=over

=item
F&lt;~/dupierc&gt; Configuration file

=item
F&lt;TK Icon Directory/file.xpm&gt; File icon for browser pane

=item
F&lt;TK Icon Directory/folder.xpm&gt; Closed directory icon for browser pane

=item
F&lt;TK Icon Directory/openfolder.xpm&gt; Open directory icon for browser pane


=back

=head1 TODO

=over

=item
It would be nice to have this work for Win32 also.  There are problems with
Tk::WaitBox for this, amongst other file attribute issues.

=item
A full Pie widget should be provided so that the display can be more
attractive and generalised.

=item
Browsing file contents by typee.

=back

=head1 README

=head1 PREREQUISITES

C&lt;strict&gt;
C&lt;Getopt::Std&gt;
C&lt;File::Basename&gt;
C&lt;Cwd&gt;
C&lt;Tk 402.003&gt;
C&lt;Tk::WaitBox&gt;
C&lt;Tk::DialogBox&gt;
C&lt;Tk::Table&gt;
C&lt;Tk::HList&gt;
C&lt;Tk::ErrorDialog&gt;;

=head1 COREQUISITES

None.

=head1 OSNAMES

UNIX

=pod SCRIPT CATEGORIES

UNIX/DiskAdmin
File/Admin
Tk/DiskAdmin

=cut

# ###########################################################################

# ###########################################################################
# Configuration - These variables are assumed to be global
#

use vars qw($DiskUsageCmd $PieRadius $PieMargin $SegOutStep @Colours
            $IconDir $OpenDirIcon $ClosedDirIcon $FileIcon $AutoUpdate);

my $VERSION = '$Revision: 1.4 $';
$VERSION =~ m/^.*: (.*) \$$/;

my ($main, $dir, %size, $total, %icons, $wait, $waitmsg);

my $rcfile = ".dupierc";	# For per-user configuration

# ###########################################################################
# ###########################################################################

#
# Initialise
#
init($rcfile);

#
# Handle events
#
MainLoop;


# ###########################################################################
# ###########################################################################
# Initialise
#
sub init
{
    my $rcfile = $_[0];
    init_rc($rcfile);
    init_opts();
    init_config();
    init_state();
    init_win();
}


# ###########################################################################
# Set up initialisation values from per-user rc file.  Syntax is perl, and
# any global parameter may be changed
#
sub init_rc
{
    my $file = $_[0];

#
#   Find the user's home directory, and look for rc file in there.
#
    my $homedir = (getpwuid($&lt;))[7];
    $file = $homedir . "/" . $file;
#
#   Read it in, and exec it (Danger, Will Robinson!)
#
    open RC, "&lt;$file" or return;
    my @rc = &lt;RC&gt;;
    eval join ' ', @rc;
    close RC;
}


# ###########################################################################
# Initialise command line options
#
sub init_opts
{
    my %opt = ();

    getopts('t:', \%opt);
    if (defined $opt{'t'})
    {
	$AutoUpdate = $opt{'t'};
    }
    else
    {
	$AutoUpdate = 0;
    }

    $dir = defined $ARGV[0] ? $ARGV[0] : cwd; # Directory currently in focus
#
#   Only useful to execute this over a directory
#
    die "Not a directory: $dir" unless -d $dir;
}


# ###########################################################################
# Initialise configuration
#
sub init_config
{
    $DiskUsageCmd = 'du -ks'  unless defined $DiskUsageCmd; # Disk usage - sum and in kB
    $PieRadius = 5            unless defined $PieRadius;    # Starting pie radius (in cm)
    $PieMargin = 0.5          unless defined $PieMargin;    # Blank space left around pie (in cm)
    $SegOutStep = 0.075       unless defined $SegOutStep;   # Proportion of radius segments
                                                            #   step out
    $FileIcon    = 'file.xpm'       unless defined $FileIcon;
    $ClosedDirIcon     = 'folder.xpm'     unless defined $ClosedDirIcon;
    $OpenDirIcon = 'openfolder.xpm' unless defined $OpenDirIcon;

    unless(defined $IconDir)
    {
	for (@INC)
	{
	    my $try = "$_/Tk";
	    $IconDir = $try, last if -f "$try/$ClosedDirIcon";
	}
    }
    die "Cannot find Tk icon directory\n" unless defined $IconDir;

#
# Colour cycle
#
    @Colours = qw(Cyan Green LightSlateBlue Orange DeepSkyBlue4
		  FireBrick Gold DarkViolet Gray10 Khaki LightBlue
		  Gray30 MistyRose Grey65 Red Grey80 Navy LightGoldenRod
		  Black LightSlateGrey Moccasin LightSteelBlue Thistle
		  MediumSlateBlue PaleGreen MidnightBlue Wheat CadetBlue
		  Yellow SteelBlue LightSkyBlue DarkSlateBlue) unless defined @Colours;
}


# ###########################################################################
# just for debugging - show configuration parameters
#
sub print_config
{
    print "Version:             $VERSION\n";
    print "Disk usage command:  $DiskUsageCmd\n";
    print "Pie radius:          $PieRadius\n";
    print "Pie margin:          $PieMargin\n";
    print "Icon directory:      $IconDir\n";
    print "File icon:           $FileIcon\n";
    print "Directory icon       $ClosedDirIcon\n";
    print "Open directory icon: $OpenDirIcon\n";
    print "Colour cycle:        (", join ' ', @Colours, ")\n";
}


# ###########################################################################
# Initialise starting state
#
sub init_state
{
    $main = '';			# Handle on main window
    $wait = '';			# Handle on wait box
    $waitmsg = '';		# Message displayed on waitbox
    %size = ();			# Size information for $dir subtree
    $total = 0;			# Total blocks allocated in $dir subtree
    %icons = ();		# Icon pixmaps
}


# ###########################################################################
# Initialise window
#
sub init_win
{
    $main = MainWindow-&gt;new;		# Main window
    die "Cannot get handle on main window!\n" unless $main;
#
#   build some icon pixmaps for filesystem elements
#
    $icons{"open"}   = $main-&gt;Pixmap(-file =&gt; "$IconDir/$OpenDirIcon");
    $icons{"closed"} = $main-&gt;Pixmap(-file =&gt; "$IconDir/$ClosedDirIcon");
    $icons{"file"} = $main-&gt;Pixmap(-file =&gt; "$IconDir/$FileIcon");

#
#   Set up a waitbox
#
    $waitmsg = "Initializing...";
    $wait = $main-&gt;WaitBox(-bitmap =&gt;'hourglass',
			   -txt1 =&gt; 'Collecting data',
			   -txt2 =&gt; 'Please be patient',
			   -title =&gt; 'Disk data',
			   -canceltext =&gt; 'Quit',
			   -cancelroutine =&gt; sub { $waitmsg = undef; }
			  );
    my $u = $wait-&gt;Subwidget('uframe');
    $u-&gt;pack(-expand =&gt;1, -fill =&gt; 'both');
    $u-&gt;Label(-textvariable =&gt; \$waitmsg)-&gt;pack(-expand =&gt; 1, -fill =&gt; 'both');

#
#   Set up the window
#     First, titles and names
    $main-&gt;title("Disk usage of $dir");	# Add title
    $main-&gt;iconname($dir);	        # name the icon

#
#   Add the frames to the window
#
#     Button frame
#
    my $buttons = $main-&gt;Frame;
    $buttons-&gt;pack(qw(-side bottom -fill x -pady 2m));

#
#   Create a frame for the piechart
#
    my $pie_frame = $main-&gt;Frame();
    $pie_frame-&gt;pack(-side =&gt; 'left', -fill =&gt; 'both', -expand =&gt; 'no');

#
#   Insert the canvas on which to draw the piechart in the frame
#
    my $pie_canvas = create_canvas($pie_frame, $PieRadius + $PieMargin);

    $pie_canvas-&gt;pack(-expand =&gt; 'no', -fill =&gt; 'both');

#
#   Create a directory browser on which to display directory entries
#
    my $browser = create_browser($main,
				 $pie_canvas,
				 $PieRadius,
				 $PieMargin,
				 $PieRadius * $SegOutStep);

    $wait-&gt;Show;

#
#   Start to gather du data.  This will fill a buffer before we read it, so
#   the we have a little more time to build the display and to make the
#   startup appear to be a little faster than it really is.
#
    my $duhandle = start_du($dir);

#
#   Add buttons to the button frame
#
#     Button to close the main window
#
    my $close = $buttons-&gt;Button(-text    =&gt; 'Close',
				 -command =&gt; [$main =&gt; 'destroy']
				)-&gt;pack(-side =&gt; 'left', -expand =&gt; 1);

#
#   Button to redraw the piechart
#
    my $redraw = $buttons-&gt;Button(-text    =&gt; 'Redraw',
				  -command =&gt; [\&amp;redraw,
					       \$dir,
					       $pie_canvas,
					       $browser,
					       $PieRadius,
					       $PieMargin]
				 )-&gt;pack(-side =&gt; 'left', -expand =&gt; 1);

#
#   Button to move up a directory
#
    my $up = $buttons-&gt;Button(-text    =&gt; 'Up',
			      -command =&gt; [\&amp;cdup,
					   \$dir,
					   $pie_canvas,
					   $browser,
					   $PieRadius,
					   $PieMargin]
			     )-&gt;pack(-side =&gt; 'left', -expand =&gt; 1);
#
#   Button to pop-up details on object
#
    my $details = $buttons-&gt;Button(-text    =&gt; 'Details',
				   -command =&gt; [\&amp;details,
						$browser,
						$pie_canvas,
						$PieRadius,
						$PieMargin]
				  )-&gt;pack(-side =&gt; 'left', -expand =&gt; 1);

#
# Now retrieve the disk data
#
    $waitmsg = "Reading data";
    $wait-&gt;update;

    %size = du_data($duhandle, \$total, \$waitmsg);

#
# Now finished with disk usage command
#
    close $duhandle;

#
# Make the piechart and populate the directory browser
#
    $waitmsg = "Building display";
    $wait-&gt;update;

    build_piechart(\%size, $total, $pie_canvas, $PieRadius, $PieMargin, $browser);

    $wait-&gt;unShow;

    $main-&gt;repeat($AutoUpdate*1000,
		  [\&amp;redraw, \$dir, $pie_canvas, $browser,
		   $PieRadius, $PieMargin]) if $AutoUpdate &gt; 0;
}


# ###########################################################################
# Start to gather disk usage data for the given directory
#
sub start_du
{
    my ($dir) = @_;
    my $cmd = "$DiskUsageCmd $dir/* 2&gt;/dev/null |";

    open DU, $cmd or die "Cannot execute $DiskUsageCmd on $dir: $!";
    return \*DU;
}


# ###########################################################################
# Return the disk usage data
#
sub du_data
{
    my($du, $total, $msg) = @_;
    my %data = ();

    while (&lt;$du&gt;)
    {
	exit 0 unless defined $$msg;

	my($s, $n) = split;
	$data{$n} = $s;
	$$total += $s;
	$$msg = basename($n) . " (" . $s . "k)\nTotal " . $$total . "k";
	$wait-&gt;update;
    }
    return %data;
}


# ###########################################################################
# Create and return the canvas on which we build the piechart
#
sub create_canvas
{
    my ($frame, $radius) = @_;
    my $x = $radius*2;
    my $y = $radius*2;

    my $canvas = $frame-&gt;Canvas(
				-scrollregion =&gt; ['0c', '0c', $x . 'c', $y . 'c'],
				-width        =&gt; $x . 'c',
				-height       =&gt; $y . 'c',
				-relief       =&gt; 'sunken',
				-bd =&gt; 2,
			       );
    return $canvas;
}


# ###########################################################################
# Build the piechart on the canvas, and populate the directory browser as
# we go
#
sub build_piechart
{
    my ($data, $total, $canvas, $radius, $margin, $list) = @_;
    my $pathname;
    my $start = 0;
    my $sweep = 0;
    my $colour = 0;
    my $item = 0;
    my $sizewidth = length $total;

#
#   Add base directory
#
    my @pi = split('/', $dir);
    my $path = '';

    $list-&gt;add('/', -itemtype =&gt; 'text', -text =&gt; '/', -data =&gt; $pathname);

    for (@pi)
    {
	next unless $_;

	$path .= "/$_";
	$list-&gt;add($path,
		   -itemtype =&gt; 'imagetext',
		   -image =&gt; $path eq $dir ? $icons{"open"} : $icons{"closed"},
		   -text =&gt; $path,
		   -data =&gt; $path);
    }

#
#   Loop though the paths making segments and inserting into directory
#   browser
#
    for $pathname (sort {$data-&gt;{$b} &lt;=&gt; $data-&gt;{$a}} keys %$data)
    {
	my $val = $data-&gt;{$pathname};
#	my $tag = sprintf("%" . $sizewidth . "dk %s", $val, basename($pathname));
	my $tag = sprintf("%s (%s)", basename($pathname), fmt_num($val*1024));

	$sweep = 360*$val/$total;

	my $seg = create_segment($canvas,
				 $radius,
				 $margin,
				 $Colours[$colour],
				 $start,
				 $sweep,
				 $pathname,
				 $list);

	$list-&gt;add($pathname,
		   -itemtype =&gt; 'imagetext',
		   -image =&gt; -d $pathname ? $icons{"closed"} : $icons{"file"},
		   -text =&gt; $tag,
		   -data =&gt; $seg);
	$item++;
	$start += $sweep;
	$colour++;
	$colour %= $#Colours + 1;
    }
    $list-&gt;update;
}


# ###########################################################################
# Create a segment on the piechart
#
sub create_segment
{
    my($canvas, $radius, $margin, $colour, $start, $sweep, $file, $list) = @_;
    my $diam = $radius*2;
    my $seg;

    if ($sweep == 360)
    {
	$seg = $canvas-&gt;createOval($margin . 'c', $margin . 'c',
				   $diam . 'c', $diam . 'c',
				   -fill =&gt; $colour,
				   -outline =&gt; "black",
				   -tags =&gt; [$file, 'JustMe']);
    }
    else
    {
	$seg = $canvas-&gt;createArc($margin . 'c', $margin . 'c',
				  $diam . 'c', $diam . 'c',
				  -fill =&gt; $colour,
				  -outline =&gt; "black",
				  -start =&gt; $start,
				  -extent =&gt; $sweep,
				  -style =&gt; "pieslice",
				  -tags =&gt; [$file]);
    }

    $canvas-&gt;bind($file, '&lt;1&gt;' =&gt; [\&amp;highlight_list, $list]);
    $canvas-&gt;bind($file, '&lt;2&gt;' =&gt; [\&amp;show_details, $list, $radius, $margin]);
    $canvas-&gt;bind($file, '&lt;3&gt;' =&gt; [\&amp;show_details, $list, $radius, $margin]);
    $canvas-&gt;bind($file, '&lt;Double-1&gt;' =&gt; [\&amp;cd_or_details_segment, $list, $radius, $margin]);

    return $seg;
}


# ###########################################################################
# If the selected item on the piechart is a directory, change directory
# focus to it.  If a file, pop up a details box.
#
sub cd_or_details_segment
{
    my ($canvas, $list, $radius, $margin, $path) = @_;
    $path = get_name($canvas) if !defined $path;
    highlight_list($canvas, $list);

    cd_or_show_details($canvas, $list, $radius, $margin, $path);
}


# ###########################################################################
# change directory or show details box
#
sub cd_or_show_details
{
    my ($canvas, $list, $radius, $margin, $path) = @_;

    if(-d $path)
    {
	$dir = $path;
	redraw(\$dir, $canvas, $list, $radius, $margin);
    }
    else
    {
	details_box($path, $canvas, $list, $radius, $margin);
    }
}


# ###########################################################################
# Highlight an iten in the directory browser, then build a details box for
# that entry.
#
sub show_details
{
    my ($canvas, $list, $radius, $margin) = @_;
    my $path = get_name($canvas);

    highlight_list($canvas, $list);
    details_box($path, $canvas, $list, $radius, $margin);
}


# ###########################################################################
# pop up a details box on an entry
#
sub details_box
{
    my($path, $canvas, $list, $radius, $margin) = @_;
    return unless defined $path;

    my $type = type_name($path);
#
#   Create a new window
#
    my $w = $main-&gt;DialogBox(-title =&gt; $path, -buttons =&gt; ["Cancel", "Remove"]);
    my $path_label = $w-&gt;add("Label",
			     -relief =&gt; 'raised',
			     -text =&gt; "$type: " . basename($path))-&gt;pack(-expand =&gt; 1, -fill =&gt; 'both');
    my $t = $w-&gt;add("Table",
		    -relief =&gt; 'sunken',
		    -fixedcolumns =&gt; 2,
		    -fixedrows =&gt; 8);

    my ($dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size, $atime,
	$mtime, $ctime,	$blksize, $blocks) = stat($path);
    my ($user, $group);
    ($user, undef) = getpwuid($uid);
    ($group, undef) = getgrgid($gid);
    $user = $uid unless defined $user;
    $group = $gid unless defined $group;

    $t-&gt;put(0, 0, $t-&gt;Label(-text =&gt; "Size", -anchor =&gt; 'e'));
    $t-&gt;put(0, 1, $t-&gt;Label(-text =&gt; "$size bytes", -anchor =&gt; 'w'));
    $t-&gt;put(1, 0, $t-&gt;Label(-text =&gt; "Links", -anchor =&gt; 'e'));
    $t-&gt;put(1, 1, $t-&gt;Label(-text =&gt; $nlink, -anchor =&gt; 'w'));
    $t-&gt;put(2, 0, $t-&gt;Label(-text =&gt; "Mode", -anchor =&gt; 'e'));
    $t-&gt;put(2, 1, $t-&gt;Label(-text =&gt; sprintf("0%04o", $mode), -anchor =&gt; 'w'));
    $t-&gt;put(3, 0, $t-&gt;Label(-text =&gt; "Owner", -anchor =&gt; 'e'));
    $t-&gt;put(3, 1, $t-&gt;Label(-text =&gt; $user, -anchor =&gt; 'w'));
    $t-&gt;put(4, 0, $t-&gt;Label(-text =&gt; "Group", -anchor =&gt; 'e'));
    $t-&gt;put(4, 1, $t-&gt;Label(-text =&gt; $group, -anchor =&gt; 'w'));
    $t-&gt;put(5, 0, $t-&gt;Label(-text =&gt; "Last access", -anchor =&gt; 'e'));
    $t-&gt;put(5, 1, $t-&gt;Label(-text =&gt; scalar localtime($atime), -anchor =&gt; 'w'));
    $t-&gt;put(6, 0, $t-&gt;Label(-text =&gt; "Last modified", -anchor =&gt; 'e'));
    $t-&gt;put(6, 1, $t-&gt;Label(-text =&gt; scalar localtime($mtime), -anchor =&gt; 'w'));
    $t-&gt;put(7, 0, $t-&gt;Label(-text =&gt; "Last Inode change", -anchor =&gt; 'e'));
    $t-&gt;put(7, 1, $t-&gt;Label(-text =&gt; scalar localtime($ctime), -anchor =&gt; 'w'));

    $t-&gt;pack(-expand =&gt; 1, -fill =&gt; 'both');

    my $button = $w-&gt;Show;
    remove_with_confirm($path, "Confirm remove $type", $canvas, $list, $radius, $margin)
      if $button eq 'Remove';
}


# ###########################################################################
# Get the filesystem name corresponding to the currently selected piechart
# segment
#
sub get_name
{
    my ($canvas) = @_;
    my $name;

  tag:
    foreach ($canvas-&gt;gettags($canvas-&gt;find('withtag', 'current')))
    {
	next tag if $_ eq 'current';
	$name = $_;
	last tag;
    }
    return $name;
}


# ###########################################################################
# Get the segment ID corresponding to a filesystem name
#
sub get_seg
{
    my ($canvas, $file) = @_;
    return $canvas-&gt;find('withtag', $file);
}


# ###########################################################################
# Create an empty directory browser
#
sub create_browser
{
    my ($p, $canvas, $radius, $margin, $segstep) = @_;
    my @font =(-font =&gt; '-*-courier-Medium-R-Normal--*-100-*-*-*-*-*-*');
    my $hlist;
    $hlist = $p-&gt;Scrolled('HList',
			  -itemtype =&gt; 'text',
			  -separator =&gt; '/',
			  -relief =&gt; 'sunken',
			  -selectmode =&gt; 'browse',
			  -browsecmd =&gt; sub
			                {
					    my $file = shift;
					    highlight_segment($canvas,
							      \$hlist,
							      $radius,
							      $margin,
							      $segstep,
							      $file);
					},
			  -command =&gt; sub
			              {
					  my $file = shift;
					  cd_or_details_browser($canvas,
								\$hlist,
								$radius,
								$margin,
								$file);
				      },
			 )-&gt;pack(-fill =&gt; 'both', -expand =&gt; 'y');
    return $hlist;
}


# ###########################################################################
# Highlight an enty in the file list
#
sub highlight_list
{
    my ($canvas, $list) = @_;
    my $path = get_name($canvas);

    $list-&gt;selection('clear');
    $list-&gt;selection('set', $path);
    $list-&gt;see($path);
    $list-&gt;update();
}


# ###########################################################################
# Highlight a segment in the piechart
#
sub highlight_segment
{
    my ($canvas, $list, $radius, $margin, $segstep, $path) = @_;

    unhighlight_segment(@_);

    my $seg = $$list-&gt;info('data', $path);

    for my $tag ($canvas-&gt;gettags($seg))
    {
	return if $tag eq 'JustMe';
    }

    my($dx, $dy) = dxdy($canvas-&gt;itemcget($seg, '-start'),
			$canvas-&gt;itemcget($seg, '-extent'),
			$segstep);
    $canvas-&gt;move($seg, $dx . 'c', $dy . 'c');
    $canvas-&gt;addtag('*moved', 'withtag', $seg);
}


# ###########################################################################
# Remove highlighting from all segments
#
sub unhighlight_segment
{
    my ($canvas, $list, $radius, $margin, $segstep, $path) = @_;

    for my $seg ($canvas-&gt;find('withtag', '*moved'))
    {
	my($dx, $dy) = dxdy($canvas-&gt;itemcget($seg, '-start'),
			    $canvas-&gt;itemcget($seg, '-extent'),
			    -$segstep);
	$canvas-&gt;move($seg, $dx . 'c', $dy . 'c');
	$canvas-&gt;dtag($seg, '*moved');
    }
}


# ###########################################################################
# dxdy - calculate delta X and delta Y for radial move of segment
#
sub dxdy
{
    my($start, $sweep, $delta) = @_;
    $start = 0 unless defined $start;
    $sweep = 0 unless defined $sweep;
    $delta = 0 unless defined $delta;

    my $phi = 3.141592654 / 180.0 * ($start + ($sweep/2));
    return ($delta*cos($phi), -$delta*sin($phi));
}


# ###########################################################################
# Return a textual description of the type of a filesystem element
#
sub type_name
{
    my $entry = $_[0];

    if(-f $entry)
    {
	return "Executable" if -x $entry;
	return "File";
    }
    return "Directory" if -d $entry;
    return "Symlink" if -l $entry;
    return "FIFO" if -p $entry;
    return "Block special file" if -b $entry;
    return "Character special file" if -c $entry;
    return "Socket" if -S $entry;
    return "File";
}


# ###########################################################################
# Unlink a file, recursively delete a directory.
# Remove element from %size hash and redraw the screen.  Do not issue
# another du (it takes too long!)
#
sub remove
{
    my($path, $canvas, $list, $data, $radius, $margin) = @_;
    my $remove_ok = 0;

    if(-d $path)
    {
	system "rm -rf $path 2&gt;/dev/null";
	$remove_ok++ unless $?;
    }
    else
    {
	$remove_ok++ if (unlink $path) == 1;
    }

    if($remove_ok)
    {
	$total -= $data-&gt;{$path};
	delete $data-&gt;{$path};
	$list-&gt;delete('all');
	$canvas-&gt;delete('all');
	build_piechart($data, $total, $canvas, $radius, $margin, $list);
    }
    return $remove_ok;
}


# ###########################################################################
# Issue a confirm box, then call remove to delete directories or files and
# update the display as required
#
sub remove_with_confirm
{
    my ($path, $msg, $canvas, $list, $radius, $margin) = @_;
    my $w = $main-&gt;DialogBox(-title =&gt; "Remove $path", -buttons =&gt; ["Cancel", "OK"]);
    my $path_label = $w-&gt;add("Label",
			     -relief =&gt; 'raised',
			     -text =&gt; $msg . " " . basename($path) . "?")-&gt;pack(-expand =&gt; 1, -fill =&gt; 'both');
    my $button = $w-&gt;Show;
    return unless $button eq 'OK';

    unless (remove($path, $canvas, $list, \%size, $radius, $margin))
    {
	my $fail = $main-&gt;DialogBox(-title =&gt; "Failed Remove $path", -buttons =&gt; ["OK"]);
	my $path_label = $fail-&gt;add("Label",
				    -relief =&gt; 'raised',
				    -text =&gt; "Could not remove " . basename($path))-&gt;pack(-expand =&gt; 1, -fill =&gt; 'both');
	$fail-&gt;Show;
    }
}


# ###########################################################################
# Change focus directory up one level, and redraw the display
#
sub cdup
{
    my($dir, $canvas, $list, $radius, $margin) = @_;

    $$dir =~ s%/[^/]+$%% if $$dir and $$dir ne '/';
    redraw($dir, $canvas, $list, $radius, $margin);
}


# ###########################################################################
# Gather disk information again, and redisplay it
#
sub redraw
{
    my($dir, $canvas, $list, $radius, $margin) = @_;

    my $duhandle = start_du($$dir);
    $waitmsg = "Re-reading disk data...";
    $wait-&gt;Show;
    $main-&gt;title("Disk usage of $$dir"); # Add title
    $main-&gt;iconname($$dir);		# name the icon
    $waitmsg = "Reading data";
    $wait-&gt;update;
    $total = 0;
    %size = du_data($duhandle, \$total, \$waitmsg);
    close $duhandle;
    $waitmsg = "Building display";
    $wait-&gt;update;

    $list-&gt;delete('all');
    $canvas-&gt;delete('all');

    build_piechart(\%size, $total, $canvas, $radius, $margin, $list);
    $wait-&gt;unShow;
}


# ###########################################################################
# Enter show_details dialog from the directory browser
#
sub details
{
    my($list, $canvas, $radius, $margin) = @_;
    my $path = $list-&gt;info('anchor');

    details_box($path, $canvas, $list, $radius, $margin)
}


# ###########################################################################
# If the selected element on the browser is a file, pop up a details box.
# If it is a directory, change focus directory into it
#
sub cd_or_details_browser
{
    my($canvas, $list, $radius, $margin, $path) = @_;

    cd_or_show_details($canvas, $$list, $radius, $margin, $path);
}


# ###########################################################################
# Format a number using k/M/G suffixes
#
sub fmt_num
{
    my $n = $_[0];

    return sprintf("%d Bytes", $n) if $n &lt; 1024;
    $n /= 1024;
    return sprintf("%d kB", $n) if( ($n &gt;= 1) &amp;&amp; ($n &lt;= 1000));
    $n /= 1000;
    return sprintf("%d MB", $n) if( ($n &gt;= 1) &amp;&amp; ($n &lt;= 1000));
    $n /= 1000;
    return sprintf("%d GB", $n);
}

</pre></body></html>