blib/lib/Tk/FileDialog.pm untested

filter: SCAR -
1 ##################################################
2 ##################################################
3 ## ##
4 ## FileDialog - a reusable Tk-widget ##
5 ## login screen ##
6 ## ##
7 ## Version 1.2 ##
8 ## ##
9 ## ##
10 ## Brent B. Powers ##
11 ## Merrill Lynch ##
12 ## powers@swaps-comm.ml.com ##
13 ## ##
14 ## ##
15 ##################################################
16 ##################################################
17  
18 # Change History:
19 # Version 1.0 - Initial implementation
20 # 96 Jan 15 ringger@cs.rochester.edu - Fixed dialogue box creation.
21 # 96 Jan 15 ringger - Added option for selecting directories.
22 # 96 Feb 29 powers - Rewrote and componentized, and added a bunch of
23 # options. Now requires perl 5.002gamma
24 # 96 May 30 mkr- add support for single character navigation within
25 # lists, e.g. typing G in list will navigate to first entry
26 # starting with G
27 # 96 May 30 mkr- fixed problem with click in empty file list
28 # 96 May 31 powers - refixed problem with click in empty list (couldn't
29 # click the first entry in list box)
30 # - altered single character navigation to prevent
31 # nudging the mouse while in an entry from grabbing
32 # focus.
33 # - altered single character navigation to go from
34 # first to next to next to first (et al)
35 # - Finished keyboard navigation with tabs
36 # Version 1.2:
37 # 96 Jun 3 powers - Added Version, ship
38 # Version 1.3
39 # 96 Jun 9 powers - Added Version, and then fixed the Makefile.PM
40 #
41 #
42  
43 =head1 NAME
44  
45 Tk::FileDialog - A highly configurable File Dialog widget for Perl/Tk.
46  
47 =head1 DESCRIPTION
48  
49 The widget is composed of a number
50 of sub-widgets, namely, a listbox for files and (optionally) directories, an entry
51 for filename, an (optional) entry for pathname, an entry for a filter pattern, a 'ShowAll'
52 checkbox (for enabling display of .* files and directories), and three buttons, namely
53 OK, Rescan, and Cancel. Note that the labels for all subwidgets (including the text
54 for the buttons and Checkbox) are configurable for foreign language support.
55 The Listboxes will respond to characters typed over them with scrolling to
56 the first line that starts with the given character (or next etc. if this
57 character is not present).
58  
59 =head1 SYNOPSIS
60  
61 =over 4
62  
63 =head2 Usage Description
64  
65 To use FileDialog, simply create your FileDialog objects during initialization (or at
66 least before a Show). When you wish to display the FileDialog, invoke the 'Show' method
67 on the FileDialog object; The method will return either a file name, a path name, or
68 undef. undef is returned only if the user pressed the Cancel button.
69  
70 =head2 Example Code
71  
72 The following code creates a FileDialog and calls it. Note that perl5.002gamma is
73 required.
74  
75 =over 4
76  
77 =item
78  
79 #!/usr/local/bin/perl -w
80  
81 use Tk;
82 use Tk::FileDialog;
83 use strict;
84  
85 my($main) = MainWindow->new;
86 my($Horiz) = 1;
87 my($fname);
88  
89 my($LoadDialog) = $main->FileDialog(-Title =>'This is my title',
90 -Create => 0);
91  
92 print "Using FileDialog Version ",$LoadDialog->Version,"\n";
93  
94 $LoadDialog->configure(-FPat => '*pl',
95 -ShowAll => 'NO');
96  
97 $main->Entry(-textvariable => \$fname)
98 ->pack(-expand => 1,
99 -fill => 'x');
100  
101 $main->Button(-text => 'Kick me!',
102 -command => sub {
103 $fname = $LoadDialog->Show(-Horiz => $Horiz);
104 if (!defined($fname)) {
105 $fname = "Fine,Cancel, but no Chdir anymore!!!";
106 $LoadDialog->configure(-Chdir =>'NO');
107 }
108 })
109 ->pack(-expand => 1,
110 -fill => 'x');
111  
112 $main->Checkbutton(-text => 'Horizontal',
113 -variable => \$Horiz)
114 ->pack(-expand => 1,
115 -fill => 'x');
116  
117 $main->Button(-text => 'Exit',
118 -command => sub {
119 $main->destroy;
120 })
121 ->pack(-expand => 1,
122 -fill => 'x');
123  
124 MainLoop;
125  
126 print "Exit Stage right!\n";
127  
128 exit;
129  
130  
131 =back
132  
133 =back
134  
135 =head1 METHODS
136  
137 =over 4
138  
139 =item
140  
141 The following non-standard methods may be used with a FileDialog object
142  
143 =item
144  
145 =head2 Show
146  
147 =over 4
148  
149 Displays the file dialog box for the user to operate. Additional configuration
150 items may be passed in at Show-time In other words, this code snippet:
151  
152 $fd->Show(-Title => 'Ooooh, Preeeeeety!');
153  
154 is the same as this code snippet:
155  
156 $fd->configure(-Title => 'Ooooh, Preeeeeety!');
157 $fd->Show;
158  
159  
160 =back
161  
162 =item
163  
164 =head2 Version
165  
166 Returns the current Version of FileDialog
167  
168 =back
169  
170 =head1 CONFIGURATION
171  
172 Any of the following configuration items may be set via the configure (or Show) method,
173 or retrieved via the cget method.
174  
175 =head2 I<Flags>
176  
177 Flags may be configured with either 1,'true', or 'yes' for 1, or 0, 'false', or 'no'
178 for 0. Any portion of 'true', 'yes', 'false', or 'no' may be used, and case does not
179 matter.
180  
181 =over 4
182  
183 =item
184  
185 =head2 -Chdir
186  
187 =over 8
188  
189 =item
190  
191 Enable the user to change directories. The default is 1. If disabled, the directory
192 list box will not be shown.
193  
194 =back
195  
196 =head2 -Create
197  
198 =over 8
199  
200 =item
201  
202 Enable the user to specify a file that does not exist. If not enabled, and the user
203 specifies a non-existent file, a dialog box will be shown informing the user of the
204 error (This Dialog Box is configurable via the EDlg* switches, below).
205  
206 default: 1
207  
208 =back
209  
210 =head2 -ShowAll
211  
212 =over 8
213  
214 =item
215  
216 Determines whether hidden files (.*) are displayed in the File and Directory Listboxes.
217 The default is 0. The Show All Checkbox reflects the setting of this switch.
218  
219 =back
220  
221 =head2 -DisableShowAll
222  
223 =over 8
224  
225 =item
226  
227 Disables the ability of the user to change the status of the ShowAll flag. The default
228 is 0 (the user is by default allowed to change the status).
229  
230 =back
231  
232 =head2 -Grab
233  
234 =over 8
235  
236 =item
237  
238 Enables the File Dialog to do an application Grab when displayed. The default is 1.
239  
240 =back
241  
242 =head2 -Horiz
243  
244 =over 8
245  
246 =item
247  
248 True sets the File List box to be to the right of the Directory List Box. If 0, the
249 File List box will be below the Directory List box. The default is 1.
250  
251 =back
252  
253 =head2 -SelDir
254  
255 =over 8
256  
257 =item
258  
259 If True, enables selection of a directory rather than a file, and disables the
260 actions of the File List Box. The default is 0.
261  
262 =back
263  
264 =back
265  
266 =head2 I<Special>
267  
268 =over 4
269  
270 =item
271  
272 =head2 -FPat
273  
274 =over 8
275  
276 =item
277  
278 Sets the default file selection pattern. The default is '*'. Only files matching
279 this pattern will be displayed in the File List Box.
280  
281 =back
282  
283 =head2 -Geometry
284  
285 =over 8
286  
287 =item
288  
289 Sets the geometry of the File Dialog. Setting the size is a dangerous thing to do.
290 If not configured, or set to '', the File Dialog will be centered.
291  
292 =back
293  
294 =head2 -SelHook
295  
296 =over 8
297  
298 =item
299  
300 SelHook is configured with a reference to a routine that will be called when a file
301 is chosen. The file is called with a sole parameter of the full path and file name
302 of the file chosen. If the Create flag is disabled (and the user is not allowed
303 to specify new files), the file will be known to exist at the time that SelHook is
304 called. Note that SelHook will also be called with directories if the SelDir Flag
305 is enabled, and that the FileDialog box will still be displayed. The FileDialog box
306 should B<not> be destroyed from within the SelHook routine, although it may generally
307 be configured.
308  
309 SelHook routines return 0 to reject the selection and allow the user to reselect, and
310 any other value to accept the selection. If a SelHook routine returns non-zero, the
311 FileDialog will immediately be withdrawn, and the file will be returned to the caller.
312  
313 There may be only one SelHook routine active at any time. Configuring the SelHook
314 routine replaces any existing SelHook routine. Configuring the SelHook routine with
315 0 removes the SelHook routine. The default SelHook routine is undef.
316  
317 =back
318  
319 =back
320  
321 =head2 I<Strings>
322  
323 The following two switches may be used to set default variables, and to get final
324 values after the Show method has returned (but has not been explicitly destroyed
325 by the caller)
326  
327 =over 4
328  
329 =item
330  
331 B<-File> The file selected, or the default file. The default is ''.
332  
333 B<-Path> The path of the selected file, or the initial path. The default is $ENV{'HOME'}.
334  
335 =back
336  
337 =head2 I<Labels and Captions>
338  
339 For support of internationalization, the text on any of the subwidgets may be
340 changed.
341  
342 =over 4
343  
344 =item
345  
346 B<-Title> The Title of the dialog box. The default is 'Select File:'.
347  
348 B<-DirLBCaption> The Caption above the Directory List Box. The default is 'Directories'.
349  
350 B<-FileLBCaption> The Caption above the File List Box. The default is 'Files'.
351  
352 B<-FileEntryLabel> The label to the left of the File Entry. The Default is 'Filename:'.
353  
354 B<-PathEntryLabel> The label to the left of the Path Entry. The default is 'Pathname:'.
355  
356 B<-FltEntryLabel> The label to the left of the Filter entry. The default is 'Filter:'.
357  
358 B<-ShowAllLabel> The text of the Show All Checkbutton. The default is 'Show All'.
359  
360 =back
361  
362 =head2 I<Button Text>
363  
364 For support of internationalization, the text on the three buttons may be changed.
365  
366 =over 4
367  
368 =item
369  
370 B<-OKButtonLabel> The text for the OK button. The default is 'OK'.
371  
372 B<-RescanButtonLabel> The text for the Rescan button. The default is 'Rescan'.
373  
374 B<-CancelButtonLabel> The text for the Cancel button. The default is 'Cancel'.
375  
376 =back
377  
378 =head2 I<Error Dialog Switches>
379  
380 If the Create switch is set to 0, and the user specifies a file that does not exist,
381 a dialog box will be displayed informing the user of the error. These switches allow
382 some configuration of that dialog box.
383  
384 =over 4
385  
386 =item
387  
388 =head2 -EDlgTitle
389  
390 =over 8
391  
392 =item
393  
394 The title of the Error Dialog Box. The default is 'File does not exist!'.
395  
396 =back
397  
398 =head2 -EDlgText
399  
400 =over 8
401  
402 =item
403  
404 The message of the Error Dialog Box. The variables $path, $file, and $filename
405 (the full path and filename of the selected file) are available. The default
406 is I<"You must specify an existing file.\n(\$filename not found)">
407  
408 =back
409  
410 =back
411  
412 =head1 Author
413  
414 B<Brent B. Powers, Merrill Lynch (B2Pi)>
415  
416 powers@ml.com
417  
418 This code may be distributed under the same conditions as Perl itself.
419  
420 =cut
421  
422 package Tk::FileDialog;
423  
424 require 5.002;
425 use Tk;
426 use Tk::Dialog;
427 use Carp;
428 use strict;
429  
430 @Tk::FileDialog::ISA = qw(Tk::Toplevel);
431  
432 Tk::Widget->Construct('FileDialog');
433  
434 $Tk::FileDialog::VERSION = '1.3';
435  
436 ### Global Variables (Convenience only)
437 my(@topPack) = (-side => 'top', -anchor => 'center');
438 my(@rightPack) = (-side => 'right', -anchor => 'center');
439 my(@leftPack) = (-side => 'left', -anchor => 'center');
440 my(@xfill) = (-fill => 'x');
441 my(@yfill) = (-fill => 'y');
442 my(@bothFill) = (-fill => 'both');
443 my(@expand) = (-expand => 1);
444 my(@raised) = (-relief => 'raised');
445  
446 my(@TabOrder) = qw (DirList
447 FileList
448 FileEntry
449 DirEntry
450 PatEntry
451 SABox
452 OK
453 Rescan
454 Can
455 DirList);
456  
457 sub Populate {
458 ## File Dialog constructor, inherits new from Toplevel
459 my($FDialog, @args) = @_;
460  
461 $FDialog->SUPER::Populate(@args);
462  
463 $FDialog->withdraw;
464  
465 $FDialog->protocol('WM_DELETE_WINDOW' => sub {
466 if (defined($FDialog->{'Can'}) && $FDialog->{'Can'}->IsWidget ) {
467 $FDialog->{'Can'}->invoke;
468 }
469 });
470 $FDialog->transient($FDialog->toplevel);
471  
472 foreach (@TabOrder) {
473 $FDialog->{'TabSel'}->{$_} = 1;
474 }
475  
476 ## Initialize variables that won't be initialized later
477 $FDialog->{'Retval'} = -1;
478 $FDialog->{'DFFrame'} = 0;
479  
480 $FDialog->{Configure}{-Horiz} = 1;
481  
482 $FDialog->BuildFDWindow;
483 $FDialog->{'activefore'} = $FDialog->{'SABox'}->cget(-foreground);
484 $FDialog->{'inactivefore'} = $FDialog->{'SABox'}->cget(-disabledforeground);
485  
486 $FDialog->ConfigSpecs(-Chdir => ['PASSIVE', undef, undef, 1],
487 -Create => ['PASSIVE', undef, undef, 1],
488 -DisableShowAll => ['PASSIVE', undef, undef, 0],
489 -FPat => ['PASSIVE', undef, undef, '*'],
490 -File => ['PASSIVE', undef, undef, ''],
491 -Geometry => ['PASSIVE', undef, undef, undef],
492 -Grab => ['PASSIVE', undef, undef, 1],
493 -Horiz => ['PASSIVE', undef, undef, 1],
494 -Path => ['PASSIVE', undef, undef, "$ENV{'HOME'}"],
495 -SelDir => ['PASSIVE', undef, undef, 0],
496 -DirLBCaption => ['PASSIVE', undef, undef, 'Directories:'],
497 -FileLBCaption => ['PASSIVE', undef, undef, 'File:'],
498 -FileEntryLabel => ['METHOD', undef, undef, 'Filename:'],
499 -PathEntryLabel => ['METHOD', undef, undef, 'Pathname:'],
500 -FltEntryLabel => ['METHOD', undef, undef, 'Filter:'],
501 -ShowAllLabel => ['METHOD', undef, undef, 'ShowAll'],
502 -OKButtonLabel => ['METHOD', undef, undef, 'OK'],
503 -RescanButtonLabel => ['METHOD', undef, undef, 'Rescan'],
504 -CancelButtonLabel => ['METHOD', undef, undef, 'Cancel'],
505 -SelHook => ['PASSIVE', undef, undef, undef],
506 -ShowAll => ['PASSIVE', undef, undef, 0],
507 -Title => ['PASSIVE', undef, undef, "Select File:"],
508 -EDlgTitle => ['PASSIVE', undef, undef,
509 'File does not exist!'],
510 -EDlgText => ['PASSIVE', undef, undef,
511 "You must specify an existing file.\n"
512 . "(\$filename not found)"]);
513 }
514  
515  
516 ### A few methods for configuration
517 sub OKButtonLabel {
518 &SetButton('OK',@_);
519 }
520 sub RescanButtonLabel {
521 &SetButton('Rescan',@_);
522 }
523 sub CancelButtonLabel {
524 &SetButton('Can',@_);
525 }
526  
527 sub SetButton {
528 my($widg, $self, $title) = @_;
529 if (defined($title)) {
530 ## This is a configure
531 $self->{$widg}->configure(-text => $title);
532 }
533 ## Return the current value
534 $self->{$widg}->cget(-text);
535 }
536  
537 sub FileEntryLabel {
538 &SetLabel('FEF', @_);
539 }
540 sub PathEntryLabel {
541 &SetLabel('PEF', @_);
542 }
543 sub FltEntryLabel {
544 &SetLabel('patFrame', @_);
545 }
546 sub ShowAllLabel {
547 &SetButton('SABox', @_);
548 }
549 sub SetLabel {
550 my($widg, $self, $title) = @_;
551 if (defined($title)) {
552 ## This is a configure
553 $self->{$widg}->{'Label'}->configure(-text => $title);
554 }
555 ## Return the current value
556 $self->{$widg}->{'Label'}->cget(-text);
557 }
558  
559 sub SetFlag {
560 ## Set the given flag to either 1 or 0, as appropriate
561 my($self, $flag, $dflt) = @_;
562  
563 $flag = "-$flag";
564  
565 ## We know it's defined as there was a ConfigDefault call after the Populate
566 ## call. Therefore, all we have to do is parse the non-numerics
567 if (&IsNum($self->{Configure}{$flag})) {
568 $self->{Configure}{$flag} = 1 unless $self->{Configure}{$flag} == 0;
569 } else {
570 my($val) = $self->{Configure}{$flag};
571  
572 my($fc) = lc(substr($val,0,1));
573  
574 if (($fc eq 'y') || ($fc eq 't')) {
575 $val = 1;
576 } elsif (($fc eq 'n') || ($fc eq 'f')) {
577 $val = 0;
578 } else {
579 ## bad value, complain about it
580 carp ("\"$val\" is not a valid flag ($flag)!");
581 $dflt = 0 if !defined($dflt);
582 $val = $dflt;
583 }
584 $self->{Configure}{$flag} = $val;
585 }
586 return $self->{Configure}{$flag};
587 }
588  
589 sub Version {return $Tk::FileDialog::VERSION;}
590  
591 sub Show {
592 my ($self) = shift;
593  
594 $self->configure(@_);
595  
596 ## Clean up flag variables
597 $self->SetFlag('Chdir');
598 $self->SetFlag('Create');
599 $self->SetFlag('ShowAll');
600 $self->SetFlag('DisableShowAll');
601 $self->SetFlag('Horiz');
602 $self->SetFlag('Grab');
603 $self->SetFlag('SelDir');
604  
605 croak "Can't SelDir and Not ChDir" if $self->{Configure}{-SelDir} &&
606 !$self->{Configure}{-Chdir};
607  
608 ## Set up, or remove, the directory box
609 &BuildListBoxes($self);
610  
611 ## Enable, or disable, the show all box
612 if ($self->{Configure}{-DisableShowAll}) {
613 $self->{'SABox'}->configure(-state => 'disabled');
614 $self->{'TabSel'}->{'SABox'} = 0;
615 } else {
616 $self->{'SABox'}->configure(-state => 'normal');
617 $self->{'TabSel'}->{'SABox'} = 1;
618 }
619  
620 ## Enable or disable the file entry box
621 if ($self->{Configure}{-SelDir}) {
622 $self->{Configure}{-File} = '';
623 $self->{'FileEntry'}->configure(-state => 'disabled',
624 -foreground => $self->{'inactivefore'});
625 $self->{'FileList'}->configure(-selectforeground => $self->{'inactivefore'});
626 $self->{'FileList'}->configure(-foreground => $self->{'inactivefore'});
627 $self->{'TabSel'}->{'FileEntry'} = $self->{'TabSel'}->{'FileList'} = 0;
628 } else {
629 $self->{'FileEntry'}->configure(-state => 'normal',
630 -foreground => $self->{'activefore'});
631 $self->{'FileList'}->configure(-selectforeground => $self->{'activefore'});
632 $self->{'FileList'}->configure(-foreground => $self->{'activefore'});
633 $self->{'TabSel'}->{'FileEntry'} = $self->{'TabSel'}->{'FileList'} = 1;
634 }
635  
636 ## Set the title
637 $self->title($self->{Configure}{-Title});
638  
639 ## Create window position (Center unless configured)
640 $self->update;
641 if (defined($self->{Configure}{-Geometry})) {
642 $self->geometry($self->{Configure}{-Geometry});
643 } else {
644 my($x,$y);
645 $x = int(($self->screenwidth - $self->reqwidth)/2 - $self->parent->vrootx);
646 $y = int(($self->screenheight - $self->reqheight)/2 - $self->parent->vrooty);
647 $self->geometry("+$x+$y");
648 }
649  
650 ## Set up the tab order
651 &SetTabs($self);
652  
653 ## Fill the list boxes
654 &RescanFiles($self);
655 ## Restore the window, and go
656 $self->update;
657 $self->deiconify;
658  
659 ## Set up the grab
660 $self->grab if ($self->{Configure}{-Grab});
661  
662 ## Initialize status variables
663 $self->{'Retval'} = 0;
664 $self->{'RetFile'} = "";
665  
666 my($i) = 0;
667 while (!$i) {
668 $self->tkwait('variable',\$self->{'Retval'});
669 $i = $self->{'Retval'};
670 if ($i != -1) {
671 ## No cancel, so call the hook if it's defined
672 if (defined($self->{Configure}{-SelHook})) {
673 ## The hook returns 0 to ignore the result,
674 ## non-zero to accept. Must release the grab before calling
675 $self->grab('release') if (defined($self->grab('current')));
676  
677 $i = &{$self->{Configure}{-SelHook}}($self->{'RetFile'});
678  
679 $self->grab if ($self->{Configure}{-Grab});
680 }
681 } else {
682 $self->{'RetFile'} = undef;
683 }
684 }
685  
686 $self->grab('release') if (defined($self->grab('current')));
687  
688 $self->withdraw;
689  
690 return $self->{'RetFile'};
691 }
692  
693 #### PRIVATE METHODS AND SUBROUTINES ####
694 sub IsNum {
695 my($parm) = @_;
696 my($warnSave) = $;
697 $ = 0;
698 my($res) = (($parm + 0) eq $parm);
699 $ = $warnSave;
700 return $res;
701 }
702  
703 sub TabNext {
704 my($self, $inc) = @_;
705 my($f) = $self->{'OK'}->focusCurrent;
706 return if !defined($f);
707 ## Find the object with the matching focus...
708 my($i) = 0;
709 foreach (@TabOrder) {
710 if ($self->{$_} eq $f) {
711 $i = $#TabOrder if !$i && $inc == -1;
712  
713 $i += $inc;
714  
715 while (!defined($TabOrder[$i]) ||
716 !ref($self->{$TabOrder[$i]}) ||
717 !$self->{$TabOrder[$i]}->IsWidget ||
718 !($self->{'TabSel'}->{$TabOrder[$i]})) {
719 # (($TabOrder[$i] == 'FileList') &&
720 # $self->{Configure}{-SelDir}) ) {
721 $i += $inc;
722 $i = $#TabOrder if !$i && $inc == -1;
723 $i = 0 if $i > $#TabOrder && $inc == 1;
724 }
725 $self->{$TabOrder[$i]}->focus;
726 $self->break;
727 return;
728 }
729 $i++;
730 }
731 }
732  
733 sub SetTabs {
734 my($self) = shift;
735  
736 foreach (@TabOrder) {
737 next if (!defined($self->{$_}) ||
738 !ref $self->{$_} ||
739 !$self->{$_}->IsWidget);
740
741 $self->{$_}->bind("<Tab>", sub {\&TabNext($self, 1);});
742 $self->{$_}->bind("<Shift-Tab>", sub {\&TabNext($self, -1);});
743 }
744 }
745  
746 sub BuildListBox {
747 my($self, $fvar, $flabel, $listvar,$hpack, $vpack) = @_;
748  
749 ## Create the subframe
750 $self->{"$fvar"} = $self->{'DFFrame'}->Frame
751 ->pack(-side => $self->{Configure}{-Horiz} ? $hpack : $vpack,
752 -anchor => 'center',
753 @bothFill, @expand);
754  
755 ## Create the label
756 $self->{"$fvar"}->Label(@raised, -text => "$flabel")
757 ->pack(@topPack, @xfill);
758  
759 ## Create the frame for the list box
760 my($fbf) = $self->{"$fvar"}->Frame
761 ->pack(@topPack, @bothFill, @expand);
762  
763 ## And the scrollbar and listbox in it
764 $self->{"$listvar"} = $fbf->Listbox(@raised, -exportselection => 0)
765 ->pack(@leftPack, @expand, @bothFill);
766  
767 $fbf->AddScrollbars($self->{"$listvar"});
768 $fbf->configure(-scrollbars => 'rse');
769 }
770  
771 sub DirSel {
772 my($self, $lbdir) = @_;
773
774 my($np) = $lbdir->curselection;
775 return if !defined($np);
776 $np = $lbdir->get($np);
777 if ($np eq "..") {
778 ## Moving up one directory
779 $_ = $self->{Configure}{-Path};
780 chop if m!/$!;
781 s!(.*/)[^/]*$!$1!;
782 $self->{Configure}{-Path} = $_;
783 } else {
784 ## Going down into a directory
785 $self->{Configure}{-Path} .= "/" . "$np/";
786 }
787 $self->{Configure}{-Path} =~ s!//*!/!g;
788 \&RescanFiles($self);
789 }
790  
791 sub BindDir {
792 ### Set up the bindings for the directory selection list box
793 my($self) = @_;
794  
795 my($lbdir) = $self->{'DirList'};
796 $lbdir->bind("<Double-1>" => sub {&DirSel($self, $lbdir);});
797  
798 # binding to take focus if clicked
799 $lbdir->bind("<1>", sub{$self->{'DirList'}->focus;});
800
801 # binding to attract focus if mouse over list
802 $lbdir->bind("<Enter>", sub{&listFocus($self, 'DirList');});
803  
804 # binding to move to requested line by hitting a key
805 $lbdir->bind("<KeyPress>", sub{\&list_see($self,'Dir');});
806  
807 # binding to select and rescan if someone hits return
808 $lbdir->bind("<Return>", sub {&DirSel($self,$lbdir);});
809  
810 }
811  
812  
813 sub FileSel {
814 my($self) = shift;
815 if (!$self->{Configure}{-SelDir}) {
816 my($f) = $self->{'FileList'}->curselection;
817 return if !defined($f);
818 $self->{'File'} = $self->{'FileList'}->get($f);
819 $self->{'OK'}->invoke;
820 }
821 }
822  
823 sub BindFile {
824 ### Set up the bindings for the file selection list box
825 my($self) = @_;
826  
827 ## A single click selects the file...
828 $self->{'FileList'}->bind("<ButtonRelease-1>", sub {
829 if (!$self->{Configure}{-SelDir}) {
830 my($n);
831 return if (!defined($n=$self->{'FileList'}->curselection));
832 ($self->{Configure}{-File} = $self->{'FileList'}->get($n));
833 ##if defined($n);
834 }
835 });
836 ## A double-click selects the file for good
837 $self->{'FileList'}->bind("<Double-1>", sub {&FileSel($self);});
838  
839 # binding to take focus if clicked
840 $self->{'FileList'}->bind("<1>", sub{
841 $self->{'FileList'}->focus;
842 });
843  
844 # binding to attract focus if mouse over list
845 $self->{'FileList'}->bind("<Enter>", sub{
846 &listFocus($self, 'FileList');
847 });
848  
849 # binding to select and be done if someone hits return
850 $self->{'FileList'}->bind("<Return>", sub {&FileSel($self);});
851  
852 # binding to move to requested line by hitting a key
853 $self->{'FileList'}->bind("<KeyPress>", sub{&list_see($self,'File');});
854  
855 $self->{'FileList'}->configure(-selectforeground => 'blue');
856 }
857  
858 sub BuildEntry {
859 ### Build the entry, label, and frame indicated. This is a
860 ### convenience routine to avoid duplication of code between
861 ### the file and the path entry widgets
862 my($self, $LabelVar, $entry) = @_;
863 $LabelVar = "-$LabelVar";
864  
865 ## Create the entry frame
866 my $eFrame = $self->Frame(@raised)
867 ->pack(@topPack, @xfill);
868  
869 ## Now create and pack the title and entry
870 $eFrame->{'Label'} = $eFrame->Label(@raised)
871 ->pack(@leftPack);
872  
873 $self->{"$entry"} = $eFrame->Entry(@raised,
874 -textvariable => \$self->{Configure}{$LabelVar})
875 ->pack(@rightPack, @expand, @xfill);
876  
877 $self->{"$entry"}->bind("<Return>",sub {
878 &RescanFiles($self);
879 $self->{'OK'}->focus;
880 });
881  
882 return $eFrame;
883 }
884  
885 sub BuildListBoxes {
886 my($self) = shift;
887  
888 ## Destroy both, if they're there
889 if ($self->{'DFFrame'} && $self->{'DFFrame'}->IsWidget) {
890 $self->{'DFFrame'}->destroy;
891 }
892  
893 $self->{'DFFrame'} = $self->Frame;
894 $self->{'DFFrame'}->pack(-before => $self->{'FEF'},
895 @topPack, @bothFill, @expand);
896  
897 ## Build the file window before the directory window, even
898 ## though the file window is below the directory window, we'll
899 ## pack the directory window before.
900 &BuildListBox($self, 'FileFrame',
901 $self->{Configure}{-FileLBCaption},
902 'FileList','right','bottom');
903 ## Set up the bindings for the file list
904 &BindFile($self);
905  
906 if ($self->{Configure}{-Chdir}) {
907 &BuildListBox($self,'DirFrame',$self->{Configure}{-DirLBCaption},
908 'DirList','left','top');
909 &BindDir($self);
910 }
911 }
912  
913 sub BuildFDWindow {
914 ### Build the entire file dialog window
915 my($self) = shift;
916  
917 ### Build the filename entry box
918 $self->{'FEF'} = &BuildEntry($self, 'File', 'FileEntry');
919  
920 ### Build the pathname directory box
921 $self->{'PEF'} = &BuildEntry($self, 'Path','DirEntry');
922  
923 ### Now comes the multi-part frame
924 my $patFrame = $self->Frame(@raised)
925 ->pack(@topPack, @xfill);
926  
927 ## Label first...
928 $self->{'patFrame'}->{'Label'} = $patFrame->Label(@raised)
929 ->pack(@leftPack);
930  
931 ## Now the entry...
932 $self->{'PatEntry'} = $patFrame->Entry(@raised, -textvariable => \$self->{Configure}{-FPat})
933 ->pack(@leftPack, @expand, @xfill);
934 $self->{'PatEntry'}->bind("<Return>",sub {\&RescanFiles($self);});
935  
936  
937 ## and the Check box
938 $self->{'SABox'} = $patFrame->Checkbutton(-variable => \$self->{Configure}{-ShowAll},
939 -command => sub {\&RescanFiles($self);})
940 ->pack(@leftPack);
941  
942 ### FINALLY!!! the button frame
943 my $butFrame = $self->Frame(@raised);
944 $butFrame->pack(@topPack, @xfill);
945  
946 $self->{'OK'} = $butFrame->Button(-command => sub {
947 \&GetReturn($self);
948 })
949 ->pack(@leftPack, @expand, @xfill);
950  
951 $self->{'Rescan'} = $butFrame->Button(-command => sub {
952 \&RescanFiles($self);
953 })
954 ->pack(@leftPack, @expand, @xfill);
955  
956 $self->{'Can'} = $butFrame->Button(-command => sub {
957 $self->{'Retval'} = -1;
958 })
959 ->pack(@leftPack, @expand, @xfill);
960 }
961  
962 sub RescanFiles {
963 ### Fill the file and directory boxes
964 my($self) = shift;
965  
966 my($fl) = $self->{'FileList'};
967 my($dl) = $self->{'DirList'};
968 my($path) = $self->{Configure}{-Path};
969 my($show) = $self->{Configure}{-ShowAll};
970 my($chdir) = $self->{Configure}{-Chdir};
971  
972 ### Remove a final / if it is there, and add it
973 $path = '' if !defined($path);
974 if ((length($path) == 0) || (substr($path,-1,1) ne '/')) {
975 $path .= '/';
976 $self->{Configure}{-Path} = $path;
977 }
978 ### path now has a trailing / no matter what
979 if (!-d $path) {
980 carp "$path is NOT a directory\n";
981 return 0;
982 }
983  
984 $self->configure(-cursor => 'watch');
985 my($OldGrab) = $self->grab('current');
986 $self->{'OK'}->grab;
987 $self->{'OK'}->configure(-state => 'disabled');
988 $self->update;
989 opendir(ALLFILES,$path);
990 my(@allfiles) = readdir(ALLFILES);
991 closedir(ALLFILES);
992  
993 my($direntry);
994  
995 ## First, get the directories...
996 if ($chdir) {
997 $dl->delete(0,'end');
998 my %see; # hold index if first occurrence of first character of direntry
999 my $n=0; # number of entry in list
1000 foreach $direntry (sort @allfiles) {
1001 next if !-d "$path$direntry";
1002 next if $direntry eq ".";
1003 if ( !$show
1004 && (substr($direntry,0,1) eq ".")
1005 && $direntry ne "..") {
1006 next;
1007 }
1008 $dl->insert('end',$direntry);
1009 if(! exists($see{substr($direntry,0,1)})){
1010 $see{substr($direntry,0,1)}=$n;
1011 }
1012 $n++;
1013 }
1014 $self->{see_Dir}=\%see;
1015 }
1016  
1017 ## Now, get the files
1018 $fl->delete(0,'end');
1019  
1020 $_ = $self->{Configure}{-FPat};
1021 s/^\s*|\s*$//;
1022 $_ = $self->{Configure}{-FPat} = '*' if $_ eq '';
1023  
1024 my($pat) = $_;
1025 undef @allfiles;
1026  
1027 @allfiles = <$path.$pat> if $show;
1028  
1029 @allfiles = (@allfiles, <$path$pat>);
1030  
1031 my %see; # hold index if first occurrence of first character of fileentry
1032 my $n=0; # number of entry in list
1033 my $fileentry;
1034 foreach $fileentry (sort @allfiles) {
1035 if (-f $fileentry) {
1036 $fileentry =~ s!.*/!!; # mkr s!.*/([^/]*)$!$1!;
1037 $fl->insert('end',$fileentry);
1038 if(! exists($see{substr($fileentry,0,1)})){
1039 $see{substr($fileentry,0,1)}=$n;
1040 }
1041 $n++;
1042 }
1043 $self->{see_File}=\%see;
1044 }
1045 $self->configure(-cursor => 'top_left_arrow');
1046  
1047 $self->{'OK'}->grab('release') if $self->grab('current') == $self->{'OK'};
1048 $OldGrab->grab if defined($OldGrab);
1049 $self->{'OK'}->configure(-state => 'normal');
1050 $self->update;
1051 return 1;
1052 }
1053  
1054 sub GetReturn {
1055 my ($self) = @_;
1056  
1057 ## Construct the filename
1058 my $path = $self->{Configure}{-Path};
1059 my $fname;
1060  
1061 $path .= "/" if (substr($path, -1, 1) ne '/');
1062  
1063 if ($self->{Configure}{-SelDir}) {
1064 $fname = $self->{'DirList'};
1065  
1066 if (defined($fname->curselection)) {
1067 $fname = $fname->get($fname->curselection);
1068 } else {
1069 $fname = '';
1070 }
1071 $fname = $path . $fname;
1072 $fname =~ s/\/$//;
1073 } else {
1074 $fname = $path . $self->{Configure}{-File};
1075 ## Make sure that the file exists, if the user is not allowed
1076 ## to create
1077 if (!$self->{Configure}{-Create} && !(-f $fname)) {
1078 ## Put up no create dialog
1079 my($path) = $self->{Configure}{-Path};
1080 my($file) = $self->{Configure}{-File};
1081 my($filename) = $fname;
1082 eval "\$fname = \"$self->{Configure}{-EDlgText}\"";
1083 $self->Dialog(-title => $self->{Configure}{-EDlgTitle},
1084 -text => $fname,
1085 -bitmap => 'error')
1086 ->Show;
1087 ## And return
1088 return;
1089 }
1090 }
1091  
1092 $self->{'RetFile'} = $fname;
1093  
1094 $self->{'Retval'} = 1;
1095  
1096 }
1097  
1098 sub listFocus {
1099 ## Change focus ONLY if current focus is not an entry...
1100 my ($self, $lb) = @_;
1101  
1102 my($f) = $self->{$lb}->focusCurrent;
1103 if (defined($f) &&
1104 $f ne $self->{'FileEntry'} &&
1105 $f ne $self->{'DirEntry'} &&
1106 $f ne $self->{'PatEntry'}) {
1107 $self->{$lb}->focus;
1108 }
1109 }
1110  
1111 sub list_see{
1112 my ($self, $what) = @_; # $what is dir or file
1113  
1114 my $list=$self->{"${what}List"}; # Dir or File
1115 my $see=$self->{"see_$what"}; # index hash
1116 my $char=$list->XEvent->A; # key pressed
1117 if (exists($see->{$char})) { # line with char there?
1118 ## Yes, it is...
1119 my ($ndx) = $see->{$char};
1120
1121 ## Is it already selected?
1122 my($cs) = $list->curselection;
1123 if (defined($cs)) {
1124
1125 if (($cs == $ndx) ||
1126 (substr($list->get($cs),0,1) eq $char)) {
1127 ## does the next in the list start with the same char?
1128 if (defined($list->get($cs + 1)) &&
1129 (substr($list->get($cs + 1),0,1) eq $char)) {
1130 $ndx = ++$cs;
1131 }
1132 }
1133 }
1134 $list->see($ndx); # yes, so show it.
1135 $list->selection('clear',0,'end');
1136 return if $self->{Configure}{-SelDir};
1137 $list->selection('set', $ndx);
1138 $self->{Configure}{-File} = $list->get($ndx) if $what eq 'File';
1139 } else { # search next line in sequence
1140 while(!exists($see->{$char}) && length($char) == 1) {
1141 $char++;
1142 }
1143 if(exists($see->{$char})){
1144 $char = $see->{$char};
1145 $list->see($char-1) if $char; # Show the one before
1146 $list->see($char); # and show this one...
1147 # } else {
1148 # $list->bell;
1149 }
1150 }
1151 }
1152  
1153  
1154 ### Return 1 to the calling use statement ###
1155 1;
1156 ### End of file FileDialog.pm ###
1157 __END__