#!/usr/local/bin/perl -w
BEGIN { unshift(@INC,'../blib','blib') }
use Tk;

$fw_font  = "-*-Courier-Medium-R-Normal--*-120-*-*-*-*-*-*";

use Tk;
require Tk::Ghostview;

use strict qw(subs);


$top = MainWindow->new();
$gs  = $top->Ghostview($ARGV[0]);
$f = $top->Frame();
$l = $top->ScrlListbox('-width' => $gs->Doc->{'LabelLen'});
$l->bind('<Double-1>',[sub { shift; shift->SetPage(@_) },$gs,Ev('index','active')]);
$l->insert("end",@{$gs->Doc->{'Label'}});
$f->Button('-text'=>'Quit','-command'=>['destroy',$top])->pack('-side'=>'left');
$f->pack('-side'=>'top','-fill'=>'x');
$l->pack('-side'=>'left','-fill'=>'y');

$mb = $f->Menubutton('-text'=>'Contents');

$contents = $gs->Doc->Contents;

foreach $kind (sort keys %{$contents})
 {
  if ($kind !~ /#[LT]len$/)
   {
    Contents($mb,$kind,$contents{$kind},
             $contents{$kind.'#Llen'},
             $contents{$kind.'#Tlen'},
             $gs);
   }
 }
$mb->pack('-side'=>'right');

$mb = $f->Menubutton('-text'=>'Orientation');
$mb->command('-label'=> 'Portrait',  '-command'=>['Orientation',$gs,'Portrait']);
$mb->command('-label'=> 'Landscape', '-command'=>['Orientation',$gs,'Landscape']);
$mb->command('-label'=> 'Upsidedown', '-command'=>['Orientation',$gs,'Upsidedown']);
$mb->command('-label'=> 'Seascape', '-command'=>['Orientation',$gs,'Seascape']);

$mb->pack('-side'=>'right');

$gs->pack('-expand'=>'yes','-fill'=>'both');

$gs->update;
$gs->focus;

MainLoop;

sub Contents
{
 my ($mb,$kind,$it,$lw,$tw,$gs) = @_;
 my $base = $mb->toplevel;
 my $top  = $base->Toplevel();
 $top->withdraw;
 $top->title($kind);
# $top->transient($base);
 $top->protocol('WM_DELETE_WINDOW',['withdraw',$top]);
 my $lb = $top->ScrlListbox('-width' => $lw+$tw,'-font' => $fw_font);
 $top->Label('-text'=>$kind)->pack('-side'=>'top');
 $lb->insert('end',map(sprintf("%-${lw}s %s",${$_}[0],${$_}[1]),@$it));
 $lb->pack('-side'=>'right','-fill'=>'y');
 $mb->command('-label'=>$kind,'-command'=>['TopRight',$top,$base]);
 $lb->bind('<Double-1>',[\&DoContent,$it,$gs]);
}

sub DoContent
{
 my ($lb,$it,$gs) = @_;
 my $key = $lb->index('active');
 my $page = ${$it}[$key][2];
 $gs->SetPage($page);
}


