File: FileDialog.pm

package info (click to toggle)
libtk-filedialog-perl 1.3-5
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 268 kB
  • ctags: 145
  • sloc: perl: 2,656; makefile: 2
file content (1071 lines) | stat: -rw-r--r-- 29,796 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
##################################################
##################################################
##						##
##	FileDialog - a reusable Tk-widget	##
##		     login screen		##
##						##
##	Version 1.2				##
##						##
##						##
##	Brent B. Powers				##
##	Merrill Lynch				##
##	powers@swaps-comm.ml.com		##
##						##
##						##
##################################################
##################################################

# Change History:
#   Version 1.0 - Initial implementation
#   96 Jan 15	ringger@cs.rochester.edu - Fixed dialogue box creation.
#   96 Jan 15	ringger - Added option for selecting directories.
#   96 Feb 29	powers - Rewrote and componentized, and added a bunch of
#		options.  Now requires perl 5.002gamma
#   96 May 30	mkr- add support for single character navigation within
#		lists, e.g. typing G in list will navigate to first entry
#		starting with G
#   96 May 30	mkr- fixed problem with click in empty file list
#   96 May 31	powers - refixed problem with click in empty list (couldn't
#			 click the first entry in list box)
#		       - altered single character navigation to prevent
#			 nudging the mouse while in an entry from grabbing
#			 focus.
#		       - altered single character navigation to go from
#			 first to next to next to first (et al)
#		       - Finished keyboard navigation with tabs
#   Version 1.2:
#   96 Jun  3	powers - Added Version, ship
#   Version 1.3
#   96 Jun  9	powers - Added Version, and then fixed the Makefile.PM
#   
#

=head1 NAME

Tk::FileDialog - A highly configurable File Dialog widget for Perl/Tk.  

=head1 DESCRIPTION

The widget is composed of a number
of sub-widgets, namely, a listbox for files and (optionally) directories, an entry
for filename, an (optional) entry for pathname, an entry for a filter pattern, a 'ShowAll'
checkbox (for enabling display of .* files and directories), and three buttons, namely
OK, Rescan, and Cancel.  Note that the labels for all subwidgets (including the text
for the buttons and Checkbox) are configurable for foreign language support.
The Listboxes will respond to characters typed over them with scrolling to
the first line that starts with the given character (or next etc. if this
character is not present).

=head1 SYNOPSIS

=head2 Usage Description

To use FileDialog, simply create your FileDialog objects during initialization (or at
least before a Show).  When you wish to display the FileDialog, invoke the 'Show' method
on the FileDialog object;  The method will return either a file name, a path name, or
undef.  undef is returned only if the user pressed the Cancel button.

=head2 Example Code

The following code creates a FileDialog and calls it.  Note that perl5.002gamma is
required.

 #!/usr/bin/perl -w

 use Tk;
 use Tk::FileDialog;
 use strict;

 my($main) = MainWindow->new;
 my($Horiz) = 1;
 my($fname);

 my($LoadDialog) = $main->FileDialog(-Title =>'This is my title',
 				    -Create => 0);

 print "Using FileDialog Version ",$LoadDialog->Version,"\n";

 $LoadDialog->configure(-FPat => '*pl',
 		       -ShowAll => 'NO');

 $main->Entry(-textvariable => \$fname)
 	->pack(-expand => 1,
 	       -fill => 'x');

 $main->Button(-text => 'Kick me!',
 	      -command => sub {
 		  $fname = $LoadDialog->Show(-Horiz => $Horiz);
 		  if (!defined($fname)) {
 		      $fname = "Fine,Cancel, but no Chdir anymore!!!";
 		      $LoadDialog->configure(-Chdir =>'NO');
 		  }
 	      })
 	->pack(-expand => 1,
 	       -fill => 'x');

 $main->Checkbutton(-text => 'Horizontal',
 		   -variable => \$Horiz)
 	->pack(-expand => 1,
 	       -fill => 'x');

 $main->Button(-text => 'Exit',
 	      -command => sub {
 		  $main->destroy;
 	      })
 	->pack(-expand => 1,
 	       -fill => 'x');

 MainLoop;

 print "Exit Stage right!\n";

 exit;

=head1 METHODS

The following non-standard methods may be used with a FileDialog object

=head2 Show

Displays the file dialog box for the user to operate.  Additional configuration
items may be passed in at Show-time In other words, this code snippet:

  $fd->Show(-Title => 'Ooooh, Preeeeeety!');

is the same as this code snippet:

  $fd->configure(-Title => 'Ooooh, Preeeeeety!');
  $fd->Show;

=head2 Version

Returns the current Version of FileDialog

=head1 CONFIGURATION

Any of the following configuration items may be set via the configure (or Show) method,
or retrieved via the cget method.

=head2 I<Flags>

Flags may be configured with either 1,'true', or 'yes' for 1, or 0, 'false', or 'no'
for 0. Any portion of 'true', 'yes', 'false', or 'no' may be used, and case does not
matter.

=over 4

=item -Chdir

Enable the user to change directories. The default is 1. If disabled, the directory
list box will not be shown.

=item -Create

Enable the user to specify a file that does not exist. If not enabled, and the user
specifies a non-existent file, a dialog box will be shown informing the user of the
error (This Dialog Box is configurable via the EDlg* switches, below).

default: 1

=item -ShowAll

Determines whether hidden files (.*) are displayed in the File and Directory Listboxes.
The default is 0. The Show All Checkbox reflects the setting of this switch.

=item -DisableShowAll

Disables the ability of the user to change the status of the ShowAll flag. The default
is 0 (the user is by default allowed to change the status).

=item -Grab

Enables the File Dialog to do an application Grab when displayed. The default is 1.

=item -Horiz

True sets the File List box to be to the right of the Directory List Box. If 0, the
File List box will be below the Directory List box. The default is 1.

=item -SelDir

If True, enables selection of a directory rather than a file, and disables the
actions of the File List Box. The default is 0.

=back

=head2 I<Special>

=over 4

=item -FPat

Sets the default file selection pattern. The default is '*'. Only files matching
this pattern will be displayed in the File List Box.

=item -Geometry

Sets the geometry of the File Dialog. Setting the size is a dangerous thing to do.
If not configured, or set to '', the File Dialog will be centered.

=item -SelHook

SelHook is configured with a reference to a routine that will be called when a file
is chosen. The file is called with a sole parameter of the full path and file name
of the file chosen. If the Create flag is disabled (and the user is not allowed
to specify new files), the file will be known to exist at the time that SelHook is
called. Note that SelHook will also be called with directories if the SelDir Flag
is enabled, and that the FileDialog box will still be displayed. The FileDialog box
should B<not> be destroyed from within the SelHook routine, although it may generally
be configured.

SelHook routines return 0 to reject the selection and allow the user to reselect, and
any other value to accept the selection. If a SelHook routine returns non-zero, the
FileDialog will immediately be withdrawn, and the file will be returned to the caller.

There may be only one SelHook routine active at any time. Configuring the SelHook
routine replaces any existing SelHook routine. Configuring the SelHook routine with
0 removes the SelHook routine. The default SelHook routine is undef.

=back

=head2 I<Strings>

The following two switches may be used to set default variables, and to get final
values after the Show method has returned (but has not been explicitly destroyed
by the caller)

=over 4

=item -File

The file selected, or the default file. The default is ''.

=item -Path

The path of the selected file, or the initial path. The default is $ENV{'HOME'}.

=back

=head2 I<Labels and Captions>

For support of internationalization, the text on any of the subwidgets may be
changed.

=over 4

=item -Title

The Title of the dialog box. The default is 'Select File:'.

=item -DirLBCaption

The Caption above the Directory List Box. The default is 'Directories'.

=item -FileLBCaption

The Caption above the File List Box. The default is 'Files'.

=item -FileEntryLabel

The label to the left of the File Entry. The Default is 'Filename:'.

=item -PathEntryLabel

The label to the left of the Path Entry. The default is 'Pathname:'.

=item -FltEntryLabel

The label to the left of the Filter entry. The default is 'Filter:'.

=item -ShowAllLabel

The text of the Show All Checkbutton. The default is 'Show All'.

=back

=head2 I<Button Text>

For support of internationalization, the text on the three buttons may be changed.

=over 4

=item -OKButtonLabel

The text for the OK button. The default is 'OK'.

=item -RescanButtonLabel

The text for the Rescan button. The default is 'Rescan'.

=item -CancelButtonLabel

The text for the Cancel button. The default is 'Cancel'.

=back

=head2 I<Error Dialog Switches>

If the Create switch is set to 0, and the user specifies a file that does not exist,
a dialog box will be displayed informing the user of the error. These switches allow
some configuration of that dialog box.

=over 4

=item -EDlgTitle

The title of the Error Dialog Box. The default is 'File does not exist!'.

=item -EDlgText

The message of the Error Dialog Box. The variables $path, $file, and $filename
(the full path and filename of the selected file) are available. The default
is I<"You must specify an existing file.\n(\$filename not found)">

=back

=head1 Author

B<Brent B. Powers, Merrill Lynch (B2Pi)>

powers@ml.com

This code may be distributed under the same conditions as Perl itself.

=cut

package Tk::FileDialog;

require 5.002;
use Tk;
use Tk::Dialog;
use Carp;
use strict;

@Tk::FileDialog::ISA = qw(Tk::Toplevel);

Tk::Widget->Construct('FileDialog');

$Tk::FileDialog::VERSION = '1.3';

### Global Variables (Convenience only)
my(@topPack) = (-side => 'top', -anchor => 'center');
my(@rightPack) = (-side => 'right', -anchor => 'center');
my(@leftPack) = (-side => 'left', -anchor => 'center');
my(@xfill) = (-fill => 'x');
my(@yfill) = (-fill => 'y');
my(@bothFill) = (-fill => 'both');
my(@expand) = (-expand => 1);
my(@raised) = (-relief => 'raised');

my(@TabOrder) = qw (DirList
		    FileList
		    FileEntry
		    DirEntry
		    PatEntry
		    SABox
		    OK
		    Rescan
		    Can
		    DirList);

sub Populate {
    ## File Dialog constructor, inherits new from Toplevel
    my($FDialog, @args) = @_;

    $FDialog->SUPER::Populate(@args);

    $FDialog->withdraw;

    $FDialog->protocol('WM_DELETE_WINDOW' => sub {
	if (defined($FDialog->{'Can'}) && $FDialog->{'Can'}->IsWidget ) {
	    $FDialog->{'Can'}->invoke;
	}
    });
    $FDialog->transient($FDialog->parent->toplevel);

    foreach (@TabOrder) {
	$FDialog->{'TabSel'}->{$_} = 1;
    }

    ## Initialize variables that won't be initialized later
    $FDialog->{'Retval'} = -1;
    $FDialog->{'DFFrame'} = 0;

    $FDialog->{Configure}{-Horiz} = 1;

    $FDialog->BuildFDWindow;
    $FDialog->{'activefore'} = $FDialog->{'SABox'}->cget(-foreground);
    $FDialog->{'inactivefore'} = $FDialog->{'SABox'}->cget(-disabledforeground);

    $FDialog->ConfigSpecs(-Chdir		=> ['PASSIVE', undef, undef, 1],
			  -Create		=> ['PASSIVE', undef, undef, 1],
			  -DisableShowAll	=> ['PASSIVE', undef, undef, 0],
			  -FPat			=> ['PASSIVE', undef, undef, '*'],
			  -File			=> ['PASSIVE', undef, undef, ''],
			  -Geometry		=> ['PASSIVE', undef, undef, undef],
			  -Grab			=> ['PASSIVE', undef, undef, 1],
			  -Horiz		=> ['PASSIVE', undef, undef, 1],
			  -Path			=> ['PASSIVE', undef, undef, "$ENV{'HOME'}"],
			  -SelDir		=> ['PASSIVE', undef, undef, 0],
			  -DirLBCaption		=> ['PASSIVE', undef, undef, 'Directories:'],
			  -FileLBCaption	=> ['PASSIVE', undef, undef, 'File:'],
			  -FileEntryLabel	=> ['METHOD', undef, undef, 'Filename:'],
			  -PathEntryLabel	=> ['METHOD', undef, undef, 'Pathname:'],
			  -FltEntryLabel	=> ['METHOD', undef, undef, 'Filter:'],
			  -ShowAllLabel		=> ['METHOD', undef, undef, 'ShowAll'],
			  -OKButtonLabel	=> ['METHOD', undef, undef, 'OK'],
			  -RescanButtonLabel	=> ['METHOD', undef, undef, 'Rescan'],
			  -CancelButtonLabel	=> ['METHOD', undef, undef, 'Cancel'],
			  -SelHook		=> ['PASSIVE', undef, undef, undef],
			  -ShowAll		=> ['PASSIVE', undef, undef, 0],
			  -Title		=> ['PASSIVE', undef, undef, "Select File:"],
			  -EDlgTitle		=> ['PASSIVE', undef, undef,
						   'File does not exist!'],
			  -EDlgText		=> ['PASSIVE', undef, undef,
						    "You must specify an existing file.\n"
						    . "(\$filename not found)"]);
}


### A few methods for configuration
sub OKButtonLabel {
    &SetButton('OK',@_);
}
sub RescanButtonLabel {
    &SetButton('Rescan',@_);
}
sub CancelButtonLabel {
    &SetButton('Can',@_);
}

sub SetButton {
    my($widg, $self, $title) = @_;
    if (defined($title)) {
	## This is a configure
	$self->{$widg}->configure(-text => $title);
    }
    ## Return the current value
    $self->{$widg}->cget(-text);
}

sub FileEntryLabel {
    &SetLabel('FEF', @_);
}
sub PathEntryLabel {
    &SetLabel('PEF', @_);
}
sub FltEntryLabel {
    &SetLabel('patFrame', @_);
}
sub ShowAllLabel {
    &SetButton('SABox', @_);
}
sub SetLabel {
    my($widg, $self, $title) = @_;
    if (defined($title)) {
	## This is a configure
	$self->{$widg}->{'Label'}->configure(-text => $title);
    }
    ## Return the current value
    $self->{$widg}->{'Label'}->cget(-text);
}

sub SetFlag {
    ## Set the given flag to either 1 or 0, as appropriate
    my($self, $flag, $dflt) = @_;

    $flag = "-$flag";

    ## We know it's defined as there was a ConfigDefault call after the Populate
    ## call.  Therefore, all we have to do is parse the non-numerics
    if (&IsNum($self->{Configure}{$flag})) {
	$self->{Configure}{$flag} = 1 unless $self->{Configure}{$flag} == 0;
    } else {
	my($val) = $self->{Configure}{$flag};

	my($fc) = lc(substr($val,0,1));

	if (($fc eq 'y') || ($fc eq 't')) {
	    $val = 1;
	} elsif (($fc eq 'n') || ($fc eq 'f')) {
	    $val = 0;
	} else {
	    ## bad value, complain about it
	    carp ("\"$val\" is not a valid flag ($flag)!");
	    $dflt = 0 if !defined($dflt);
	    $val = $dflt;
	}
	$self->{Configure}{$flag} = $val;
    }
    return $self->{Configure}{$flag};
}

sub Version {return $Tk::FileDialog::VERSION;}

sub Show {
    my ($self) = shift;

    $self->configure(@_);

    ## Clean up flag variables
    $self->SetFlag('Chdir');
    $self->SetFlag('Create');
    $self->SetFlag('ShowAll');
    $self->SetFlag('DisableShowAll');
    $self->SetFlag('Horiz');
    $self->SetFlag('Grab');
    $self->SetFlag('SelDir');

    croak "Can't SelDir and Not ChDir" if $self->{Configure}{-SelDir} &&
	    !$self->{Configure}{-Chdir};

    ## Set up, or remove, the directory box
    &BuildListBoxes($self);

    ## Enable, or disable, the show all box
    if ($self->{Configure}{-DisableShowAll}) {
	$self->{'SABox'}->configure(-state => 'disabled');
	$self->{'TabSel'}->{'SABox'} = 0;
    } else {
	$self->{'SABox'}->configure(-state => 'normal');
	$self->{'TabSel'}->{'SABox'} = 1;
    }

    ## Enable or disable the file entry box
    if ($self->{Configure}{-SelDir}) {
	$self->{Configure}{-File} = '';
	$self->{'FileEntry'}->configure(-state => 'disabled',
					-foreground => $self->{'inactivefore'});
	$self->{'FileList'}->configure(-selectforeground => $self->{'inactivefore'});
	$self->{'FileList'}->configure(-foreground => $self->{'inactivefore'});
	$self->{'TabSel'}->{'FileEntry'} = $self->{'TabSel'}->{'FileList'} = 0;
    } else {
	$self->{'FileEntry'}->configure(-state => 'normal',
					-foreground => $self->{'activefore'});
	$self->{'FileList'}->configure(-selectforeground => $self->{'activefore'});
	$self->{'FileList'}->configure(-foreground => $self->{'activefore'});
	$self->{'TabSel'}->{'FileEntry'} = $self->{'TabSel'}->{'FileList'} = 1;
    }

    ## Set the title
    $self->title($self->{Configure}{-Title});

    ## Create window position (Center unless configured)
    $self->update;
    if (defined($self->{Configure}{-Geometry})) {
	$self->geometry($self->{Configure}{-Geometry});
    } else {
	my($x,$y);
	$x = int(($self->screenwidth - $self->reqwidth)/2 - $self->parent->vrootx);
	$y = int(($self->screenheight - $self->reqheight)/2 - $self->parent->vrooty);
	$self->geometry("+$x+$y");
    }

    ## Set up the tab order
    &SetTabs($self);

    ## Fill the list boxes
    &RescanFiles($self);
    ## Restore the window, and go
    $self->update;
    $self->deiconify;

    ## Set up the grab
    $self->grab if ($self->{Configure}{-Grab});

    ## Initialize status variables
    $self->{'Retval'} = 0;
    $self->{'RetFile'} = "";

    my($i) = 0;
    while (!$i) {
	$self->tkwait('variable',\$self->{'Retval'});
	$i = $self->{'Retval'};
	if ($i != -1) {
	    ## No cancel, so call the hook if it's defined
	    if (defined($self->{Configure}{-SelHook})) {
		## The hook returns 0 to ignore the result,
		## non-zero to accept.  Must release the grab before calling
		$self->grab('release') if (defined($self->grab('current')));

		$i = &{$self->{Configure}{-SelHook}}($self->{'RetFile'});

		$self->grab if ($self->{Configure}{-Grab});
	    }
	} else {
	    $self->{'RetFile'} = undef;
	}
    }

    $self->grab('release') if (defined($self->grab('current')));

    $self->withdraw;

    return $self->{'RetFile'};
}

####  PRIVATE METHODS AND SUBROUTINES ####
sub IsNum {
    my($parm) = @_;
    my($warnSave) = $^W;
    $^W = 0;
    my($res) = (($parm + 0) eq $parm);
    $^W = $warnSave;
    return $res;
}

sub TabNext {
    my($self, $inc) = @_;
    my($f) = $self->{'OK'}->focusCurrent;
    return if !defined($f);
    ## Find the object with the matching focus...
    my($i) = 0;
    foreach (@TabOrder) {
	if ($self->{$_} eq $f) {
	    $i = $#TabOrder if !$i && $inc == -1;

	    $i += $inc;

	    while (!defined($TabOrder[$i]) ||
		   !ref($self->{$TabOrder[$i]}) ||
		   !$self->{$TabOrder[$i]}->IsWidget ||
		   !($self->{'TabSel'}->{$TabOrder[$i]})) {
# 		   (($TabOrder[$i] == 'FileList') &&
# 		    $self->{Configure}{-SelDir}) ) {
		$i += $inc;
		$i = $#TabOrder if !$i && $inc == -1;
		$i = 0 if $i > $#TabOrder && $inc == 1;
	    }
	    $self->{$TabOrder[$i]}->focus;
	    $self->break;
	    return;
	}
	$i++;
    }
}

sub SetTabs {
    my($self) = shift;

    foreach (@TabOrder) {
	next if (!defined($self->{$_}) ||
		 !ref $self->{$_} ||
		 !$self->{$_}->IsWidget);
    
	$self->{$_}->bind("<Tab>", sub {\&TabNext($self, 1);});
	$self->{$_}->bind("<Shift-Tab>", sub {\&TabNext($self, -1);});
    }
}

sub BuildListBox {
    my($self, $fvar, $flabel, $listvar,$hpack, $vpack) = @_;

    ## Create the subframe
    $self->{"$fvar"} = $self->{'DFFrame'}->Frame
	    ->pack(-side => $self->{Configure}{-Horiz} ? $hpack : $vpack,
		   -anchor => 'center',
		   @bothFill, @expand);

    ## Create the label
    $self->{"$fvar"}->Label(@raised, -text => "$flabel")
	    ->pack(@topPack, @xfill);

    ## Create the frame for the list box
    my($fbf) = $self->{"$fvar"}->Frame
	    ->pack(@topPack, @bothFill, @expand);

    ## And the scrollbar and listbox in it
    $self->{"$listvar"} = $fbf->Listbox(@raised, -exportselection => 0)
	    ->pack(@leftPack, @expand, @bothFill);

    $fbf->AddScrollbars($self->{"$listvar"});
    $fbf->configure(-scrollbars => 'rse');
}

sub DirSel {
    my($self, $lbdir) = @_;
    
    my($np) = $lbdir->curselection;
    return if !defined($np);
    $np = $lbdir->get($np);
    if ($np eq "..") {
	## Moving up one directory
	$_ = $self->{Configure}{-Path};
	chop if m!/$!;
	s!(.*/)[^/]*$!$1!;
	$self->{Configure}{-Path} = $_;
    } else {
	## Going down into a directory
	$self->{Configure}{-Path} .= "/" . "$np/";
    }
    $self->{Configure}{-Path} =~ s!//*!/!g;
    \&RescanFiles($self);
}

sub BindDir {
    ### Set up the bindings for the directory selection list box
    my($self) = @_;

    my($lbdir) = $self->{'DirList'};
    $lbdir->bind("<Double-1>" => sub {&DirSel($self, $lbdir);});

    # binding to take focus if clicked
    $lbdir->bind("<1>", sub{$self->{'DirList'}->focus;});
    
    # binding to attract focus if mouse over list
    $lbdir->bind("<Enter>", sub{&listFocus($self, 'DirList');});

    # binding to move to requested line by hitting a key
    $lbdir->bind("<KeyPress>", sub{\&list_see($self,'Dir');});

    # binding to select and rescan if someone hits return
    $lbdir->bind("<Return>", sub {&DirSel($self,$lbdir);});

}


sub FileSel {
    my($self) = shift;
    if (!$self->{Configure}{-SelDir}) {
	my($f) = $self->{'FileList'}->curselection;
	return if !defined($f);
	$self->{'File'} = $self->{'FileList'}->get($f);
	$self->{'OK'}->invoke;
    }
}

sub BindFile {
    ### Set up the bindings for the file selection list box
    my($self) = @_;

    ## A single click selects the file...
    $self->{'FileList'}->bind("<ButtonRelease-1>", sub {
	if (!$self->{Configure}{-SelDir}) {
	    my($n);
	    return if (!defined($n=$self->{'FileList'}->curselection));
	    ($self->{Configure}{-File} = $self->{'FileList'}->get($n));
	    ##if defined($n);
	}
    });
    ## A double-click selects the file for good
    $self->{'FileList'}->bind("<Double-1>", sub {&FileSel($self);});

    # binding to take focus if clicked
    $self->{'FileList'}->bind("<1>", sub{
				 $self->{'FileList'}->focus;
			     });

    # binding to attract focus if mouse over list
    $self->{'FileList'}->bind("<Enter>", sub{
				  &listFocus($self, 'FileList');
			      });

    # binding to select and be done if someone hits return
    $self->{'FileList'}->bind("<Return>", sub {&FileSel($self);});

    # binding to move to requested line by hitting a key
    $self->{'FileList'}->bind("<KeyPress>", sub{&list_see($self,'File');});

    $self->{'FileList'}->configure(-selectforeground => 'blue');
}

sub BuildEntry {
    ### Build the entry, label, and frame indicated.  This is a
    ### convenience routine to avoid duplication of code between
    ### the file and the path entry widgets
    my($self, $LabelVar, $entry) = @_;
    $LabelVar = "-$LabelVar";

    ## Create the entry frame
    my $eFrame = $self->Frame(@raised)
	    ->pack(@topPack, @xfill);

    ## Now create and pack the title and entry
    $eFrame->{'Label'} = $eFrame->Label(@raised)
	    ->pack(@leftPack);

    $self->{"$entry"} = $eFrame->Entry(@raised,
				     -textvariable => \$self->{Configure}{$LabelVar})
	    ->pack(@rightPack, @expand, @xfill);

    $self->{"$entry"}->bind("<Return>",sub {
	&RescanFiles($self);
	$self->{'OK'}->focus;
    });

    return $eFrame;
}

sub BuildListBoxes {
    my($self) = shift;

    ## Destroy both, if they're there
    if ($self->{'DFFrame'} && $self->{'DFFrame'}->IsWidget) {
	$self->{'DFFrame'}->destroy;
    }

    $self->{'DFFrame'} = $self->Frame;
    $self->{'DFFrame'}->pack(-before => $self->{'FEF'},
			     @topPack, @bothFill, @expand);

    ## Build the file window before the directory window, even
    ## though the file window is below the directory window, we'll
    ## pack the directory window before.
    &BuildListBox($self, 'FileFrame',
		  $self->{Configure}{-FileLBCaption},
		  'FileList','right','bottom');
    ## Set up the bindings for the file list
    &BindFile($self);

    if ($self->{Configure}{-Chdir}) {
	&BuildListBox($self,'DirFrame',$self->{Configure}{-DirLBCaption},
		      'DirList','left','top');
	&BindDir($self);
    }
}

sub BuildFDWindow {
    ### Build the entire file dialog window
    my($self) = shift;

    ### Build the filename entry box
    $self->{'FEF'} = &BuildEntry($self, 'File', 'FileEntry');

    ### Build the pathname directory box
    $self->{'PEF'} = &BuildEntry($self, 'Path','DirEntry');

    ### Now comes the multi-part frame
    my $patFrame = $self->Frame(@raised)
	    ->pack(@topPack, @xfill);

    ## Label first...
    $self->{'patFrame'}->{'Label'} = $patFrame->Label(@raised)
	    ->pack(@leftPack);

    ## Now the entry...
    $self->{'PatEntry'} = $patFrame->Entry(@raised, -textvariable => \$self->{Configure}{-FPat})
	    ->pack(@leftPack, @expand, @xfill);
    $self->{'PatEntry'}->bind("<Return>",sub {\&RescanFiles($self);});


    ## and the Check box
    $self->{'SABox'} = $patFrame->Checkbutton(-variable => \$self->{Configure}{-ShowAll},
					     -command => sub {\&RescanFiles($self);})
	    ->pack(@leftPack);

    ### FINALLY!!! the button frame
    my $butFrame = $self->Frame(@raised);
    $butFrame->pack(@topPack, @xfill);

    $self->{'OK'} = $butFrame->Button(-command => sub {
	\&GetReturn($self);
    })
	    ->pack(@leftPack, @expand, @xfill);

    $self->{'Rescan'} = $butFrame->Button(-command => sub {
	\&RescanFiles($self);
    })
	    ->pack(@leftPack, @expand, @xfill);

    $self->{'Can'} = $butFrame->Button(-command => sub {
	$self->{'Retval'} = -1;
    })
	    ->pack(@leftPack, @expand, @xfill);
}

sub RescanFiles {
    ### Fill the file and directory boxes
    my($self) = shift;

    my($fl) = $self->{'FileList'};
    my($dl) = $self->{'DirList'};
    my($path) = $self->{Configure}{-Path};
    my($show) = $self->{Configure}{-ShowAll};
    my($chdir) = $self->{Configure}{-Chdir};

    ### Remove a final / if it is there, and add it
    $path = '' if !defined($path);
    if ((length($path) == 0) || (substr($path,-1,1) ne '/')) {
	$path .= '/';
	$self->{Configure}{-Path} = $path;
    }
    ### path now has a trailing / no matter what
    if (!-d $path) {
	carp "$path is NOT a directory\n";
	return 0;
    }

    $self->configure(-cursor => 'watch');
    my($OldGrab) = $self->grab('current');
    $self->{'OK'}->grab;
    $self->{'OK'}->configure(-state => 'disabled');
    $self->update;
    opendir(ALLFILES,$path);
    my(@allfiles) = readdir(ALLFILES);
    closedir(ALLFILES);

    my($direntry);

    ## First, get the directories...
    if ($chdir) {
	$dl->delete(0,'end');
	my %see; # hold index if first occurrence of first character of direntry
	my $n=0; # number of entry in list
	foreach $direntry (sort @allfiles) {
	    next if !-d "$path$direntry";
	    next if $direntry eq ".";
	    if (   !$show
		&& (substr($direntry,0,1) eq ".")
		&& $direntry ne "..") {
		next;
	    }
	    $dl->insert('end',$direntry);
	    if(! exists($see{substr($direntry,0,1)})){
	       $see{substr($direntry,0,1)}=$n;
	    }
	    $n++;
	}
	$self->{see_Dir}=\%see;
    }

    ## Now, get the files
    $fl->delete(0,'end');

    $_ = $self->{Configure}{-FPat};
    s/^\s*|\s*$//;
    $_ = $self->{Configure}{-FPat} = '*' if $_ eq '';

    my($pat) = $_;
    undef @allfiles;

    @allfiles = <$path.$pat> if $show;

    @allfiles = (@allfiles, <$path$pat>);

    my %see; # hold index if first occurrence of first character of fileentry
    my $n=0; # number of entry in list
    my $fileentry;
    foreach $fileentry (sort @allfiles) {
	if (-f $fileentry) {
	    $fileentry =~ s!.*/!!; # mkr s!.*/([^/]*)$!$1!;
	    $fl->insert('end',$fileentry);
	    if(! exists($see{substr($fileentry,0,1)})){
	       $see{substr($fileentry,0,1)}=$n;
	    }
	    $n++;
	}
	$self->{see_File}=\%see;
    }
    $self->configure(-cursor => 'top_left_arrow');

    $self->{'OK'}->grab('release') if $self->grab('current') == $self->{'OK'};
    $OldGrab->grab if defined($OldGrab);
    $self->{'OK'}->configure(-state => 'normal');
    $self->update;
    return 1;
}

sub GetReturn {
    my ($self) = @_;

    ## Construct the filename
    my $path = $self->{Configure}{-Path};
    my $fname;

    $path .= "/" if (substr($path, -1, 1) ne '/');

    if ($self->{Configure}{-SelDir}) {
	$fname = $self->{'DirList'};

	if (defined($fname->curselection)) {
	    $fname = $fname->get($fname->curselection);
	} else {
	    $fname = '';
	}
	$fname = $path . $fname;
	$fname =~ s/\/$//;
    } else {
	$fname = $path . $self->{Configure}{-File};
	## Make sure that the file exists, if the user is not allowed
	## to create
	if (!$self->{Configure}{-Create} && !(-f $fname)) {
	    ## Put up no create dialog
	    my($path) = $self->{Configure}{-Path};
	    my($file) = $self->{Configure}{-File};
	    my($filename) = $fname;
	    eval "\$fname = \"$self->{Configure}{-EDlgText}\"";
	    $self->Dialog(-title => $self->{Configure}{-EDlgTitle},
			  -text => $fname,
			  -bitmap => 'error')
		    ->Show;
	    ## And return
	    return;
	}
    }

    $self->{'RetFile'} = $fname;

    $self->{'Retval'} = 1;

}

sub listFocus {
    ## Change focus ONLY if current focus is not an entry...
    my ($self, $lb) = @_;

    my($f) = $self->{$lb}->focusCurrent;
    if (defined($f) &&
	$f ne $self->{'FileEntry'} &&
	$f ne $self->{'DirEntry'} &&
	$f ne $self->{'PatEntry'}) {
	$self->{$lb}->focus;
    }
}

sub list_see{
    my ($self, $what) = @_; # $what is dir or file

    my $list=$self->{"${what}List"}; # Dir or File
    my $see=$self->{"see_$what"};    # index hash
    my $char=$list->XEvent->A;       # key pressed
    if (exists($see->{$char})) {     # line with char there?
	## Yes, it is...
	my ($ndx) = $see->{$char};
	
	## Is it already selected?
	my($cs) = $list->curselection;
	if (defined($cs)) {
	    
	    if (($cs == $ndx) ||
		(substr($list->get($cs),0,1) eq $char)) {
		## does the next in the list start with the same char?
		if (defined($list->get($cs + 1)) &&
		    (substr($list->get($cs + 1),0,1) eq $char)) {
		    $ndx = ++$cs;
		}
	    }
	}
	$list->see($ndx);    # yes, so show it.
	$list->selection('clear',0,'end');
	return if $self->{Configure}{-SelDir};
	$list->selection('set', $ndx);
	$self->{Configure}{-File} = $list->get($ndx) if $what eq 'File';
    } else {                          # search next line in sequence
	while(!exists($see->{$char}) && length($char) == 1) {
	    $char++;
	}
	if(exists($see->{$char})){
	    $char = $see->{$char};
	    $list->see($char-1) if $char;    # Show the one before
	    $list->see($char);    # and show this one...
# 	} else {
# 	    $list->bell;
	}
    }   
}


### Return 1 to the calling  use statement ###
1;
### End of file FileDialog.pm ###
__END__