home *** CD-ROM | disk | FTP | other *** search
/ Hackers Magazine 57 / CdHackersMagazineNr57.iso / Software / Multimedia / k3d-setup-0.7.11.0.exe / lib / site-packages / gtk-2.0 / gobject / option.py < prev    next >
Encoding:
Python Source  |  2008-05-23  |  12.2 KB  |  334 lines

  1. # -*- Mode: Python; py-indent-offset: 4 -*-
  2. # pygobject - Python bindings for the GObject library
  3. # Copyright (C) 2006  Johannes Hoelzl
  4. #
  5. #   gobject/option.py: GOption command line parser
  6. #
  7. # This library is free software; you can redistribute it and/or
  8. # modify it under the terms of the GNU Lesser General Public
  9. # License as published by the Free Software Foundation; either
  10. # version 2.1 of the License, or (at your option) any later version.
  11. #
  12. # This library is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  15. # Lesser General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU Lesser General Public
  18. # License along with this library; if not, write to the Free Software
  19. # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
  20. # USA
  21.  
  22. """GOption command line parser
  23.  
  24. Extends optparse to use the GOptionGroup, GOptionEntry and GOptionContext
  25. objects. So it is possible to use the gtk, gnome_program and gstreamer command
  26. line groups and contexts.
  27.  
  28. Use this interface instead of the raw wrappers of GOptionContext and
  29. GOptionGroup in gobject.
  30. """
  31.  
  32. import sys
  33. import optparse
  34. from optparse import OptParseError, OptionError, OptionValueError, \
  35.                      BadOptionError, OptionConflictError
  36. import _gobject as gobject
  37.  
  38. __all__ = [
  39.     "OptParseError",
  40.     "OptionError",
  41.     "OptionValueError",
  42.     "BadOptionError",
  43.     "OptionConflictError"
  44.     "Option",
  45.     "OptionGroup",
  46.     "OptionParser",
  47.     "make_option",
  48. ]
  49.  
  50. class Option(optparse.Option):
  51.     """Represents a command line option
  52.  
  53.     To use the extended possibilities of the GOption API Option
  54.     (and make_option) are extended with new types and attributes.
  55.  
  56.     Types:
  57.         filename   The supplied arguments are read as filename, GOption
  58.                    parses this type in with the GLib filename encoding.
  59.  
  60.     Attributes:
  61.         optional_arg  This does not need a arguement, but it can be supplied.
  62.         hidden        The help list does not show this option
  63.         in_main       This option apears in the main group, this should only
  64.                       be used for backwards compatibility.
  65.  
  66.     Use Option.REMAINING as option name to get all positional arguments.
  67.  
  68.     NOTE: Every argument to an option is passed as utf-8 coded string, the only
  69.           exception are options which use the 'filename' type, its arguments
  70.           are passed as strings in the GLib filename encoding.
  71.  
  72.     For further help, see optparse.Option.
  73.     """
  74.     TYPES = optparse.Option.TYPES + (
  75.         'filename',
  76.     )
  77.  
  78.     ATTRS = optparse.Option.ATTRS + [
  79.         'hidden',
  80.         'in_main',
  81.         'optional_arg',
  82.     ]
  83.  
  84.     REMAINING = '--' + gobject.OPTION_REMAINING
  85.  
  86.     def __init__(self, *args, **kwargs):
  87.         optparse.Option.__init__(self, *args, **kwargs)
  88.         if not self._long_opts:
  89.             raise ValueError("%s at least one long option name.")
  90.  
  91.         if len(self._long_opts) < len(self._short_opts):
  92.             raise ValueError(
  93.                 "%s at least more long option names than short option names.")
  94.  
  95.         if not self.help:
  96.             raise ValueError("%s needs a help message.", self._long_opts[0])
  97.  
  98.  
  99.     def _set_opt_string(self, opts):
  100.         if self.REMAINING in opts:
  101.             self._long_opts.append(self.REMAINING)
  102.         optparse.Option._set_opt_string(self, opts)
  103.         if len(self._short_opts) > len(self._long_opts):
  104.             raise OptionError("goption.Option needs more long option names "
  105.                               "than short option names")
  106.  
  107.     def _to_goptionentries(self):
  108.         flags = 0
  109.  
  110.         if self.hidden:
  111.             self.flags |= gobject.OPTION_FLAG_HIDDEN
  112.  
  113.         if self.in_main:
  114.             self.flags |= gobject.OPTION_FLAG_IN_MAIN
  115.  
  116.         if self.takes_value():
  117.             if self.optional_arg:
  118.                 flags |= gobject.OPTION_FLAG_OPTIONAL_ARG
  119.         else:
  120.             flags |= gobject.OPTION_FLAG_NO_ARG
  121.  
  122.         if self.type == 'filename':
  123.             flags |= gobject.OPTION_FLAG_FILENAME
  124.  
  125.         for (long_name, short_name) in zip(self._long_opts, self._short_opts):
  126.             yield (long_name[2:], short_name[1], flags, self.help, self.metavar)
  127.  
  128.         for long_name in self._long_opts[len(self._short_opts):]:
  129.             yield (long_name[2:], '\0', flags, self.help, self.metavar)
  130.  
  131. class OptionGroup(optparse.OptionGroup):
  132.     """A group of command line options.
  133.  
  134.     Arguements:
  135.        name:             The groups name, used to create the
  136.                          --help-{name} option
  137.        description:      Shown as title of the groups help view
  138.        help_description: Shown as help to the --help-{name} option
  139.        option_list:      The options used in this group, must be option.Option()
  140.        defaults:         A dicitionary of default values
  141.        translation_domain: Sets the translation domain for gettext().
  142.  
  143.     NOTE: This OptionGroup does not exactly map the optparse.OptionGroup
  144.           interface. There is no parser object to supply, but it is possible
  145.           to set default values and option_lists. Also the default values and
  146.           values are not shared with the OptionParser.
  147.  
  148.     To pass a OptionGroup into a function which expects a GOptionGroup (e.g.
  149.     gnome_program_init() ). OptionGroup.get_option_group() can be used.
  150.  
  151.     For further help, see optparse.OptionGroup.
  152.     """
  153.     def __init__(self, name, description, help_description="",
  154.                  option_list=None, defaults=None,
  155.                  translation_domain=None):
  156.         optparse.OptionContainer.__init__(self, Option, 'error', description)
  157.         self.name = name
  158.         self.parser = None
  159.         self.help_description = help_description
  160.         if defaults:
  161.             self.defaults = defaults
  162.  
  163.         self.values = None
  164.  
  165.         self.translation_domain = translation_domain
  166.  
  167.         if option_list:
  168.             for option in option_list:
  169.                 self.add_option(option)
  170.  
  171.     def _create_option_list(self):
  172.         self.option_list = []
  173.         self._create_option_mappings()
  174.  
  175.     def _to_goptiongroup(self, parser):
  176.         def callback(option_name, option_value, group):
  177.             if option_name.startswith('--'):
  178.                 opt = self._long_opt[option_name]
  179.             else:
  180.                 opt = self._short_opt[option_name]
  181.  
  182.             try:
  183.                 opt.process(option_name, option_value, self.values, parser)
  184.             except OptionValueError, error:
  185.                 gerror = gobject.GError(str(error))
  186.                 gerror.domain = gobject.OPTION_ERROR
  187.                 gerror.code = gobject.OPTION_ERROR_BAD_VALUE
  188.                 gerror.message = str(error)
  189.                 raise gerror
  190.  
  191.         group = gobject.OptionGroup(self.name, self.description,
  192.                                     self.help_description, callback)
  193.         if self.translation_domain:
  194.             group.set_translation_domain(self.translation_domain)
  195.  
  196.         entries = []
  197.         for option in self.option_list:
  198.             entries.extend(option._to_goptionentries())
  199.         group.add_entries(entries)
  200.  
  201.         return group
  202.  
  203.     def get_option_group(self, parser = None):
  204.         """ Returns the corresponding GOptionGroup object.
  205.  
  206.         Can be used as parameter for gnome_program_init(), gtk_init().
  207.         """
  208.         self.set_values_to_defaults()
  209.         return self._to_goptiongroup(parser)
  210.  
  211.     def set_values_to_defaults(self):
  212.         for option in self.option_list:
  213.             default = self.defaults.get(option.dest)
  214.             if isinstance(default, basestring):
  215.                 opt_str = option.get_opt_string()
  216.                 self.defaults[option.dest] = option.check_value(
  217.                     opt_str, default)
  218.         self.values = optparse.Values(self.defaults)
  219.  
  220. class OptionParser(optparse.OptionParser):
  221.     """Command line parser with GOption support.
  222.  
  223.     NOTE: The OptionParser interface is not the exactly the same as the
  224.           optparse.OptionParser interface. Especially the usage parameter
  225.           is only used to show the metavar of the arguements.
  226.  
  227.     Attribues:
  228.         help_enabled:           The --help, --help-all and --help-{group}
  229.                                 options are enabled (default).
  230.         ignore_unknown_options: Do not throw a exception when a option is not
  231.                                 knwon, the option will be in the result list.
  232.  
  233.     OptionParser.add_option_group() does not only accept OptionGroup instances
  234.     but also gobject.OptionGroup, which is returned by gtk_get_option_group().
  235.  
  236.     Only gobject.option.OptionGroup and gobject.option.Option instances should
  237.     be passed as groups and options.
  238.  
  239.     For further help, see optparse.OptionParser.
  240.     """
  241.  
  242.     def __init__(self, *args, **kwargs):
  243.         if 'option_class' not in kwargs:
  244.             kwargs['option_class'] = Option
  245.         self.help_enabled = kwargs.pop('help_enabled', True)
  246.         self.ignore_unknown_options = kwargs.pop('ignore_unknown_options',
  247.                                                  False)
  248.         optparse.OptionParser.__init__(self, add_help_option=False,
  249.                                        *args, **kwargs)
  250.  
  251.     def set_usage(self, usage):
  252.         if usage is None:
  253.             self.usage = ''
  254.         elif usage.startswith("%prog"):
  255.             self.usage = usage[len("%prog"):]
  256.         else:
  257.             self.usage = usage
  258.  
  259.     def _to_goptioncontext(self, values):
  260.         if self.description:
  261.             parameter_string = self.usage + " - " + self.description
  262.         else:
  263.             parameter_string = self.usage
  264.         context = gobject.OptionContext(parameter_string)
  265.         context.set_help_enabled(self.help_enabled)
  266.         context.set_ignore_unknown_options(self.ignore_unknown_options)
  267.  
  268.         for option_group in self.option_groups:
  269.             if isinstance(option_group, gobject.OptionGroup):
  270.                 g_group = option_group
  271.             else:
  272.                 g_group = option_group.get_option_group(self)
  273.             context.add_group(g_group)
  274.  
  275.         def callback(option_name, option_value, group):
  276.             if option_name.startswith('--'):
  277.                 opt = self._long_opt[option_name]
  278.             else:
  279.                 opt = self._short_opt[option_name]
  280.             opt.process(option_name, option_value, values, self)
  281.  
  282.         main_group = gobject.OptionGroup(None, None, None, callback)
  283.         main_entries = []
  284.         for option in self.option_list:
  285.             main_entries.extend(option._to_goptionentries())
  286.         main_group.add_entries(main_entries)
  287.         context.set_main_group(main_group)
  288.  
  289.         return context
  290.  
  291.     def add_option_group(self, *args, **kwargs):
  292.         if isinstance(args[0], basestring):
  293.             optparse.OptionParser.add_option_group(self,
  294.                 OptionGroup(self, *args, **kwargs))
  295.             return
  296.         elif len(args) == 1 and not kwargs:
  297.             if isinstance(args[0], OptionGroup):
  298.                 if not args[0].parser:
  299.                     args[0].parser = self
  300.                 if args[0].parser is not self:
  301.                     raise ValueError("invalid OptionGroup (wrong parser)")
  302.             if isinstance(args[0], gobject.OptionGroup):
  303.                 self.option_groups.append(args[0])
  304.                 return
  305.         optparse.OptionParser.add_option_group(self, *args, **kwargs)
  306.  
  307.     def _get_all_options(self):
  308.         options = self.option_list[:]
  309.         for group in self.option_groups:
  310.             if isinstance(group, optparse.OptionGroup):
  311.                 options.extend(group.option_list)
  312.         return options
  313.  
  314.     def _process_args(self, largs, rargs, values):
  315.         context = self._to_goptioncontext(values)
  316.         largs.extend(context.parse([sys.argv[0]] + rargs))
  317.  
  318.     def parse_args(self, args=None, values=None):
  319.         try:
  320.             return optparse.OptionParser.parse_args(self, args, values)
  321.         except gobject.GError, error:
  322.             if error.domain != gobject.OPTION_ERROR:
  323.                 raise
  324.             if error.code == gobject.OPTION_ERROR_BAD_VALUE:
  325.                 raise OptionValueError(error.message)
  326.             elif error.code == gobject.OPTION_ERROR_UNKNOWN_OPTION:
  327.                 raise BadOptionError(error.message)
  328.             elif error.code == gobject.OPTION_ERROR_FAILED:
  329.                 raise OptParseError(error.message)
  330.             else:
  331.                 raise
  332.  
  333. make_option = Option
  334.