#!/usr/local/bin/perl -w

use AddINC qw(./blib .);

use Tk;
require Tk::SunDragDrop;
require Tk::Tiler;

{package Dragable;
 @ISA = qw(Tk::Label);
 (bless \qw(Dragable))->WidgetClass;

 sub classinit
 {my $class = shift;
 }

 sub new
  {my $class  = shift;
   my $parent = shift;
   my $obj = $parent->Label(@_);
   $obj->bind('<B1-Motion>','DragDrop');
   return bless $obj,$class;
  }

 sub Handle
 {
  my $w = shift;
  my $seln = $w->{'DragDrop'};
  $seln = $w->DragDropSource unless(defined $seln);
  $w->SelectionHandle('-selection'=>$seln,@_);
 }

}

$icon_dir = "Tk/demos/images";

%icons = ();

sub choose_icon
{
 my $w    = shift;
 my $name = shift;
 my $icon = (-d $name) ? "dir" : ($name =~ /\.([^\.]+)$/) ? $1 : "page";
 if (!defined $icons{$icon})
  {
  RESTART:
   my $file = "$icon_dir/$icon.icon";
   my $mask = "$icon_dir/$icon.mask";
   $file = "$icon_dir/page.icon" unless (-f $file);
   $mask = "$icon_dir/page.mask" unless (-f $mask);
   $icons{$icon} = $w->Bitmap($icon,-file=> $file,-maskfile=>$mask); 
   if ($icons{$icon}->width != 32)
    {
     $icon = 'page';
     goto RESTART;
    }
  }
 return $icons{$icon};
}

sub Edit
{
 my $w = shift;
 my $path = shift;
 if (-T $path)
  {
   fork || exec("$ENV{EDITOR} $path");
  }
}

sub handle_string
{my ($string,$offset,$max) = @_;
 return $string;
}

sub do_dir
{
 my $w   = shift; 
 my $dir = shift;
 opendir(DIR,$dir);
 my @files = readdir(DIR);
 closedir(DIR);
 my @windows = ();
 my $width  = 0;
 my $height = 0;
 my $bg     = $w->cget(-background);
 my @win    = ();
 foreach (sort @files)
  {
   next if (/^\.*$/);
   my $path = "$dir/$_";
   my $f = $w->Frame(-background=>$bg);
   my $i = $f->Dragable(-image=> choose_icon($w,$path),-background=>$bg);
   $i->Handle('-type'=>'FILE_NAME',[\&handle_string,"$dir/$_"]);
   my $l = $f->Label(-text=> $_,-background=>$bg);
   $i->bind('<FocusIn>','break');
   $i->pack(-side=>'top');
   $l->pack(-side=>'bottom',-fill=> 'x');
   if (-d $path)
    {
     $w->Manage($f);
    }
   else
    {
     $i->bind('<Double-1>',[\&Edit,$path]);
     push(@win,$f);
    }
  }
 $w->Manage(@win);
}

$dir = shift || `pwd`;

$top = MainWindow->new();

$f   = $top->Frame(-width=>100, -height=>100);
$t   = $f->Tiler();
$s   = $f->Scrollbar(-orient=>'vertical',-command=>['yview',$t]);
$t->configure(-yscrollcommand=>['set',$s]);
$s->pack(-side=>'left',-fill=>'y');
$t->pack(-side=>'right',-fill=>'both',-expand=>1);
$f->pack(-fill=>'both',-expand=>1);
do_dir($t,$dir);

$t->focus;

MainLoop;
