blib/lib/Getopt/GUI/Long.pm untested

filter: Statementstmt 0.0% 0 / 360 Branchbran 0.0% 0 / 184 Conditioncond 0.0% 0 / 111 MC/DCmcdc 0.0% 0 / 62 Subroutinesub 0.0% 0 / 21 Podpod 0.0% 0 / 13 totaltotal 0.0% 0 / 751 CC 92 SCAR 75.1
CC
92
Cov
0%
GetOptions
3422.0
display_help
342.0
MapToGetoptLong
72.0
CRAP 1834.1
1 package Getopt::GUI::Long;
2  
3 # Copyright 2005-2006, Sparta, Inc.
4 # All rights reserved.
5  
6 use strict;
7 use Text::Wrap;
8 use Getopt::Long qw();
9 use File::Temp qw(tempfile);
10  
11 our $VERSION="0.93";
12  
13 require Exporter;
14  
15 our @ISA = qw(Exporter Getopt::Long);
16 our @EXPORT = qw(GetOptions);
17 our $GUI_qw;
18 our $verbose;
19 our @ARGVsaved;
20  
21 #
22 # Configuration variables
23 #
24 my %config = (
25 capture_output => 0,
26 display_help => 0,
27 no_gui => 0,
28 allow_zero => 0,
29 );
30  
31 my @pass_to_qwizard_qs = qw(helpdesc helptext values labels default
32 check_value doif submit refresh_on_change
33 handle_results text name type indent);
34  
35 # Primary storage for QWizard
36 my %primaries =
37 (
38 display_results =>
39 {
40 title => (defined($ARGV) ? $ARGV : "") . " Output",
41 questions =>
42 [
43 { type => 'paragraph',
44 values => sub {
45 my $data;
46 # XXX: arg. optimize with read() and then a file display widget
47 open(I,$config{'output_file'});
48 while (<I>) {
49 $data .= $_;
50 }
51 close(I);
52 return $data;
53 }
54 },
55 { type => 'hidden',
56 name => 'QWizard_finish',
57 values => '_Exit' }
58 ]
59 }
60 );
61  
62  
63 #
64 # changes the default for a given question to a memorized value
65 #
66 sub set_default_opt {
67 my ($cache, @qs) = @_;
68 if ($cache) {
69 foreach my $q (@qs) {
70 if (!$q->{'default'}) {
71 $q->{'default'} = $cache->get($q->{'name'});
72 }
73 }
74 }
75 return @qs;
76 }
77  
78 sub GetOptions(@) {
79 my ($st, $cb, @opts) = ((ref($_[0]) eq 'HASH') ?
80 (1, 1, @_) : (0, 2, @_));
81 my @savedopts = @_;
82  
83 my %GUI_info;
84 my $dohelp;
85  
86 my $firstarg = "";
87  
88 if ($#main::ARGV > -1 &&
89 ($main::ARGV[0] =~ /--*gui/ || $main::ARGV[0] =~ /--*no-gui/ ||
90 $main::ARGV[0] =~ /--*nogui/)) {
91 $firstarg = shift @main::ARGV;
92 $firstarg = '-' . $firstarg if ($firstarg =~ /^-[^-]/);
93 }
94  
95 # If the user didn't specify any arguments, we display a GUI for them.
96 if ($firstarg ne '--nogui' &&
97 $firstarg ne '--no-gui' &&
98 (($#main::ARGV == -1 && !$config{'no_gui'} && !$config{'allow_zero'}) ||
99 $firstarg eq '--gui') &&
100 eval "require QWizard") {
101  
102 require QWizard;
103 import QWizard;
104 require QWizard::Storage::File;
105 import QWizard::Storage::File;
106 require QWizard::Plugins::Bookmarks;
107 import QWizard::Plugins::Bookmarks qw(init_bookmarks);
108  
109 # load the cache of saved default values
110 my $progname = $main::0;
111 my $cache;
112 my %addpris;
113  
114 $progname =~ s/([^a-zA-Z0-9])/'_' . ord($1)/eg;
115 my $cachefile = "$ENV{HOME}/.GetoptLongGUI/$progname";
116 my $marksfile = "$ENV{HOME}/.GetoptLongGUI/$progname-bookmarks";
117 if (-f $cachefile) {
118 $cache = new QWizard::Storage::File (file => $cachefile);
119 $cache->load_data();
120 }
121  
122 $config{'GUI_on'} = 1;
123
124 # create the qwizard instance
125 my $qw = new QWizard(no_confirm => 1,
126 title => $main::0);
127  
128 # they called us with no options, offer them a GUI screen full
129 my @names;
130 my %names;
131 my @qs;
132 my $screencount = 0;
133 my @saveqs;
134 my $pris;
135
136 # Define the first screen
137 $pris->{'screen' . $screencount} =
138 { title => "Options for $main::0", };
139  
140 for (my $i = $st; $i <= $#opts; $i += $cb) {
141 my ($spec, $desc, %rest);
142 if (ref($opts[$i]) eq 'ARRAY') {
143 $spec = $opts[$i][0];
144 $desc = $opts[$i][1];
145 %rest = @{$opts[$i]}[2..$#{$opts[$i]}];
146 } elsif ($opts[$i] eq '') {
147 push @qs,"";
148 next;
149 } else {
150 $spec = $opts[$i];
151 }
152  
153 next if ($rest{'nocgi'} && ref($qw->{'generator'}) =~ /HTML/);
154  
155 if ($spec =~ /^GUI:(.*)/) {
156 my $guiname = $1;
157
158 if ($guiname eq "guionly") {
159 #
160 # a specific QWizard question to be added
161 #
162 push @qs,
163 set_default_opt($cache,@{$opts[$i]}[1..$#{$opts[$i]}]);
164  
165 } elsif ($guiname eq "separator") {
166 #
167 # add a separator label.
168 #
169 push @qs, "", { type => 'label', text => $opts[$i][1]};
170  
171 } elsif ($guiname eq "screen") {
172 #
173 # Start a brand new screen
174 #
175  
176 # If the screen is optional via a previous flag
177 if (exists($rest{'doif'}) &&
178 ref($rest{'doif'}) ne 'CODE') {
179 $rest{'doifstr'} = $rest{'doif'};
180 $rest{'doif'} =
181 sub { return qwparam($_[2]{'doifstr'})};
182 }
183  
184 # Define the new screen
185 if ($#qs == -1) {
186 # screen definition occured before the first
187 # question, have this only affect the current
188 # screen.
189 foreach my $tok (keys(%rest)) {
190 $pris->{'screen' . $screencount}{$tok} =
191 $rest{$tok};
192 }
193 # maybe set the title
194 $pris->{'screen' . $screencount}{'title'} = $desc
195 if ($desc);
196 } else {
197 $pris->{'screen' . $screencount}{'questions'} = [@qs];
198 $screencount++;
199 $pris->{'screen' . $screencount} =
200 { title => $desc || "Options for $main::0",
201 # allow user to override
202 %rest };
203 @qs = ();
204 }
205 } else {
206 # generic GUI config token; store the name
207 @{$GUI_info{$guiname}} = @{$opts[$i]}[1..$#{$opts[$i]}];
208 }
209 next;
210 }
211  
212 # regexp stolen (and modified) from Getopt::Long
213 # XXX: copy copyright
214 $spec =~ m;^
215 # $1 = whole name pattern
216 (
217 # $2 = Option name
218 (\w+[-\w]* )
219 # $3 = first name, or "?"
220 (?: \| (\? | \w[-\w]* )? )?
221 # Alias names, or "?"
222 (?: \| (?: \? | \w[-\w]* )? )*
223 )?
224 # $4 = arguments
225 (
226 # Either modifiers ...
227 [!+]
228 |
229 # ... or a value/dest specification
230 [=:] [ionfs] [@%]?
231 |
232 # ... or an optional-with-default spec
233 : (?: -?\d+ | \+ ) [@%]?
234 )?
235 $;x;
236  
237 # map option pieces into variables
238 my ($pat, $optname, $firstname, $args) = ($1, $2, $3, $4);
239  
240  
241 # calculate the option name to use from the list of names.
242 my $name = (length($optname) == 1 ?
243 ((length($firstname) > 1) ? $firstname : $optname) :
244 $optname);
245  
246 # if no description, we copy the name and use that.
247 $desc = $name if (!$desc);
248  
249 # remember the name of the option we're working on
250 push @names,$name;
251 $names{$name} = $args;
252  
253 # get default value from the user preference if they had
254 # one already.
255 my $defval;
256 $defval = $cache->get($name) if ($cache);
257  
258 # calculate a default value based on the passed in hash
259 # ref or variable reference.
260 if (!$defval) {
261 $defval = (($cb == 1) ?
262 (exists($_[0]{$optname}) ? $_[0]{$optname} : undef) :
263 $opts[$i+1]);
264 }
265  
266 #
267 # Now constructure the needed GUI question
268 #
269 if ($rest{'question'}) {
270 # if a QWizard question definition was passed to us, use that.
271 if (ref($rest{'question'}) ne 'ARRAY') {
272 $rest{'question'} = [$rest{'question'}];
273 }
274 map {
275 $_->{'name'} = $name if ($_->{'name'} eq '');
276 $_->{'text'} = $desc if ($_->{'text'} eq '');
277 $_->{'default'} = $defval if (!exists($_->{'default'}));
278 } @{$rest{'question'}};
279 push @qs, set_default_opt($cache, @{$rest{'question'}});
280  
281 } elsif ($desc =~ /^!GUI/) {
282 # if the description was marked as not-for-the-GUI, don't
283 # dispaly aynthing and skip it but remember the parameter name.
284 push @qs, {type => 'hidden', name => $name, default => $defval};
285  
286 } elsif (!$args || $args =~ /[!+]/) {
287 #
288 # Boolean => Checkbox
289 #
290 push @qs,
291 {
292 'text' => $desc,
293 'type' => 'checkbox',
294 values => [1, undef],
295 default => (($defval)?1:undef),
296 'name' => $name,
297 };
298  
299 } elsif ($args =~ /i/) {
300 #
301 # Integer => textbox with int check
302 #
303 push @qs,
304 {
305 'text' => $desc,
306 'type' => 'text',
307 default => $defval,
308 'name' => $name,
309 check_value => (($rest{'required'}) ?
310 \&qw_integer : \&qw_optional_integer),
311 };
312 } elsif ($args =~ /[sf]/) {
313 #
314 # Float/string => textbox
315 #
316 # XXX: deal with floats seperately
317 push @qs,
318 {
319 'text' => $desc,
320 'type' => 'text',
321 default => $defval,
322 'name' => $name,
323 };
324 } else {
325 #
326 # Unknown => textbox
327 #
328 push @qs,
329 {
330 'text' => $desc,
331 'type' => 'text',
332 default => $defval,
333 'name' => $name,
334 };
335 }
336  
337 # if the required flag was set, force a requirement check.
338 if ($rest{'required'} && !exists($qs[$#qs]{'check_answer'})) {
339 $qs[$#qs]{'check_value'} = \&qw_required_field;
340 }
341  
342 # check the other auto-passing arguments
343 foreach my $k (@pass_to_qwizard_qs) {
344 $qs[$#qs]{$k} = $rest{$k} if (exists($rest{$k}));
345 }
346 }
347  
348 # include other primary information passed to us
349 if (exists($GUI_info{'otherprimaries'})) {
350 %addpris = @{$GUI_info{'otherprimaries'}};
351 }
352  
353 # Prompt for remaining arguments (or don't if requested to
354 # skip it or don't for CGIs by default). Normally this would
355 # be stuff handled beyond the realm of the Getopt processing
356 # like file-names, etc.
357 if ($GUI_info{'nootherargs'}) {
358 push @{$pris->{'screen0'}{'questions'}},
359 { type => 'hidden', name => '__otherargs' };
360 } elsif (ref($qw->{'generator'}) !~ /HTML/ ||
361 $GUI_info{'allowcgiargs'}) {
362 my $q = { type => 'text',
363 width => 80,
364 name => '__otherargs',
365 default =>
366 ($cache) ? $cache->get('__otherargs') : '',
367 text =>
368 $GUI_info{'otherargs_text'} || "Other Arguments",
369 };
370 if ($GUI_info{'otherargs_required'}) {
371 $q->{'check_value'} = \&qw_required_field;
372 }
373 push @{$pris->{'screen0'}{'questions'}}, "", $q;
374 }
375  
376 # our last primary setup
377 $pris->{'screen' . $screencount}{'questions'} = [@qs];
378 push @{$pris->{'screen' . $screencount}{'actions'}},
379 [sub {
380 #
381 # map all the defined option names from
382 # qwparam values pulled from the GUI back
383 # into ARGV options to be passed to
384 # Getopt::Long for processing
385 #
386 my ($qw, $name_array, $name_hash) = @_;
387 for (my $i = 0; $i <= $#{$name_array}; $i++) {
388 if (qwparam($name_array->[$i])) {
389 if (!$name_hash->{$name_array->[$i]} ||
390 $name_hash->{$name_array->[$i]} =~ /[+!]/) {
391 push @main::ARGV,
392 "--" . $name_array->[$i];
393 } else {
394 push @main::ARGV,
395 "--" . $name_array->[$i],
396 qwparam($name_array->[$i]);
397 }
398 }
399 }
400 if (ref($qw->{'generator'}) !~ /HTML/ ||
401 $GUI_info{'allowcgiargs'}) {
402 push @main::ARGV,
403 split(/\s+/,qwparam('__otherargs'));
404 }
405  
406 return 'OK';
407 }, \@names, \%names];
408  
409 # add in later screens if needed
410 if ($screencount > 0) {
411 push @{$pris->{'screen0'}{'post_answers'}},
412 [sub {
413 my ($wiz, $screencount) = @_;
414 for (my $i = $screencount; $i >= 1; $i--) {
415 $wiz->add_todos('screen' .$i);
416 }
417 }, $screencount];
418 }
419
420 # add in an post_answers clauses to the master primary
421 # XXX: move to each screen def
422 if ($GUI_info{'post_answers'}) {
423 push @{$pris->{'screen0'}{'post_answers'}},
424 @{$GUI_info{'post_answers'}};
425 }
426  
427 push @{$pris->{'screen' . $screencount}{'questions'}},
428 { type => 'hidden', name => 'QWizard_finish', values => '' };
429 push @{$pris->{'screen' . $screencount}{'post_answers'}},
430 [sub {
431 my ($wiz, $screencount) = @_;
432 qwparam('QWizard_finish', $GUI_info{'run_button'} || '_Run');
433 }];
434  
435 # add in an actions clauses to the master primary
436 if ($GUI_info{'actions'}) {
437 unshift @{$pris->{'screen0'}{'actions'}}, @{$GUI_info{'actions'}};
438 }
439  
440 # Finally, construct the QWizard GUI class...
441 $qw->merge_primaries($pris);
442  
443 # add the bookmarks menu
444 if (ref($qw->{'generator'}) !~ /HTML/ && !$GUI_info{'nosavebutton'}) {
445 my $marks = new QWizard::Storage::File (file => $marksfile);
446 $marks->load_data();
447 init_bookmarks($qw, $marks, title => 'Save Settings');
448 }
449  
450 # ... remember it ...
451 $GUI_qw = $qw;
452  
453 # ... load in our other primaries ...
454 $qw->merge_primaries(\%primaries);
455 $qw->merge_primaries(\%addpris);
456  
457 # ... and tell it to go
458 $qw->magic('screen0', @{$GUI_info{'submodules'}});
459 $qw->finished(); # drop the window for long running apps
460  
461 # ... if we aren't finished processing then exit. This should
462 # only happen if we're in a CGI script where we're not done yet.
463 exit if (!$qw->is_done());
464
465 # if there are any final hook routines to call, do so.
466 if ($GUI_info{'hook_finished'}) {
467 foreach my $h (@{$GUI_info{'hook_finished'}}) {
468 $h->();
469 }
470 }
471 } elsif ($#main::ARGV == -1 && !$config{'allow_zero'}) {
472 # no qwizard, but no args so force usage
473 $dohelp = 1;
474 $opts[0]{'h'} = 1;
475 }
476  
477 # map the options passed to us to ones that are compliant with
478 # Getopt::Long
479 @opts = MapToGetoptLong(\%GUI_info, @_);
480  
481 # save the arguments we contstructed for future use.
482 @ARGVsaved = @main::ARGV;
483  
484 # display the results to the user if verbose was requested.
485 if ($verbose) {
486 print STDERR "passing $#main::ARGV args to Getopt::Long: ",
487 join(",",@main::ARGV),"\n";
488 }
489  
490 # finally, pass on to the original Getopt::Long routine.
491 my $ret = 1;
492 $ret = Getopt::Long::GetOptions(@opts) if (!$dohelp);
493  
494 if ($verbose) {
495 print STDERR "ret from long: $ret\n";
496 }
497  
498 # capture stderr/out if required to display later.
499 if ($config{'capture_output'} && $config{'GUI_on'}) {
500 ($config{'fh'}, $config{'output_file'}) =
501 tempfile("guilongXXXXXX", SUFFIX => 'txt');
502 close(STDOUT);
503 close(STDERR);
504 *STDOUT = $config{'fh'};
505 *STDERR = $config{'fh'};
506 }
507  
508 if (defined($config{'display_help'}) && $config{'display_help'} &&
509 (ref($_[0]) eq 'HASH' &&
510 ($_[0]{'help'} || $_[0]{'help-full'} || $_[0]{'h'})) ||
511 $dohelp) {
512 display_help($st, $cb, \%GUI_info, \@savedopts, @_);
513 }
514  
515 if (ref($_[0]) eq 'HASH' && exists($_[0]{'getopt-to-pod'})) {
516 _getopt_to_pod($st, $cb, \%GUI_info, \@savedopts, @_);
517 }
518  
519 if (defined($config{'display_help'}) && $config{'display_help'} &&
520 defined($GUI_info{'VERSION'}) &&
521 ref($_[0]) eq 'HASH' && ($_[0]{'version'})) {
522 print STDERR "Version: ",$GUI_info{'VERSION'},"\n";
523 exit(0);
524 }
525 return $ret;
526 }
527  
528 #
529 # prints help information
530 #
531 sub display_help {
532 my $st = shift;
533 my $cb = shift;
534 my $GUI_info = shift;
535 my $savedopts = shift;
536 # Print help message if auto_help is on (XXX)
537  
538 my $topod = $GUI_info->{'__pod_to_text'};
539  
540 print STDERR "Usage: $0 [OPTIONS] ",
541 ($GUI_info->{'otherargs_text'} ||
542 ($GUI_info->{'nootherargs'} ? "" : "Other Arguments")),
543 "\n\nOPTIONS:\n"
544 if (!$topod);
545  
546 for (my $i = $st; $i <= $#{$savedopts}; $i += $cb) {
547 my ($spec, $desc, %rest);
548 if (ref($savedopts->[$i]) eq 'ARRAY') {
549 $spec = $savedopts->[$i][0];
550 $desc = $savedopts->[$i][1];
551 %rest = @{$savedopts->[$i]}[2..$#{$savedopts->[$i]}];
552 } elsif ($savedopts->[$i] eq '') {
553 print STDERR "\n";
554 next;
555 } else {
556 $spec = $savedopts->[$i];
557 }
558  
559 # print separators
560 if ($spec =~ /^GUI:(separator|screen)/) {
561 if ($topod) {
562 print STDERR "=head2 $desc\n\n";
563 } else {
564 print STDERR "\n$desc\n";
565 }
566 next;
567 }
568  
569 next if ($spec =~ /^GUI:(.*)/);
570  
571 # regexp stolen (and modified) from Getopt::Long
572 # XXX: copy copyright
573 $spec =~ m;^
574 # $1 = whole name pattern
575 (
576 # $2 = Option name
577 (\w+[-\w]* )
578 # $3 = first name, or "?"
579 (?: \| (\? | \w[-\w]* )? )?
580 # Alias names, or "?"
581 (?: \| (?: \? | \w[-\w]* )? )*
582 )?
583 # $4 = arguments
584 (
585 # Either modifiers ...
586 [!+]
587 |
588 # ... or a value/dest specification
589 [=:] [ionfs] [@%]?
590 |
591 # ... or an optional-with-default spec
592 : (?: -?\d+ | \+ ) [@%]?
593 )?
594 $;x;
595  
596 # map option pieces into variables
597 my ($pat, $optname, $firstname, $argspec) = ($1, $2, $3, $4);
598  
599 # turn argspecs into human consumable versions.
600 if ($argspec =~ /i/) {
601 $argspec = "INTEGER";
602 } elsif ($argspec =~ /f/) {
603 $argspec = "FLOAT";
604 } elsif ($argspec =~ /s/) {
605 $argspec = "STRING";
606 } else {
607 $argspec = "";
608 }
609  
610 my @args=split(/\|/,$pat);
611 if ($_[0]{'help-full'} || $topod) {
612 # they want *everything*
613 for (my $argc=0; $argc <= $#args; $argc++) {
614 _display_help_option($args[$argc], $argspec,
615 ($argc == $#args)?$desc:"", $topod);
616 }
617  
618 } elsif ($_[0]{'h'}) {
619 # assume short names perferred and always show the shortest
620 _display_help_option($args[0], $argspec, $desc);
621  
622 } elsif ($_[0]{'help'}) {
623 # assume long names perferred and use those if possible
624 if ($#args == 0) {
625 # only one is avialable
626 _display_help_option($args[0], $argspec, $desc);
627 } elsif (length($args[0]) == 1) {
628 # first one is short, display the second...
629 _display_help_option_long($args[1], $argspec, $desc);
630 } else {
631 # first one itself is long, display it.
632 _display_help_option_long($args[0], $argspec, $desc);
633 }
634 }
635 }
636  
637 # display the display_help options
638 print STDERR "\nHelp Options:\n";
639 _display_help_option_short('h','',
640 'Display help options -- short flags preferred');
641 _display_help_option_long('help','',
642 'Display help options -- long flags preferred');
643 _display_help_option_long('help-full','',
644 'Display all help options -- short and long');
645 _display_help_option_long('gui','',
646 'Display a help GUI');
647 _display_help_option_long('no-gui','',
648 'Do not display the default help GUI');
649 _display_help_option_long('version','',
650 'Display the version number')
651 if ($GUI_info->{'VERSION'});
652  
653 exit(1);
654 }
655  
656 sub _getopt_to_pod {
657 my $st = shift;
658 my $cb = shift;
659 my $GUI_info = shift;
660 my $savedopts = shift;
661 $GUI_info->{'__pod_to_text'} = 1;
662 display_help($st, $cb, $GUI_info, $savedopts, @_);
663 }
664  
665 sub _display_help_option {
666 my ($arg,$spec,$desc,$topod) = @_;
667 if ($topod) {
668 _display_help_option_pod(@_);
669 } elsif (length($arg) == 1) {
670 _display_help_option_short(@_);
671 } else {
672 _display_help_option_long(@_);
673 }
674 }
675  
676 sub _display_help_option_short {
677 my ($arg,$spec,$desc) = @_;
678 printf STDERR (" -%-20s %-55s\n", $arg . " " . $spec, $desc);
679 }
680  
681 sub _display_help_option_long {
682 my ($arg,$spec,$desc) = @_;
683 printf STDERR (" --%-20s %-55s\n",
684 $arg . ($spec ? "=" : "") . $spec, $desc);
685 }
686  
687 sub _display_help_option_pod {
688 my ($arg,$spec,$desc) = @_;
689 printf STDERR ("=item -%s%s\n\n%s\n\n",
690 ((length($arg) == 1) ? $arg : "-" . $arg),
691 ($spec ? ((length($arg) == 1) ? " " : "=") : "") . $spec,
692 $desc);
693 }
694  
695  
696 sub MapToGetoptLong {
697 my $guiinfo = shift;
698 my ($st, $cb, @opts) = ((ref($_[0]) eq 'HASH')
699 ? (1, 1, $_[0]) : (0, 2));
700 for (my $i = $st; $i <= $#_; $i += $cb) {
701 if ($_[$i]) {
702 if (ref($_[$i]) eq 'ARRAY' && $_[$i][0] =~ /^GUI:(.*)/) {
703 $guiinfo->{$1} = $_[$i][1];
704 next;
705 }
706 push @opts, ((ref($_[$i]) eq 'ARRAY') ? $_[$i][0] : $_[$i]);
707 push @opts, $_[$i+1] if ($cb == 2);
708 }
709 }
710 push @opts,GetHelpOptions() if ($config{'display_help'});
711 push @opts,GetInternalOptions() unless ($config{'no_internal_options'});
712 return @opts;
713 }
714  
715 sub GetHelpOptions {
716 return ('help','h','help-full','version');
717 }
718  
719 sub GetInternalOptions {
720 return ('getopt-to-pod', 'gui', 'no-gui|nogui');
721 }
722  
723 #
724 # Configure's the running operation of the module. Any unknown
725 # arguments are passed to the parent Configure script.
726 #
727 sub Configure (@) {
728 my @options = @_;
729 my @passopts;
730 foreach my $opt (@options) {
731 if (exists($config{$opt})) {
732 $config{$opt} = 1;
733 } else {
734 push @passopts, $opt;
735 }
736 }
737 Getopt::Long::Configure(@passopts);
738 }
739  
740 #
741 # Calls qwizard at the end if output capture was turned on.
742 #
743 sub END {
744 if ($config{'capture_output'} && $config{'GUI_on'} && $config{'fh'}) {
745 $config{'fh'}->close();
746 $GUI_qw->magic('display_results');
747 unlink($config{'output_file'});
748 $GUI_qw->finished();
749 }
750 }
751  
752 1;
753  
754 =pod
755  
756 =head1 NAME
757  
758 Getopt::GUI::Long
759  
760 =head1 SYNOPSIS
761  
762 use Getopt::GUI::Long;
763  
764 # pass useful config options to Configure
765 Getopt::GUI::Long::Configure(qw(display_help no_ignore_case capture_output));
766 GetOptions(\%opts,
767 ["GUI:separator", "Important Flags:"],
768 ["f|some-flag=s", "A flag based on a string"],
769 ["o|other-flag", "A boloean"],
770 );
771  
772 # or use references instead of a hash (less tested, however):
773  
774 GetOptions(["some-flag=s", "perform some flag based on a value"] => \$flag,
775 ["other-flag=s", "perform some flag based on a value"] => \$other);
776  
777 # displays auto-help given the input above:
778  
779 % opttest -h
780 Usage: opttest [OPTIONS] Other Arguments
781  
782 OPTIONS:
783  
784 Important Flags:
785 -f STRING A flag based on a string
786 -o A boloean
787  
788 Help Options:
789 -h Display help options -- short flags preferred
790 --help Display help options -- long flags preferred
791 --help-full Display all help options -- short and long
792  
793  
794  
795 # or long help:
796  
797 % opttest --help
798 Usage: opttest [OPTIONS] Other Arguments
799  
800 OPTIONS:
801  
802 Important Flags:
803 --some-flag=STRING A flag based on a string
804 --other-flag A boloean
805  
806 Help Options:
807 -h Display help options -- short flags preferred
808 --help Display help options -- long flags preferred
809 --help-full Display all help options -- short and long
810  
811 # or a GUI screen:
812  
813 (see http://www.dnssec-tools.org/images/getopt_example.png )
814  
815 =head1 DESCRIPTION
816  
817 This module is a wrapper around Getopt::Long that extends the value of
818 the original Getopt::Long module to:
819  
820 1) add a simple graphical user interface option screen if no
821 arguments are passed to the program. Thus, the arguments to
822 actually use are built based on the results of the user
823 interface. If arguments were passed to the program, the user
824 interface is not shown and the program executes as it normally
825 would and acts just as if Getopt::Long::GetOptions had been
826 called instead.
827  
828 2) provide an auto-help mechanism such that -h and --help are
829 handled automatically. In fact, calling your program with -h
830 will default to showing the user a list of short-style arguments
831 when one exists for the option. Similarly --help will show the
832 user a list of long-style when possible. --help-full will list
833 all potential arguments for an option (short and long both).
834  
835 It's designed to make the creation of graphical shells trivial
836 without the programmer having to think about it much as well as
837 providing automatic good-looking usage output without the
838 programmer needing to write usage() functions.
839  
840 This also can turn normal command line programs into web CGI scripts
841 as well (automatically). If the Getopt::GUI::Long program is
842 installed as a CGI script then it will automatically prompt the user
843 for the same variables.
844  
845 =head1 USAGE
846  
847 The Getopt::GUI::Long module can work identically to the Getopt::Long
848 module but really benefits from some slightly different usage
849 conventions described below.
850  
851 =head2 Option format:
852  
853 Option strings passed should be formatted in one of the following ways:
854  
855 =over
856  
857 =item Empty String
858  
859 Empty strings are ignored by the non-GUI version of the command, but
860 are treated as vertical separators between questions when displaying
861 the GUI screen.
862  
863 =item Standard flag specification string
864  
865 EG: "some-flag|optional-flag=s"
866  
867 This is the standard method by which Getopt::Long does things and is
868 merely treated the same way here. In this case, the text presented to
869 the user screen will be the first name in the list ("some-flag") in
870 the above option. The type of wdget displayed with the text will
871 depend on the optional =s/i/whatever flag and will be either a
872 checkbox, entry box, ...
873  
874 =item Array Reference
875  
876 EG: ["some-flag|optional-flag=s", 'Prompt text', OTHER],
877  
878 The values passed in this array are as follows:
879  
880 =over
881  
882 =item 0: Standard flag specification string
883  
884 Same as always, and as above.
885  
886 =item 1: Prompt text about flag
887  
888 The help text that should be shown to the user in the graphical
889 interface. In the example above rather than "some-flag" being shown,
890 "Prompt text" will be shown next to the widget instead.
891  
892 If the prompt text is equal to "!GUI" then this option will not be
893 displayed (automatically at least) within the GUI.
894  
895 =item 2...: OTHER options
896  
897 Beyond the name and description, key value pairs can indicate more
898 about how the option should be handled.
899  
900 =over
901  
902 =item required => 1
903  
904 Forces a screen option to be filled out by the user.
905  
906 =item question => { QUESTION FORM }
907  
908 =item question => [{ QUESTION1}, {QUESTION2}, ...]
909  
910 These allows you to build custom QWizard widgets to meet a particular
911 question need. It's highly useful for doing menus and single choice
912 fields that normally command line options don't handle well. For
913 example consider a numeric priority level between 0 and 10. The
914 following question definition will give them a menu rather than a fill
915 in the blank field:
916  
917 ['priority=i','Priority Level',
918 question => { type => 'menu', values => [1..10] }]
919  
920 Note you can specify multiple question widgets if needed as well,
921 though this will probably be rare in usage.
922  
923 =item QWizard question tokens
924  
925 Any of the following items can be passed as well, which will be added
926 to the QWizard question structure. See the QWizard documantion on
927 "QUESTION DEFINITIONS" for details on the usage of these.
928  
929 =over
930  
931 =item type
932  
933 =item helpdesc
934  
935 =item helptext
936  
937 =item default
938  
939 =item check_value
940  
941 =item doif
942  
943 =item submit
944  
945 =item refresh_on_change
946  
947 =item handle_results
948  
949 =item text
950  
951 (Warning: Replaces the text already extracted from the prompt text
952 described above).
953  
954 =item name
955  
956 (Warning: Replaces the option name extracted from the position 0
957 standard flag specification string above. Do not use this unless you
958 really know what you're doing.)
959  
960 =back
961  
962 =back
963  
964 [others TBD]
965  
966 =back
967  
968 =back
969  
970 =head1 Special Flag Names
971  
972 Flags that start with GUI: are not passed to the normal Getopt::Long
973 routines and are instead for internal GUI digestion only. If the GUI
974 screen is going to be displayed (remember: only if the user didn't
975 specify any options), these extra options control how the GUI behaves.
976  
977 Some of these options requires some knowledge of the QWizard
978 programming system. Knowledge of QWizard should only be required if
979 you want to make use of those particular extra features.
980  
981 =over
982  
983 =item GUI:guionly
984  
985 EG: ['GUI:guionly', { type => 'checkbox', name => 'myguiflag'}]
986  
987 Specifies a valid QWizard question(s) to only be shown when the gui is
988 displayed, and the specification is ignored during normal command line
989 usage.
990  
991 =item GUI:separator
992  
993 EG: ['GUI:separator', 'Task specific options:']
994  
995 Inserts a label above a set of options to identify them as a group.
996  
997 =item GUI:screen
998  
999 EG: ['GUI:screen', 'Next Screen Title', ...]
1000  
1001 Specifies that a break in the option requests should occur and the
1002 remaining options should appear on another screen(s). This allows
1003 applications with a lot of options to reduce the complexity it offers
1004 users and offers a more "wizard" like approach to helping them decide
1005 what they're trying to do.
1006  
1007 You can also make this next screen definition conditional by defining
1008 an earlier option that may be, say, a boolean flag called
1009 "feature_flag". Using this you can then only go into the next screen
1010 if the "feature_flag" was set by doing the following:
1011  
1012 ['feature-flag',
1013 'turn on a special feature needing more options'],
1014  
1015 ['GUI:screen', 'Next Screen Title', doif => 'feature-flag']
1016 ['feature-arg1', 'extra argument #1 for special feature'],
1017 ...
1018  
1019 Also, if you need to do more complex calculations use the qwparam()
1020 function of the passed in QWizard object in a subroutine reference instead:
1021  
1022 ['feature1','Turn on feature #1"],
1023 ['feature2','Turn on feature #2"],
1024  
1025 ['GUI:screen', 'Next Screen Title',
1026 doif => sub {
1027 return ($_[1]->qwparam('feature1') && $_[1]->qwparam('feature2'));
1028 }]
1029  
1030 =item GUI:otherargs_text
1031  
1032 EG: ['GUI:otherargs', 'Files to process:']
1033  
1034 Normally the GUI screen shows a "Other Arguments:" option at the
1035 bottom of the main GUI screen to allow users to entry additional flags
1036 (needed for file names, etc, and other non-option arguments to be
1037 passed). However, since it doesn't know what these arguments should
1038 be it can only provide a generic "Other Arguments:" description. This
1039 setting lets you change that text to something specific to what your
1040 application experts, such as "Files:" or "HTML Files:" or something
1041 that helps the user understand what is expected of them.
1042  
1043 If you want to self-handle the argument prompting using other QWizard
1044 constructs, then use the nootherargs token described below instead.
1045  
1046 =item GUI:nootherargs
1047  
1048 EG: ['GUI:nootherargs', 1]
1049  
1050 Normally the GUI screen shows a "Other Arguments:", or programmer
1051 described text as described above, option at the bottom of the main
1052 GUI screen. If you're going to handle the additional arguments
1053 yourself in some way (using either some GUI:guionly or
1054 (GUI:otherprimaries and GUI:submodules) flags), then you should
1055 specify this so the other arguments field is not shown. You're
1056 expected, in your self-handling code, to set the __otherargs QWizard
1057 parameter to the final arguments that should be passed on.
1058  
1059 =item GUI:nosavebutton
1060  
1061 EG: ['GUI:nosavebutton', 1]
1062  
1063 Normally the GUI screen offers a "save" menu that lets users save
1064 their current screen settings for future calls. Using this setting
1065 turns off this behavior so the button isn't shown.
1066  
1067 =item GUI:otherprimaries
1068  
1069 EG: ['GUI:otherprimaries', primaryname =>
1070 { title => '...', questions => [...] }]
1071  
1072 Defines other primaries to be added to the QWizard primary set.
1073  
1074 =item GUI:submodules
1075  
1076 EG: ['GUI:submodules', 'primaryname']
1077  
1078 Defines a list of other primaries that should be called after the
1079 initial one.
1080  
1081 =item GUI:post_answers
1082  
1083 EG: ['GUI:post_answers', sub { do_something(); }]
1084  
1085 Defines an option for QWizard post_answers subroutines to run.
1086  
1087 =item GUI:actions
1088  
1089 EG: ['GUI:actions', sub { do_something(); }]
1090  
1091 Defines an option for QWizard actions subroutines to run.
1092  
1093 =item GUI:hook_finished
1094  
1095 EG: ['GUI:hook_finished', sub { do_something(); }]
1096  
1097 Defines subroutine(s) to be called after the GUI has completely finished.
1098  
1099 =item GUI:run_button
1100  
1101 EG: ['GUI:run_button', 'My Run Button']
1102  
1103 Defines the text to use for the final "Run" button (which normally
1104 just says "Run").
1105  
1106 =item GUI:VERSION
1107  
1108 If display_help is defined, and the above token is specified
1109 Getopt::GUI::Long takes over the output for --version output as well.
1110  
1111 EG: ['GUI:VERSION','0.9']
1112  
1113 Produces the --version help option:
1114  
1115 Help Options:
1116 -h Display help options -- short flags preferred
1117 --help Display help options -- long flags preferred
1118 --help-full Display all help options -- short and long
1119 --version Display the version number
1120  
1121 And also auto-handles the --version switch:
1122  
1123 % PROGRAM --version
1124 Version: 0.9
1125  
1126 =back
1127  
1128 =head1 CONFIGURATION
1129  
1130 If you call Getopt::GUI::Long's Configure routine, it will accept a
1131 number of configure tokens and will pass the remaining ones to the
1132 Getopt::Long Configure routine. The tokens that it recognizes itself
1133 are described below:
1134  
1135 =over
1136  
1137 =item display_help
1138  
1139 The Getopt::GUI::Long package will auto-display help messages based on
1140 the text included in the GetOptions call. No more writing those silly
1141 usage() functions!
1142  
1143 Note that this differs from the Getopt::Long's implementation of the
1144 auto_help token in that the information is pulled from the extended
1145 GetOptions called instead of the pod documentation.
1146  
1147 The display_help token will automatically add the following options to
1148 the options the application will accept, and will catch and process
1149 them as well.
1150  
1151 =over
1152  
1153 =item -h
1154  
1155 Command line help preferring short options if present in the help
1156 specification.
1157  
1158 =item --help
1159  
1160 Command line help preferring long options if present in the help
1161 specification.
1162  
1163 =item --help-full
1164  
1165 Shows all available option names for a given option
1166  
1167 =item --gui
1168  
1169 If the default GUI is not showing up because no_gui has been
1170 specified, a sure can still call the application with only the --gui
1171 flag to make it appear.
1172  
1173 =item --no-gui
1174  
1175 If the no_gui option hasn't been set and the user doesn't want to see
1176 the GUI then they can use the --no-gui flag as the only argument to
1177 ensure it doesn't appear.
1178  
1179 =back
1180  
1181 =item capture_output
1182  
1183 This tells the Getopt::GUI::Long module that it should caputure the
1184 resulting STDOUT and STDERR results from the script and display the
1185 results in a window once the script has finished.
1186  
1187 =item no_gui
1188  
1189 This option defaults to not presenting a GUI form for the user to fill
1190 out B<unless> they specify --gui as the first and only argument on the
1191 command line.
1192  
1193 =item allow_zero
1194  
1195 By default the GUI will always pop up if zero-arguments have been
1196 specified (or the help info will be displayed if no_gui is set). This
1197 options specifies that zero arguments is a normal usage case. Thus
1198 the only way to force the GUI or help to appear will be the command
1199 line --gui flag.
1200  
1201 =back
1202  
1203 =head1 Using the QWizard object for other purposes
1204  
1205 The Getopt::GUI::Long qwizard object is stored at
1206 $Getopt::GUI::Long::GUI_qw, which is usable for other GUI screens you
1207 may need to create after the options screens have been processed. You
1208 can also use it during the script to optionally display a progress
1209 meter by making use of the QWizard::set_progress function. However,
1210 you should test to see if the GUI screen mode was actually used before
1211 operating with the object though. As an example:
1212  
1213 $Getopt::GUI::Long::GUI_qw->set_progress(3/5)
1214 if ($Getopt::GUI::Long::GUI_qw);
1215  
1216 =head1 PORTABILITY
1217  
1218 If programs desire to not require this module, the following code
1219 snippit can be used instead which will not fail even if this module is
1220 not available. To be used this way, the LocalGetOptions and
1221 LocalOptionsMap functions should be copied to your perl script.
1222  
1223 LocalGetOptions(\%opts,
1224 ["h|help", "Show help for command line options"],
1225 ["some-flag=s", "perform some flag based on a value"]);
1226  
1227 sub LocalGetOptions {
1228 if (eval {require Getopt::GUI::Long;}) {
1229 import Getopt::GUI::Long;
1230 # optional configure call
1231 Getopt::GUI::Long::Configure(qw(display_help no_ignore_case capture_output));
1232 return GetOptions(@_);
1233 }
1234 require Getopt::Long;
1235 import Getopt::Long;
1236 # optional configure call
1237 Getopt::Long::Configure(qw(auto_help no_ignore_case));
1238 GetOptions(LocalOptionsMap(@_));
1239 }
1240  
1241 sub LocalOptionsMap {
1242 my ($st, $cb, @opts) = ((ref($_[0]) eq 'HASH')
1243 ? (1, 1, $_[0]) : (0, 2));
1244 for (my $i = $st; $i <= $#_; $i += $cb) {
1245 if ($_[$i]) {
1246 next if (ref($_[$i]) eq 'ARRAY' && $_[$i][0] =~ /^GUI:/);
1247 push @opts, ((ref($_[$i]) eq 'ARRAY') ? $_[$i][0] : $_[$i]);
1248 push @opts, $_[$i+1] if ($cb == 2);
1249 }
1250 }
1251 return @opts;
1252 }
1253  
1254 =head2 Forcing a Particular Generator
1255  
1256 There a times where you may want to force a particular generator to be
1257 used. This can be accomplished by setting the QWIZARD_GENERATOR
1258 environmental variable. this can actually be done in code within
1259 something like LocalGetOptions function as well:
1260  
1261 sub LocalGetOptions {
1262 # force the library by using $ENV{'QWIZARD_GENERATOR'}
1263 # if Gtk2, Tk, HTML or Readline generators are required, set the
1264 # QWIZARD_GENERATOR ENV variable either externally or in this
1265 # script Example: Force QWizard to use Tk instead of the
1266 # preferred default of Gtk2 like this:
1267 $ENV{'QWIZARD_GENERATOR'} = 'Tk' if (not exists($ENV{'QWIZARD_GENERATOR'}));
1268
1269 # ... conitune with the rest of the LocalGetOptions shown above
1270  
1271 =head1 Usage as a CGI Script
1272  
1273 If a Getopt::GUI::Long script is installed as a CGI script, then the
1274 Getopt::GUI::Long system will automatically create a web front end for
1275 the perl script. It will present the user with all the normal
1276 arguments that it would normally to a Gtk2 or other windowing system.
1277  
1278 It will not present the box for generic additional arguments since
1279 this is not safe to do. If you trust your users (ie, you have an
1280 authentication system in place) then you can set the I<allowcgiargs>
1281 GUI variable to make this box appear. Example invocation (not
1282 generally recommended):
1283  
1284 ['GUI:allowcgiargs',1]
1285  
1286 It also allows you to not present certain options to web users that
1287 you will to command line users (some options may not be safe for CGI
1288 use). You can do this by setting the I<nocgi> variable in option
1289 definitions you wish to disallow via CGI. E.G., if you had an option
1290 to specify a location where to load configuration a file from, this
1291 would likely be unsafe to publish in a CGI script. So remove it:
1292  
1293 ["c|config-file","Load a specific configuration file", nocgi => 1]
1294  
1295 =head1 EXAMPLES
1296  
1297 See the getopttest program in the examples directory for an exmaple
1298 script that uses a lot of these features.
1299  
1300 =head1 AUTHOR
1301  
1302 Wes Hardaker, hardaker@users.sourceforge.net
1303  
1304 =head1 COPYRIGHT and LICENSE
1305  
1306 Copyright (c) 2006-2009, SPARTA, Inc. All rights reserved
1307  
1308 Copyright (c) 2006-2007, Wes Hardaker. All rights reserved
1309  
1310 Getopt::GUI::Long is free software; you can redistribute it and/or modify
1311 it under the same terms as Perl itself.
1312  
1313 =head1 SEE ALSO
1314  
1315 perl(1)
1316  
1317 modules: QWizard
1318  
1319 =head1 HISTORY
1320  
1321 This module was originally named Getopt::Long::GUI but the
1322 Getopt::Long author wanted to reserve the Getopt::Long namespace
1323 entirely for himself and thus it's been recently renamed to
1324 Getopt::GUI::Long instead. The class tree isn't as clean this way, as
1325 this module still inherits from Getopt::Long but it everything still
1326 works of course.
1327  
1328 =cut
1329  
1330 1;