#!/usr/local/bin/perl -w
#
# This script generates a directory browser, which lists the working directory and allows you to open files or subdirectories
# by double-clicking.
#
# Tcl/Tk -> Perl translation by Stephen O. Lidie.  lusol@Lehigh.EDU  95/01/16

require 5.001;
use English;
use File::Basename;
use Tk;

$top = MainWindow->new;

# Create a scrollbar on the right side of the main window and a listbox on the left side.

$scroll = $top->Scrollbar();
$scroll->pack(-side => 'right', -fill => 'y');
$list = $top->Listbox(-yscrollcommand => ['set', $scroll], -relief => 'sunken', -width => 20, -height => 20, -setgrid => 'yes');
$list->pack(-side => 'left', -fill => 'both', -expand => 'yes');
$scroll->configure(-command => ['yview', $list]);
$top->minsize(1, 1);

# Fill the listbox with a list of all the files in the directory.

if (scalar @ARGV > 0) {
    $dir = $ARGV[0];
} else {
    $dir = '.';
}
foreach $i (<${dir}/*>) {
    $list->insert('end', basename($i));
}

# Set up bindings for the browser.

$list->bind('all', '<Control-c>' => sub {exit});
$list->bind('<Double-Button-1>' => sub {
    my($l, $e, $i) = @ARG;
    foreach $i (split ' ', $l->get('active')) {
	&browse($dir, $i);
    }
});

MainLoop;


sub browse {

    # The procedure below is invoked to open a browser on a given file;  if the file is a directory then another instance of
    # this program is invoked; if the file is a regular file then an editor is invoked to display the file.

    my($dir, $file) = @ARG;

    if ($dir ne '.') {
	$file = "$dir/$file";
    }
    if (-d $file) {
	system "browse $file &";
    } else {
	if (-f $file) {
	    print STDOUT "Viewing file $file ...\n";
	    if (defined $ENV{'EDITOR'}) {
		system "$ENV{'EDITOR'} $file &";
	    } else {
		system "vi $file &";
	    }
	} else {
	    print STDOUT "\"$file\" isn't a directory or regular file\n";
	}
    } # ifend

} # end browse
