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

BEGIN 
 {
  require lib;
  chomp($dir = `pwd`);
  import lib "$dir/blib";
 }

use Tk;
use Tk::DropSite qw(Sun);
use Tk::DragDrop qw(Sun);
require Tk::TextUndo;
require Tk::FileSelect;
require Tk::Menubar;
use Tk::ErrorDialog;

my $top = MainWindow->new();

my $mb = $top->Menubar;

$top->optionAdd('*TextUndo.Background' => '#fff5e1');

my $fs  = $top->Component(FileSelect => 'fs',-width => 25, -height => 8,
                       '-accept'   => sub 
                                     { my $file = shift ; 
                                       return 0 if (-s $file && !(stat(_))[12]);
                                       return (-r $file) && (-T $file);  
                                     },
                       Name => 'fs', -filter => '*');

my $t = $top->Scrolled(TextUndo, -wrap => 'none', -scrollbars => 'osre');

my $dd = $t->DragDrop(-event => '<Meta-B1-Motion>');
$dd->configure(-startcommand => 
               sub
                {
                 return 1 unless (eval { $t->tagNextrange(sel => '1.0','end')});
                 $dd->configure(-text => $t->get('sel.first','sel.last')); 
                });
                
$t->DropSite(-motioncommand => 
              sub 
               { my ($x,$y) = @_;
                 $t->markSet(insert => "\@$x,$y");
               },
              -dropcommand => 
              sub 
               { my ($seln,$x,$y) = @_;
                 $t->markSet(insert => "\@$x,$y");
                 $t->insert(insert => $t->SelectionGet(-selection => $seln));
               }
             );

$mb->Menubutton(-text => '~File', -menuitems => 
                  [[Button => '~Open',
                   -command => sub { my $file = $fs->Show(-popover => $top);
                               $t->Load($file) if (defined $file);
                             }
                  ]]);

$mb->Menubutton(-text => '~File', -menuitems => 
                 [['Button' => '~Save', -command => [ $t , 'Save' ]],
                  ['Button' => '~Quit', -command => [ 'destroy',$top ]],
                  ['Button' => '~Empty', -command => [ $t,'delete','1.0','end']]
                 ]);

$mb->Menubutton(-text => '~Help', -side => 'right');


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

if (@ARGV) {
    if (! -e $ARGV[0]) {
        open(FILE,">$ARGV[0]") or die "Could not open $ARGV[0]: $!";
        close(FILE) or die "There was trouble with $ARGV[0]: $!";
    }
    $t->Load($ARGV[0]);
}

MainLoop;
