# Pmw megawidget base classes. # This module provides a foundation for building megawidgets. It # contains the MegaArchetype class which manages component widgets and # configuration options. Also provided are the MegaToplevel and # MegaWidget classes, derived from the MegaArchetype class. The # MegaToplevel class contains a Tkinter Toplevel widget to act as the # container of the megawidget. This is used as the base class of all # megawidgets that are contained in their own top level window, such # as a Dialog window. The MegaWidget class contains a Tkinter Frame # to act as the container of the megawidget. This is used as the base # class of all other megawidgets, such as a ComboBox or ButtonBox. # # Megawidgets are built by creating a class that inherits from either # the MegaToplevel or MegaWidget class. import os import string import sys import traceback import types import Tkinter # Special values used in index() methods of several megawidgets. END = ['end'] SELECT = ['select'] DEFAULT = ['default'] # Constant used to indicate that an option can only be set by a call # to the constructor. INITOPT = ['initopt'] _DEFAULT_OPTION_VALUE = ['default_option_value'] _useTkOptionDb = 0 # Symbolic constants for the indexes into an optionInfo list. _OPT_DEFAULT = 0 _OPT_VALUE = 1 _OPT_FUNCTION = 2 # Stacks _busyStack = [] # Stack which tracks nested calls to show/hidebusycursor (called # either directly or from activate()/deactivate()). Each element # is a dictionary containing: # 'newBusyWindows' : List of windows which had busy_hold called # on them during a call to showbusycursor(). # The corresponding call to hidebusycursor() # will call busy_release on these windows. # 'busyFocus' : The blt _Busy window which showbusycursor() # set the focus to. # 'previousFocus' : The focus as it was when showbusycursor() # was called. The corresponding call to # hidebusycursor() will restore this focus if # the focus has not been changed from busyFocus. _grabStack = [] # Stack of grabbed windows. It tracks calls to push/popgrab() # (called either directly or from activate()/deactivate()). The # window on the top of the stack is the window currently with the # grab. Each element is a dictionary containing: # 'grabWindow' : The window grabbed by pushgrab(). The # corresponding call to popgrab() will release # the grab on this window and restore the grab # on the next window in the stack (if there is one). # 'globalMode' : True if the grabWindow was grabbed with a # global grab, false if the grab was local # and 'nograb' if no grab was performed. # 'previousFocus' : The focus as it was when pushgrab() # was called. The corresponding call to # popgrab() will restore this focus. # 'deactivateFunction' : # The function to call (usually grabWindow.deactivate) if # popgrab() is called (usually from a deactivate() method) # on a window which is not at the top of the stack (that is, # does not have the grab or focus). For example, if a modal # dialog is deleted by the window manager or deactivated by # a timer. In this case, all dialogs above and including # this one are deactivated, starting at the top of the # stack. # Note that when dealing with focus windows, the name of the Tk # widget is used, since it may be the '_Busy' window, which has no # python instance associated with it. #============================================================================= # Functions used to forward methods from a class to a component. # Fill in a flattened method resolution dictionary for a class (attributes are # filtered out). Flattening honours the MI method resolution rules # (depth-first search of bases in order). The dictionary has method names # for keys and functions for values. def __methodDict(cls, dict): # the strategy is to traverse the class in the _reverse_ of the normal # order, and overwrite any duplicates. baseList = list(cls.__bases__) baseList.reverse() # do bases in reverse order, so first base overrides last base for super in baseList: __methodDict(super, dict) # do my methods last to override base classes for key, value in cls.__dict__.items(): # ignore class attributes if type(value) == types.FunctionType: dict[key] = value def __methods(cls): # Return all method names for a class. # Return all method names for a class (attributes are filtered # out). Base classes are searched recursively. dict = {} __methodDict(cls, dict) return dict.keys() # Function body to resolve a forwarding given the target method name and the # attribute name. The resulting lambda requires only self, but will forward # any other parameters. __stringBody = ( 'def %(method)s(this, *args, **kw): return ' + 'apply(this.%(attribute)s.%(method)s, args, kw)') # Get a unique id __counter = 0 def __unique(): global __counter __counter = __counter + 1 return str(__counter) # Function body to resolve a forwarding given the target method name and the # index of the resolution function. The resulting lambda requires only self, # but will forward any other parameters. The target instance is identified # by invoking the resolution function. __funcBody = ( 'def %(method)s(this, *args, **kw): return ' + 'apply(this.%(forwardFunc)s().%(method)s, args, kw)') def forwardmethods(fromClass, toClass, toPart, exclude = ()): # Forward all methods from one class to another. # Forwarders will be created in fromClass to forward method # invocations to toClass. The methods to be forwarded are # identified by flattening the interface of toClass, and excluding # methods identified in the exclude list. Methods already defined # in fromClass, or special methods with one or more leading or # trailing underscores will not be forwarded. # For a given object of class fromClass, the corresponding toClass # object is identified using toPart. This can either be a String # denoting an attribute of fromClass objects, or a function taking # a fromClass object and returning a toClass object. # Example: # class MyClass: # ... # def __init__(self): # ... # self.__target = TargetClass() # ... # def findtarget(self): # return self.__target # forwardmethods(MyClass, TargetClass, '__target', ['dangerous1', 'dangerous2']) # # ...or... # forwardmethods(MyClass, TargetClass, MyClass.findtarget, # ['dangerous1', 'dangerous2']) # In both cases, all TargetClass methods will be forwarded from # MyClass except for dangerous1, dangerous2, special methods like # __str__, and pre-existing methods like findtarget. # Allow an attribute name (String) or a function to determine the instance if type(toPart) != types.StringType: # check that it is something like a function if callable(toPart): # If a method is passed, use the function within it if hasattr(toPart, 'im_func'): toPart = toPart.im_func # After this is set up, forwarders in this class will use # the forwarding function. The forwarding function name is # guaranteed to be unique, so that it can't be hidden by subclasses forwardName = '__fwdfunc__' + __unique() fromClass.__dict__[forwardName] = toPart # It's not a valid type else: raise TypeError, 'toPart must be attribute name, function or method' # get the full set of candidate methods dict = {} __methodDict(toClass, dict) # discard special methods for ex in dict.keys(): if ex[:1] == '_' or ex[-1:] == '_': del dict[ex] # discard dangerous methods supplied by the caller for ex in exclude: if dict.has_key(ex): del dict[ex] # discard methods already defined in fromClass for ex in __methods(fromClass): if dict.has_key(ex): del dict[ex] for method, func in dict.items(): d = {'method': method, 'func': func} if type(toPart) == types.StringType: execString = \ __stringBody % {'method' : method, 'attribute' : toPart} else: execString = \ __funcBody % {'forwardFunc' : forwardName, 'method' : method} exec execString in d # this creates a method fromClass.__dict__[method] = d[method] #============================================================================= def setgeometryanddeiconify(window, geom): # To avoid flashes on X and to position the window correctly on NT # (caused by Tk bugs). if os.name == 'nt' or \ (os.name == 'posix' and sys.platform[:6] == 'cygwin'): # Require overrideredirect trick to stop window frame # appearing momentarily. redirect = window.overrideredirect() if not redirect: window.overrideredirect(1) window.deiconify() if geom is not None: window.geometry(geom) # Call update_idletasks to ensure NT moves the window to the # correct position it is raised. window.update_idletasks() window.tkraise() if not redirect: window.overrideredirect(0) else: if geom is not None: window.geometry(geom) # Problem!? Which way around should the following two calls # go? If deiconify() is called first then I get complaints # from people using the enlightenment or sawfish window # managers that when a dialog is activated it takes about 2 # seconds for the contents of the window to appear. But if # tkraise() is called first then I get complaints from people # using the twm window manager that when a dialog is activated # it appears in the top right corner of the screen and also # takes about 2 seconds to appear. #window.tkraise() # Call update_idletasks to ensure certain window managers (eg: # enlightenment and sawfish) do not cause Tk to delay for # about two seconds before displaying window. #window.update_idletasks() #window.deiconify() window.deiconify() if window.overrideredirect(): # The window is not under the control of the window manager # and so we need to raise it ourselves. window.tkraise() #============================================================================= class MegaArchetype: # Megawidget abstract root class. # This class provides methods which are inherited by classes # implementing useful bases (this class doesn't provide a # container widget inside which the megawidget can be built). def __init__(self, parent = None, hullClass = None): # Mapping from each megawidget option to a list of information # about the option # - default value # - current value # - function to call when the option is initialised in the # call to initialiseoptions() in the constructor or # modified via configure(). If this is INITOPT, the # option is an initialisation option (an option that can # be set by the call to the constructor but can not be # used with configure). # This mapping is not initialised here, but in the call to # defineoptions() which precedes construction of this base class. # # self._optionInfo = {} # Mapping from each component name to a tuple of information # about the component. # - component widget instance # - configure function of widget instance # - the class of the widget (Frame, EntryField, etc) # - cget function of widget instance # - the name of the component group of this component, if any self.__componentInfo = {} # Mapping from alias names to the names of components or # sub-components. self.__componentAliases = {} # Contains information about the keywords provided to the # constructor. It is a mapping from the keyword to a tuple # containing: # - value of keyword # - a boolean indicating if the keyword has been used. # A keyword is used if, during the construction of a megawidget, # - it is defined in a call to defineoptions() or addoptions(), or # - it references, by name, a component of the megawidget, or # - it references, by group, at least one component # At the end of megawidget construction, a call is made to # initialiseoptions() which reports an error if there are # unused options given to the constructor. # # After megawidget construction, the dictionary contains # keywords which refer to a dynamic component group, so that # these components can be created after megawidget # construction and still use the group options given to the # constructor. # # self._constructorKeywords = {} # List of dynamic component groups. If a group is included in # this list, then it not an error if a keyword argument for # the group is given to the constructor or to configure(), but # no components with this group have been created. # self._dynamicGroups = () if hullClass is None: self._hull = None else: if parent is None: parent = Tkinter._default_root # Create the hull. self._hull = self.createcomponent('hull', (), None, hullClass, (parent,)) _hullToMegaWidget[self._hull] = self if _useTkOptionDb: # Now that a widget has been created, query the Tk # option database to get the default values for the # options which have not been set in the call to the # constructor. This assumes that defineoptions() is # called before the __init__(). option_get = self.option_get _VALUE = _OPT_VALUE _DEFAULT = _OPT_DEFAULT for name, info in self._optionInfo.items(): value = info[_VALUE] if value is _DEFAULT_OPTION_VALUE: resourceClass = string.upper(name[0]) + name[1:] value = option_get(name, resourceClass) if value != '': try: # Convert the string to int/float/tuple, etc value = eval(value, {'__builtins__': {}}) except: pass info[_VALUE] = value else: info[_VALUE] = info[_DEFAULT] def destroy(self): # Clean up optionInfo in case it contains circular references # in the function field, such as self._settitle in class # MegaToplevel. self._optionInfo = {} if self._hull is not None: del _hullToMegaWidget[self._hull] self._hull.destroy() #====================================================================== # Methods used (mainly) during the construction of the megawidget. def defineoptions(self, keywords, optionDefs, dynamicGroups = ()): # Create options, providing the default value and the method # to call when the value is changed. If any option created by # base classes has the same name as one in , the # base class's value and function will be overriden. # This should be called before the constructor of the base # class, so that default values defined in the derived class # override those in the base class. if not hasattr(self, '_constructorKeywords'): # First time defineoptions has been called. tmp = {} for option, value in keywords.items(): tmp[option] = [value, 0] self._constructorKeywords = tmp self._optionInfo = {} self._initialiseoptions_counter = 0 self._initialiseoptions_counter = self._initialiseoptions_counter + 1 if not hasattr(self, '_dynamicGroups'): self._dynamicGroups = () self._dynamicGroups = self._dynamicGroups + tuple(dynamicGroups) self.addoptions(optionDefs) def addoptions(self, optionDefs): # Add additional options, providing the default value and the # method to call when the value is changed. See # "defineoptions" for more details # optimisations: optionInfo = self._optionInfo optionInfo_has_key = optionInfo.has_key keywords = self._constructorKeywords keywords_has_key = keywords.has_key FUNCTION = _OPT_FUNCTION for name, default, function in optionDefs: if '_' not in name: # The option will already exist if it has been defined # in a derived class. In this case, do not override the # default value of the option or the callback function # if it is not None. if not optionInfo_has_key(name): if keywords_has_key(name): value = keywords[name][0] optionInfo[name] = [default, value, function] del keywords[name] else: if _useTkOptionDb: optionInfo[name] = \ [default, _DEFAULT_OPTION_VALUE, function] else: optionInfo[name] = [default, default, function] elif optionInfo[name][FUNCTION] is None: optionInfo[name][FUNCTION] = function else: # This option is of the form "component_option". If this is # not already defined in self._constructorKeywords add it. # This allows a derived class to override the default value # of an option of a component of a base class. if not keywords_has_key(name): keywords[name] = [default, 0] def createcomponent(self, componentName, componentAliases, componentGroup, widgetClass, *widgetArgs, **kw): # Create a component (during construction or later). if self.__componentInfo.has_key(componentName): raise ValueError, 'Component "%s" already exists' % componentName if '_' in componentName: raise ValueError, \ 'Component name "%s" must not contain "_"' % componentName if hasattr(self, '_constructorKeywords'): keywords = self._constructorKeywords else: keywords = {} for alias, component in componentAliases: # Create aliases to the component and its sub-components. index = string.find(component, '_') if index < 0: self.__componentAliases[alias] = (component, None) else: mainComponent = component[:index] subComponent = component[(index + 1):] self.__componentAliases[alias] = (mainComponent, subComponent) # Remove aliases from the constructor keyword arguments by # replacing any keyword arguments that begin with *alias* # with corresponding keys beginning with *component*. alias = alias + '_' aliasLen = len(alias) for option in keywords.keys(): if len(option) > aliasLen and option[:aliasLen] == alias: newkey = component + '_' + option[aliasLen:] keywords[newkey] = keywords[option] del keywords[option] componentPrefix = componentName + '_' nameLen = len(componentPrefix) for option in keywords.keys(): if len(option) > nameLen and option[:nameLen] == componentPrefix: # The keyword argument refers to this component, so add # this to the options to use when constructing the widget. kw[option[nameLen:]] = keywords[option][0] del keywords[option] else: # Check if this keyword argument refers to the group # of this component. If so, add this to the options # to use when constructing the widget. Mark the # keyword argument as being used, but do not remove it # since it may be required when creating another # component. index = string.find(option, '_') if index >= 0 and componentGroup == option[:index]: rest = option[(index + 1):] kw[rest] = keywords[option][0] keywords[option][1] = 1 if kw.has_key('pyclass'): widgetClass = kw['pyclass'] del kw['pyclass'] if widgetClass is None: return None if len(widgetArgs) == 1 and type(widgetArgs[0]) == types.TupleType: # Arguments to the constructor can be specified as either # multiple trailing arguments to createcomponent() or as a # single tuple argument. widgetArgs = widgetArgs[0] widget = apply(widgetClass, widgetArgs, kw) componentClass = widget.__class__.__name__ self.__componentInfo[componentName] = (widget, widget.configure, componentClass, widget.cget, componentGroup) return widget def destroycomponent(self, name): # Remove a megawidget component. # This command is for use by megawidget designers to destroy a # megawidget component. self.__componentInfo[name][0].destroy() del self.__componentInfo[name] def createlabel(self, parent, childCols = 1, childRows = 1): labelpos = self['labelpos'] labelmargin = self['labelmargin'] if labelpos is None: return label = self.createcomponent('label', (), None, Tkinter.Label, (parent,)) if labelpos[0] in 'ns': # vertical layout if labelpos[0] == 'n': row = 0 margin = 1 else: row = childRows + 3 margin = row - 1 label.grid(column=2, row=row, columnspan=childCols, sticky=labelpos) parent.grid_rowconfigure(margin, minsize=labelmargin) else: # horizontal layout if labelpos[0] == 'w': col = 0 margin = 1 else: col = childCols + 3 margin = col - 1 label.grid(column=col, row=2, rowspan=childRows, sticky=labelpos) parent.grid_columnconfigure(margin, minsize=labelmargin) def initialiseoptions(self, dummy = None): self._initialiseoptions_counter = self._initialiseoptions_counter - 1 if self._initialiseoptions_counter == 0: unusedOptions = [] keywords = self._constructorKeywords for name in keywords.keys(): used = keywords[name][1] if not used: # This keyword argument has not been used. If it # does not refer to a dynamic group, mark it as # unused. index = string.find(name, '_') if index < 0 or name[:index] not in self._dynamicGroups: unusedOptions.append(name) if len(unusedOptions) > 0: if len(unusedOptions) == 1: text = 'Unknown option "' else: text = 'Unknown options "' raise KeyError, text + string.join(unusedOptions, ', ') + \ '" for ' + self.__class__.__name__ # Call the configuration callback function for every option. FUNCTION = _OPT_FUNCTION for info in self._optionInfo.values(): func = info[FUNCTION] if func is not None and func is not INITOPT: func() #====================================================================== # Method used to configure the megawidget. def configure(self, option=None, **kw): # Query or configure the megawidget options. # # If not empty, *kw* is a dictionary giving new # values for some of the options of this megawidget or its # components. For options defined for this megawidget, set # the value of the option to the new value and call the # configuration callback function, if any. For options of the # form _