4702l4

Listing 4. GladeControllerGenerator.py

#!/usr/bin/env python
"""GladeControllerGenerator.py
This module can generate stubbed Controller classes for Glade
top-level windows."""

import sys, string
from GladeProjectSignals import GladeProjectSignals

_moduleTemplate = '''#!/usr/bin/env python
"""This module provides a Controller for %(gladeFilename)s.

$Id$
$Author$"""

__version__ = "$Revision$"

import gtk, GladeBase

class Controller(GladeBase.Controller):
    """This is a controller for user interfaces instantiated from
    the %(toplevelName)s hierarchy in %(gladeFilename)s."""
    
%(signalHandlerStubs)s

def main():
    """Module mainline for standalone execution."""
    
    # This is just a dummy UI with no special view-updating
    # methods.  You will probably want to define your own UI class...
    ui = GladeBase.UI(%(gladeFilename)s, %(toplevelName)s)
    
    theController = Controller(ui)
    gtk.mainloop()
    
if __name__ == "__main__":
    main()'''

_methodTemplate = '''    def %(handlerName)s(self, *args):
        """"""
'''

class Error(Exception):  """For reporting errors detected by this module."""

class ControllerGenerator:
    """This class generates Controller class stubs for Glade top-level
    windows."""
    
    def generate(self, gladeFilename, widgetName):
        """Generate a new controller module stub.
        Returns the stub as a string."""

        self.widgetList = GladeProjectSignals(gladeFilename)
        widget = self.widgetList.widgets.get(widgetName)
        if not widget:
            raise Error("Can't find toplevel widget %s." % `widgetName`)
        
        signalHandlerStubs = self._signalHandlerStubs(widget)

        formatDict = {
            'gladeFilename': `gladeFilename`,
            'toplevelName': `widgetName`,
            'signalHandlerStubs': signalHandlerStubs
            }
        return  _moduleTemplate % formatDict

    def _signalHandlerStubs(self, widget):
        """Generate a string of signal handler stubs for handlers
        declared in widget's hierarchy."""
        
        stubs = []
        for handler in widget.handlers:
            stubs.append(self._oneSignalHandlerStub(handler))
        return string.join(stubs, "\n")

    def _oneSignalHandlerStub(self, handlerName):
        """Generate a stub for a single signal handler."""
        
        return _methodTemplate % {'handlerName': handlerName}
    
def showUsage(errorInfo=None):
    """Show how to use this module as a program, then exit."""
    if errorInfo:
        print errorInfo
        print
    print """Usage: %s glade_filename widget_name

    `glade_filename' is the name of a Glade project file.
    `widget_name' is the name of a toplevel widget within the project file.

    This program generates a stubbed controller module to manage the
    widget hierarchy rooted at `widget_name' in the specified
    `glade_filename'.
    """ % sys.argv[0]
    raise SystemExit

def main():
    """Module mainline (for standalone execution)"""
    if len(sys.argv) < 3:
        showUsage()

    gladeFilename, widgetName = sys.argv[1:3] # Ignore add'l args
    generator = ControllerGenerator()
    try:
        print generator.generate(gladeFilename, widgetName)
    except (Error, IOError), info:
        showUsage(info)
    
if __name__ == "__main__":
    main()
