JComboBox.pm untested

filter: Statementstmt 0.0% 0 / 963 Branchbran 0.0% 0 / 480 Conditioncond 0.0% 0 / 138 MC/DCmcdc 0.0% 0 / 88 Subroutinesub 0.0% 0 / 117 Podpod 0.0% 0 / 101 totaltotal 0.0% 0 / 1887 CC 242 SCAR 37.5
CC
242
Cov
0%
AutoFind
306.0
UpdateWidth
90.0
PopupCreate
72.0
CRAP 42.4
1 #######################################################################
2 ## LICENSE:
3 ## This source code, is copyright (c) 2001-2006 of Rob Seegel
4 ## <RobSeegel@comcast.net>, and is free software; you can
5 ## redistribute and/or modify it under the same terms as Perl itself.
6 ##
7 ## ACKNOWLEDGEMENTS:
8 ## Very little comes from nothing, and as the name suggests,
9 ## JComboBox.pm is *superficially* similar to the javax.swing.JComboBox
10 ## class which is owned by Sun Microsystems. At best, this module shares
11 ## some method names, and basic look and feel, but the similarities end
12 ## there. None of this code comes from the Swing class.
13 ##
14 ## JComboBox.pm owes its original structure to Graham Barr's MenuEntry
15 ## (Thanks, Graham - it was a fine base). It also uses various methods
16 ## and options borrowed from BrowseEntry, Optionmenu, and the
17 ## ComboEntry widget (part of Tk-DKW). This was done to make the widget
18 ## seem familiar to users of those widgets, and lessen the pain of
19 ## migration, and because I thought they were *good* features that I
20 ## wanted in one widget. In addition, features that others have asked
21 ## for have been added over time. So this widget represents a combo box
22 ## stew with a few extra spices that I've come up with myself.
23 ##
24 ## Finally, thanks to all those who have contributed bug reports,
25 ## patches, and new ideas over the years. I have attempted to track
26 ## who did what within the Changes file, and in some cases within the
27 ## source when patches were submitted. Your help and feedback has been
28 ## appreciated.
29 #######################################################################
30 package Tk::JComboBox;
31  
32 use strict;
33 use Carp;
34  
35 use Tie::Watch;
36 use Tk;
37 use Tk::CWidget;
38 use Tk::CWidget::Util::Boolean qw(:all);
39  
40 use vars qw($VERSION);
41 our $VERSION = "1.14";
42  
43 BEGIN
44 {
45 ## Setup a series of private accessors used within public/private
46 ## methods. These are all intended for INTERNAL use only. The
47 ## methods act as a way of consolidating the internal hash keys
48 ## that are being used. Using method calls instead of hash keys
49 ## helps ensure consistant usage throughout, and easier on my eyes.
50  
51 sub CreateGetSet
52 {
53 my ($method, $key) = @_;
54 my $sub = sub {
55 my ($cw, $value) = @_;
56 return $cw->{$key} unless defined $value;
57 $cw->{$key} = $value;
58 };
59 no strict 'refs';
60 *{$method} = $sub;
61 }
62 CreateGetSet(IsButtonDown => '__JCB__BTN_DOWN');
63 CreateGetSet(LastAFIndex => '__JCB__LAST_INDEX');
64 CreateGetSet(LastAFSearch => '__JCB__LAST_SEARCH');
65 CreateGetSet(LastSelection => '__JCB__LAST_SELECT');
66 CreateGetSet(LastSelName => '__JCB__LAST_SNAME');
67 CreateGetSet(List => '__JCB__LIST');
68 CreateGetSet(Mode => '__JCB__MODE');
69 CreateGetSet(LongestEntry => '__JCB__ENTRY_LEN');
70 CreateGetSet(Selected => '__JCB__SELECTION');
71 CreateGetSet(TempRelief => '__JCB__RELIEF');
72 CreateGetSet(WatchVar => '__JCB__WATCH_VAR');
73 CreateGetSet(WatchList => '__JCB__WATCH');
74 }
75  
76 use base qw(Tk::CWidget);
77 Tk::Widget->Construct('JComboBox');
78  
79 ## this struct below meant to represent the contents displayed in the
80 ## pulldown list. Name is the text which is displayed, value is for
81 ## text which could be offered as an alternative to the displayed
82 ## text. It is slightly overkill having a structure to hold these
83 ## values, but it is intended to hold additional values in the
84 ## future (bitmaps, images, formats, etc).
85  
86 use Class::Struct;
87 struct '_JCBListItem' =>
88 [
89 name => '$',
90 value => '$',
91 ];
92  
93 ## The following constants are meant for internal use only. I wanted
94 ## to use hash keys that were not likely to be used by anyone else
95 ## (including classes that I extended), but the longer versions
96 ## seemed clumsy within the code. It is also a convenient means in
97 ## tracking all of the keys that I'm using.
98  
99 use constant {
100 MODE_UNEDITABLE => "readonly",
101 MODE_EDITABLE => "editable",
102 VAL_MODE_CSMATCH => "cs-match",
103 VAL_MODE_MATCH => "match",
104 };
105  
106 my $BITMAP;
107 my $SWAP_BG = "__JCB__SWAP_BG";
108 my $SWAP_FG = "__JCB__SWAP_FG";
109  
110 sub ClassInit {
111 my($class,$mw) = @_;
112  
113 unless(defined($BITMAP)) {
114 $BITMAP = __PACKAGE__ . "::downarrow";
115  
116 ## A smaller bitmap suits Win32 better I think
117 if ($Tk::platform =~ /Win32/) {
118 my $bits = pack("b10"x4,
119 ".11111111.",
120 "..111111..",
121 "...1111...",
122 "....11...."
123 );
124 $mw->DefineBitmap($BITMAP => 10,4, $bits);
125  
126 ## Just as this size looks better on other platforms
127 } else {
128 my $bits = pack("b12"x5,
129 ".1111111111.",
130 "..11111111..",
131 "...111111...",
132 "....1111....",
133 ".....11....."
134 );
135 $mw->DefineBitmap($BITMAP => 12,5, $bits);
136 }
137 $mw->bind($class, '<ButtonRelease-1>', 'NonSelect');
138 $mw->bind($class, '<FocusIn>', 'RedirectFocus');
139 }
140 }
141  
142 sub Populate {
143 my ($cw ,$args) = @_;
144  
145 my $choices = delete $args->{-choices} || delete $args->{-options};
146 $cw->SUPER::Populate($args);
147  
148 ## Initiallize Member variables
149 $cw->LastAFIndex(-1);
150 $cw->LastAFSearch("");
151 $cw->LastSelection(-1);
152 $cw->LastSelName("");
153 $cw->List([]);
154 $cw->LongestEntry(0);
155 $cw->Selected(-1);
156  
157 my $frame = $cw->Component(
158 Frame => 'Frame',
159 -background => 'white',
160 -bd => 2,
161 -highlightthickness => 0
162 )->pack(qw/ -side right -fill both -expand 1/);
163  
164 ## Mode is set once at construction time, things get overly
165 ## complicated if mode can be switched after construction time,
166 ## and how often is this sort of thing done? Mode determines the
167 ## widget that makes up the Entry, a Button. I used to allow the
168 ## mode to be switched on-the-fly, and may again in the future.
169  
170 my $mode = delete $args->{'-mode'} || MODE_UNEDITABLE;
171 $cw->mode(lc($mode), $args);
172  
173 ## Layout ComboBox controls
174 $cw->LayoutControls();
175 $cw->CreateListboxPopup();
176 $cw->BindSubwidgets();
177  
178 ## Get All Advertised Widgets - constructed within Subroutines
179 ## So that they can be used for ConfigSpecs routine
180 my $entry = $cw->Subwidget('Entry');
181 my $button = $cw->Subwidget('Button');
182 my $listbox = $cw->Subwidget('Listbox');
183 my $popup = $cw->Subwidget('Popup');
184  
185 ## This ConfigSpecs functions as a core set for the entire
186 ## widget, and assumes that the mode is MODE_UNEDITABLE. Some
187 ## specs are overridden if the mode is MODE_EDITABLE.
188 $cw->ConfigSpecs(
189 ## Basic
190 -arrowbitmap => [{-bitmap => $button}, undef, undef, $BITMAP],
191 -arrowimage => [{-image => $button}],
192 -background => [qw/DESCENDANTS background Background/],
193 -borderwidth => [qw/Frame borderwidth BorderWidth 2/],
194 -cursor => [qw/DESCENDANTS cursor Cursor/],
195 -disabledbackground => [qw/METHOD/, undef, undef, Tk::NORMAL_BG],
196 -disabledforeground => [qw/METHOD/, undef, undef, Tk::DISABLED],
197 -entrybackground => [{-background => [$entry, $button, $listbox]}],
198 -entrywidth => [qw/METHOD entryWidth EntryWidth -1/],
199 -font => [[$entry, $listbox], qw/font Font/],
200 -foreground => [[$entry, $listbox], qw/foreground Foreground/],
201 -gap => [qw/METHOD gap Gap 0/],
202 -highlightbackground => [qw/METHOD/, undef, undef,
203 $frame->cget('-highlightbackground')],
204 -highlightcolor => [qw/METHOD/, undef, undef,
205 $frame->cget('-highlightcolor')],
206 -highlightthickness => [$frame, undef, undef, 0],
207 -pady => [qw/METHOD padY PadY/],
208 -relief => [qw/Frame relief Relief groove/],
209 -selectbackground => [$listbox],
210 -selectforeground => [$listbox],
211 -selectborderwidth => [$listbox],
212 -state => [qw/METHOD state State normal/],
213 -takefocus => [$entry, qw/takeFocus TakeFocus/, TRUE],
214 -textvariable => [qw/METHOD textVariable Variable/],
215  
216 ## Callbacks
217 -buttoncommand => [qw/CALLBACK/, undef, undef, \&see],
218 -keycommand => [qw/CALLBACK/],
219 -matchcommand => [qw/CALLBACK/],
220 -popupcreate => [qw/CALLBACK/],
221 -popupmodify => [qw/CALLBACK/],
222 -selectcommand => [qw/CALLBACK/],
223 -validatecommand => [qw/CALLBACK/],
224  
225 ## Functionality
226 -autofind => [qw/PASSIVE/],
227 -choices => [qw/METHOD/],
228 -listhighlight => [qw/PASSIVE lightHighlight ListHighlight/, TRUE],
229 -listwidth => [qw/PASSIVE listWidth ListWidth -1/],
230 -maxrows => [qw/METHOD maxRows MaxRows 10/],
231 -mode => [qw/METHOD mode Mode/],
232 -updownselect => [qw/PASSIVE updownSelect UpDownSelect/, TRUE],
233 -validate => [qw/METHOD validate Validate none/],
234 );
235  
236 ## Override readonly option settings
237 if ($cw->mode eq MODE_EDITABLE) {
238 $cw->ConfigSpecs(
239 -entrybackground => [{-background => [$entry, $listbox]}],
240 -relief => [$frame, qw/relief Relief sunken/],
241 -selectbackground => [[$entry, $listbox]],
242 -selectforeground => [[$entry, $listbox]],
243 -selectborderwidth => [[$entry, $listbox]],
244 );
245 }
246  
247 $cw->ConfigAlias(
248 -browsecmd => '-selectcommand',
249 -listcmd => '-popupcreate',
250 -options => '-choices',
251 );
252  
253 $cw->choices($choices) if $choices;
254  
255 return $cw;
256 }
257  
258 ############################################################
259 ## Configuration Methods
260 ############################################################
261 sub choices
262 {
263 my ($cw, $newAR) = @_;
264 return $cw->WatchList unless defined $newAR;
265 return if $newAR eq "" && !defined $cw->WatchList;
266  
267 my $oldAR = $cw->WatchList;
268 my $tie = Tk::JComboBox::Tie->tie($cw, $newAR, $oldAR);
269 if (defined($tie)) { $cw->WatchList($newAR); }
270 else { $cw->WatchList(""); }
271 }
272  
273 sub disabled
274 {
275 my ($cw, $option, $color) = @_;
276 return $cw->{Configure}{"-disabled$option"} unless defined $color;
277  
278 my $entry = $cw->Subwidget('Entry');
279 if ($cw->mode eq MODE_EDITABLE && $Tk::VERSION >= 804) {
280 $entry->configure("-disabled$option" => $color);
281 return;
282 }
283 if ($cw->state eq 'disabled') {
284 $entry->configure("-$option" => $color);
285 $cw->Subwidget('Button')->configure("-$option" => $color)
286 if $cw->mode eq MODE_UNEDITABLE;
287 }
288 }
289  
290 sub disabledbackground
291 {
292 my ($cw, $color) = @_;
293 return $cw->disabled("background", $color);
294 }
295  
296 sub disabledforeground
297 {
298 my ($cw, $color) = @_;
299 return $cw->disabled("foreground", $color);
300 }
301  
302 sub entrybackground
303 {
304 my ($cw, $val) = @_;
305 return $cw->{Configure}{'-entrybackground'} unless defined $val;
306 $cw->configureSubwidgets([qw/Entry Listbox/] => {-bg => $val});
307 }
308  
309 sub entrywidth
310 {
311 my ($cw, $width) = @_;
312 return $cw->{Configure}{'-entrywidth'} unless defined $width;
313 $cw->gap(0) if !defined($cw->gap);
314 $cw->UpdateWidth('delete', "");
315 }
316  
317 sub gap
318 {
319 my ($cw, $gap) = @_;
320 if (!defined($gap)) {
321 return $cw->{Configure}{'-gap'} if defined $cw->{Configure}{'-gap'};
322 return 0;
323 }
324 $cw->UpdateWidth('add', "");
325 }
326  
327 sub highlightbackground
328 {
329 my ($cw, $color) = @_;
330 return $cw->{Configure}{'-highlightbackground'} unless defined $color;
331 $cw->Subwidget('Frame')->configure(-highlightbackground => $color);
332 }
333  
334 sub highlightcolor
335 {
336 my ($cw, $color) = @_;
337 return $cw->{Configure}{'-highlightcolor'} unless defined $color;
338 $cw->Subwidget('Frame')->configure(-highlightcolor => $color);
339 }
340  
341 sub maxrows
342 {
343 my ($cw, $rows) = @_;
344 return $cw->{Configure}{'-maxrows'} unless defined $rows;
345 $cw->UpdateListboxHeight;
346 }
347  
348 sub mode
349 {
350 ## Stores the mode within another variable. One problem with how the
351 ## configuration methods currently work is that they current "store"
352 ## the new value before the method is even called. If a method was
353 ## intended to validate prior to changing the value then this complicates
354 ## things, because the original value is no longer available. In this
355 ## case, the variable is only allowed to be set once per instance.
356  
357 my ($cw, $mode, $args) = @_;
358 return $cw->Mode unless defined $mode;
359 return if $cw->Mode;
360  
361 my $frame = $cw->Subwidget('Frame');
362 my $entry;
363 if ($mode eq MODE_EDITABLE) {
364 $entry = $frame->Entry(
365 -highlightthickness => 0,
366 -borderwidth => 1,
367 -insertwidth => 1,
368 -relief => 'flat',
369 -validatecommand => [$cw => 'ValidateCommand']
370 );
371 $cw->Advertise(Entry => $entry);
372 $cw->Advertise(ED_Entry => $entry);
373 }
374 elsif ($mode eq MODE_UNEDITABLE) {
375 $entry = $cw->CreateButton(
376 -ignoreleave => TRUE,
377 -anchor => 'w',
378 -padx => 4,
379 -borderwidth => 0,
380 -takefocus => 1
381 );
382 $cw->Advertise(Entry => $entry);
383 $cw->Advertise(RO_Entry => $entry);
384 }
385 else {
386 croak "Invalid JComboBox mode: $mode\n";
387 return;
388 }
389 $cw->Mode($mode);
390 }
391  
392 sub pady
393 {
394 my ($cw, $pad) = @_;
395 return $cw->{Configure}{'-pady'} unless defined $pad;
396 my $button = $cw->Subwidget('Button');
397 my %gridInfo = $button->gridInfo;
398 $gridInfo{'-ipady'} = $pad;
399 $button->gridForget;
400 $button->grid(%gridInfo);
401 }
402  
403 sub state
404 {
405 my ($cw, $state) = @_;
406 return $cw->{Configure}{'-state'} || "normal" unless defined $state;
407  
408 $state = lc($state);
409 croak "Invalid value for -state: $state!"
410 if ($state !~ /normal|disabled/);
411  
412 my $button = $cw->Subwidget('Button');
413 my $entry = $cw->Subwidget('Entry');
414  
415 if ($state eq 'disabled') { $cw->DisableControls; }
416 elsif ($state eq 'normal') { $cw->EnableControls; }
417 }
418  
419 sub textvariable
420 {
421 my ($cw, $value) = @_;
422 my $existing = $cw->{Configure}{'-textvariable'};
423 return $existing unless defined $value;
424  
425 croak "Invalid textvariable type! Expected scalar reference"
426 if defined($value) && ref($value) ne "SCALAR";
427  
428 $cw->WatchVar->Unwatch if defined($cw->WatchVar);
429 my $tmpVal = $$value;
430  
431 untie $value if tied $value;
432  
433 my $watch = Tie::Watch->new(
434 -variable => $value,
435 -store => sub {$cw->TextvarStore(@_);},
436 -fetch => sub {return $cw->TextvarFetch(@_);}
437 );
438 $cw->WatchVar($watch);
439 $cw->TextvarStore($watch, $tmpVal) if defined($tmpVal);
440 }
441  
442 #############################################################################
443 ## For the most part, this option is delegated to the Entry subwidget in
444 ## MODE_EDITABLE, however two additional options: match and cs-match will
445 ## indicate that the entry should use the Listbox entries for validation. If
446 ## either of these two options are set, then a default validatecommand will
447 ## be used.
448 #############################################################################
449 sub validate
450 {
451 my ($cw, $mode) = @_;
452  
453 return $cw->{Configure}{'-validate'} unless $mode;
454 return if $cw->mode eq MODE_UNEDITABLE;
455  
456 $mode = lc($mode);
457 croak "Invalid validate value: $mode"
458 if ($mode !~ /^(none|focus|focusin|focusout|key|match|cs-match)$/);
459  
460 ## validate is only used in editble mode as a way of constraining
461 ## what a user can type in the Entry. If the mode is match or cs-match
462 ## a default -validate callback is provided. Otherwise, the validation
463 ## mode is passed directly to the Entry widget's validate option.
464  
465 my $entry = $cw->Subwidget('Entry');
466 if ($mode =~ /match/)
467 {
468 $entry->configure(
469 -validate => 'key',
470 );
471 }
472 else {
473 $entry->configure(-validate => $mode);
474 }
475 }
476  
477 ## ======================================================================== ##
478 ## Public Methods ##
479 ## ======================================================================== ##
480  
481 sub addItem { shift->insertItemAt('end', @_) };
482  
483 sub clearSelection
484 {
485 my $cw = shift;
486 $cw->LastAFIndex(-1);
487 $cw->LastAFSearch("");
488 $cw->Selected(-1);
489  
490 $cw->Subwidget('Listbox')->selectionClear(0, 'end');
491 my $entry = $cw->Subwidget('Entry');
492 if ($cw->mode eq MODE_EDITABLE) {
493 my $v = $entry->cget('-validate');
494 $entry->configure(-validate => 'none');
495 $entry->delete(0, 'end');
496 $entry->configure(-validate => $v);
497 }
498 elsif ($cw->mode eq MODE_UNEDITABLE) {
499 $entry->configure(-text => "");
500 }
501 }
502  
503 ## Override the following focus methods to ensure the
504 ## correct
505 sub focus { shift->Subwidget('Entry')->focus; }
506 sub tabFocus { shift->Subwidget('Entry')->focus; }
507  
508 sub getItemCount
509 {
510 return scalar( @{shift->List} );
511 }
512  
513 sub getItemIndex
514 {
515 my ($cw, $searchStr, %args) = @_;
516  
517 ## start - which index to start looking. Defaults to 0;
518 ## if the start is out of range, then reset it to 0.
519 my $start = delete $args{'-start'} || 0;
520 $start = 0 if $start >= $cw->Subwidget('Listbox')->size || $start < 0;
521  
522 ## wrap - only use when start is not 0, it determines
523 ## whether or not the search should continue at the beginning
524 ## of the list until the start point when at the end of the list
525 my $wrap = delete $args{'-wrap'} || 0;
526  
527 ## type - which string is being searched - the name, or value.
528 my $type = lc($args{'-type'}) || "name";
529 if ($type !~ /^(name|value)$/) {
530 carp "Invalid value for -type in getItemIndex (valid: name|value)";
531 return;
532 }
533  
534 my $index;
535 foreach my $i ($start .. ($cw->getItemCount - 1)) {
536 my $field;
537 if ($type eq 'name') { $field = $cw->List->[$i]->name }
538 elsif ($type eq 'value') { $field = $cw->getItemValueAt($i) }
539  
540 if ($cw->MatchCommand($searchStr, $field, %args)) {
541 $index = $i; last;
542 }
543 }
544  
545 $index = $cw->getItemIndex($searchStr, %args)
546 if (!defined($index) && IsTrue($wrap));
547  
548 return $index;
549 }
550  
551 sub getItemNameAt
552 {
553 my ($cw, $index) = @_;
554 $index = $cw->index($index);
555 return $cw->DisplayedName() if (!defined($index) || $index < 0);
556 return $cw->List->[$index]->name;
557 }
558  
559 sub getItemValueAt
560 {
561 my ($cw, $index) = @_;
562 $index = $cw->index($index);
563  
564 ## If index is out of array bounds or indicated non-selection
565 ## then the value will come from the displayed name.
566 return $cw->DisplayedName() if (!defined($index) || $index < 0);
567  
568 my $item = $cw->List->[$index];
569 return $item->value if defined($item->value) && $item->value ne "";
570 return $item->name;
571 }
572  
573 sub getSelectedIndex { return shift->Selected; }
574  
575 sub getSelectedValue { return shift->getItemValueAt('selected'); }
576  
577 sub hidePopup
578 {
579 my ($cw) = @_;
580 my $popup = $cw->Subwidget('Popup');
581 return unless $popup->ismapped;
582  
583 $popup->withdraw;
584 $cw->grabRelease;
585  
586 ## PATCH (submitted by Ken Prows for CPAN bug#12372)
587 ## PATCH Modified to fix CPAN bug#14520
588 if ($Tk::oldGrab && Exists($Tk::oldGrab) && $Tk::oldGrab->ismapped)
589 {
590 if ($Tk::oldGrabStatus) {
591 $Tk::oldGrab->grab if $Tk::oldGrabStatus eq 'local';
592 $Tk::oldGrab->grabGlobal if $Tk::oldGrabStatus eq 'global';
593 }
594 }
595 ## END PATCH
596 }
597  
598 sub index
599 {
600 my ($cw, $index) = @_;
601 return undef unless defined($index);
602  
603 return 0 if (lc($index) eq 'first');
604 return $cw->getSelectedIndex if (lc($index) eq 'selected');
605 return $cw->getItemCount - 1 if (lc($index) eq 'last');
606 return $cw->getItemCount if (lc($index) eq 'end');
607  
608 my $listbox = $cw->Subwidget('Listbox');
609 return $listbox->index($index) if ($index =~ /\D/);
610 return $index;
611 }
612  
613 sub insertItemAt
614 {
615 my ($cw, $i, $name, %args) = @_;
616  
617 if (!defined($name)) {
618 carp "Insert failed: undefined element";
619 return;
620 }
621 my $index = $cw->index($i);
622 my $lb = $cw->Subwidget('Listbox');
623  
624 ## Create new ListItem and set name
625 my $item = _JCBListItem->new;
626 $item->name($name);
627  
628 ## Set the value if it's given
629 my $value = $args{'-value'};
630 $item->value($value) if defined($value);
631  
632 ## Add ListItem to Internal Array and Listbox(append or splice)
633 my $listAR = $cw->List;
634 if ($lb->index('end') == $index) {
635 push @{$listAR}, $item;
636 } else {
637 splice(@$listAR, $index, 0, ($item, splice(@$listAR, $index)));
638 }
639  
640 $cw->List($listAR);
641 $cw->ListboxInsert($index, $name);
642  
643 ## Set Entry as selected if option is set
644 my $selIndex = $cw->Selected;
645 my $sel = $args{'-selected'};
646 if ($sel && $sel =~ /yes|true|1/i) {
647 $cw->setSelectedIndex($index);
648 }
649 elsif ($index <= $selIndex)
650 {
651 $cw->setSelectedIndex($selIndex + 1);
652 }
653 $cw->UpdateWidth('add', $name);
654 }
655  
656 sub popupIsVisible { return shift->Subwidget('Popup')->ismapped; }
657  
658 sub removeAllItems
659 {
660 my $cw = shift;
661 return unless $cw->getItemCount > 0;
662  
663 $cw->clearSelection;
664 $cw->List([]);
665 $cw->ListboxClear;
666 $cw->LongestEntry(0);
667 }
668  
669 sub removeItemAt
670 {
671 my ($cw, $index) = @_;
672 my $count = $cw->getItemCount;
673 if ($count == 0) {
674 carp "There are no list elements to remove";
675 return;
676 }
677  
678 my $delIndex = $cw->index($index);
679 $delIndex-- if (defined($index) && $index eq "end");
680 return unless defined $delIndex;
681  
682 if ($delIndex < 0 || $delIndex >= $count) {
683 carp "Index: $index is out of array bounds!";
684 return;
685 }
686  
687 my $selIndex = $cw->getSelectedIndex;
688 $cw->clearSelection;
689  
690 ## Delete from List and Listbox
691 my $listAR = $cw->List;
692 splice(@$listAR, $delIndex, 1);
693 $cw->List($listAR);
694 $cw->ListboxDelete($delIndex);
695  
696 if ($selIndex != $delIndex) {
697 $selIndex-- if $delIndex < $selIndex;
698 $cw->setSelectedIndex($selIndex);
699 }
700 $cw->UpdateWidth('delete');
701 }
702  
703 sub see
704 {
705 my ($cw, $index) = @_;
706 $index = $cw->index($index);
707 $cw->showPopup;
708 $cw->Subwidget('Listbox')->see($index) if defined($index);
709 }
710  
711 sub setSelected
712 {
713 my ($cw, $str, %args) = @_;
714 my $index = $cw->getItemIndex($str, %args);
715 $cw->setSelectedIndex($index) if defined($index);
716 return 1 if defined($index);
717 return 0;
718 }
719  
720 sub setSelectedIndex
721 {
722 my ($cw, $index) = @_;
723 $index = $cw->index($index) unless $index == -1;
724 return unless defined($index);
725  
726 $cw->LastSelection($cw->Selected);
727 $cw->Selected($index);
728  
729 ## Adjust Listbox selection
730 my $listbox = $cw->Subwidget('Listbox');
731 $listbox->selectionClear(0, 'end');
732  
733 if ($index >= 0) {
734  
735 $listbox->selectionSet($index);
736 my $display = $cw->getItemNameAt($index);
737 $cw->DisplayedName($display);
738 }
739 $cw->SelectCommand();
740 }
741  
742 sub showPopup
743 {
744 my $cw = shift;
745  
746 $cw->Callback(-popupcreate => $cw)
747 if (ref($cw->cget('-popupcreate')) eq 'Tk::Callback');
748  
749 ## Set up Popup height/width and positioning, based on various
750 ## configured options.
751 $cw->PopupCreate;
752  
753 ## Provide a hook for developers to override details taken
754 ## care of within PopupCreate. -popupcreate should be
755 ## encouraged over -popupmodify.
756 $cw->Callback(-popupmodify => $cw)
757 if (ref($cw->cget('-popupmodify')) eq 'Tk::Callback');
758  
759 return if ($cw->popupIsVisible || $cw->getItemCount == 0);
760  
761 my $popup = $cw->Subwidget('Popup');
762 $popup->deiconify;
763 $popup->raise;
764 $cw->Subwidget('Entry')->focus;
765  
766 ## PATCH (submitted by Ken Prows for CPAN BUG#12372)
767 if ($cw->grabCurrent)
768 {
769 $Tk::oldGrab = $cw->grabCurrent;
770 $Tk::oldGrabStatus = $Tk::oldGrab->grabStatus;
771 }
772 ## END PATCH
773  
774 $cw->grabGlobal;
775 }
776  
777 ## ===================================================================== ##
778 ## Private Methods - avoid calling these directly - they may change ##
779 ## ===================================================================== ##
780  
781 sub AddList
782 {
783 my ($cw, $listAR, $where) = @_;
784  
785 $where = "end" unless defined $where;
786 croak "2nd Parameter may only be 'start' or 'end'\n"
787 unless $where =~ /end|start|\d+/;
788 $where = 0 if $where eq "start";
789  
790 foreach my $el (@{$listAR}) {
791 if (ref($el) eq 'HASH') {
792 my $name = $el->{'-name'} ||
793 croak "Invalid Menu Item. -name must be given when " .
794 "using a Hash reference";
795  
796 my $index = $cw->insertItemAt($where, $name, %$el);
797 }
798 else {
799 $cw->insertItemAt($where, $el);
800 }
801 $where++ if $where ne "end";
802 }
803 }
804  
805 sub AutoFind
806 {
807 my ($cw, $letter, $key) = @_;
808  
809 ## Determine if autofind is enabled/disabled return
810 ## immediately if disabled. No need to continue if AutoFind
811 ## is disabled
812  
813 my $params = $cw->cget('-autofind') || {};
814 my $enabledOpt = GetProperty('-enable' , $params, TRUE);
815 my $casesensOpt = GetProperty('-casesensitive', $params, FALSE);
816 my $popupOpt = GetProperty('-showpopup', $params, TRUE);
817 my $completeOpt = GetProperty('-complete', $params, FALSE);
818 my $selectOpt = GetProperty('-select', $params, FALSE);
819 return unless IsTrue($enabledOpt);
820  
821 ## select takes priority over complete
822 $completeOpt = "false"
823 if (IsTrue($completeOpt) && IsTrue($selectOpt));
824  
825 my $mode = $cw->cget('-mode');
826 my $entry = $cw->Subwidget('Entry');
827 my $listbox = $cw->Subwidget('Listbox');
828  
829 my $searchStr = $letter;
830 if ($mode eq MODE_EDITABLE) {
831 $searchStr = substr($entry->get, 0, $entry->index('insert'));
832 }
833  
834 if (! defined($searchStr) || length($searchStr) == 0) {
835 if ($mode eq MODE_EDITABLE) {
836 $cw->clearSelection;
837 $cw->hidePopup if $cw->popupIsVisible;
838 }
839 return;
840 }
841  
842 ## -casesensitive option: if enabled then distinguishes
843 ## between a k and K key press or search string.
844  
845 my $csVal = "ignorecase";
846 $csVal = "usecase" if IsTrue($casesensOpt);
847  
848 my $start = 0;
849 $start = $cw->LastAFIndex + 1
850 if $searchStr eq $cw->LastAFSearch && defined $cw->LastAFIndex;
851  
852 my $index = $cw->getItemIndex($searchStr,
853 -mode => $csVal,
854 -start => $start,
855 -wrap => 1);
856  
857 $index = -1 if (! defined($index));
858 $cw->LastAFIndex($index);
859 $cw->LastAFSearch($searchStr);
860  
861 ## For all Cases, clear the selection from the Listbox
862 $listbox->selectionClear(0, 'end');
863  
864 ## There is no matching entry: Hide the popup if displayed, and
865 ## Delete any autocompletion characters from the Edit Box, if
866 ## -complete is enabled.
867  
868 if (!defined($index) || $index < 0) {
869 $cw->hidePopup;
870 if ($mode eq MODE_EDITABLE) {
871 $cw->clearSelection;
872 $cw->DisplayedName($searchStr);
873 $entry->icursor(length($searchStr));
874 }
875 return;
876 }
877  
878 ## -select option: if enabled set Box and Listbox selection,
879 ## otherwise only set Listbox selection. -select and -complete
880 ## should never be enabled at the same time.
881 if (IsTrue($selectOpt)) {
882 $cw->setSelectedIndex($index);
883 $entry->icursor(length($searchStr)) if $mode eq MODE_EDITABLE;
884 } else {
885 $listbox->selectionSet($index);
886 }
887  
888 ## -complete option: enables autocompletion for the entry
889 ## autocompletion does nothing in MODE_UNEDITABLE, and is
890 ## ignored if the -select option is enabled.
891  
892 if (IsTrue($completeOpt) && $mode eq MODE_EDITABLE) {
893  
894 my $insertIndex = $entry->index('insert');
895 $insertIndex-- if $key eq "BackSpace";
896 my $endLetters = substr($cw->getItemNameAt($index), $insertIndex);
897 my $validateMode = $entry->cget('-validate');
898 $entry->configure(-validate => 'none');
899 $entry->selectionClear();
900 $entry->delete($insertIndex, 'end');
901 $entry->insert('end', $endLetters);
902 $entry->icursor($insertIndex);
903 $entry->selectionRange($insertIndex, 'end');
904 $entry->configure(-validate => $validateMode);
905 }
906  
907 ## -showpopup option: Some ComboBox implementations do not
908 ## show a popup when their version of AutoFind is called. This
909 ## option allows that behavior to be configured.
910 $cw->showPopup if IsTrue($popupOpt);
911  
912 ## BUG FIX (cpan#11707/Ken Prows) As of v1.03/03 Mar 05
913 $listbox->see($index);
914 }
915  
916 sub BindSubwidgets
917 {
918 my $cw = shift;
919 my $e = $cw->Subwidget('Entry');
920  
921 $e->bind('<Alt-Down>', [$cw => 'AltDown']);
922 $e->bind('<Alt-Up>', [$cw => 'hidePopup']);
923 $e->bind('<Down>', [$cw => 'UpDown', '1']);
924 $e->bind('<Return>', [$cw => 'Return']);
925 $e->bind('<FocusIn>', [$cw => 'Focus', 'In']);
926 $e->bind('<FocusOut>', [$cw => 'Focus', 'Out']);
927 $e->bind('<Escape>', [$cw => 'hidePopup']);
928 $e->bind('<KeyPress>', [$cw => 'KeyPress', Ev('A'), Ev('K')]);
929 $e->bind('<Tab>', [$cw => 'Tab']);
930 $e->bind('<Up>', [$cw => 'UpDown', '-1']);
931  
932 if ($cw->mode eq MODE_UNEDITABLE) {
933 my $b = $cw->Subwidget('Button');
934 $b->bind('<Leave>', [$cw => 'ButtonLeave', $b, [$e]]);
935 $e->bind('<Leave>', [$cw => 'ButtonLeave', $e, [$b]]);
936 }
937 }
938  
939 ##############################################################################
940 ## Creates a "pseudo-Button" which is a Label with some
941 ## simpleButton-like bindings. At last check, a Button has a slightly
942 ## different appearance on Windows than on Unix, and a Label is more
943 ## consistent on the two platforms. On the downside, users expecting a
944 ## Button when extracting the Subwidget are going to be disappointed...
945 ##############################################################################
946 sub CreateButton {
947 my ($cw, %args) = @_;
948  
949 my $ignoreLeave = delete $args{'-ignoreleave'};
950 my $frame = $cw->Subwidget('Frame');
951 my $button = $frame->Label(%args);
952 $button->bind('<ButtonPress-1>', [$cw => 'ButtonDown']);
953 $button->bind('<ButtonRelease-1>', [$cw => 'ButtonUp']);
954 $button->bind('<Leave>', [$cw => 'ButtonUp'])
955 if (IsFalse($ignoreLeave));
956 return $button;
957 }
958  
959 #############################################################################
960 ## Creates and advertises the widgets used for the ComboBox Popup window. The
961 ## Popup consists of a Toplevel widget, advertised as 'Popup', that contains
962 ## a Listbox Widget and Scrollbar. These widgets are gridded, except for the
963 ## Scrollbar which will be gridded only when it needs to be.
964 #############################################################################
965 sub CreateListboxPopup {
966 my $cw = shift;
967  
968 my $c = $cw->Component(
969 Toplevel => 'Popup',
970 -bd => 2,
971 -relief => 'groove'
972 );
973 $c->overrideredirect(1);
974 $c->withdraw;
975  
976 my $lb = $c->Listbox(
977 -takefocus => 0,
978 -selectmode => "browse",
979 -exportselection => 0,
980 -bd => 0,
981 -width => 0,
982 -highlightthickness => 0,
983 )->grid(qw/-row 0 -column 0 -sticky nsew/);
984 $cw->Advertise(Listbox => $lb);
985 $cw->ListboxClear;
986  
987 $c->gridRowconfigure(0, -weight => 1);
988 $c->gridColumnconfigure(0, -weight => 1);
989  
990 my $sb = $c->Scrollbar(
991 -takefocus => 0,
992 -command => [yview => $lb]);
993 $lb->configure(-yscrollcommand => [set => $sb]);
994 $cw->Advertise(Scrollbar => $sb);
995  
996 $lb->bind('<Motion>', [$cw => 'ListboxMotion', Ev('@')]);
997 $lb->bind('<Leave>', [$cw => 'ListboxLeave', Ev('x'), Ev('y')]);
998 $lb->bind('<Enter>', [$cw => 'ListboxEnter']);
999 $lb->bind('<ButtonRelease-1>',
1000 [$cw => 'ButtonRelease', Ev('index',Ev('@'))]);
1001 }
1002  
1003 #############################################################################
1004 ## Responsible for handling logic that implements state changes to and from
1005 ## a disabled state.
1006 ##
1007 ## NOTE: Code in this method was updated using a patch submitted by
1008 ## Neal, 8 MAY 2006 that corrected a bug. When state was set to disabled
1009 ## twice in a row, the foreground color would not be changed back.
1010 #############################################################################
1011 sub DisableControls
1012 {
1013 my $cw = shift;
1014 my $button = $cw->Subwidget('Button');
1015 my $entry = $cw->Subwidget('Entry');
1016  
1017 my $bg = $cw->cget('-disabledbackground');
1018 my $fg = $cw->cget('-disabledforeground');
1019 if ($fg ne $button->cget('-foreground')) {
1020 $button->{$SWAP_FG} = $button->cget('-foreground');
1021 $button->configure(-foreground => $fg);
1022 }
1023 $cw->configure(-takefocus => 0);
1024 if ($cw->mode eq MODE_EDITABLE) {
1025 $entry->configure(-state => 'disabled');
1026 return if $Tk::VERSION >= 804;
1027  
1028 if ($bg ne $button->cget('-background')) {
1029 $entry->{$SWAP_BG} = $entry->cget('-background');
1030 $entry->configure(-background => $bg);
1031 }
1032 }
1033 if ($fg ne $button->cget('-foreground')) {
1034 $entry->{$SWAP_FG} = $entry->cget('-foreground');
1035 $entry->configure(-foreground => $fg);
1036 }
1037 }
1038  
1039 sub EnableControls
1040 {
1041 my $cw = shift;
1042 my $button = $cw->Subwidget('Button');
1043 my $entry = $cw->Subwidget('Entry');
1044  
1045 my $fg = $button->{$SWAP_FG};
1046 return unless defined $fg;
1047  
1048 $button->{$SWAP_FG} = $button->cget('-foreground');
1049 $button->configure(-foreground => $fg);
1050  
1051 if ($cw->mode eq MODE_EDITABLE) {
1052 $entry->configure(-state => 'normal');
1053 return if $Tk::VERSION >= 804;
1054  
1055 my $bg = $entry->{SWAP_BG};
1056 $entry->{$SWAP_BG} = $entry->cget('-background');
1057 $entry->configure(-background => $bg);
1058 }
1059 $fg = $entry->{$SWAP_FG};
1060 $entry->{$SWAP_FG} = $entry->cget('-foreground');
1061 $entry->configure(-foreground => $fg);
1062 $cw->configure(-takefocus => 1);
1063 }
1064  
1065 #############################################################################
1066 ## Displays a value within the Entry Subwidget, and hides the differences
1067 ## between the different modes.
1068 #############################################################################
1069 sub DisplayedName
1070 {
1071 my ($cw, $value) = @_;
1072 my $entry = $cw->Subwidget('Entry');
1073  
1074 ## "Get routine"
1075 if (!defined($value)) {
1076 if ($cw->mode eq MODE_EDITABLE) {
1077 my $val = $entry->get;
1078 my $index = $entry->index('insert');
1079 return substr($val, 0, $index);
1080 }
1081 elsif ($cw->mode eq MODE_UNEDITABLE) {
1082 return $entry->cget('-text') || "";
1083 }
1084 return "";
1085 }
1086  
1087 ## Mode is readonly, so we're dealing with Label widget.
1088 if ($cw->mode eq MODE_UNEDITABLE) {
1089 $entry->configure(-text => $value);
1090  
1091 ## If the mode is editable, then we're dealing with an Entry
1092 ## Widget which may have validation routines bound to it so
1093 ## there's a chance that the selected value will be rejected.
1094 ## The main idea of using a ComboBox is that the List should
1095 ## contain several values, any of which should already be valid.
1096 ## For this reason, validation is temporarily disabled then
1097 ## reenabled after Entry has been set.
1098  
1099 } elsif ($cw->mode eq MODE_EDITABLE) {
1100 my $validateMode = $cw->cget('-validate');
1101 $cw->configure(-validate => 'none');
1102 $entry->delete(0, 'end');
1103 $entry->insert(0, $value);
1104 $cw->configure(-validate => $validateMode);
1105 }
1106 }
1107  
1108 sub GetProperty {
1109 my ($name, $hashRef, $default, $delete) = @_;
1110  
1111 croak "Unable to extract property from undefined Hash Reference\n"
1112 if (!defined($hashRef));
1113  
1114 my $val = $hashRef->{$name};
1115 $val = $default if (!defined($val) && defined($default));
1116 delete $hashRef->{$name} if IsTrue($delete);
1117 return $val;
1118 }
1119  
1120 #############################################################################
1121 ## Arranges layout of the Advertised Entry and Button widgets. These subwidgets
1122 ## are laid out using the grid manager, which I find tends to scale downwards
1123 ## better.
1124 #############################################################################
1125 sub LayoutControls {
1126 my $cw = shift;
1127  
1128 my $frame = $cw->Subwidget('Frame');
1129 my $entry = $cw->Subwidget('Entry');
1130  
1131 ## Editable "Button" is really a Label widget with minimal bindings. There
1132 ## were Win32 display issues with the Button widget, so I created a VERY
1133 ## basic version using Label. Look at using ImageButton in a future release.
1134 my $button = $cw->CreateButton(
1135 -anchor => 'center',
1136 -bitmap => $BITMAP,
1137 -pady => 0,
1138 );
1139 $button->configure(-relief => 'raised')
1140 if $cw->mode eq MODE_EDITABLE;
1141  
1142 $cw->Advertise(Button => $button);
1143 $cw->Advertise(ED_Button => $button) if $cw->mode eq MODE_EDITABLE;
1144 $cw->Advertise(RO_Button => $button) if $cw->mode eq MODE_UNEDITABLE;
1145  
1146 my %buttonInfo = (qw/-row 0 -column 2 -sticky nsew -ipadx 2/);
1147 $buttonInfo{"-ipady"} = 5 if $cw->mode eq MODE_UNEDITABLE;
1148  
1149 $frame->GeometryRequest($button->ReqWidth + 2,0);
1150 $entry->grid(qw/-row 0 -column 0 -sticky nsew/);
1151 $button->grid(%buttonInfo);
1152  
1153 $frame->gridRowconfigure(qw/0 -weight 1/);
1154 $frame->gridColumnconfigure(qw/0 -weight 1/);
1155 }
1156  
1157 sub ListboxClear
1158 {
1159 my $cw = shift;
1160 if ($Tk::version >= 8.4) {
1161 $cw->Subwidget('Listbox')->configure(-listvariable => []);
1162 } else {
1163 $cw->Subwidget('Listbox')->delete(0, 'end');
1164 }
1165 }
1166  
1167 sub ListboxDelete
1168 {
1169 my ($cw, $index) = @_;
1170 if ($Tk::version >= 8.4) {
1171 my @data = $cw->Subwidget('Listbox')->get(0, 'end');
1172 splice(@data, $index, 1);
1173 $cw->Subwidget('Listbox')->configure(-listvariable => \@data);
1174 } else {
1175 $cw->Subwidget('Listbox')->delete($index);
1176 }
1177 }
1178
1179 sub ListboxInsert
1180 {
1181 my ($cw, $index, $value) = @_;
1182  
1183 ## There appear to be issues associated with using cget to retrieve
1184 ## the array ref from the listbox, and reusing that object. Creating
1185 ## a new array seems to work fine... odd.
1186 if ($Tk::version >= 8.4) {
1187 my @data = $cw->Subwidget('Listbox')->get(0, 'end');
1188 if ($cw->Subwidget('Listbox')->index('end') == $index) {
1189 push @data, $value;
1190 } else {
1191 splice(@data, $index, 0, ($value, splice(@data, $index)));
1192 }
1193 $cw->Subwidget('Listbox')->configure(-listvariable => \@data);
1194 } else {
1195 $cw->Subwidget('Listbox')->insert($index, $value);
1196 }
1197 }
1198  
1199 sub MatchCommand
1200 {
1201 my ($cw, $searchStr, $field, %args) = @_;
1202  
1203 ## Check for and use matchcommand if it exists
1204 ## Otherwise use default routines
1205 my $retVal = $cw->Callback(-matchcommand => $searchStr, $field, %args)
1206 if (ref($cw->cget('-matchcommand')) eq 'Tk::Callback');
1207 return $retVal if defined $retVal;
1208  
1209 ## Extract mode (defaults to exact if not set
1210 my $mode = lc($args{'-mode'}) || "exact";
1211 if ($mode !~ /^((use|ignore)case|exact)$/) {
1212 $mode = "exact";
1213 carp "Invalid value $mode for -mode in getItemIndex - " .
1214 "value of 'exact' assumed";
1215 }
1216 return 1 if $mode eq 'exact' && $field eq $searchStr;
1217 return 1 if $mode eq 'usecase' && $field =~ /^\Q$searchStr\E/;
1218 return 1 if $mode eq 'ignorecase' && $field =~ /^\Q$searchStr\E/i;
1219 return 0;
1220 }
1221  
1222 #############################################################################
1223 ## Takes a list of one or more subwidgets and returns 1
1224 ## if the mouse pointer is pointed over any one of them.
1225 ## Returns 0 otherwise.
1226 #############################################################################
1227 sub PointerOverWidget {
1228 my ($cw, @widgets) = @_;
1229 my $xPos = $cw->pointerx;
1230 my $yPos = $cw->pointery;
1231 my $overWidget = $cw->containing($xPos, $yPos);
1232  
1233 foreach my $w (@widgets) {
1234 return TRUE if defined $overWidget && $w == $overWidget ;
1235 }
1236 return FALSE;
1237 }
1238  
1239 #############################################################################
1240 ## Notifies a registered SelectCommand that a new item has
1241 ## been selected. A selection can occur in a large number
1242 ## of ways. The tricky bit is to ensure that it gets called
1243 ## when the selection changes, but does not get called
1244 ## repeatedly for the same selection. Most of the complication
1245 ## has to do with the editable mode.
1246 #############################################################################
1247 sub SelectCommand
1248 {
1249 my $cw = shift;
1250 my $selIndex = $cw->getSelectedIndex;
1251 my $selName = $cw->DisplayedName || "";
1252  
1253 ## First validate each index
1254 my $newIndex;
1255 $newIndex = $cw->getItemIndex($selName) unless $selName eq "";
1256 $newIndex = -1 unless defined($newIndex);
1257 if ($selIndex != $newIndex) {
1258 $cw->setSelectedIndex($newIndex);
1259 return;
1260 }
1261  
1262 ## Selected index has been validated - now, check to
1263 ## see if there was a difference between it and the
1264 ## last selection.
1265 my $notifyObserver = 0;
1266 $notifyObserver = 1 if
1267 ($selIndex != $cw->LastSelection || $selName ne $cw->LastSelName);
1268  
1269 if ($notifyObserver) {
1270 my $selValue = $cw->getSelectedValue;
1271 $cw->LastSelName($selName);
1272 $cw->LastSelection($selIndex);
1273 $cw->Callback(-selectcommand => $cw, $selIndex, $selName, $selValue)
1274 if (ref($cw->cget('-selectcommand')) eq 'Tk::Callback');
1275 }
1276 }
1277  
1278 #############################################################################
1279 ## Default Callback for -popupcreate option this method determines the correct
1280 ## size and placement of the Popup triggered by the ComboBox Button, and then
1281 ## displays it. Just prior to displaying the Popup, the Callback assigned to
1282 ## to -popupmodify will be called allowing additional popup configuration to
1283 ## be modified prior to being displayed. This would be used if someone wants
1284 ## to make minor changes to Popup, but still use the ShowPopup implementation.
1285 #############################################################################
1286 sub PopupCreate {
1287 my $cw = shift;
1288  
1289 my $popup = $cw->Subwidget("Popup");
1290 my $listbox = $cw->Subwidget("Listbox");
1291 my $scrollbar = $cw->Subwidget("Scrollbar");
1292 my $entry = $cw->Subwidget("Entry");
1293  
1294 $cw->UpdateListboxHeight;
1295  
1296 ## Scrolled turns propagate off, but I need it on
1297 $listbox->Tk::pack('propagate',1);
1298  
1299 my $maxX = $cw->vrootwidth; ## Max X position
1300 my $maxY = $cw->vrootheight; ## Max Y position
1301  
1302 ## Determine X/Y position of Popup -- Initially, the Popup should be
1303 ## displayed directly below the ComboBox, and aligned to the left side.
1304 ## This may change depending on placement of the ComboBox on the Screen.
1305 my $popupPosX = $cw->rootx;
1306 my $popupPosY = $cw->rooty + $cw->height;
1307 my $popupWidth = $cw->width; ## Defaults to width of the ComboBox
1308 my $popupHeight = $listbox->ReqHeight + $popup->cget('-borderwidth') * 2;
1309  
1310 ## Override width if -listwidth is defined
1311 my $listWidth = $cw->cget('-listwidth');
1312 if (defined $listWidth && $listWidth > -1) {
1313 $listbox->configure(-width => $listWidth);
1314 $popupWidth = $listbox->ReqWidth + $popup->cget('-borderwidth') * 2;
1315 $popupWidth = $popupWidth + $scrollbar->ReqWidth if $scrollbar->manager;
1316 }
1317  
1318 ## X/Y values must be at least 0, to display popup on screen. Typically,
1319 ## this will only ever be a problem for the X value.
1320 $popupPosX = 0 if $popupPosX < 0;
1321 $popupPosY = 0 if $popupPosY < 0;
1322  
1323 ## X/Y values must not allow the popup to be displayed beyond the maximum
1324 ## limits allowed for the screen. Again, this will might happen
1325 $popupPosX = $maxX - $popupWidth if (($popupPosX + $popupWidth) > $maxX);
1326 $popupPosY = $maxY - $popupHeight if (($popupPosY + $popupHeight) > $maxY);
1327  
1328 ## Unfortunately, just moving the Popup will only do so much if the Popup
1329 ## is larger than what the screen will support. So, to prevent this from
1330 ## occurring the following failsafe should prevent the popup from being
1331 ## displayed off screen. A mandatory maximum height is placed on the List.
1332 ## Currently, this does not override the maxrows option and will have to be
1333 ## calculated each time the popup is displayed. Hopefully, this condition
1334 ## will only be needed for exceptional cases.
1335 my $listboxHeight = $listbox->size;
1336 if ($popupHeight > $maxY) {
1337 while ($popupHeight > $maxY) {
1338 $listboxHeight--;
1339 $listbox->configure(-height => $listboxHeight);
1340 $listbox->update;
1341 $popupHeight = $listbox->ReqHeight + $popup->cget('-borderwidth') * 2;
1342 }
1343 $popupPosY = $maxY - $popupHeight;
1344 }
1345
1346 ## Position and adjust the width/height of the Popup prior to display.
1347 $popup->geometry(sprintf("%dx%d+%d+%d",
1348 $popupWidth,
1349 $popupHeight,
1350 $popupPosX,
1351 $popupPosY));
1352 }
1353  
1354 sub UpdateListboxHeight
1355 {
1356 my $cw = shift;
1357 my $listbox = $cw->Subwidget('Listbox');
1358 my $sb = $cw->Subwidget('Scrollbar');
1359  
1360 ## Ensure that the Listbox is no larger than the maxrow size
1361 ## and at least as large as 1. If maxrow size is set to 0 or
1362 ## lower then the Listbox will grow/shrink as large as it needs
1363 ## to display all items. The Listbox drives what the height of the
1364 ## popup will be.
1365  
1366 my $rows = $listbox->size;
1367 my $maxRows = $cw->cget('-maxrows');
1368  
1369 if ($maxRows >= 0 && $maxRows < $rows) {
1370 $rows = $maxRows;
1371 $sb->grid(qw/-row 0 -column 1 -sticky ns/) if ! $sb->manager;
1372 }
1373 else {
1374 $sb->gridForget if $sb->manager;
1375 }
1376 $listbox->configure(-height => $rows);
1377 }
1378  
1379 ##############################################################################
1380 ## Updates the width of the widget dynamically based on the longest list
1381 ## entry. This is similar to specifying 0 or less for the Listbox widget. If
1382 ## -entrywidth is greater than 0
1383 #############################################################################
1384 sub UpdateWidth {
1385 my ($cw, $action, $name) = @_;
1386 my $entry = $cw->Subwidget('Entry');
1387  
1388 ## updates the width automatically if width has been set to -1, which
1389 ## is the default, and anything greater than the default will force the
1390 ## width to be static, otherwise it will be as wide as the longest element
1391 ## in the List. *Feature request: Bryan Williams (bitbucketz2002@yahoo.com)
1392 ## - 2003-06-18
1393 my $w = $cw->cget('-entrywidth');
1394 $w = -1 unless defined $w; ## Assume -1
1395 if ($w >= 0) {
1396 my $gap = $cw->gap;
1397 $w = $w + $gap if $w > 0;
1398 $entry->configure(-width => $w);
1399 return;
1400 }
1401  
1402 if ($action eq "add") {
1403 my $len = length($name);
1404 return if ($len <= $cw->LongestEntry);
1405 $cw->LongestEntry($len);
1406 }
1407 elsif ($action eq "delete") {
1408 my $currLen = 0;
1409 foreach my $item (@{$cw->List}) {
1410 $currLen = length($item->name) if $currLen < length($item->name);
1411 }
1412 $cw->LongestEntry($currLen) if $cw->LongestEntry > $currLen;
1413 }
1414 $cw->LongestEntry($cw->gap + $cw->LongestEntry);
1415 $entry->configure(-width => $cw->LongestEntry);
1416 }
1417  
1418 #############################################################################
1419 ## Callback registered to -validatecommand when the -validate options values
1420 ## is "match" or "cs-match".
1421 #############################################################################
1422 sub ValidateCommand
1423 {
1424 my ($cw, $str, $chars, $currval, $i, $action) = @_;
1425 my $mode = $cw->cget('-validate');
1426  
1427 if ($mode !~ /match/) {
1428 my $vc = $cw->cget('-validatecommand');
1429 return TRUE unless defined $vc;
1430 return $vc->Call($str, $chars, $currval, $i, $action) if defined($vc);
1431 }
1432  
1433 my $index;
1434 if ($mode eq VAL_MODE_MATCH) {
1435 $index = $cw->getItemIndex($str, -mode => 'ignorecase');
1436 }
1437 elsif ($mode eq VAL_MODE_CSMATCH) {
1438 $index = $cw->getItemIndex($str, -mode => 'usecase');
1439 }
1440 return TRUE if (defined($index));
1441 return FALSE;
1442 }
1443  
1444 ## ========================================================= ##
1445 ## JComboBox Event Handler Routines
1446 ## ========================================================= ##
1447  
1448 sub AltDown
1449 {
1450 my $cw = shift;
1451 return unless $cw->state eq 'normal';
1452 if ($cw->popupIsVisible) { $cw->hidePopup; }
1453 else { $cw->showPopup; }
1454 }
1455  
1456 sub ButtonDown
1457 {
1458 my $cw = shift;
1459 return unless ($cw->state eq 'normal');
1460 my $mode = $cw->cget('-mode');
1461  
1462 my $button;
1463 $button = $cw->Subwidget('Frame') if $cw->mode eq MODE_UNEDITABLE;
1464 $button = $cw->Subwidget('Button') if $cw->mode eq MODE_EDITABLE;
1465  
1466 $cw->IsButtonDown(TRUE);
1467 $cw->TempRelief($button->cget('-relief'));
1468 $button->configure(-relief => 'sunken');
1469  
1470 ## Call buttoncommand if defined
1471 $cw->Callback(-buttoncommand => $cw, $cw->getSelectedIndex)
1472 if (ref($cw->cget('-buttoncommand')) eq 'Tk::Callback');
1473 }
1474  
1475 sub ButtonLeave
1476 {
1477 my ($cw, $trigger, $ignoreLeave) = @_;
1478 return unless $cw->state eq 'normal';
1479 return if (IsFalse($cw->IsButtonDown));
1480  
1481 if (defined($ignoreLeave) && ref($ignoreLeave) eq "ARRAY") {
1482
1483 if (IsTrue($cw->PointerOverWidget($ignoreLeave))) {
1484 $trigger->bind('<Motion>',
1485 [$cw => 'ButtonMotion', $trigger, [$trigger, @$ignoreLeave]]);
1486 return;
1487 }
1488 }
1489 $cw->ButtonUp;
1490 }
1491  
1492 sub ButtonMotion
1493 {
1494 my ($cw, $trigger, $widgetAR) = @_;
1495 return unless $cw->state eq 'normal';
1496  
1497 ## If The Button is Up, then we no longer need this binding.
1498 if (IsFalse($cw->IsButtonDown)) {
1499 $trigger->bind('<Motion>', "");
1500 return;
1501 }
1502 if (IsFalse($cw->PointerOverWidget(@{$widgetAR}))) {
1503 $cw->ButtonUp;
1504 }
1505 }
1506  
1507 sub ButtonRelease
1508 {
1509 my ($cw, $index) = @_;
1510 return unless $cw->state eq 'normal';
1511 return unless $cw->popupIsVisible;
1512 $cw->hidePopup;
1513 $cw->setSelectedIndex($index) if defined($index);
1514  
1515 }
1516  
1517 sub ButtonUp {
1518 my $cw = shift;
1519 return unless $cw->state eq 'normal';
1520  
1521 ## Take care of returning the button relief
1522 my $button;
1523 my $mode = $cw->cget('-mode');
1524 if ($mode eq MODE_UNEDITABLE) { $button = $cw->Subwidget('Frame'); }
1525 elsif ($mode eq MODE_EDITABLE) { $button = $cw->Subwidget('Button'); }
1526  
1527 if ($cw->TempRelief) {
1528 $button->configure(-relief => $cw->TempRelief);
1529 $cw->TempRelief(0);
1530 }
1531 $cw->IsButtonDown(FALSE);
1532 }
1533  
1534 sub Focus
1535 {
1536 my ($cw, $inOut) = @_;
1537 my $bg = $cw->highlightcolor;
1538 my $color = $cw->highlightbackground;
1539 $cw->highlightcolor($color);
1540 $cw->highlightbackground($bg);
1541 $cw->SelectCommand if (defined($inOut) && $inOut eq "Out");
1542 }
1543  
1544 sub KeyPress
1545 {
1546 my ($cw, $uChar, $keySym) = @_;
1547 return unless $cw->state eq 'normal';
1548 my $kc = $cw->cget('-keycommand');
1549 $kc->Call($cw, $uChar, $keySym) if defined $kc;
1550 $cw->AutoFind($uChar, $keySym);
1551 }
1552  
1553 sub ListboxEnter
1554 {
1555 my $cw = shift;
1556 return if IsFalse($cw->cget('-listhighlight'));
1557 $cw->Subwidget('Listbox')->CancelRepeat;
1558 }
1559  
1560 sub ListboxLeave
1561 {
1562 my ($cw, $x, $y) = @_;
1563 return if IsFalse($cw->cget('-listhighlight'));
1564 $cw->Subwidget('Listbox')->AutoScan($x, $y);
1565 }
1566  
1567 sub ListboxMotion
1568 {
1569 my ($cw, $xy) = @_;
1570 return if IsFalse($cw->cget('-listhighlight'));
1571 my $listbox = $cw->Subwidget('Listbox');
1572 my $index = $listbox->index($xy);
1573 $listbox->Motion($index);
1574 }
1575  
1576 ## TO DO -- I don't think this method is doing the right thing
1577 ## it is called NonSelect yet it IS selecting.
1578 sub NonSelect {
1579 my $cw = shift;
1580 return unless $cw->popupIsVisible;
1581 $cw->hidePopup;
1582 my $index = $cw->getSelectedIndex;
1583 $cw->setSelectedIndex($index) if defined($index);
1584 }
1585  
1586 sub RedirectFocus { shift->Subwidget('Entry')->focus; }
1587  
1588 sub Return
1589 {
1590 my $cw = shift;
1591 return unless $cw->state eq 'normal';
1592 my ($index) = $cw->Subwidget('Listbox')->curselection;
1593 $index = -1 unless defined($index);
1594  
1595 $cw->hidePopup if $cw->popupIsVisible;
1596 $cw->Subwidget('Entry')->selectionClear() if $cw->mode eq MODE_EDITABLE;
1597 $cw->setSelectedIndex($index) if defined($index);
1598 }
1599  
1600 sub Tab
1601 {
1602 my $cw = shift;
1603 $cw->Return;
1604 $cw->focusNext;
1605 }
1606  
1607 sub TextvarFetch
1608 {
1609 return shift->getItemValueAt('selected');
1610 }
1611  
1612 sub TextvarStore
1613 {
1614 my ($cw, $watch, $value) = @_;
1615  
1616 if (!defined($value) || $value eq "") {
1617 $cw->clearSelection();
1618 return;
1619 }
1620  
1621 ## If the item value exists within the list, then selected it.
1622 my $index = $cw->getItemIndex($value, -type => 'value');
1623 if (defined($index) && $index != -1) {
1624 $cw->setSelectedIndex($index);
1625 }
1626 ## Otherwise, only set it, if the mode is editable (allows
1627 ## values that are not in the list.
1628 else {
1629 $cw->DisplayedName($value) if $cw->mode eq MODE_EDITABLE;
1630 }
1631 }
1632  
1633 sub UpDown
1634 {
1635 my ($cw, $mod) = @_;
1636 return unless $cw->state eq 'normal';
1637 return unless (defined($mod) && ($mod =~ /^(|-)?\d+$/));
1638  
1639 my $lastIndex = $cw->getItemCount() - 1;
1640 my $listbox = $cw->Subwidget('Listbox');
1641 my ($index) = $listbox->curselection;
1642 $index = -1 if !defined($index) || $index eq "";
1643  
1644 my $modIndex = $index + $mod;
1645 $modIndex = $lastIndex if $modIndex > $lastIndex;
1646 $modIndex = 0 if $modIndex < 0;
1647 return if $modIndex == $index;
1648  
1649 my $selectOpt = $cw->cget('-updownselect');
1650 if (IsTrue($selectOpt)) {
1651 $cw->setSelectedIndex($modIndex);
1652 }
1653 else {
1654 $listbox = $cw->Subwidget('Listbox');
1655 $listbox->selectionClear(0, 'end');
1656 $listbox->selectionSet($modIndex);
1657 }
1658 }
1659  
1660 ###########################################################################
1661 ## The package below is highly experimental and subject to massive change
1662 ## and/or deprecation in future versions of JComboBox. Use at your own risk.
1663 ###########################################################################
1664 package Tk::JComboBox::Tie;
1665  
1666 use strict;
1667 use Carp;
1668 use Tie::Array;
1669  
1670 use vars qw($VERSION);
1671 our $VERSION = "0.01";
1672  
1673 use base qw(Tie::Array);
1674  
1675 sub addWatcher
1676 {
1677 my ($self, $watcher) = @_;
1678 return unless ref($watcher) eq 'Tk::JComboBox';
1679 push @{$self->{LISTENERS}}, $watcher
1680 if $self->FindWatcher($watcher) < 0;
1681 }
1682  
1683 sub removeWatcher
1684 {
1685 my ($self, $watcher) = @_;
1686 my $index = $self->FindWatcher($watcher);
1687 splice @{$self->{LISTENERS}}, $index, 1 unless $index < 0;
1688 }
1689  
1690 sub tie
1691 {
1692 my ($pkg, $jcb, $newListAR, $oldListAR) = @_;
1693  
1694 ## 1st Determine if the oldListAR has been tied to. It
1695 ## will almost ALWAYS be tied to, except for the first
1696 ## time -choices have been configured to a JComboBox.
1697 my $listenerAR;
1698  
1699 my $oldTie = tied @$oldListAR
1700 if (defined $oldListAR && ref($oldListAR) eq 'ARRAY');
1701  
1702 if (defined($oldTie)) {
1703  
1704 ## This widget was the master, copy all listeners
1705 ## before breaking the tie, so that we can maintain
1706 ## existing ties.
1707 if ($jcb == $oldTie->Master) {
1708 $oldTie->CLEAR;
1709 $listenerAR = $oldTie->{LISTENERS};
1710 shift @$listenerAR;
1711  
1712 $oldTie = undef;
1713 untie @$oldListAR;
1714 }
1715  
1716 ## This widget is not the master, the tie is not ours
1717 ## to break. Remove this widget as a listener -- it
1718 ## will be a master of a it's own tie. Then clear all
1719 ## its items.
1720  
1721 else {
1722 $oldTie->removeWatcher($jcb);
1723 }
1724 }
1725 $jcb->removeAllItems if $jcb->getItemCount > 0;
1726  
1727 ## At this point, there should be no tie, or the JCombobox
1728 ## has been removed as a listener from an existing one. This
1729 ## is to clear the way to either create a new tie or add it
1730 ## as a listener to a different tie.
1731 my $newTie;
1732  
1733 if (ref($newListAR) eq 'ARRAY') {
1734 $newTie = tied @$newListAR;
1735 my @items = @$newListAR;
1736  
1737 ## Check to see if the new ListAR already is tied. If it is, and
1738 ## and it is tied to a JComboBox, then we will register this
1739 ## widget as a listener, and will not recreate the tie.
1740 if (defined($newTie) && ref($newTie) eq 'Tk::JComboBox::Tie') {
1741 $newTie->addWatcher($jcb);
1742 $jcb->AddList(\@items, "end");
1743 }
1744  
1745 ## The new list has not been tied to anything yet, so we're going
1746 ## to create a new Tie with the specified JComboBox as the master.
1747 ## If this widget was a previous master, then all of its listeners
1748 ## will be swapped to the new tie.
1749 else {
1750 $newTie = tie @$newListAR, 'Tk::JComboBox::Tie', $jcb;
1751 $jcb->AddList(\@items, "end");
1752  
1753 foreach my $l (@$listenerAR) {
1754 $l->configure(-choices => \@$newListAR);
1755 }
1756 }
1757 }
1758 return $newTie;
1759 }
1760  
1761 ## ========================================================= ##
1762 ## PRIVATE METHODS ##
1763 ## ========================================================= ##
1764  
1765 sub CLEAR
1766 {
1767 my $self = shift;
1768 $self->Notify(-method => 'CLEAR_W') if $self->FETCHSIZE > 0;
1769 }
1770 sub CLEAR_W { $_[1]->removeAllItems }
1771  
1772 sub DELETE { shift->SPLICE(shift, 1) }
1773  
1774 sub DESTROY
1775 {
1776 my $self = shift;
1777 foreach my $listener (@{$self->{LISTENERS}}) {
1778 $listener->configure(-choices => "")
1779 if ref($listener) eq 'Tk::JComboBox' && Tk::Exists($listener);
1780 }
1781 }
1782  
1783 sub FETCH
1784 {
1785 my ($self, $index) = @_;
1786 return undef if $index + 1 > $self->FETCHSIZE;
1787 return $self->GetItemValues($self->Master, $index);
1788 }
1789  
1790 sub FETCHSIZE { shift->Master->getItemCount }
1791  
1792 sub FindWatcher
1793 {
1794 my ($self, $watcher) = @_;
1795 if (ref($watcher)) {
1796 foreach my $i (0 .. (scalar(@{$self->{LISTENERS}})-1)) {
1797 return $i if ($self->{LISTENERS}->[$i] == $watcher);
1798 }
1799 }
1800 return -1;
1801 }
1802  
1803 sub GetItemValues
1804 {
1805 my ($self, $w, $index) = @_;
1806 $index = $w->index($index);
1807 my $count = $w->getItemCount;
1808 return if $index >= $w->getItemCount;
1809  
1810 my $item = $w->List->[$index];
1811 my $rv = $item->name;
1812  
1813 if ($item->value) {
1814 $rv = { -name => $item->name };
1815 $rv->{'-value'} = $item->value if defined($item->value);
1816 }
1817 return $rv;
1818 }
1819  
1820 sub Master { return shift->{LISTENERS}->[0] }
1821  
1822 sub Notify
1823 {
1824 my ($self, %args) = @_;
1825  
1826 ## For some reason, the JComboBox sticks around in memory
1827 ## after it's been destroyed. Remove any destroyed
1828 ## widgets from the list of listeners prior to notification.
1829 my @good;
1830 foreach my $listener (@{$self->{LISTENERS}}) {
1831 if (Tk::Exists($listener)) {
1832 push @good, $listener;
1833 }
1834 else {
1835 undef $listener;
1836 }
1837 }
1838 $self->{LISTENERS} = \@good;
1839  
1840 my $method = delete $args{-method};
1841 my $except = delete $args{-except};
1842 my $paramAR = delete $args{-params};
1843  
1844 foreach my $listener (@{$self->{LISTENERS}})
1845 {
1846 next if (defined($except) && $listener == $except);
1847 $self->$method($listener, @$paramAR);
1848 }
1849 }
1850  
1851 sub POP { shift->SPLICE("last", 1) }
1852 sub PUSH { shift->SPLICE("end", 0, @_) }
1853  
1854 sub RemoveItemValues
1855 {
1856 my ($self, $w, $index) = @_;
1857 $index = $w->index($index);
1858 my $rv = $self->GetItemValues($w, $index);
1859 $w->removeItemAt($index);
1860 return $rv;
1861 }
1862  
1863 sub RemoveList
1864 {
1865 my ($self, $w, $start, $length) = @_;
1866 my @rv;
1867 return if $start + 1 > $w->getItemCount;
1868 $length = $w->getItemCount - $start if !defined($length);
1869 $length = ($w->getItemCount + $length) - $start if $length < 0;
1870 if ($length > 0) {
1871 foreach (1 .. $length) {
1872 push @rv, $self->RemoveItemValues($w, $start++);
1873 }
1874 }
1875 return @rv;
1876 }
1877  
1878 sub SHIFT { shift->SPLICE("first", 1) }
1879  
1880 sub SPLICE
1881 {
1882 my $self = shift;
1883 my $master = $self->Master;
1884 return if !defined($master);
1885  
1886 $self->Notify(
1887 -method => 'SPLICE_W',
1888 -params => \@_,
1889 -except => $master
1890 );
1891 $self->SPLICE_W($master, @_);
1892 }
1893  
1894 sub SPLICE_W
1895 {
1896 my ($self, $w, $offset, $length, @list) = @_;
1897 my $bounds = $w->getItemCount;
1898 $offset = 0 unless defined $offset;
1899 $offset = $w->index($offset);
1900 $offset = $bounds + $offset if $offset < 0;
1901 return if $offset > $bounds;
1902  
1903 my @removed = $self->RemoveList($w, $offset, $length);
1904 $w->AddList(\@list, $offset) if @list;
1905  
1906 return undef unless @removed;
1907 return wantarray ? @removed : $removed[scalar(@removed)-1];
1908 }
1909  
1910 sub STORESIZE {}
1911 sub STORE { shift->SPLICE(shift, 1, shift) }
1912  
1913 sub TIEARRAY
1914 {
1915 my ($class, $jcb) = @_;
1916  
1917 croak "Widget parameter was not a Tk::JComboBox!"
1918 unless defined($jcb) && ref($jcb) eq 'Tk::JComboBox';
1919  
1920 my $state = {
1921 LISTENERS => [$jcb]
1922 };
1923 return bless $state, $class;
1924 }
1925  
1926 sub UNSHIFT { shift->SPLICE(0, 0, @_) }
1927 1;
1928