PopUpSelectBox.pm untested

filter: Statementstmt 0.0% 0 / 620 Branchbran 0.0% 0 / 216 Conditioncond 0.0% 0 / 49 MC/DCmcdc 0.0% 0 / 30 Subroutinesub 0.0% 0 / 68 Podpod 0.0% 0 / 44 totaltotal 0.0% 0 / 1027 CC 109 SCAR 40.0
CC
109
Cov
0%
popup
240.0
_add_option
132.0
list_selected
110.0
CRAP 54.5
1 ######################################## SOH ###########################################
2 ## Function : Alternate version for Tk:Optionbox with scroller, better for larger amounts
3 ## of selectable items
4 ##
5 ## Copyright (c) 2008 Michael Krause. All rights reserved.
6 ## This program is free software; you can redistribute it and/or modify it
7 ## under the same terms as Perl itself.
8 ##
9 ## History : V0.01 27-Feb-2008 Class derived from original Optionbox. MK
10 ## V0.02 03-Mar-2008 First usable version
11 ##
12 ######################################## EOH ###########################################
13 package Tk::PopUpSelectBox;
14 use Tk;
15  
16 ########################################################################
17 # ResizeCBox is a a slightly modified version of Damion K. Wilson's
18 # CornerBox (derived from Tk-DKW-0.03) Thanx.
19 ########################################################################
20  
21 package Tk::PopUpSelectBox::ResizeCBox;
22  
23 use Tk::Canvas;
24 use Tk::Frame;
25  
26 use vars qw ($VERSION);
27 use base qw (Tk::Frame);
28  
29 $VERSION = '0.01';
30  
31 #---------------------------------------------
32 use constant TRIMCOUNT => '3';
33 use constant MINSIZE_X => '100';
34 use constant MINSIZE_Y => '50';
35  
36 #---------------------------------------------
37 Tk::Widget->Construct ('ResizeCBox');
38  
39 #---------------------------------------------
40 sub Populate
41 {
42 my ($this, $args) = @_;
43  
44 # retrieve extra option
45 my $size = $this->{_size} = delete $args->{-size} || 20; $size = 15 if $size < 15;
46  
47 $this->SUPER::Populate (@_);
48  
49 #Widget Creation
50 my $canvas = $this->Canvas(
51 -borderwidth => 0,
52 -highlightthickness => 0,
53 -height => $size,
54 -width => $size,
55 )->pack(
56 -fill => 'both',
57 -expand => '1',
58 );
59 $this->Advertise('canvas' => $canvas);
60  
61 $canvas->Tk::bind ('<ButtonPress-1>' => [\&Press, $this]);
62 $canvas->Tk::bind ('<B1-Motion>' => [\&Resize, $this]);
63 $canvas->Tk::bind ('<Configure>' => [\&Configure, $this]);
64 $this->Tk::bind ('<Enter>' => [\&Enter, $this]);
65 $this->Tk::bind ('<Leave>' => [\&Leave, $this]);
66  
67 return $this;
68 }
69  
70 #---------------------------------------------
71 sub Configure
72 {
73 my ($canvas, $this) = @_;
74  
75 return unless ($this->IsMapped());
76  
77 my $height = $this->height();
78 my $width = $this->width();
79 my $trimcount = TRIMCOUNT();
80  
81 $canvas->configure(-scrollregion => [0, 0, $width, $height]);
82  
83 unless (defined ($this->{'m_TrimList'})) {
84 my $highColor = $this->Darken ($this->cget ('-background'), 150);
85 my $lowColor = $this->Darken ($this->cget ('-background'), 60);
86  
87 my $scale = $this->{_size} / 2 * 3;
88 for (my $l_Index = 0; $l_Index < $trimcount; ++$l_Index) {
89 push (@{$this->{'m_TrimList'}},
90 $canvas->create ('line', $scale, 0, 0, $scale, '-fill' => $highColor),
91 $canvas->create ('line', $scale, 1, 1, $scale, '-fill' => $lowColor),
92 );
93 }
94 }
95  
96 for (my $l_Index = 0; $l_Index <= $#{$this->{'m_TrimList'}}; $l_Index += 2) {
97 my ($l_Light, $l_Dark) = @{$this->{'m_TrimList'}} [$l_Index .. ($l_Index + 1)];
98 my $l_Divisor = (($l_Index + 2) / 2) - 1;
99  
100 $canvas->coords($l_Light,
101 $width, ($height / ($trimcount + 1)) * $l_Divisor,
102 ($width / ($trimcount + 1)) * $l_Divisor, $height,
103 );
104  
105 $canvas->coords($l_Dark,
106 $width, (($height / ($trimcount + 1)) * $l_Divisor) + 2,
107 ($width / (($trimcount + 1)) * $l_Divisor) + 2, $height,
108 );
109 }
110 }
111  
112 #---------------------------------------------
113 sub Enter
114 {
115 $_[0]->{'m_Cursor'} = $_[0]->cget ('-cursor');
116 $_[0]->configure ('-cursor' => ($^O =~ /^(MSWin32|DOS)$/ ? 'size_nw_se' : 'bottom_right_corner'));
117 }
118  
119 #---------------------------------------------
120 sub Leave
121 {
122 $_[0]->configure ('-cursor' => $_[0]->{'m_Cursor'} || 'arrow');
123 }
124  
125 #---------------------------------------------
126 sub Press
127 {
128 $_[1]->{'-deltax'} = $_[1]->pointerx();
129 $_[1]->{'-deltay'} = $_[1]->pointery();
130 }
131  
132 #---------------------------------------------
133 sub Resize
134 {
135 my @geometry = split (/[+x]/, $_[1]->toplevel()->geometry());
136  
137 # Take care that we stay in the visible area
138 my $x = $_[1]->pointerx();
139 if ($x < 0) {
140 $geometry [0] = $_[1]->{'-deltax'};
141 }
142 else {
143 $geometry [0] += ($x - $_[1]->{'-deltax'});
144 $_[1]->{'-deltax'} = $x;
145 }
146
147 my $y = $_[1]->pointery();
148 if ($y < 0) {
149 $geometry [1] = $_[1]->{'-deltay'};
150 }
151 else {
152 $geometry [1] += ($y - $_[1]->{'-deltay'});
153 $_[1]->{'-deltay'} = $y;
154 }
155  
156 # Force absolute min-sizes of the steered window
157 $geometry [0] = MINSIZE_X() if $geometry [0] < MINSIZE_X();
158 $geometry [1] = MINSIZE_Y() if $geometry [1] < MINSIZE_Y();
159  
160 # Set the new geometry
161 $_[1]->toplevel()->geometry($geometry [0] . 'x' . $geometry [1]);
162 }
163  
164 1;
165  
166 ########################################################################
167 # For changing some aspects here we clone the TK-Tree Widget
168 ########################################################################
169 package Tk::PopUpSelectBox::SelectTree;
170  
171 use vars qw($VERSION);
172 $VERSION = '0.01';
173  
174 use Tk qw(Ev);
175 use Tk::Derived;
176 use Tk::HList;
177 use base qw(Tk::Derived Tk::HList);
178  
179 #---------------------------------------------
180 Tk::Widget->Construct ('SelectTree');
181  
182 my $minus_data = <<'minus_data_EOP';
183 /* XPM */
184 static char *xpm[] = {
185 "13 13 2 1",
186 ". c none",
187 "X c black",
188 ".............",
189 ".............",
190 ".............",
191 "XXXXXXXXXXXXX",
192 ".XX.......XX.",
193 "..XX.....XX..",
194 "...XX...XX...",
195 "....XX.XX....",
196 ".....XXX.....",
197 "......X......",
198 ".............",
199 ".............",
200 ".............",
201 };
202 minus_data_EOP
203  
204 my $minus_arm_data = <<'minus_arm_data_EOP';
205 /* XPM */
206 static char *xpm[] = {
207 "13 13 3 1",
208 ". c none",
209 "X c black",
210 "a c red",
211 ".............",
212 ".............",
213 ".............",
214 "XXXXXXXXXXXXX",
215 ".XXXXXXXXXXX.",
216 "..XXXXXXXXX..",
217 "...XXXXXXX...",
218 "....XXXXX....",
219 ".....XXX.....",
220 "......X......",
221 ".............",
222 ".............",
223 ".............",
224 };
225 minus_arm_data_EOP
226  
227 my $plus_data = <<'plus_data_EOP';
228 /* XPM */
229 static char *xpm[] = {
230 "13 13 2 1",
231 ". c none",
232 "X c black",
233 "...X.........",
234 "...XX........",
235 "...XXX.......",
236 "...X.XX......",
237 "...X..XX.....",
238 "...X...XX....",
239 "...X....XX...",
240 "...X...XX....",
241 "...X..XX.....",
242 "...X.XX......",
243 "...XXX.......",
244 "...XX........",
245 "...X.........",
246 };
247 plus_data_EOP
248  
249 my $plus_arm_data = <<'plus_arm_data_EOP';
250 /* XPM */
251 static char *xpm[] = {
252 "13 13 3 1",
253 ". c none",
254 "X c black",
255 "a c red",
256 "...X.........",
257 "...XX........",
258 "...XXX.......",
259 "...XXXX......",
260 "...XXXXX.....",
261 "...XXXXXX....",
262 "...XXXXXXX...",
263 "...XXXXXX....",
264 "...XXXXX.....",
265 "...XXXX......",
266 "...XXX.......",
267 "...XX........",
268 "...X.........",
269 };
270 plus_arm_data_EOP
271  
272 my %indicators;
273 my %indicators_data = ('minus', $minus_data, 'minusarm', $minus_arm_data,
274 'plus', $plus_data, 'plusarm', $plus_arm_data);
275  
276 #---------------------------------------------
277 sub ClassInit {
278 my ($class, $window) = (@_);
279 $class->SUPER::ClassInit($window);
280  
281 # Note these keyboard-Keys are only usable, if the widget gets 'focus'
282 $window->bind($class, '<ButtonRelease-1>', sub { # print "DBG: reached function [BR-Release] with >@_<, called by >", caller, "<\n";
283 my $this = shift;
284 my $path = ($this->infoSelection)[0];
285 if (defined $path and $this->infoChildren($path)) {
286 my $mode = $this->getmode($path);
287 if ($mode eq 'open') { $this->open($path) }
288 elsif ($mode eq 'close') { $this->close($path) }
289 }
290 }
291 );
292  
293 # Auto-Select entries while hovering in the list/tree
294 $window->bind($class, '<Motion>', sub { my $this = shift;
295 my $e = $this->XEvent;
296 my $y = $e->y;
297 my $inx = $this->nearest($y);
298 if (defined $inx) {
299 $this->anchorClear();
300 $this->selectionClear();
301 $this->selectionSet($inx);
302 }
303 }
304 );
305  
306 # Keyboard selection
307 $window->bind($class,'<KeyPress>', ['KeyPress', Ev('A')]);
308 }
309  
310 #---------------------------------------------
311 sub Populate
312 {
313 my ($this, $args) = @_;
314  
315 $this->SUPER::Populate($args);
316  
317 $this->ConfigSpecs(
318 -ignoreinvoke => ['PASSIVE', 'ignoreInvoke', 'IgnoreInvoke', 0],
319 -opencmd => ['CALLBACK', 'openCmd', 'OpenCmd', 'OpenCmd' ],
320 -indicatorcmd => ['CALLBACK', 'indicatorCmd', 'IndicatorCmd', 'IndicatorCmd'],
321 -closecmd => ['CALLBACK', 'closeCmd', 'CloseCmd', 'CloseCmd'],
322 -indicator => ['SELF', 'indicator', 'Indicator', 1],
323 -indent => ['SELF', 'indent', 'Indent', 15],
324 -width => ['SELF', 'width', 'Width', 20],
325 -itemtype => ['SELF', 'itemtype', 'Itemtype', 'imagetext'],
326 -foreground => ['SELF'],
327 );
328  
329 # preset indicator images
330 foreach (qw(plus plusarm minus minusarm)) {
331 $indicators{$_} = $this->Pixmap(-data => $indicators_data{$_});
332 }
333 }
334  
335 #---------------------------------------------
336 sub autosetmode
337 {
338 shift->setmode();
339 }
340  
341 #---------------------------------------------
342 sub IndicatorCmd
343 {
344 my ($this, $ent, $event) = @_;
345  
346 my $mode = $this->getmode($ent);
347  
348 if ($event eq '<Arm>') {
349 if ($mode eq 'open') {
350 $this->_indicator_image($ent, 'plusarm');
351 }
352 else {
353 $this->_indicator_image($ent, 'minusarm');
354 }
355 }
356 elsif ($event eq '<Disarm>') {
357 if ($mode eq 'open') {
358 $this->_indicator_image($ent, 'plus');
359 }
360 else {
361 $this->_indicator_image($ent, 'minus');
362 }
363 }
364 elsif ($event eq '<Activate>') {
365 $this->Activate($ent, $mode);
366 $this->Callback(-browsecmd => $ent);
367 }
368 }
369  
370 #---------------------------------------------
371 sub close
372 {
373 my ($this, $ent) = @_;
374 my $mode = $this->getmode($ent);
375 $this->Activate($ent, $mode) if ($mode eq 'close');
376 }
377  
378 #---------------------------------------------
379 sub open
380 {
381 my ($this, $ent) = @_;
382 my $mode = $this->getmode($ent);
383 $this->Activate($ent, $mode) if ($mode eq 'open');
384 }
385  
386 #---------------------------------------------
387 sub getmode
388 {
389 my ($this, $ent) = @_;
390  
391 return ('none') unless $this->indicatorExists($ent);
392  
393 my $img = $this->_indicator_image($ent);
394 return ('open') if ($img eq 'plus' || $img eq 'plusarm');
395 return ('close');
396 }
397  
398 #---------------------------------------------
399 sub setmode
400 {
401 my ($this, $ent, $mode) = @_;
402 unless (defined $mode) {
403 $mode = 'none';
404 my @args;
405 push(@args,$ent) if defined $ent;
406 my @children = $this->infoChildren(@args);
407 if (@children) {
408 $mode = 'close';
409 foreach my $c (@children) {
410 $mode = 'open' if $this->infoHidden($c);
411 $this->setmode($c);
412 }
413 }
414 }
415  
416 if (defined $ent) {
417 if ($mode eq 'open') {
418 $this->_indicator_image($ent, 'plus');
419 }
420 elsif ($mode eq 'close') {
421 $this->_indicator_image($ent, 'minus');
422 }
423 elsif ($mode eq 'none') {
424 $this->_indicator_image($ent, undef);
425 }
426 }
427 }
428  
429 #---------------------------------------------
430 sub Activate
431 {
432 my ($this, $ent, $mode) = @_;
433 if ($mode eq 'open') {
434 $this->Callback(-opencmd => $ent);
435 $this->_indicator_image($ent, 'minus');
436 }
437 elsif ($mode eq 'close') {
438 $this->Callback(-closecmd => $ent);
439 $this->_indicator_image($ent, 'plus');
440 }
441 else {
442 }
443 }
444  
445 #---------------------------------------------
446 sub OpenCmd
447 {
448 my ($this, $ent) = @_;
449 # The default action
450 foreach my $kid ($this->infoChildren($ent)) {
451 $this->show(-entry => $kid);
452 }
453 }
454  
455 #---------------------------------------------
456 sub CloseCmd
457 {
458 my ($this, $ent) = @_;
459  
460 # The default action
461 foreach my $kid ($this->infoChildren($ent)) {
462 $this->hide(-entry => $kid);
463 }
464 }
465  
466 #---------------------------------------------
467 sub Command
468 {
469 my ($this, $ent) = @_;
470  
471 return if $this->{Configure}{-ignoreInvoke};
472  
473 $this->Activate($ent, $this->getmode($ent)) if $this->indicatorExists($ent);
474 }
475  
476 #---------------------------------------------
477 sub _indicator_image
478 {
479 my ($this, $ent, $image) = @_;
480 my $data = $this->privateData();
481 if (@_ > 2) {
482 if (defined $image) {
483 $this->indicatorCreate($ent, -itemtype => 'image') unless $this->indicatorExists($ent);
484 $data->{$ent} = $image;
485 #$this->indicatorConfigure($ent, -image => $this->Getimage($image));
486 $this->indicatorConfigure($ent, -image => $indicators{$image});
487 }
488 else {
489 $this->indicatorDelete($ent) if $this->indicatorExists($ent);
490 delete $data->{$ent};
491 }
492 }
493 return $data->{$ent};
494 }
495  
496  
497  
498 #----------------------------------------------------------------------
499 # Accelerator key bindings
500 #----------------------------------------------------------------------
501 # inspired by tkIconList_KeyPress --
502 #
503 # Gets called when user enters an arbitrary key in the listbox.
504 #
505 sub KeyPress
506 {
507 my ($w, $key) = @_;
508  
509 $w->{'_HLAccel'} .= $key;
510 $w->Goto($w->{'_HLAccel'});
511 eval { $w->afterCancel($w->{'_HLAccel_afterid'}) };
512 $w->{'_HLAccel_afterid'} = $w->after(500, ['Reset', $w]);
513 }
514 sub Goto
515 {
516 my ($w, $text) = @_;
517
518 # Locals
519 my (@children, $pattern, $selitem);
520  
521 return if (not defined $text or $text eq '');
522 @children = $w->collectChildren();
523  
524 $pattern = qr/^(?i)$text/;
525 foreach (@children) {
526 $entry = $w->itemCget($_, 0, '-text');
527 if ($entry =~ $pattern) {
528 $selitem = $_;
529 last
530 }
531 }
532 if ($selitem) {
533 $w->selectionClear();
534 $w->selectionSet($selitem);
535 $w->anchorSet($selitem);
536 $w->see($selitem);
537 $w->Callback(-browsecmd =>$selitem);
538 }
539 }
540 sub collectChildren
541 {
542 my ($w, $item) = @_;
543  
544 # Locals
545 my (@children, @grandchilds);
546 @children = $w->infoChildren($item);
547 foreach (@children) {
548 push @grandchilds, $w->collectChildren($_)
549 }
550 return @children, @grandchilds;
551 }
552  
553 sub Reset {
554 my $w = shift;
555 undef $w->{'_HLAccel'};
556 }
557  
558 1;
559  
560  
561  
562 ########################################################################
563 # Here we start with the Real Widget
564 ########################################################################
565  
566  
567 package Tk::PopUpSelectBox;
568  
569 ##############################################
570 ### Use
571 ##############################################
572 use Storable qw(freeze);
573 use Tk;
574  
575 use Tk::Button;
576 use Tk::Tree;
577  
578 use Carp qw(:DEFAULT cluck);
579  
580 use vars qw ($VERSION);
581 use base qw(Tk::Frame);
582 use strict;
583  
584 $VERSION = '1.0';
585  
586  
587 #---------------------------------------------
588 use constant DEFAULT_SEPARATOR => '.';
589 use constant MIN_BLOCK_TIME => '250'; # in ms
590  
591  
592 #---------------------------------------------
593 Tk::Widget->Construct ('PopUpSelectBox');
594  
595  
596 my $cbx_arrow = << 'cbx_arrow_EOP';
597 /* XPM */
598 static char *cbxarrow[] = {
599 /* columns rows colors chars-per-pixel */
600 "11 14 2 1",
601 " c black",
602 ". c gray100",
603 /* pixels */
604 "...........",
605 ".... ....",
606 ".... ....",
607 ".... ....",
608 ".... ....",
609 ".... ....",
610 ". .",
611 ".. ..",
612 "... ...",
613 ".... ....",
614 "..... .....",
615 "...........",
616 ". .",
617 ". ."
618 };
619 cbx_arrow_EOP
620  
621 my $arrowdownwin = << 'arrowdownwin_EOP';
622 /* XPM */
623 static char *arrowdownwin[] = {
624 /* columns rows colors chars-per-pixel */
625 "9 13 2 1",
626 " c black",
627 ". c gray100",
628 /* pixels */
629 ".........",
630 ".........",
631 ".........",
632 ".........",
633 ".........",
634 ".. ..",
635 "... ...",
636 ".... ....",
637 ".........",
638 ".........",
639 ".........",
640 ".........",
641 "........."
642 };
643 arrowdownwin_EOP
644  
645  
646 #---------------------------------------------
647 sub Populate {
648 # Parameters
649 my ($this, $args) = @_;
650  
651 # Locals
652 my ($var, $bttn, $tl, $list, $separator, %defaults);
653 local $_;
654  
655 # check for special options
656 $this->{'_ignoreExisting'} = delete $args->{-ignoreExisting};
657 $separator = delete $args->{-separator} || DEFAULT_SEPARATOR();
658 $this->{separator} = $separator;
659  
660 # Create a Closure for saving the current value
661 $var = delete $args->{-variable};
662 unless ($var) {
663 my $gen = undef;
664 $var = \$gen;
665 }
666
667 # Createa the widget
668 $this->Tk::Frame::Populate($args);
669  
670 # store the os-style
671 $this->{_style} = delete $args->{-style} || $Tk::platform;
672  
673 #my $bitmap = '@' . Tk->findINC($this->{_style} eq 'MSWin32' ? 'arrowdownwin.xbm' : 'cbxarrow.xbm');
674 my $image = $this->Pixmap(-data => ($this->{_style} eq 'MSWin32' ? $arrowdownwin : $cbx_arrow));
675 $bttn = $this->Button(
676 # -bitmap => $bitmap,
677 -image => $image,
678 -relief => 'flat',
679 -bd => 0,
680 -padx => -1,
681 -pady => -1,
682 )->pack(-side => 'right', -anchor => 's');
683 $this->Advertise('arrow' => $bttn);
684  
685 # popup shell for listbox with values.
686 $tl = $this->Toplevel(-bd => 2, -relief => ($this->{_style} eq 'MSWin32' ? "solid" : "raised"));
687 $tl->overrideredirect(1);
688 $tl->minsize(30,30);
689 $tl->withdraw;
690 #my $fr = $tl->Frame(-relief => 'sunken', -borderwidth => 2)->pack(qw(-fill both -expand 1));
691 #my $sl = $fr->Scrolled('SelectTree',
692 my $sl = $tl->Scrolled('SelectTree',
693 -scrollbars => 'e',
694 -separator => $separator,
695 -borderwidth => 0, -relief => 'flat',
696 -selectmode => 'single',
697 -command => sub {
698 my $path = shift;
699 my $tree = $this->{_tree};
700 my $mode = $tree->getmode($path);
701 # Eventually open or close te child-tree
702 if ($mode eq 'open') {
703 $tree->open($path);
704 }
705 elsif ($mode eq 'close') {
706 $tree->close($path);
707 }
708 },
709 )->pack(-expand => 1, -fill => 'both');
710 #
711 if ($this->{_style} eq 'MSWin32' and $Tk::platform eq 'MSWin32') {
712 $sl->configure(-bg => 'SystemWindow', -relief => "flat");
713 }
714 my $tree = $this->{_tree} = $sl->Subwidget('scrolled');
715 $tree->configure();
716  
717 # Position the Resizer in the lower right area of the scroller
718 $sl->Subwidget('ysbslice')->ResizeCBox(-size => 15)->pack(
719 -side => 'bottom', -anchor => 'se', -before => $sl->Subwidget('yscrollbar'),
720 );
721 # Brush up the scroller
722 $sl->Subwidget('yscrollbar')->configure(-relief => 'flat', -width => 10, -borderwidth => 2);
723  
724 # Propagate the internal structure
725 $this->Advertise('window' => $tl);
726  
727 # other initializations
728 # set bind tags
729 $this->bindtags([$this, 'Tk::PopUpSelectBox', $this->toplevel, 'all']);
730  
731 # bindings for the button and entry
732 $bttn->bind('<1>',[$this, 'button_down']);
733 $bttn->toplevel->bind('<ButtonRelease-1>', [$this, 'button_restore']);
734 $bttn->bind('<space>', [$this, 'space']);
735  
736 # bindings for listbox
737 $tree->bind('<ButtonRelease-1>', sub { $this->list_selected(@_) });
738 $tree->bind('<Escape>' => [$this, 'list_close']);
739 $tree->bind('<Return>' => [$this, 'return', $tree]);
740 $tree->bind('<Enter>' => sub { $this->{'_inside'} = 1 });
741 $tree->bind('<Leave>' => sub { $this->{'_inside'} = 0 });
742  
743 # allow click outside the popped up listbox to pop it down.
744 $this->bind('<1>','button_down');
745  
746 $this->{'_popped'} = 0;
747 $this->Delegates(get => $bttn, DEFAULT => $bttn);
748  
749 # Setup DEFAULT Configs
750 %defaults = (
751 -selectborderwidth => [$tree, 'selectBorderwidth', 'SelectBorderwidth', '1'],
752 -selectbackground => [$tree, 'selectBackground', 'SelectBackground', '#ececec'],
753 -selectforeground => [$tree, 'selectForeground', 'SelectForeground', 'Black'],
754 -activebackground => [$bttn, 'activeBackground', 'ActiveBackground', '#ececec'],
755 -activeforeground => [$bttn, 'activeForeground', 'ActiveForeground', 'Black'],
756 -takefocus => ['SELF', 'takefocus', 'Takefocus', 1],
757 -highlightthickness => ['SELF', 'highlightThickness', 'HighlightThickness', 1],
758 -borderwidth => [['SELF', 'PASSIVE'], 'borderwidth', 'BorderWidth', 2],
759 -relief => [['SELF', 'PASSIVE'], 'relief', 'Relief', 'raised'],
760 -anchor => [['SELF', 'PASSIVE'], 'anchor', 'Anchor', 'w'],
761 #-ignoreExisting => [['SELF', 'PASSIVE'], 'ignoreExisting', 'IgnoreExisting', '0'],
762 -listbackground => [{-background => $tree}, 'background', 'Background', '#ececec'],
763 -font => ['DESCENDANTS', 'font', 'Font', 'Helvetica 12 bold'],
764 -variable => ['PASSIVE', 'variable', 'Variable', $var],
765 -activate => ['PASSIVE', 'activate', 'Activate', 1],
766 -separator => ['PASSIVE', 'separator', 'Separator', $separator],
767 -options => ['METHOD', undef, undef, undef],
768 -command => ['CALLBACK',undef,undef,undef],
769 -validatecommand => ['PASSIVE', 'validatecommand', 'ValidateCommand', sub {0}],
770  
771 -listwidth => [qw/PASSIVE listWidth ListWidth/, undef],
772 -listmaxheight => [qw/PASSIVE listMaxHeight ListMaxHeight 0/],
773 -listcmd => [qw/CALLBACK listCmd ListCmd/, undef],
774 -autolistwidth => [qw/PASSIVE autoListWidth AutoListWidth/, 1],
775 -autolimitheight => [qw/PASSIVE autoLimitHeight AutoLimitHeight 1/],
776 -state => [qw/METHOD state State normal/],
777 -listheight => ['METHOD', undef, undef, undef],
778 -image => [ {-image => $bttn}, qw/arrowImage ArrowImage/, undef],
779 -arrowimage => '-image',
780 -rows => '-listheight',
781 -buttontakefocus => [{-takefocus => $bttn}, 'buttonTakefocus', 'ButtonTakefocus', 1],
782 -bitmap => [{-bitmap => $bttn}, 'bitmap', 'Bitmap', 'question'],
783 DEFAULT => [$bttn]
784  
785 );
786 $this->ConfigSpecs(%defaults);
787  
788 $this->bind('<ButtonPress-3>' => [$this => 'b3prs', Ev('x'), Ev('y')]);
789 $this->bind('<ButtonRelease-3>' => [$this => 'b3rls', Ev('X'), Ev('Y')]);
790  
791 # Reset internal storage
792 $this->{'_item_count'} = 0;
793 $this->{'_item_width'} = 0;
794 $this->{'_item_table'} = {};
795  
796 }
797
798 #---------------------------------------------
799 sub listheight
800 {
801 #print "DBG: reached function [listheight] with >@_<, called by >", caller, "<\n";
802 my ($this, $height) = @_;
803  
804 my $oldh = $this->{_tree}->cget('-height');
805 $this->{_tree}->configure('-height' => $height + 1) if $height;
806 return ($oldh);
807 }
808  
809 #---------------------------------------------
810 sub state {
811 my $this = shift;
812  
813 my $button = $this->Subwidget('arrow');
814  
815 if (@_) {
816 $button->configure(-state => shift);
817 }
818 else {
819 return $button->cget('-state');
820 }
821 }
822  
823 #---------------------------------------------
824 sub space
825 {
826 my $this = shift;
827  
828 $this->button_down;
829 $this->{'_savefocus'} = $this->focusCurrent;
830 $this->Subwidget('list')->focus;
831 }
832  
833 #---------------------------------------------
834 sub button_down
835 {
836 #print "DBG: reached function [button_down] with >@_<, called by >", caller, "<\n";
837 my $this = shift;
838 return if $this->cget('-state') eq 'disabled';
839  
840 if ($this->{'_popped'}) {
841 $this->list_popdown;
842 $this->{'_button_restore'} = 0;
843 } else {
844 $this->popup;
845 $this->{'_button_restore'} = 1;
846 }
847 }
848  
849 #---------------------------------------------
850 # triggered the listbox after selection
851 sub list_selected
852 {
853 #print "DBG: reached function [list_selected] with >@_<, called by >", caller, "<\n";
854 my $this = shift;
855 return if $this->{'_popping'};
856
857 if ($this->{'_inside'}) {
858 my $tree = $this->{_tree};
859 my $path = ($tree->infoSelection)[0];
860  
861 # Do not take this click as a real selection, if it is a subhierarchy
862 my @children = $tree->infoChildren($path);
863 if (@children) {
864 #print "DBG: variable [\@children] = >@children<\n";
865 my ($len, $child); $len = 0;
866 foreach (@children) {
867 if (length($_) > $len) {
868 $child = $_;
869 $len = length($_);
870 }
871 }
872 # Show the last child if there is enough space in the list
873 my $tmp1 = $tree->cget('-height');
874 if (@children > $tree->cget('-height')) {
875 $tree->see($children[0]);
876 }
877 else {
878 $tree->see($children[-1]);
879 }
880  
881 my $width = $this->fontMeasure($this->cget('-font'), $child);
882 if ($this->cget('-autolistwidth') and defined $path and $path ne "") {
883 my $geom = $tree->toplevel->geometry;
884 my ($w, $h, $x, $y) = $geom =~ /(\d+)x(\d+)([+-]\d+)([+-]\d+)/;
885 $w = int($width * 1.5) + ($tree->indicatorSize($path))[0];
886
887 # if listbox is too far right, pull it back to the left
888 $x = $this->vrootwidth - $w - 5 if (($x + $w) > $this->vrootwidth);
889  
890 # if listbox is too far left, pull it back to the right
891 $x = 0 if $x < 0;
892 $x = '+' . $x if ($x =~ /^\d/o);
893 #print "DBG: variable [\$x] = >$x<\n";
894 $tree->toplevel->geometry($w . 'x' . $h . $x . $y);
895 #print "DBG: variable [\@geometry] = >@geometry<\n";
896 }
897 return;
898 }
899  
900 my $value = $tree->infoData($path);
901 $this->set_option($tree->itemCget($path, 0, '-text'), $value, $path);
902
903 # ....
904 $this->list_popdown();
905 }
906 #print "DBG: end function [list_selected]\n";
907 }
908 #---------------------------------------------
909 # close the listbox after restoring the button
910 sub list_release
911 {
912 #print "DBG: reached function [list_release] with >@_<, called by >", caller, "<\n";
913 my ($this, $x, $y) = @_;
914  
915 unless ($this->{'_inside'}) {
916 $this->button_restore;
917 $this->list_close($x, $y);
918 }
919 }
920  
921 #---------------------------------------------
922 # close the listbox after clearing selection
923 sub list_close
924 {
925 #print "DBG: reached function [list_close] with >@_<, called by >", caller, "<\n";
926 my $this = shift;
927  
928 my $tree = $this->{_tree};
929 $tree->selectionClear();
930 $this->list_popdown;
931 }
932  
933 #---------------------------------------------
934 # pop down the listbox
935 sub list_popdown
936 {
937 #print "DBG: reached function [list_popdown] with >@_<, called by >", caller, "<\n";
938 my $this = shift;
939  
940 if ($this->{'_savefocus'} && Tk::Exists($this->{'_savefocus'})) {
941 $this->{'_savefocus'}->focus;
942 delete $this->{'_savefocus'};
943 }
944 if ($this->{'_popped'}) {
945 my $c = $this->Subwidget('window');
946 $this->{'_geometry'} = $c->geometry;
947 $c->withdraw;
948 $this->grabRelease;
949 if (ref $this->{'_grabinfo'} eq 'CODE') {
950 $this->{'_grabinfo'}->();
951 delete $this->{'_grabinfo'};
952 }
953 # Restore the focus
954 $this->{'_focus'}->focus() if $this->{'_focus'};
955 undef $this->{'_focus'};
956  
957 $this->{'_popped'} = 0;
958 }
959 $this->button_restore;
960 }
961  
962 #---------------------------------------------
963 # Pressed ENTER bttn
964 sub return
965 {
966 #print "DBG: reached function [return] with >@_<, called by >", caller, "<\n";
967 my $this = shift;
968  
969 my $tree = $this->{_tree};
970 my $path = $tree->infoSelection();
971 my $value = $tree->infoData($path);
972 $this->set_option($tree->itemCget($path, 0, '-text'), $value, $path);
973  
974 $this->list_popdown();
975 }
976  
977 #---------------------------------------------
978 # This hack is to prevent the ugliness of the arrow being depressed.
979 sub button_restore
980 {
981 #print "DBG: reached function [button_restore] with >@_<, called by >", caller, "<\n";
982 my $this = shift;
983  
984 my $b = $this->Subwidget('arrow');
985 if ($this->{'_button_restore'}) {
986 $b->butUp;
987 delete $this->{'_button_restore'};
988 }
989 }
990  
991 #---------------------------------------------
992 # displaying the selection list
993 sub popup
994 {
995 #print "DBG: reached function [popup] with >@_<, called by >", caller, "<\n";
996 my $this = shift;
997  
998 unless ($this->{'_popping'} or $this->{'_popped'}) {
999 $this->{'_popping'} = 1;
1000  
1001 $this->Callback(-listcmd => $this);
1002 my $c = $this->Subwidget('window');
1003 my $a = $this->Subwidget('arrow');
1004  
1005 my $y1 = $a->rooty + $a->height / 2;
1006 my $bd = $c->cget(-bd) + $c->cget('-highlightthickness');
1007 # using the real listbox reqheight rather than the
1008 # container frame one, which does not change after resizing the
1009 # listbox
1010 my $ht = $this->{_tree}->reqheight + 4 * $bd + 2;
1011 $ht = $this->{_tree}->height + 4 * $bd + 2 if $this->{'_geometry'};
1012 $ht = 50 if $ht < 20;
1013 #print "DBG: variable [\$ht] = >$ht<\n";
1014  
1015 my $x1 = $a->rootx;
1016
1017 my ($width, $x2);
1018 if (defined $this->cget('-listwidth')) {
1019 $width = $this->cget('-listwidth');
1020 $x2 = $x1 + $width;
1021 }
1022 else {
1023 $x2 = $a->rootx + $a->width;
1024 $width = $x2 - $x1;
1025 }
1026 my $rw = $c->reqwidth;
1027 if ($rw < $width) {
1028 $rw = $width
1029 }
1030 else {
1031 if ($rw > $width * 3) {
1032 $rw = $width * 3;
1033 }
1034 if ($rw > $this->vrootwidth) {
1035 $rw = $this->vrootwidth;
1036 }
1037 }
1038 $width = $rw;
1039  
1040 # if listbox is too far right, pull it back to the left
1041 $x1 = $this->vrootwidth - $width if $x2 > $this->vrootwidth;
1042  
1043 # if listbox is too far left, pull it back to the right
1044 $x1 = 0 if $x1 < 0;
1045  
1046  
1047 # if listbox is below bottom of screen, pull it up.
1048 # check the Win32 taskbar, if possible
1049 my $rootheight;
1050 if ($Tk::platform eq 'MSWin32' and $^O eq 'MSWin32') {
1051 eval {
1052 require Win32Util; # XXX should not use a non-CPAN widget
1053 $rootheight = (Win32Util::screen_region($this))[3];
1054 };
1055 }
1056 $rootheight = $this->vrootheight unless defined $rootheight;
1057  
1058  
1059 my $y2 = $y1 + $ht;
1060 if ($y2 > $rootheight) {
1061 $y1 = $y1 - $ht - ($a->height - 5);
1062 }
1063 $this->after(MIN_BLOCK_TIME(), sub { $this->{'_popping'} = 0 });
1064  
1065 $y1 = 0 if $y1 < 0;
1066 if ($this->{'_geometry'}) {
1067 my @geometry = $this->{'_geometry'} =~ /(\d+)x(\d+)([+-]\d+)([+-]\d+)/;
1068 $rw = $geometry[0]; $ht = $geometry[1];
1069 }
1070  
1071 #print "DBG: variable [\$rw] = >$rw< [\$ht] = >$ht< [\$x1] = >$x1< [\$y1] = >$y1< \n";
1072 $c->geometry(sprintf('%dx%d+%d+%d', $rw, $ht, $x1, $y1));
1073 $c->deiconify;
1074 $c->raise;
1075 $this->{'_popped'} = 1;
1076  
1077 # highlight current selection
1078 # TODO - needed ?
1079
1080 $c->configure(-cursor => 'arrow');
1081 $this->{'_grabinfo'} = $this->grabSave;
1082 $this->grabGlobal; #block all in system
1083 #$this->grab; # block only other windows in app
1084
1085 # move the focus into the list to ease keyboard usage
1086 $this->{'_focus'} = $this->focusCurrent();
1087 $this->{_tree}->focus();
1088 }
1089 #print "DBG: end function [popup]\n";
1090 }
1091 # Screen-move methods.
1092  
1093 sub b3prs {
1094 my ($self, $x, $y) = @_;
1095 $self->{ofx} = $x;
1096 $self->{ofy} = $y;
1097 } # end b3prs
1098  
1099 sub b3rls {
1100 my($self, $X, $Y) = @_;
1101 $X -= $self->{ofx};
1102 $Y -= $self->{ofy};
1103 $self->geometry("+${X}+${Y}");
1104 } # end b3rls
1105  
1106 #---------------------------------------------
1107 {
1108 my ($List, $Separator, $FingerPrint); # Use global instead of func-arg for speed
1109 sub add_options
1110 {
1111 #print "DBG: reached function [add_options] with >@_<, called by >", caller, "<\n";
1112  
1113 # Parameters
1114 my ($this, @args) = @_;
1115  
1116 # Locals
1117 my ($old, $var, $items, $test);
1118  
1119 #-----------------------------------------------------------------------------
1120 if (ref $args[0] eq 'ARRAY') {
1121 $items = $args[0];
1122 }
1123 elsif (@args) {
1124 $items = \@args;
1125 }
1126  
1127 #-----------------------------------------------------------------------------
1128 # Check if we already prepared exactly the same tree
1129 $test = freeze($items);
1130 return if $FingerPrint and $FingerPrint eq $test and $this->{'_item_count'} > 0;
1131 $FingerPrint = $test;
1132 #print "building new tree...\n";
1133  
1134 # Fake a busy state
1135 my $a = $this->Subwidget('arrow');
1136 my $old_cursor = $a->cget('-cursor'); $a->configure(-cursor => 'watch');
1137 $a->update();
1138  
1139 $var = $this->cget('-variable');
1140 # Store old selection
1141 $old = $$var;
1142  
1143 # Clear & Fill the list with new values
1144 $List = $this->{_tree};
1145 $Separator = $List->cget('-separator');
1146  
1147 $List->delete('all');
1148 $this->{'_item_count'} = 0;
1149 $this->{'_item_width'} = 0;
1150 $this->{'_item_table'} = {};
1151  
1152
1153 $this->_add_option('', $items);
1154 #-----------------------------------------------------------------------------
1155 #print "DBG: variable [$this->{'_item_count'}] = >", $this->{'_item_count'}, "<\n";
1156
1157 $this->limitheight() if $this->cget('-autolimitheight');
1158 $this->updateListWidth() if $this->cget('-autolistwidth');
1159  
1160 $a->configure(-cursor => $old_cursor);
1161 $a->update();
1162 }
1163  
1164 #-----------------------------------------------------------------------------
1165 sub _add_option
1166 {
1167 #print "DBG: reached function [_add_option] with >@_<, called by >", caller, "<\n";
1168 # Parameters
1169 my ($this, $parent, $items) = @_;
1170  
1171 my ($item, $path, $label, $value, $width);
1172  
1173 foreach $item (@$items) {
1174 if (ref $item) {
1175 ($label, $value) = @$item
1176 }
1177 else {
1178 $label = $value = $item
1179 }
1180  
1181 if (ref $label) {
1182 if ($parent eq '') {
1183 $path = $label->[0];
1184 }
1185 else {
1186 $path = $parent . $Separator . $label->[0];
1187 }
1188 $List->add($path, -text => $label->[0], -data => undef) unless $List->infoExists($path);
1189 $this->_add_option($path, $label->[1]);
1190 $List->Activate($path, 'close');
1191 $this->{'_item_count'}++ unless $parent; #count only toplevel entries
1192 }
1193 else {
1194 if ($parent eq '') {
1195 $path = $label;
1196 }
1197 else {
1198 $path = $parent . $Separator . $label;
1199 }
1200 if ($List->infoExists($path)) {
1201 croak "Entry already exists!\n" unless $this->{'_ignoreExisting'};
1202 }
1203 else {
1204 $List->add($path, -text => $label, -data => $value);
1205 #print "DBG: variable [\$path] = >$path< [\$label] = >$label< [\$value] = >$value<\n";
1206 # Update internal storages
1207 $this->{'_item_count'}++ unless $parent; #count only toplevel entries
1208 $this->{'_item_table'}{$path} = $value;
1209 $width = $this->fontMeasure($this->cget('-font'), $label);
1210 $this->{'_item_width'} = $width if $width > $this->{'_item_width'};
1211 }
1212 }
1213 }
1214 #print "end function [_add_option]\n";
1215 }
1216 }
1217 #-----------------------------------------------------------------------------
1218 sub limitheight
1219 {
1220 my $this = shift;
1221  
1222 my $listheight = shift || $this->{'_item_count'};
1223 #print "DBG: variable 1 [\$listheight] = >$listheight<\n";
1224 my $listmaxheight = $this->cget('-listmaxheight');
1225 $listheight = $this->cget('-listmaxheight') if $listmaxheight > 0 and $listheight > $listmaxheight;
1226 $this->configure(-listheight => $listheight) if ($listheight > 0);
1227 }
1228  
1229 #-----------------------------------------------------------------------------
1230 sub updateListWidth
1231 {
1232 #print "DBG: reached function [updateListWidth] with >@_<, called by >", caller, "<\n";
1233 my $this = shift;
1234  
1235 my $width = $this->{'_item_width'};
1236 #print "DBG: variable [\$width] = >$width<\n";
1237 if ($this->{'_item_width'} > 10) { # be sane
1238 $this->configure(-listwidth => $this->{'_item_width'} + 5); # + XXX for scrollbar
1239 }
1240 }
1241  
1242 #---------------------------------------------
1243 sub set_option
1244 {
1245 #print "DBG: reached function [set_option] with >@_<, called by >", caller, "<\n";
1246 # Parameters
1247 my ($this, $label, $value, $full_label) = @_;
1248 # Locals
1249 my ($failed, $validatecommand, $variable, $textvariable, $old_label, $old_value);
1250
1251 # Some presettings
1252 $value = $label if @_ == 2;
1253 $full_label = $label unless $full_label;
1254 return if $full_label eq "";
1255  
1256 $validatecommand = $this->cget('-validatecommand');
1257 $textvariable = $this->cget('-variable');
1258 $variable = $this->cget('-variable');
1259  
1260 $old_value = $variable ? $$variable : $this->{OldValue};
1261 $old_label = $$textvariable;
1262
1263 # Perform validate operation, if available
1264 do { $failed = &$validatecommand ($this, $value, $label, $full_label, $old_value, $old_label) } if $validatecommand;
1265
1266 #Do the changes
1267 unless ($failed) {
1268 $$variable = $value if $variable;
1269 $this->{OldValue} = $value;
1270 $$textvariable = $label;
1271  
1272 my $list = $this->{_tree};
1273 $list->selectionClear();
1274 $list->selectionSet($full_label);
1275 $list->see($full_label);
1276  
1277 # Now invoke the callback
1278 $this->{CallBackActive} = 1;
1279 $this->Callback(-command => $value, $label, $full_label);
1280 delete $this->{CallBackActive};
1281 }
1282 }
1283  
1284 #---------------------------------------------
1285 sub options
1286 {
1287 my ($this, $opts) = @_;
1288 if (@_ > 1) {
1289 if ($this->{CallBackActive}) {
1290 cluck "\nTk::PopupSelectionBox Error: Found an illegal recursion loop: from Callback() to options() which is not allowed!\nAuto-shutting-down now, please let the developer fix this!";
1291 kill 9, $$;
1292 }
1293 $this->add_options($opts);
1294 }
1295 else {
1296 #return $this->_cget('-options');
1297 }
1298  
1299 }
1300 #---------------------------------------------
1301 sub itemtable
1302 {
1303 my $this = shift;
1304 my %itemtable = $this->{'_item_table'} ? %{$this->{'_item_table'}} : ();
1305  
1306 return wantarray ? %itemtable : \%itemtable;
1307 }
1308  
1309 ########################################################################
1310 1;
1311 __END__