widgetfactory.py 2.66 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
# widget factory
# tools to generate any type of plot widget you want

#    Copyright (C) 2004 Jeremy S. Sanders
#    Email: Jeremy Sanders <jeremy@jeremysanders.net>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License along
#    with this program; if not, write to the Free Software Foundation, Inc.,
#    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
##############################################################################

22
from __future__ import division
23
from ..compat import citems
24

25 26 27 28 29 30 31 32 33 34 35
class WidgetFactory(object):
    """Class to help produce any type of widget you want by name."""

    def __init__(self):
        """Initialise the class."""
        self.regwidgets = {}

    def register(self, classobj):
        """Register a class with the factory."""
        self.regwidgets[classobj.typename] = classobj

36
    def makeWidget(self, widgettype, parent, document, name=None, autoadd=True,
37 38 39 40 41
                   index=-1, **optargs):
        """Make a new widget of the appropriate type."""

        # check for / in name of widget
        if name is not None and name.find('/') != -1:
42
            raise ValueError('name cannot contain "/"')
43

44 45 46
        w = self.regwidgets[widgettype](parent, name=name)
        w.document = document
        w.linkToStylesheet()
47 48

        # set all the passed default settings
49
        for name, val in citems(optargs):
50 51 52
            # allow subsettings to be set using __ -> syntax
            name = name.replace('__', '/')

53
            document.resolveSettingPath(w, name).set(val)
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70

        if autoadd:
            w.addDefaultSubWidgets()

        # move around child afterwards, yuck
        if index != -1:
            del parent.children[-1]
            parent.children.insert(index, w)

        return w

    def getWidgetClass(self, name):
        """Get the class for the widget."""
        return self.regwidgets[name]

    def listWidgets(self):
        """Return an array of the widgets the factory can make."""
71
        return sorted(self.regwidgets)
72 73 74

    def listWidgetClasses(self):
        """Return list of allowed classes."""
75
        return list(self.regwidgets.values())
76 77 78

# singleton
thefactory = WidgetFactory()