Slaven Rezić > Tk-Getopt-0.50 > Tk::Getopt

Download:
Tk-Getopt-0.50.tar.gz

Dependencies

Annotate this POD

CPAN RT

Open  0
View/Report Bugs
Module Version: 0.50   Source  

NAME ^

Tk::Getopt - User configuration window for Tk with interface to Getopt::Long

SYNOPSIS ^

    use Tk::Getopt;
    @opttable = (['opt1', '=s', 'default'], ['opt2', '!', 1], ...);
    $opt = new Tk::Getopt(-opttable => \@opttable,
                          -options => \%options,
                          -filename => "$ENV{HOME}/.options");
    $opt->set_defaults;     # set default values
    $opt->load_options;     # configuration file
    $opt->get_options;      # command line
    $opt->process_options;  # process callbacks, check restrictions ...
    print $options->{'opt1'}, $options->{'opt2'} ...;
    ...
    $top = new MainWindow;
    $opt->option_editor($top);

or using a Getopt::Long-like interface

    $opt = new Tk::Getopt(-getopt => ['help'   => \$HELP,
                                      'file:s' => \$FILE,
                                      'foo!'   => \$FOO,
                                      'num:i'  => \$NO,
                                     ]);

or an alternative Getopt::Long interface

    %optctl = ('foo' => \$foo,
               'bar' => \$bar);
    $opt = new Tk::Getopt(-getopt => [\%optctl, "foo!", "bar=s"]);

DESCRIPTION ^

Tk::Getopt provides an interface to access command line options via Getopt::Long and editing with a graphical user interface via a Tk window.

Unlike Getopt::Long, this package uses a object oriented interface, so you have to create a new Tk::Getopt object with new. Unlike other packages in the Tk hierarchy, this package does not define a Tk widget. The graphical interface is calles by the method option_editor.

After creating an object with new, you can parse command line options by calling get_options. This method calls itself Getopt::Long::GetOptions.

METHODS ^

new Tk::Getopt(arg_hash)

Constructs a new object of the class Tk::Getopt. Arguments are passed in a hash (just like Tk widgets and methods). There are many variants to specify the option description. You can use an interface similar to Getopt::Long::GetOptions by using -getopt or a more powerful interface by using -opttable. Internally, the option description will be converted to the -opttable interface. One of the arguments -getopt or -opttable are mandatory.

The arguments for new are:

-getopt

-getopt should be a reference to a hash or an array. This hash has the same format as the argument to the Getopt::Long::GetOptions function. Look at Getopt::Long for a detailed description. Note also that not all of GetOptions is implemented, see "BUGS" for further information.

Example:

    new Tk::Getopt(-getopt => [\%options,
                               "opt1=i", "opt2=s" ...]);
-opttable

-opttable provides a more powerful interface. The options are stored in variables named $opt_XXX or in a hash when -options is given (see below). -opttable should be a reference to an array containing all options. Elements of this array may be strings, which indicate the beginning of a new group, or array references describing the options. The first element of this array is the name of the option, the second is the type (=s for string, =i for integer, ! for boolean, =f for float etc., see Getopt::Long) for a detailed list. The third element is optional and contains the default value (otherwise the default is undefined). Further elements are optional too and describe more attributes. For a complete list of these attributes refer to "OPTTABLE ARGUMENTS".

If an option has no name, then the third element in the description array will be used as an global message for the current option page. This message can be multi-line. Example: ['', '', 'This is an explanation for this option group.']

To insert horizontal lines, use: ['', '', '-']

Here is an example for a simple opttable:

    @opttable =
        ('First section',
         ['', '', 'Section description'],
         ['debug', '!',  0],
         ['age',   '=i', 18],

         'Second section',
         ['', '', 'Description for 2nd section'],
         ['browser', '=s', 'tkweb'],
         ['foo',     '=f', undef],
        );
    new Tk::Getopt(-opttable => \@opttable,
                   -options => \%options);
-options

This argument should be a reference to an (empty) hash. Options are set into this hash. If this argument is missing, options will be stored in variables named $opt_XXX.

-filename

This argument is optional and specifies the filename for loading and saving options.

-nosafe

If set to true, do not use a safe compartment when loading options (see load_options).

-useerrordialog

If set to true, then use an error dialog in user-relevant error conditions. Otherwise, the error message is printed to STDERR. This only includes errors which may happen in normal operation, but not programming errors like specifying erroneous options. If no Tk context is available (i.e. there is no MainWindow), then the error message will also be printed to STDERR.

set_defaults

Sets default values. This only applies if the -opttable variant is used.

load_options(filename)

Loads options from file filename, or, if not specified, from object's filename as specified in new. The loading is done in a safe compartment ensure security.The loaded file should have a reference to a hash named $loadoptions.

save_options(filename)

Writes options to file filename, or, if not specified, from object's filename as specified in new. The saving is done with Data::Dumper. Since saving may fail, you should call this method inside of eval {} and check $@. Possible exceptions are No Data::Dumper (cannot find the Data::Dumper module) and Writing failed (cannot write to file).

get_options

Gets options via GetOptions. Returns the same value as GetOptions, i.e. 0 indicates that the function detected one or more errors.

If you want to process options which does not appear in the GUI, you have two alternatives:

  • Use the -opttable variant of the new constructor and mark all non-GUI options with nogui, e.g.
        new Tk::Getopt(-opttable => ['not-in-gui', '!', undef,
                                     nogui => 1], ...)
  • Use Getopt::Long::passthrough and process non-GUI options directly with Getopt::Long::GetOptions. The remaining args can be passed to get_options.

    Example:

        use Tk::Getopt;
        use Getopt::Long;
    
        $Getopt::Long::passthrough = 1;
        GetOptions('options!' => \$preloadopt);
        $Getopt::Long::passthrough = 0;
    
        $opt = new Tk::Getopt( ... );
        $opt->get_options;
usage

Generates an usage string from object's opttable. The usage string is constructed from the option name, default value and help entries.

process_options([undo_hash])

Checks wheather given values are valid (if strict is set) and calls any callbacks specified by the sub option. If undo_hash is given and the new value of an option did not change, no sub is called.

option_editor(widget, [arguments ...])

Pops the option editor up. The editor provides facilitied for editing options, undoing, restoring to their default valued and saving to the default options file.

The option editor is non-modal. For a modal dialog, see below for the "option_dialog" method.

The first argument is the parent widget. Further optional arguments are passed as a hash:

-callback

Execute additional callback after creating the option editor. Arguments passed to this callback are: reference to the Tk::Getopt object and a reference to the option editor window.

-nosave

Disable saving of options.

-savevar

When saving with the saveoptions method, use the specified variable reference instead of the -var reference. This is useful if -var is a subroutine reference.

-buttons

Specify, which buttons should be drawn. It is advisable to draw at least the OK and Cancel buttons. The default set looks like this:

    -buttons => [qw/ok apply cancel undo lastsaved save defaults/]

A minimal set could look like (here OK means accept and save)

    -buttons => [qw/oksave cancel/]

(and using less buttons is recommended).

-toplevel

Use another widget class instead of Toplevel for embedding the option editor, e.g. Frame to embed the editor into another toplevel widget (do not forget to pack the frame!). See also the -pack option below.

-transient

Set the transient flag on the toplevel window. See the description of the transient method in Tk::Wm.

    -transient => $mw
-pack

If using -toplevel with a non-Toplevel widget (e.g. Frame) and using the -wait option, then packing have to be done through the -pack option. The argument to this option is a array reference of pack options, e.g.

    $opt->option_editor(-toplevel => "Frame",
                        -wait => 1,
                        -pack => [-fill => "both", -expand => 1]);
-statusbar

Use an additional status bar for help messages.

-string

Change button labels and title. This argument should be a hash reference with all or a subset of the following keys: optedit, undo, lastsaved, save, defaults, ok, cancel, helpfor.

-wait

Do not return immediately, but rather wait for the user pressing OK or Cancel.

-page

Raise the named notebook page (if grouping is used, see below).

Since the option editor uses the NoteBook widget, options may be grouped in several pages. Grouping is only possible if using the -opttable variant of new. Help messages are shown in balloons and, if specified, in a statusbar.

option_editor returns a reference to the created window.

Note: this method returns immediately to the calling program.

Buttons in the option editor window:

OK

Accept options and close option editor window.

Cancel

Set old values and close option editor window.

Undo

Set old values. Further selections toggle between new and old values.

Last saved

Set last saved options. This button is not displayed if no filename was given in new.

Save

Save options to file. This button is not displayed if no filename was given in new.

The option types are translated to following widgets:

Boolean

Checkbutton (_boolean_widget)

Integer and Float

Scale, if range is set, otherwise either BrowseEntry or Entry (_integer_widget, _float_widget).

String

BrowseEntry if choices is set, otherwise entry (_string_widget). FileDialog if subtype is set to file.

option_dialog(widget, [arguments ...])

This method works like "option_editor", but it shows the option editor as a modal dialog. Additionaly, the return value is either ok or cancel depending on how the user quits the editor.

OPTTABLE ARGUMENTS ^

Additional attributes in an option description have to be key-value pairs with following keys:

alias

An array of aliases also accepted by Getopt::Long.

callback

Call a subroutine every time the option changes (e.g. after pressing on Apply, Ok or after loading). The callback will get a hash with the following keys as argument:

optdef

The opttable item definition for this option.

bag

A hash reference which is persistent for this "process_options" call. This can be used to share state between multiple callbacks.

callback-interactive

Like callback, but only applies in interactive mode.

label

A label to be displayed in the GUI instead of the option name.

help

A short help string used by usage and the Balloon help facility in option_editor.

longhelp

A long help string used by option_editor.

choices

An array of additional choices for the option editor.

If strict is set to a true value, then the elements of choices may also contain array references. In this case the first value of the "sub" array references are the display labels and the second value the used value. This is similar to Tk::Optionmenu (in fact, for displaying this option an Optionmenu is used).

     choices => ["one", "two", "three"]

     choices => [["english"  => "en"],
                 ["deutsch"  => "de"],
                 ["hrvatski" => "hr"]]
range

An array with the beginning and end of a range for an integer or float value.

strict

Must be used with choices or range. When set to true, options have to match either the choices or the range.

subtype

Valid subtypes are file, savefile, dir, geometry, font and color. These can be used with string options. For file and savefile, the GUI interface will pop up a file dialog, using getOpenFile for the former and getSaveFile for the latter. For dir, the GUI interface will pop up a dialog for selecting directories (using either Tk::chooseDirectory, Tk::DirSelect, or a custom dialog built on top of Tk::DirTree). If the geometry subtype is specified, the user can set the current geometry of the main window. The color subtype is not yet implemented.

var

Use variable instead of $options->{optname} or $opt_optname to store the value.

nogui

This option will not have an entry in the GUI.

size

Create an entry with the specified size.

maxlength

Restrict the maximum number of characters in entries.

widget

This should be a reference to a subroutine for creating an own widget. Folowing arguments will be passed to this subroutine: a reference to the Tk::Getopt object, Frame object, and the options entry. The options entry should be used to get the variable reference with the _varref method. The subroutine should create a widget in the frame (packing is not necessary!) and should return a reference to the created widget.

A sample with an opttable entry for a custom numeric entry using the CPAN module Tk::NumEntry:

   ['numentry', '=i', 50,
    range => [0, 100],
    widget => sub { numentry_widget(@_) },
   ],

And numentry_widget defined as:

    use Tk::NumEntry;
    sub numentry_widget {
        my($self, $frame, $opt) = @_;
        my $v = $self->varref($opt);
        $frame->NumEntry(-minvalue => $opt->[3]{range}[0],
                         -maxvalue => $opt->[3]{range}[1],
                         -variable => $v,
                         -value => $$v,
                        );
    }

Here is an example for using a complex opttable description:

    @opttable =
        ('Misc',   # Head of first group
         ['debug', # name of the option (--debug)
          '!',     # type boolean, accept --nodebug
          0,       # default is 0 (false)
          callback => sub { $^W = 1
                                if $options->{'debug'}; }
          # additional attribute: callback to be called if
          # you set or change the value
          ],
         ['age',
          '=i',    # option accepts integer value
          18,
          strict => 1, # value must be in range
          range => [0, 100], # allowed range
          alias => ['year', 'years'] # possible aliases
          ],
         'External', # Head of second group
         ['browser',
          '=s',    # option accepts string value
          'tkweb',
          choices => ['mosaic', 'netscape',
                      'lynx', 'chimera'],
          # choices for the list widget in the GUI
          label => 'WWW browser program'
          # label for the GUI instead of 'browser'
          ],
         ['foo',
          '=f',    # option accepts float value
          undef,   # no default value
          help => 'This is a short help',
          # help string for usage() and the help balloon
          longhelp => 'And this is a slightly longer help'
          # longer help displayed in the GUI's help window
          ]);

OPTION ENTRY METHODS ^

These methods operate on option entries:

varref(optentry)

Return the variable reference for this entry.

optextra(optentry, optarg)

Return the value for the specified optarg argument. See the "OPTTABLE ARGUMENTS" section above for a list of possible arguments.

COMPATIBILITY ^

The argument to -opttable can be converted to a Getopt::Long compatible argument list with the following function:

  sub opttable_to_getopt {
      my(%args) = @_;
      my $options = $args{-options};
      my @getopt;
      for (@{$args{-opttable}}) {
        if (ref $_) {
            push @getopt, $_->[0].$_->[1];
            if (defined $_->[3] and ref $_->[3] ne 'HASH') {
                my %h = splice @$_, 3;
                $_->[3] = \%h;
            }
            if ($_->[3]{'var'}) {
                push @getopt, $_->[3]{'var'};
            } else {
                push @getopt, \$options->{$_->[0]};
            }
        }
      }
      @getopt;
  }

REQUIREMENTS ^

You need at least:

BUGS ^

Be sure to pass a real hash reference (not a uninitialized reference) to the -options switch in new Tk::Getopt. Use either:

    my %options;
    my $opt = new Tk::Getopt(-options => \%options ...)

or

    my $options = {};
    my $opt = new Tk::Getopt(-options => $options ...)

Note the initial assignement for $options in the second example.

Not all of Getopt::Long is supported (array and hash options, <>, abbrevs).

The option editor probably should be a real widget.

The option editor window may grow very large if NoteBook is not used (should use a scrollable pane).

If the user resizes the window, the buttons at bottom may disappear. This is confusing and it is advisable to disallow the resizing:

    $opt_editor = $opt->option_editor;
    $opt_editor->resizable(0,0);

The API will not be stable until version 1.00.

This manual is confusing. In fact, the whole module is confusing.

Setting variables in the editor should not set immediately the real variables. This should be done only by Apply and Ok buttons.

There's no -font option (you have to use tricks with the option db and a special Name for the option editor):

    $top->optionAdd("*somename*font" => $font);
    $opt->option_editor(Name => "somename", ...);

There's no (easy) way to get a large option editor fit on small screens. Try -font, if it would exist, but see above.

AUTHOR ^

Slaven Rezic <slaven@rezic.de>

This package is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

SEE ALSO ^

perl Getopt::Long Data::Dumper Tk Tk::FileDialog Tk::NoteBook Tk::Tiler Safe

syntax highlighting: