#!/usr/local/bin/perl5.6.1 -w
#
# $Id: display_preview.pm,v 1.26 2004/06/23 14:24:32 mng Exp $
#
# $Log: display_preview.pm,v $
# Revision 1.26  2004/06/23  14:24:32  mng
# Removed highlighting of multiple versions.
#
# Revision 1.25  2004/01/15  14:03:37  mng
# Fixed page sizes so that it matches print out.
#
# Revision 1.24  2003/11/06  11:43:58  mng
# CHanged permissions for submit file in badger dir.
#
# Revision 1.23  2003/02/05  11:50:39  mng
# *** empty log message ***
#
# Revision 1.22  2003/02/05  11:43:02  mng
# changed zoom cursor to grab hand.
#
# Revision 1.21  2003/01/20  11:04:40  mng
# Added experimental 'zoom into area stroked out with right mouse button' function.
#
# Revision 1.20  2002/10/30  11:33:39  mng
# *** empty log message ***
#
# Revision 1.19  2002/10/30  11:31:10  mng
# changed to perl5.6.1.
#
# Revision 1.18  2002/01/02  13:20:54  mng
# Removed hard-coding of number of pages. Altered to work out
# the number of pages needed to display.
#
# Revision 1.17  2001/12/07  11:12:00  mng
# Removed error tagging from overlapping clones where clone and
# length is not specified.
#
# Revision 1.16  2001/04/05  07:37:46  mng
# *** empty log message ***
#
# Revision 1.15  2001/02/27  09:32:29  mng
# added tags for version deletion
#
# Revision 1.14  2001/02/21  10:36:27  mng
# Fixed warning dialog
#
# Revision 1.13  2001/02/21  07:48:57  mng
# added andy's fixing code.
#
# Revision 1.11  2001/02/09  10:59:29  holroyd
# *** empty log message ***
#
# Revision 1.10  2001/02/09  10:30:42  holroyd
# Entered STDERR message for user when project
# is submitted.
#
# Revision 1.9  2001/02/08  08:49:49  mng
# added check for error rate value.
#
# Revision 1.8  2001/01/23  10:03:43  mng
# added cursor changes when zoomed in.
#
# Revision 1.7  2001/01/23  09:42:23  mng
# Fixed scrollregion.
#
# Revision 1.6  2001/01/23  09:29:27  mng
# added grab for preview.
#
# Revision 1.5  2001/01/19  15:15:11  mng
# *** empty log message ***
#
# Revision 1.4  2001/01/19  15:10:41  mng
# added page count window to canvas.
#
# Revision 1.3  2001/01/15  14:39:30  mng
# *** empty log message ***
#
# Revision 1.2  2001/01/15  11:18:43  mng
# Fixed problems writing files for split databases.
#
# Revision 1.1  2001/01/12  15:20:29  mng
# Initial revision
#
#
#
# 67 lpp
#
#
# perl module ( just playing ) that i cobbled together
# to look like print preview. Used a small font that gets
# tagged red when a value is expected. This allows 'at a glance'
# checking of the form. 
#
#       ** if it's not all black....send it back **
#

use strict;
use Tk::BrowseEntry;
use Tk::Dialog;

package display_preview;

use POSIX qw(ceil);

sub new {
  my ($type, $main, $file, $printers, $proj, @data) = @_;
  my $self = {
	      window   => $main,     # Main window for app.
	      filename => $file,     # Current load file.
	      project  => $proj,     # projectname.
	      formdata => [@data],   # the entire form in memory.
              printers => $printers  # scalar array of printers.
	     };
  bless  $self, $type;

  $self->buildwindow;
  return $self;
}


#
# Construct the main window.
#
sub buildwindow {

  my $self = shift;
  my $n = 0;

  my $lc = 0;
  my $set = 0;
  my $printer = $ENV{PRINTER};
  my ($pri,$rer);
  my $images= '/usr/local/badger/lib/images';
  my %iinfo = ();		# item information hash
  $iinfo{areaX1} = 0;
  $iinfo{areaY1} = 0;
  $iinfo{areaX2} = 0;
  $iinfo{areaY2} = 0;
  $iinfo{restore_cmd} = '';

  $self->{mw} = $self->{window}->Toplevel();  
  $self->{mw}->title("Preview");
  $self->{mw}->wm('minsize',800, 510,);
  $self->{mw}->wm('maxsize',800, 510,);
  $self->{mw}->grab();
  
  $self->{mf} = $self->{mw}->Frame(-width => 100,
				   -relief => 'raised',
				   -borderwidth => 4)
    ->pack(-side => 'left', -fill => 'y');
  
  $self->{frame} = $self->{mw}->Frame()
    ->pack(-side => 'left');
  
  $self->{dis} = $self->{frame}->Canvas(-width => '800', 
					-height => '600',                                        
                                        );
  
  $self->{vscroll} = $self->{frame}->Scrollbar(-borderwidth => 1,
					       -command => [$self->{dis} => 'yview']);
  $self->{hscroll} = $self->{frame}->Scrollbar(-borderwidth => 1,
					       -orient => 'horiz',
					       -command => [$self->{dis} => 'xview']);
					      
  
  $self->{dis}->configure(-xscrollcommand => [$self->{hscroll} => 'set']);
  $self->{dis}->configure(-yscrollcommand => [$self->{vscroll} => 'set']);
  
  $self->{hscroll}->pack(-side => 'bottom', -fill => 'x');
  $self->{vscroll}->pack(-side => 'right', -fill => 'y');			     
  
  
  $self->{dis}->pack(-side => 'left');
  
  $self->{dis}->packPropagate(0);

  #############################################################
  # Dynamically work out and add the relevant number of pages.
  #

  my $number_of_pages = ceil(scalar(@{$self->{formdata}}) / 86); # Get number of pages using POSIX func..  
  
  # constant values for pages.
  my $const_x = 50;
  my $const_y = 580;

  # start values;
  my $start_x = 20;
  my $start_y = 330;
  for(my $num_page = 1; $num_page <= $number_of_pages; $num_page++) {      
      $self->{num_page} = $self->{dis}->createRectangle($start_x,
                                                        $const_x,
                                                        $start_y,
                                                        $const_y, 
                                                        -fill => 'white', 
                                                        -tags => 'PAGE'); 
      $start_x += 320;
      $start_y += 320;
  }

  my $ypos = 65;
  my $xpos = 25;
  foreach my $line (@{$self->{formdata}}) {
      my $er;
      # Flag the checks that really need an answer.
      if($line =~ /Final/) { chomp $line; ($er) = $line =~ /(\d+)$/;}
      if(($line =~ /[^overlapping clone|overlap]\s+~\s+$/)
         || ($line =~  /^\(.*\s+NO/) 
         || ($er && $er < 50000)) {
          ($er < 50000) ? $rer = $er : "";
          $self->{$n} = $self->{dis}->createText($xpos,
                                                 $ypos,
                                                 -font => '-*-clean-medium-r-normal-*-5-80-*-*-c-*-*-*',
                                                 -fill => 'red',
                                                 -text => $line,
                                                 -anchor => 'w',
                                                 -tags => ['TEXT','RED',"$line"]);
      }else {
          $self->{$n} = $self->{dis}->createText($xpos,
                                                 $ypos,
                                                 -font => '-*-clean-medium-r-normal-*-5-80-*-*-c-*-*-*',
                                                 -text => $line,
                                                 -anchor => 'w',
                                                 -tags => 'TEXT','',"$line");
      }
      ++$n; $ypos += 6; ++$lc; 
      if(($lc % 86)==0) {
          $n = 0;
          $xpos += 320;
          $ypos = 65;
      }
  }

  my $scroll_distance;
  if($number_of_pages > 2) { 
      $scroll_distance = $number_of_pages * 10;
      $scroll_distance .= "c";
      $self->{dis}->configure(-scrollregion => ['0c','0c',"$scroll_distance",'0c']);   
  }
  
  
  $self->{cl} = $self->{mf}->Button(-text => 'Close',
				    -command => sub { 
				      $self->{mw}->destroy(); 
				    })
    ->pack(-side => 'top', -pady => 5);
  
  
  $self->{zoom} = $self->{mf}->Button(-text => 'Zoom +',
				      -command => sub {
                                          if($set) {
                                              $self->{zoom}->configure(-text => 'Zoom +');
                                              ($number_of_pages > 2) ? $self->{dis}->configure(-scrollregion => ['0c','0c',$scroll_distance,'0c']) : 
                                                  $self->{dis}->configure(-scrollregion => ['0c','0c','0c','0c']);
                                              $self->{dis}->scale('PAGE',1,1,0.5,0.5);
                                              $self->{dis}->scale('TEXT',1,1,0.5,0.5);
                                              $self->{dis}->itemconfigure('TEXT',-font => '-*-clean-medium-r-normal-*-5-80-*-*-c-*-*-*');
					      $self->{dis}->configure(-cursor=> 'top_left_arrow');
                                              --$set;
                                          }else{
                                              $self->{zoom}->configure(-text => 'Zoom -');
                                              my $dist = $number_of_pages * 20;
                                              $dist .= "c";
                                              ($number_of_pages > 2) ? $self->{dis}->configure(-scrollregion => ['0c','1.5c',$dist,'35c'])  
                                                  : $self->{dis}->configure(-scrollregion => ['0c','1.5c','36c','35c']);
                                              $self->{dis}->scale('PAGE',1,1,2,2);
                                              $self->{dis}->scale('TEXT',1,1,2,2);
                                              $self->{dis}->itemconfigure('TEXT',-font => '-*-clean-medium-r-normal-*-14-80-*-*-c-*-*-*');
                                              $self->{dis}->configure(-cursor=>["@/usr/local/badger/lib/images/hand.xbm","$images/hand_mask.xbm","black","white"]);
                                              ++$set;				      
                                          }
                                      })
      ->pack(-side => 'top',-pady => 50);
  
  $self->{dis}->Tk::bind('<ButtonPress-2>' => sub {			   
      if($set) {
          $self->{dis}->configure(-cursor => ["@/usr/local/badger/lib/images/grab.xbm","$images/grab_mask.xbm","black","white"]);
          my $e = $self->{dis}->XEvent;
          $self->{dis}->scan('mark', $e->x, $e->y);
      }
  });
  $self->{dis}->Tk::bind('<B2-Motion>' => sub {
      if($set) {
          my $e = $self->{dis}->XEvent;
          $self->{dis}->scan('dragto', $e->x, $e->y);
      }
  });
  
  $self->{dis}->Tk::bind('<B2-ButtonRelease>' => sub {
			   if($set) {
                               $self->{dis}->configure(-cursor => ["@/usr/local/badger/lib/images/hand.xbm","$images/hand_mask.xbm","black","white"]);
			   }
                       });

  $self->{dis}->CanvasBind('<3>' => 
                           sub { if(!$set) { &items_mark(shift, $Tk::event->x, $Tk::event->y, \%iinfo)}});
  
  $self->{dis}->CanvasBind('<B3-Motion>' =>
                           sub { if(!$set) { &items_stroke(shift, $Tk::event->x, $Tk::event->y, \%iinfo);}});
  
  $self->{dis}->CanvasBind('<B3-ButtonRelease>' => 
                           sub {
                               if(!$set) { 
                                   my $e = $self->{dis}->XEvent;
                                   &items_under_area($self, \%iinfo, \$set, $number_of_pages, $scroll_distance);   
                               }
                           });
  

  $self->{iframe} = $self->{dis}->Frame(-relief => 'ridge',
					-borderwidth => 4,
				       );	
  
  $self->{dis}->createWindow(70,26,-window => $self->{iframe});


  $self->{pages} = $self->{iframe}->Label(-text => "View : $number_of_pages pages") 
      ->pack(-anchor => 'center');

  $self->{eframe} = $self->{mf}->Frame();
  $self->{submit} = $self->{eframe}->Button(-text => 'Submit',
					    -command => sub {&check_submit($self)},
					    -fg => 'green'
					   );
  
  $self->{append} = $self->{eframe}->Button(-text => 'Append',
					    -command => sub {&append_notes($self)},
					   );
  

  $self->{pl} = $self->{mf}->Label(-text => 'Printer');
  $self->{pr} = $self->{mf}->BrowseEntry(-variable => \$pri, 
					 -width => 8,
					 -state => 'normal');
  $self->{e} = $self->{pr}->Subwidget("entry")->Subwidget("entry");
  $self->{e}->configure(-bg => 'LemonChiffon2');

  foreach my $choice (@{$self->{printers}}) {
    $self->{pr}->insert("end", $choice);
  }
  $self->{e}->insert('0',$printer) if ($printer);
  
  $self->{pb} = $self->{mf}->Button(-text => 'Print copy',
				    -command => sub{&print_submit_file($self,$pri)});
  
  $self->{submit}->pack(-side => 'top');
  $self->{append}->pack(-side => 'top');
  $self->{eframe}->pack(-side => 'top', -pady => 60);

  $self->{pl}->pack(-side => 'top',-pady => 5);
  $self->{pr}->pack(-side => 'top',-pady => 5); 
  $self->{pb}->pack(-side => 'top',-pady => 5);

  # deny submission if error rate is less than 50000.
  if($rer) {
    $self->{submit}->configure(-state => 'disabled');
  }	
  

}

#
# Raise an 'are you sure' box for the premature finisher :-)
#
sub check_submit {

  my ($self) = @_;
  
  my ( $badness ) = $self->{dis}->find('withtag','RED');
  if( $badness ) {
    return if ! $self->askSure("Errors found! Are you sure you want to submit ?" );
    &write_badger_file($self);
  }else{
    &write_badger_file($self);
  }
}

#
# Entry box for filename to append.
#
sub append_notes {

  my($self) = @_;
  
  my $file = $self->{project} . '.assembly.notes';
  my $pop = $self->{mw}->Toplevel();
  $pop->grab();
  $pop->configure(-title => 'Filename...');
  my $poplabel = $pop->Label(-text => 'Enter filename to write to:',
			     -font => '*times*-r*20*')
    ->pack(-anchor => 'n');
  my $popent = $pop->Entry(-width => '35',
			   -textvariable => \$file)
    ->pack(-anchor => 'n');
  
  my $cancel =  $pop->Button(-text => 'Stop',
			     -font => '*times*-r*20*',
			     -bg => 'red',
			     -command => sub{$pop->destroy;})
    ->pack(-side => 'left');
  my $ok = $pop->Button(-text => 'Go',
			-font => '*times*-r*20*',
			-bg => 'green',
			-command => sub{
			  $pop->destroy; 
			  &write_to_file($self,$file)
			})
    ->pack(-side => 'right');
  
}
#
# Print the form.....
#
sub print_submit_file {

my ($self,$pri) = @_;

unless(open(LP,"| lpr -P$pri")) {
  print STDERR " Unable to open pipe to printer.$!\n";
  return;
}
print LP "@{$self->{formdata}}\n";
close(LP);
}
#
# Append the form....
#
sub write_to_file {
my ($self,$filename) = @_;

unless(open(FILE,">>$filename")) {
  print STDERR " Unable to open filename $filename for writing.$!\n";
  return;
}
print FILE "@{$self->{formdata}}\n";
close(FILE);
}

#
# Write the form....
#
sub write_badger_file {

  my($self) = @_;
  my $ftw;
  my($ap) = $self->{filename};
  if($ap) { $ftw = "$self->{project}"."."."$ap"; }else{ $ftw = $self->{project}; }	

  unless(open(KO,">/nfs/disk54/badger/SUBMIT/$ftw")) {
    warn " Unable to open badger file for writing. Mail Bug $!\n";
    return;
  }
  
  print KO "@{$self->{formdata}}\n";
  close(KO);

  my $mode = 0666;
  chmod $mode, "/nfs/disk54/badger/SUBMIT/$ftw";
  
  print STDERR "SUCCESS: $ftw has been submitted\n";
  
}

sub askSure {
        my ($self,$text) = @_;

        my $d = $self->{window}->Dialog(-text=> $text,
					   -buttons=>['Yes', 'No', 'Cancel'],
					   -justify=>'center',
					   -wraplength=>0,
                                        );
	my $reply = $d->Show;
	$d->wm('resizable', 0, 0);
	if ($reply eq 'Yes') { return 1; }
	if ($reply eq 'No') { return 0; }
	if ($reply eq 'Cancel') { return 0; }
	
      }

sub items_stroke {

    my($c, $x, $y, $iinfo) = @_;

    $x = $c->canvasx($x);
    $y = $c->canvasy($y);
    if (($iinfo->{areaX1} != $x) and ($iinfo->{areaY1} != $y)) {
	$c->delete('area');
	$c->addtag('area', 'withtag', $c->create('rectangle',
	    $iinfo->{areaX1}, $iinfo->{areaY1}, $x, $y, -outline => 'black'));
	$iinfo->{areaX2} = $x;
	$iinfo->{areaY2} = $y;
    }

}
sub items_mark {

    my($c, $x, $y, $iinfo) = @_;

    $iinfo->{areaX1} = $c->canvasx($x);
    $iinfo->{areaY1} = $c->canvasy($y);
    $c->delete('area');

}

sub items_under_area {

    my($self, $iinfo, $set, $number_of_pages, $scroll_distance) = @_;

    my $c = $self->{dis};

    my $area = $c->find('withtag', 'area');
    my @items  = ();
    my $i;
    foreach $i ($c->find('overlapping', $iinfo->{areaX1},
            $iinfo->{areaY1}, $iinfo->{areaX2}, $iinfo->{areaY2})) {
	my @tags = $c->gettags($i); 
	if (defined($tags[0]) and grep $_ eq 'TEXT', @tags) {
	    push @items, $i;
	}
    }
    if(!@items) { $c->delete('area'); return; }

    $self->{zoom}->configure(-text => 'Zoom -');
    my $dist = $number_of_pages * 20;
    $dist .= "c";
    ($number_of_pages > 2) ? $self->{dis}->configure(-scrollregion => ['0c','1.5c',$dist,'35c'])  
        : $self->{dis}->configure(-scrollregion => ['0c','1.5c','35.5c','35c']);
    $self->{dis}->scale('PAGE',1,1,2,2);
    $self->{dis}->scale('TEXT',1,1,2,2);
    $self->{dis}->itemconfigure('TEXT',-font => '-*-clean-medium-r-normal-*-14-80-*-*-c-*-*-*');
    ++$$set;				      
    
    my @coords_list = $c->coords($items[0]);
    $c->xview("scroll",$coords_list[0]/90,"units");
    $c->yview("scroll",$coords_list[1]/100,"units");
    $c->delete('area');
    
}

1;

