Optionbox.pm untested

filter: Statementstmt 0.0% 0 / 209 Branchbran 0.0% 0 / 70 Conditioncond 0.0% 0 / 21 MC/DCmcdc 0.0% 0 / 13 Subroutinesub 0.0% 0 / 17 Podpod 0.0% 0 / 8 totaltotal 0.0% 0 / 338 CC 36 SCAR 40.7
CC
36
Cov
0%
add_options
110.0
generate_menu
110.0
set_option
72.0
CRAP 58.5
1 ######################################## SOH ###########################################
2 ## Function : Replacement for Tk:Optionmenu (more flexible handling for 'image_only')
3 ##
4 ## Copyright (c) 2002-2009 Michael Krause. All rights reserved.
5 ## This program is free software; you can redistribute it and/or modify it
6 ## under the same terms as Perl itself.
7 ##
8 ## History : V1.0 30-Aug-2002 Class derived from original Optionmenu. MK
9 ## V1.1 19-Nov-2002 Added popup() function MK.
10 ## V1.2 07-Nov-2003 Added -tearoff option MK.
11 ## V1.3 16-Dec-2004 Added multicolumn & activate option (-rows/-activate option) MK.
12 ## V1.4 14-Jun-2005 Added second hierarchy for the options,
13 ## Optionformat: [ label, value], [[keylabel, \@subopts], undef], [], ... MK.
14 ## V1.5 29-Jul-2005 Added columnbreak for second hierarchy options
15 ## V1.6 14-Sep-2005 Rewrite: Added TRUE multi-level hierarchy options with color opts. MK
16 ## V1.7 30-Sep-2005 Added selection-validate operation. MK
17 ## V1.8 25-Sep-2006 Added detection for loops, which might crash the app for linux. MK
18 ## V1.9 11-Mar-2009 Added -popover 'cursor for popup() func. MK
19 ## V2.0 06-Feb-2014 Added '-clearoption*' function to automatically add a 'clear entry'. MK
20 ##
21 ######################################## EOH ###########################################
22 package Tk::Optionbox;
23  
24 ##############################################
25 ### Use
26 ##############################################
27 use Storable qw(freeze);
28 use Tk;
29 use Tk::Menubutton;
30 use Tk::Menu;
31  
32 use strict;
33 use Carp qw(:DEFAULT cluck);
34  
35 use vars qw ($VERSION);
36 $VERSION = '2.0';
37  
38 use base qw (Tk::Derived Tk::Menubutton);
39  
40  
41 use constant CLEAR_OPTION_TAG => '__CLEAR__OPTIONBOX_ENTRY__';
42  
43 ########################################################################
44 Tk::Widget->Construct ('Optionbox');
45  
46 my $ClearXPM;
47  
48 #---------------------------------------------
49 sub ClassInit {
50 my ($class, $window) = (@_);
51
52 $class->SUPER::ClassInit($window);
53 $window->bind ($class, '<Control-Tab>','focusNext');
54 $window->bind ($class, '<Control-Shift-Tab>','focusPrev');
55 $window->bind ($class, '<Tab>', 'focus');
56  
57 ###################################################
58 # The following Image is borrowed from free
59 # Silk icon set 1.3 by Mark James
60 # http://www.famfamfam.com/lab/icons/silk/
61 ###################################################
62 $ClearXPM = $window->Pixmap( -data => <<'ClearXPM_EOP'
63 /* XPM */
64 static char *cancel[] = {
65 /* columns rows colors chars-per-pixel */
66 "16 16 10 1",
67 " c #EE0000",
68 ". c #F70706",
69 "X c #F9231D",
70 "o c #FB3230",
71 "O c #F84737",
72 "+ c #FC504A",
73 "@ c #FE6659",
74 "# c #FECACA",
75 "$ c #FFEFEF",
76 "% c None",
77 /* pixels */
78 "%%%%%%%%%%%%%%%%",
79 "%%%%....... %%%%",
80 "%%% o@@@@+@X.%%%",
81 "%% o@+ooooo@X %%",
82 "%.o@+#+oo+#++X %",
83 "%.@O#$$++$$#oO.%",
84 "%.@o@$$$$$$oXO.%",
85 "%.@oo+$$$$OX.O.%",
86 "%.@oX+$$$$oX.+ %",
87 "%.+o+$$$$$$o.O %",
88 "%.+o#$$oo$$#Xo.%",
89 "% X++#+..o#oOX %",
90 "%% X+X.X..XoX %%",
91 "%%% XOOOOOOX %%%",
92 "%%%% ... . %%%%",
93 "%%%%%%%%%%%%%%%%"
94 };
95 ClearXPM_EOP
96 ) unless $ClearXPM;
97  
98 }
99  
100 #---------------------------------------------
101 sub Populate {
102 # Parameters
103 my ($this, $args) = @_;
104  
105 # Locals
106 my ($var, $menu, %defaults, %all_presets, $value);
107 local $_;
108  
109 # Check whether we're in backward compatibility mode
110 unless (defined $args->{-image}) {
111 $args->{-indicatoron} = 1;
112 $this->{no_image} = 1;
113 }
114
115 $this->SUPER::Populate ($args);
116
117 # Create a Closure for saving the current value
118 $var = delete $args->{-textvariable};
119 unless (defined $var) {
120 my $gen = undef;
121 $var = \$gen;
122 }
123 $this->configure(-textvariable => $var);
124  
125 # Setup DEFAULT Configs
126 %defaults = (
127 -takefocus => ['SELF', 'takefocus', 'Takefocus', 1],
128 -highlightthickness => ['SELF', 'highlightThickness', 'HighlightThickness', 1],
129 -borderwidth => [['SELF', 'PASSIVE'], 'borderwidth', 'BorderWidth', 2],
130 -relief => [['SELF', 'PASSIVE'], 'relief', 'Relief', 'raised'],
131 -anchor => [['SELF', 'PASSIVE'], 'anchor', 'Anchor', 'w'],
132 -direction => [['SELF', 'PASSIVE'], 'direction', 'Direction', 'flush'],
133 -font => [['SELF', 'PASSIVE'], 'font', 'Font', 'Helvetica 12 bold'],
134 -variable => ['PASSIVE', undef, undef, undef],
135 -tearoff => ['PASSIVE', 'tearoff', 'TearOff', 1],
136 -rows => ['PASSIVE', 'rows', 'Rows', 20],
137 -activate => ['PASSIVE', 'activate', 'Activate', 1],
138 -separator => ['PASSIVE', 'separator', 'Separator', '.'],
139 -options => ['METHOD', undef, undef, undef],
140 -command => ['CALLBACK',undef,undef,undef],
141 -validatecommand => ['PASSIVE', 'validatecommand', 'ValidateCommand', sub {0}],
142 # automatic clear entry configs
143 -clearoptionon => ['PASSIVE', 'clearoption', 'ClearOption', 0],
144 -clearoptiontext => ['PASSIVE', 'clearoptiontext', 'Clearoptiontext', 'CLEAR OPTION'],
145 -clearoptionimage => ['PASSIVE', 'clearoptionimage', 'Clearoptionimage', $ClearXPM],
146 -clearoptionforeground => ['PASSIVE', 'clearoptionforeground', 'Clearoptionforeground', 'Black'],
147 -clearoptionbackground => ['PASSIVE', 'clearoptionbackground', 'Clearoptionbackground', '#d9d9d9'],
148 -clearoptionactiveforeground => ['PASSIVE', 'clearoptionactiveforeground', 'Clearoptionactiveforeground', 'Black'],
149 -clearoptionactivebackground => ['PASSIVE', 'clearoptionactivebackground', 'Clearoptionactivebackground', '#ececec'],
150 );
151 $this->ConfigSpecs(%defaults);
152  
153 # configure those opts needed by a create-time-configure
154 # @ target-widget-creation here & now
155 %all_presets = (%defaults, %$args);
156 foreach (keys %all_presets) {
157 $value = defined $args->{$_} ? $args->{$_} : $defaults{$_}[-1];
158 next if /-options/;
159 $this->configure($_ => $value);
160 }
161
162 # initialize internals
163 $this->{MenuItems} = [];
164 }
165 #---------------------------------------------
166 sub popup
167 {
168 # Parameters
169 my ($this, %args) = @_;
170 # Locals
171 my ($menu, $xpos, $ypos);
172  
173 $menu = $this->menu;
174
175 if ($args{-popover} and $args{-popover} eq 'cursor') {
176 my $e = $Tk::event;
177 $xpos = $e->X;
178 $ypos = $e->Y;
179 }
180 else {
181 $xpos = $this->rootx;
182 $ypos = $this->rooty;
183 }
184 $menu->post($xpos, $ypos);
185 }
186 #---------------------------------------------
187 sub set_option
188 {
189 # Parameters
190 my ($this, $label, $value, $full_label) = @_;
191 #print "DBG: variable [\$this, \$label, \$value, \$full_label] = >$this, $label, $value, $full_label<\n";
192 # Locals
193 my ($failed, $validatecommand, $variable, $textvariable, $old_label, $old_value);
194
195 $validatecommand = $this->cget('-validatecommand');
196 $textvariable = $this->cget('-textvariable');
197 $variable = $this->cget('-variable');
198  
199 $old_value = $variable ? $$variable : $this->{OldValue};
200 $old_label = $$textvariable;
201  
202 # Some presettings
203 $value = $label if @_ == 2;
204 $full_label = $label unless $full_label;
205 $full_label = '' if $label eq CLEAR_OPTION_TAG();
206
207 # Perform validate operation, if available
208 do { $failed = &$validatecommand ($this, $value, $label, $full_label, $old_value, $old_label)
209 } if $validatecommand and $label ne CLEAR_OPTION_TAG();
210  
211 #Do the changes
212 unless ($failed) {
213 $$variable = $value if $variable;
214 $this->{OldValue} = $value;
215 $$textvariable = $label;
216  
217 # Now invoke the callback
218 $this->{CallBackActive} = 1;
219 $this->Callback(-command => $value, $label, $full_label);
220 delete $this->{CallBackActive};
221 }
222 }
223 #---------------------------------------------
224 my $FingerPrint;
225 sub add_options
226 {
227 # Parameters
228 my ($this, @args) = @_;
229
230 # Locals
231 my ($test, $menu, $var, $old, $width, $activate, $menu_items, $first,
232 $font, $foreground, $background, $activeforeground, $activebackground);
233  
234 #-----------------------------------------------------------------------------
235 $this->{MenuItems} = [] unless $this->{MenuItems};
236 # Check if we already prepared exactly the same tree
237 $test = freeze(\@args);
238 return if $FingerPrint and $FingerPrint eq $test and scalar @{$this->{MenuItems}} > 0;
239 $FingerPrint = $test;
240 #print "building new tree...\n";
241  
242 $var = $this->cget('-textvariable');
243 $width = $this->cget('-width');
244 $activate = $this->cget('-activate');
245 $font = $this->cget('-font');
246 $foreground = $this->cget('-foreground');
247 $background = $this->cget('-background');
248 $activeforeground = $this->cget('-activeforeground');
249 $activebackground = $this->cget('-activebackground');
250  
251 # Store old selection
252 $old = $$var;
253  
254 ($menu_items, $width, $first) = $this->generate_menu(undef, (ref $args[0] eq 'ARRAY') ? @{$args[0]} : @args);
255  
256 # Check for Auto-gen CLEAR entry
257 if ($this->cget('-clearoptionon')) {
258 my $clearoptiontext = $this->cget('-clearoptiontext');
259 unshift @$menu_items, [ 'command', $clearoptiontext,
260 -command => sub { $this->set_option(CLEAR_OPTION_TAG(), '', '') },
261 #-columnbreak => $columnbreak,
262 -font => $font,
263 -foreground => $this->cget('-clearoptionforeground'),
264 -background => $this->cget('-clearoptionbackground'),
265 -activeforeground => $this->cget('-clearoptionactiveforeground'),
266 -activebackground => $this->cget('-clearoptionactivebackground'),
267 -image => $this->cget('-clearoptionimage'),
268 ($clearoptiontext ? (-compound => 'left') : ()),
269 ];
270 }
271  
272 push @{$this->{MenuItems}}, @$menu_items;
273 $menu = $this->Menu(-menuitems => $this->{MenuItems});
274 $menu->configure(-font => $font);
275 $menu->configure(-tearoff => $this->cget('-tearoff') );
276 $menu->configure(-foreground => $this->cget('-foreground') );
277 $menu->configure(-background => $this->cget('-background') );
278 $menu->configure(-activeforeground => $this->cget('-activeforeground') );
279 $menu->configure(-activebackground => $this->cget('-activebackground') );
280  
281 # check for old menu
282 my $old_menu = $this->cget(-menu);
283 if ($old_menu) {
284 #print "found an old menu!\n";
285 $old_menu->delete(0, 'end');
286 $old_menu->destroy;
287 }
288  
289 # attach it
290 $this->configure(-menu => $menu);
291 $this->configure(-font => $font);
292
293 if (!defined($old) || !exists($this->{MenuItemSetupTable}{$old})) {
294 $this->set_option($first, $this->{MenuItemSetupTable}{$first}) if defined $first and $activate;
295 }
296 if ($this->{no_image}) {
297 $this->configure('-width' => $width);
298 }
299 }
300 #---------------------------------------------
301 sub generate_menu
302 {
303 # Parameters
304 my ($this, $parent) = (shift, shift);
305  
306 # Locals
307 my ($column, $item, $label, $value, $maxrows, @menu_items,
308 $separator, $length, $width, $first,
309 $font, $foreground, $background, $activeforeground, $activebackground);
310 local $_;
311  
312 $column = 0;
313 $maxrows = $this->cget('-rows');
314 $separator = $this->cget('-separator');
315 $font = $this->cget('-font');
316 $foreground = $this->cget('-foreground');
317 $background = $this->cget('-background');
318 $activeforeground = $this->cget('-activeforeground');
319 $activebackground = $this->cget('-activebackground');
320
321 $parent = '' unless $parent;
322 $separator = $this->cget('-separator');
323  
324 foreach (@_) {
325 my $columnbreak = $column ? (($column % $maxrows) ? 0 : 1) : 0; # Closure
326  
327 $label = $value = $_;
328 ($label, $value) = @$label if ref $label;
329
330 if (ref $label) {
331 ($label, $value) = @$label;
332 my ($menuitems, undef, $first) = $this->generate_menu(($parent ? ($parent . $separator . $label) : $label), @$value);
333 $item = [ 'cascade', $label,
334 -tearoff => '0',
335 -menuitems => $menuitems,
336 -columnbreak => $columnbreak,
337 -font => $font,
338 -foreground => $foreground,
339 -background => $background,
340 -activeforeground => $activeforeground,
341 -activebackground => $activebackground,
342 ];
343 $label = $first;
344 }
345 else {
346 my ($cmd_label, $cmd_value, $full_label); # Closures
347 $cmd_label = $label; $cmd_value = $value;
348 $length = length($label);
349 $width = $length if (!defined($width) or $length > $width);
350 $full_label = ($parent ? ($parent . $separator . $label) : $label);
351 $this->{MenuItemSetupTable}{$full_label} = $value;
352 $item = [ 'command', $cmd_label,
353 -command => sub { $this->set_option($cmd_label, $cmd_value, $full_label) },
354 -columnbreak => $columnbreak,
355 -font => $font,
356 -foreground => $foreground,
357 -background => $background,
358 -activeforeground => $activeforeground,
359 -activebackground => $activebackground,
360 ];
361 $label = $full_label;
362 }
363 $first = $label unless $first;
364 $column++;
365 push @menu_items, $item;
366 }
367 return (\@menu_items, $width, $first);
368 }
369 #---------------------------------------------
370 sub options
371 {
372 my ($this, $opts) = @_;
373 if (@_ > 1) {
374 if ($this->{CallBackActive}) {
375 cluck "\nTk::Optionbox Error: Found an illegal recursion loop: from Callback() to options() which is not allowed!\nAuto-shutting-down now, please let the developer fix this!";
376 kill 9, $$;
377 }
378 delete $this->{MenuItemSetupTable};
379 delete $this->{MenuItems};
380 $this->add_options($opts);
381 }
382 else {
383 return $this->_cget('-options');
384 }
385  
386 }
387 #---------------------------------------------
388 sub itemtable
389 {
390 my $this = shift;
391 my %itemtable = $this->{MenuItemSetupTable} ? %{$this->{MenuItemSetupTable}} : ();
392  
393 return wantarray ? %itemtable : \%itemtable;
394 }
395  
396 ########################################################################
397 1;
398 __END__