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

use Tk;
use Tk::DropSite qw(Sun);
use Tk::DragDrop qw(Sun);
use File::Basename qw(fileparse);
require Tk::TextUndo;
require Tk::Menubar;
use Tk::ErrorDialog;

my $top = MainWindow->new();

my $mb = $top->Menubar;

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

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

unless ($^O eq 'MSWin32')
 {
  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 = $t->getOpenFile;
                               $t->Load($file) if (defined $file);
                             }],
                   [Button => 'Save ~As ...', -command => [\&SaveAs, $t ]],
                  ]);

$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 => '~Options', -menuitems => 
                 [['Button' => '~Colour', 
                    -command => sub { 
                                      my $c = $t->cget('-background');
                                      $c = $t->chooseColor(-initialcolor => $c);
                                      $t->configure(-background => $c) if defined $c;
                                     }],
                 ]);

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


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

$t->Load($ARGV[0]) if (@ARGV);

MainLoop;                     

sub SaveAs
{ 
 my $t = shift;
 my $path = $t->FileName || "./NewFile.txt";                   
 my ($file,$dir,$suffix) = fileparse($path);
 $path = $t->getSaveFile(-initialdir => $dir, -initialfile => $file);
 $t->Save($file) if (defined $path);
}
