[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
r6279 - in trunk/gnue-forms/src: . uidrivers/_base uidrivers/curses uidr
From: |
johannes |
Subject: |
r6279 - in trunk/gnue-forms/src: . uidrivers/_base uidrivers/curses uidrivers/gtk2 uidrivers/win32 uidrivers/wx |
Date: |
Tue, 14 Sep 2004 08:47:30 -0500 (CDT) |
Author: johannes
Date: 2004-09-14 08:47:28 -0500 (Tue, 14 Sep 2004)
New Revision: 6279
Modified:
trunk/gnue-forms/src/GFClient.py
trunk/gnue-forms/src/GFInstance.py
trunk/gnue-forms/src/uidrivers/_base/UIdriver.py
trunk/gnue-forms/src/uidrivers/curses/UIdriver.py
trunk/gnue-forms/src/uidrivers/gtk2/UIdriver.py
trunk/gnue-forms/src/uidrivers/win32/UIdriver.py
trunk/gnue-forms/src/uidrivers/wx/UIdriver.py
Log:
Improved exception handling, changed initialisation of UI drivers
Modified: trunk/gnue-forms/src/GFClient.py
===================================================================
--- trunk/gnue-forms/src/GFClient.py 2004-09-13 17:21:34 UTC (rev 6278)
+++ trunk/gnue-forms/src/GFClient.py 2004-09-14 13:47:28 UTC (rev 6279)
@@ -1,6 +1,9 @@
+# GNU Enterprise Forms - The Forms Client
#
-# This file is part of GNU Enterprise.
+# Copyright 2001-2004 Free Software Foundation
#
+# This file is part of GNU Enterprise
+#
# GNU Enterprise 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
@@ -16,173 +19,155 @@
# write to the Free Software Foundation, Inc., 59 Temple Place
# - Suite 330, Boston, MA 02111-1307, USA.
#
-# Copyright 2000-2004 Free Software Foundation
-#
-# FILE:
-# GFClient.py
-#
-# DESCRIPTION:
+# $Id$
+
"""
-Command line client startup file that parses args,
-imports the required UI, configures the controling
-GFInstance and passes control to it.
+Command line client startup file that parses args, imports the required UI,
+configures the controling GFInstance and passes control to it.
"""
-# NOTES:
-#
import os, sys
+from gnue.common.apps import GConfig, errors
from gnue.common.apps.GClientApp import *
-from gnue.common.apps import GDebug
-from gnue.common.apps import GConfig
-from gnue.common.datasources import GDataObjects, GConnections
from gnue.common.utils.FileUtils import dyn_import
-from gnue.common.logic.language import CompileError
from gnue.forms import VERSION
from gnue.forms.GFInstance import *
from gnue.forms.GFConfig import ConfigOptions
from gnue.forms.uidrivers._base import Exceptions
-class GFClient(GClientApp):
- #
- # GClientApp() overrides
- #
+
+# =============================================================================
+# GNU Enterprise Forms Client
+# =============================================================================
+
+class GFClient (GClientApp):
+
VERSION = VERSION
COMMAND = "gnue-forms"
- NAME = "GNUe Forms"
- USAGE = GClientApp.USAGE + " file"
+ NAME = "GNUe Forms"
+ USAGE = "%s file" % GClientApp.USAGE
SUMMARY = \
- _("GNUe Forms is the primary user interface to the GNU Enterprise
system.")
- USE_DATABASE_OPTIONS = 1
+ _("GNUe Forms is the primary user interface to the GNU Enterprise system.")
+ USE_DATABASE_OPTIONS = True
- def __init__(self, connections=None):
- self.addCommandOption('user_interface', 'u', 'interface',
- argument="ui", category="ui",
- help=_("The name of the user interface to use to display your form. "
- "For a list of interfaces, use the --help-ui options."))
+ # ---------------------------------------------------------------------------
+ # Constructor
+ # ---------------------------------------------------------------------------
- self.addCommandOption('help-ui', action=self.__listUIs,category="ui",
- help=_("Prints a list of user interfaces that forms supports."))
+ def __init__ (self, connections = None):
- self.addCommandOption('no-splash','s', category="ui",
- help=_('Disables the splash screen'))
+ self.addCommandOption ('user_interface', 'u', 'interface', argument = "ui",
+ category = "ui",
+ help = _("The name of the user interface to use to display your form. "
+ "For a list of interfaces, use the --help-ui options."))
- GClientApp.__init__(self, connections,'forms',ConfigOptions)
- self.configurationManager.registerAlias('gConfigForms', 'forms')
+ self.addCommandOption ('help-ui', action = self.__listUIs, category = "ui",
+ help = _("Prints a list of user interfaces that forms supports."))
- #
+ self.addCommandOption ('no-splash', 's', category = "ui",
+ help = _('Disables the splash screen'))
+
+ GClientApp.__init__(self, connections, 'forms', ConfigOptions)
+ self.configurationManager.registerAlias ('gConfigForms', 'forms')
+
+
+ # ---------------------------------------------------------------------------
# Run the client application
- #
- def run(self):
+ # ---------------------------------------------------------------------------
- #
+ def run (self):
+
# Initialize user interface
- #
- self.ui_type = self.OPTIONS['user_interface']
+ self.ui_type = self.OPTIONS ['user_interface']
if self.ui_type:
SPECIFIC_UI = True
else:
- SPECIFIC_UI = False
- self.ui_type = gConfigForms('DefaultUI')
+ SPECIFIC_UI = False
+ self.ui_type = gConfigForms ('DefaultUI')
while 1:
try:
- self._ui = dyn_import("gnue.forms.uidrivers.%s" % (self.ui_type))
+ self._ui = dyn_import ("gnue.forms.uidrivers.%s" % self.ui_type)
break
+
except ImportError, err:
- gDebug (1, u_("Unknown UI Driver: %s") % self.ui_type)
+ gDebug (1, "Unknown UI Driver: %s" % self.ui_type)
gDebug (1, err)
+
try:
- self._ui = dyn_import("%s" % (self.ui_type.replace('/','.')))
+ self._ui = dyn_import ("%s" % self.ui_type.replace ('/', '.'))
break
+
except ImportError, err:
- # raise # TODO: TEMPORARY
- gDebug (1, u_("Unknown UI Driver: %s") % self.ui_type)
- gDebug (1,err)
+ gDebug (1, "Unknown UI Driver: %s" % self.ui_type)
+ gDebug (1, err)
- self.handleStartupError(u_("Unknown UI driver specified: %s") \
- % self.ui_type)
+ raise StartupError, \
+ u_("Unknown UI driver specified: %s") % self.ui_type
except Exceptions.UIException, err:
-
- # If user specified a specific UI, don't cycle...
- if SPECIFIC_UI:
- self.handleStartupError(u_("Unable to load UI driver: %s") % err)
-
- if self.ui_type != 'curses':
+ if not SPECIFIC_UI and self.ui_type.lower () != 'curses':
self.ui_type = 'curses'
- else:
- self.handleStartupError(_("Unable to load any valid UI drivers."
- "Aborting."))
- if hasattr(self._ui,'handleStartupError') and not
self.OPTIONS['debug-level']:
- self.handleStartupError = self._ui.handleStartupError
-
-## if hasattr(self._ui,'handleUncaughtException'):
-## sys._orig_excepthook = sys.excepthook
-## sys.excepthook = self._ui.handleUncaughtException
-
-
- #
- # assign form file from 1st free argument
- #
- try:
- formfile = self.ARGUMENTS[0]
- except:
- try:
- basename=os.path.basename(sys.argv[0])
- # If no form specified, then see if this is a symlinked form definition
- if not (string.split(string.lower(basename),'.')[0] in
('gnue-forms','gfclient')):
- formfile = os.path.join (
-
GConfig.getInstalledBase('forms_appbase','common_appbase','install_prefix'),
- gConfigForms('FormDir'),basename+".gfd" )
else:
- raise IndexError
- except IndexError:
- self.handleStartupError (_("No Forms Definition File Specified."))
+ raise StartupError, u_("Unable to load UI driver: %s") % err
- #
# Get the user supplied parameters
- #
- userParameters = self.getCommandLineParameters(self.ARGUMENTS[1:])
+ userParameters = self.getCommandLineParameters (self.ARGUMENTS [1:])
-
- if gConfigForms('disableSplash') == True:
+ if gConfigForms ('disableSplash') == True:
self.disableSplash = True
else:
self.disableSplash = self.OPTIONS['no-splash']
- #
# Assign the proper login handler based upon the user interface choice
- #
- self.getConnectionManager().setLoginHandler(self._ui.UILoginHandler())
+ self.getConnectionManager ().setLoginHandler (self._ui.UILoginHandler ())
- #
- # Create the Instance that will control the loaded form(s)
- #
- instance = GFInstance(self,
- connections=self.connections, ui=self._ui,
- disableSplash=self.disableSplash,
- parameters=userParameters)
+ # Create the instance that will control the loaded form(s)
+ instance = GFInstance (self, self.connections, self._ui,
+ self.disableSplash, userParameters)
- instance.addFormFromFile(formfile)
- instance.addDialogs()
- try:
- instance.activate()
- except CompileError, msg:
- self.handleStartupError(msg)
+ # UI is now loaded and in a usable state, so use better exception display
+ self.showException = instance._uiinstance.showException
- def __listUIs(self):
- self.printHelpHeader()
+ # assign form file from 1st free argument
+ if len (self.ARGUMENTS):
+ formfile = self.ARGUMENTS [0]
+
+ else:
+ basename = os.path.basename (sys.argv [0])
+
+ # If no form specified, then see if this is a symlinked form definition
+ if not basename.lower ().split ('.') [0] in ('gnue-forms', 'gfclient'):
+ formfile = os.path.join (
+ GConfig.getInstalledBase ('forms_appbase', 'common_appbase',
+ 'install_prefix'),
+ gConfigForms ('FormDir'), basename + ".gfd")
+ else:
+ raise StartupError, _("No Forms Definition File Specified.")
+
+ instance.addFormFromFile (formfile)
+ instance.addDialogs ()
+ instance.activate ()
+
+
+ # ---------------------------------------------------------------------------
+ # List all available user interfaces
+ # ---------------------------------------------------------------------------
+
+ def __listUIs (self):
+ self.printHelpHeader ()
print _("The following interfaces are supported by GNUe Forms. "
"You can select an\ninterface via the --interface option.")
print
print _("To view general help, run this command with the --help option.")
print
print _('User interface command line options:')
- print self.buildHelpOptions("ui")
+ print self.buildHelpOptions ("ui")
+
# TODO: This should be automated
print "Available user interfaces:"
print " wx wxPython-based graphical interface"
@@ -190,10 +175,12 @@
print " qt QT3-based graphical interface"
print " win32 Native Windows graphical interface"
print " curses Text-based interface that uses ncurses"
- self.printHelpFooter()
- sys.exit()
+ self.printHelpFooter ()
+ sys.exit ()
-if __name__ == '__main__':
- GFClient().run()
+# =============================================================================
+# Main program
+# =============================================================================
-
+if __name__ == '__main__':
+ GFClient ().run ()
Property changes on: trunk/gnue-forms/src/GFClient.py
___________________________________________________________________
Name: svn:keywords
+ Id
Modified: trunk/gnue-forms/src/GFInstance.py
===================================================================
--- trunk/gnue-forms/src/GFInstance.py 2004-09-13 17:21:34 UTC (rev 6278)
+++ trunk/gnue-forms/src/GFInstance.py 2004-09-14 13:47:28 UTC (rev 6279)
@@ -1,6 +1,9 @@
+# GNU Enterprise Forms - Forms Instance Management
#
-# This file is part of GNU Enterprise.
+# Copyright 2001-2004 Free Software Foundation
#
+# This file is part of GNU Enterprise
+#
# GNU Enterprise 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
@@ -16,17 +19,14 @@
# write to the Free Software Foundation, Inc., 59 Temple Place
# - Suite 330, Boston, MA 02111-1307, USA.
#
-# Copyright 2001-2004 Free Software Foundation
-#
-# FILE:
-# GFInstance.py
-#
-# DESCRIPTION:
+# $Id$
+
"""
-GFInstance manages forms instances in a 1:N relationship.
-It sits between the UI and the form and passes events
-between the two in a semi-intelligent manner.
+GFInstance manages forms instances in a 1:N relationship. It sits between the
+UI and the form and passes events between the two in a semi-intelligent
+manner.
"""
+
# NOTES:
# Once all the events are moved back in here
# make the next/prec methods more generic in the GFForm
@@ -40,9 +40,8 @@
from gnue.forms.GFParser import loadFile
from gnue.forms import VERSION
from gnue.forms import GFKeyMapper
-from gnue.common.apps import GDebug, i18n
+from gnue.common.apps import i18n, errors
from gnue.common.datasources import GDataObjects, GConnections
-from gnue.common.datasources.Exceptions import LoginError
from gnue.common.datasources.GDataSource import getAppserverResource
from gnue.common import events
from gnue.common.utils.FileUtils import dyn_import
@@ -50,18 +49,35 @@
from gnue.common.logic.language import AbortRequest
from gnue.common.apps.GClientApp import *
-class GFInstance(events.EventAware):
- #
- # Initialize the class
- #
- def __init__(self, manager, connections, ui, disableSplash=0,
- parameters={}, parentContainer=None):
- #
+
+# =============================================================================
+# Exceptions
+# =============================================================================
+
+class FileOpenError (StartupError):
+ def __init__ (self, message):
+ msg = u_("Unable to open file\n%s") % message
+ StartupError.__init__ (self, msg)
+
+
+
+# =============================================================================
+# Forms instance manager class
+# =============================================================================
+
+class GFInstance (events.EventAware):
+
+ # ---------------------------------------------------------------------------
+ # Constructor
+ # ---------------------------------------------------------------------------
+
+ def __init__ (self, manager, connections, ui, disableSplash = False,
+ parameters = {}, parentContainer = None):
+
# Configure event handling
- #
- self.eventController = events.EventController()
- events.EventAware.__init__(self, self.eventController)
- self.registerEventListeners( {
+ self.eventController = events.EventController ()
+ events.EventAware.__init__ (self, self.eventController)
+ self.registerEventListeners ({
# First, all events are passed to the focus widget
'__before__' : self.__beforeEvent,
@@ -114,7 +130,7 @@
## # Dialog Support
## 'requestDIALOG' : self.activateDialog,
- } )
+ })
self.connections = connections # Link to the GBaseApp's GConnections
self.manager = manager # Link to the GBaseApp Instance that
@@ -128,22 +144,27 @@
self._parentContainer = parentContainer
- #
# Load user customized key mappings
- #
options = gConfigDict()
mapping = {}
- for key in options.keys():
- if string.lower(key)[:4] == 'key_':
- mapping[key[4:]] = options[key]
+ for key in options.keys ():
+ if string.lower (key) [:4] == 'key_':
+ mapping [key [4:]] = options [key]
- GFKeyMapper.KeyMapper.loadUserKeyMap(mapping)
+ GFKeyMapper.KeyMapper.loadUserKeyMap (mapping)
+ # Construct an instance of the UI driver
+ self._uiinstance = self._uimodule.GFUserInterface (self.eventController,
+ disableSplash = self._disableSplash,
+ parentContainer = self._parentContainer)
+ # ---------------------------------------------------------------------------
+ # Add the basic dialogs
+ # ---------------------------------------------------------------------------
- def addDialogs(self):
+ def addDialogs (self):
"""
Loads the base dialogs into memory.
@@ -151,183 +172,166 @@
dialog and error dialogs.
"""
-
- #
# Import and register dialogs
- #
- basedir = os.path.dirname(sys.modules[self.__module__].__file__)
- basedir +='/dialogs/'
- for dialogName in dircache.listdir(basedir):
- #try:
- if dialogName[0] != '_' and dialogName != '.svn':
+ basedir = os.path.dirname (sys.modules [self.__module__].__file__)
+ basedir = os.path.join (basedir, 'dialogs')
- if os.path.isfile(basedir+dialogName) and
os.path.splitext(dialogName)[1] == ".py":
- dialogName = os.path.splitext(dialogName)[0]
- dialog = dyn_import('gnue.forms.dialogs.%s' %(dialogName))
- elif os.path.isdir(basedir+dialogName):
- dialog = dyn_import('gnue.forms.dialogs.%s' %(dialogName))
- try:
- self.addFormFromBuffer(dialog.buildForm())
- except StandardError, mesg:
- print "WARNING: Cannot build %s form \n%s" % (dialogName,mesg)
+ for dialogName in dircache.listdir (basedir):
- #except ImportError, mesg:
- # GDebug.printMesg(2,"dialogs.%s doesn't appear to be a valid dialog"
% (dialogName))
- # GDebug.printMesg(5,' --> %s' % (mesg))
+ if dialogName [0] == '_' or dialogName == '.svn':
+ continue
+ filename = os.path.join (basedir, dialogName)
+ (name, ext) = os.path.splitext (dialogName)
- def addFormFromBuffer(self,buffer):
+ if os.path.isfile (filename) and ext == '.py':
+ dialog = dyn_import ('gnue.forms.dialogs.%s' % name)
+
+ elif os.path.isdir (filename):
+ dialog = dyn_import ('gnue.forms.dialogs.%s' % dialogName)
+
+ else:
+ continue
+
+ try:
+ self.addFormFromBuffer (dialog.buildForm ())
+
+ except StandardError, mesg:
+ print "WARNING: Cannot build %s form \n%s" % (dialogName, mesg)
+
+
+ # ---------------------------------------------------------------------------
+ # Load a form from a buffer
+ # ---------------------------------------------------------------------------
+
+ def addFormFromBuffer (self, buffer):
"""
- Loads a GObj based form tree when passed a string containing
- gfd markup.
+ Loads a GObj based form tree when passed a string containing gfd markup.
- @param fileName: A string containing a URI
+ @param buffer: A string containing the forms definition (gfd)
"""
+
try:
- fileHandle=openBuffer(buffer)
- self.addFormFromFilehandle(fileHandle)
- fileHandle.close()
+ fileHandle = openBuffer (buffer)
+ self.addFormFromFilehandle (fileHandle)
+ fileHandle.close ()
except IOError, mesg:
- self.manager.handleStartupError (u_("Unable to open file\n\n %s") \
- % mesg)
+ raise FileOpenError, mesg
- def addFormFromFile(self,fileName):
+
+ # ---------------------------------------------------------------------------
+ # Load a form from a file specified by it's filename
+ # ---------------------------------------------------------------------------
+
+ def addFormFromFile (self, fileName):
"""
Loads a GObj based form tree when passed a file name.
@param fileName: A string containing a URI
"""
+
try:
if fileName [:12] == 'appserver://':
# (w, h) = self._uimodule.getMaxFormSize ()
param = {'language': i18n.language, 'formwidth': 80, 'formheight': 20}
fileHandle = getAppserverResource (fileName, param, self.connections)
else:
- fileHandle=openResource(fileName)
+ fileHandle = openResource (fileName)
- self.addFormFromFilehandle(fileHandle)
- fileHandle.close()
+ self.addFormFromFilehandle (fileHandle)
+ fileHandle.close ()
-
except IOError, mesg:
- self.manager.handleStartupError(u_("Unable to open file\n\n %s") \
- % mesg)
+ raise FileOpenError, mesg
- except Exception, mesg:
- self.manager.handleStartupError ("%s" % mesg)
+ # ---------------------------------------------------------------------------
+ # Add a form from a file-like object specified by it's filehandle
+ # ---------------------------------------------------------------------------
- def addFormFromFilehandle(self,fileHandle):
+ def addFormFromFilehandle (self, fileHandle):
"""
Loads a GObj based form tree when passed a valid python file handle.
- A copy of the instance is passed into the parser so that
- it can work with things like the GConnections stored in
- the base app
+ A copy of the instance is passed into the parser so that it can work with
+ things like the GConnections stored in the base app.
@param fileHandle: A python file handle.
"""
- #
- # Load the file bypassing the initialization
- # We bypass the initialization because <dialog>s are
- # really <form>s and they don't like being children
+ # Load the file bypassing the initialization We bypass the initialization
+ # because <dialog>s are really <form>s and they don't like being children
# of another form
- #
- form = loadFile (fileHandle, self, initialize=0)
+ form = loadFile (fileHandle, self, initialize = 0)
- #
# Extract the child <dialog>s from the main form tree
- #
- self.reapSubforms(form)
+ self.reapSubforms (form)
- #
# Add the main form into the dictionary
- #
- self._formsDictionary[form.name] = form
+ self._formsDictionary [form.name] = form
- #
- # removes the subforms from the main tree before
- # any UI stuff is constructed.
- #
- # NOTE: using list.remove() will not work in a
- # for loop as it skips the very next item
- # in the list
- #
- def reapSubforms(self,formTree):
- childList = []
- for child in formTree._children:
- if isinstance(child, GFForm):
+ # ---------------------------------------------------------------------------
+ # Remove sub-forms from the main tree
+ # ---------------------------------------------------------------------------
+
+ def reapSubforms (self, formTree):
+
+ for child in formTree._children [:]:
+ if isinstance (child, GFForm):
child._parent = None
- self._formsDictionary[child.name] = child
- else:
- childList.append(child)
- formTree._children = childList
+ self._formsDictionary [child.name] = child
+ formTree._children.remove (child)
- #
- # activate
- #
- # Tells the instance to bring up it's UI, activate the __main__ form,
- # and pass control to the UI
- #
- def activate(self):
- #
+
+ # ---------------------------------------------------------------------------
+ # Initialize the UI and activate the main form
+ # ---------------------------------------------------------------------------
+
+ def activate (self):
+
# Initialize all the forms loaded into memory
- #
try:
- for dialog in self._formsDictionary.keys():
- object = self._formsDictionary[dialog]
- object.phaseInit()
+ for formObject in self._formsDictionary.values ():
+ formObject.phaseInit ()
- except GConnections.Error, mesg:
- self.manager.handleStartupError(mesg)
-
except GDataObjects.ConnectError, mesg:
- self.manager.handleStartupError(
- u_("Unable to login to datasource.\n\n %s") % mesg)
+ raise StartupError, \
+ u_("Unable to login to datasource.\n\n %s") % mesg
except GDataObjects.ConnectionError, mesg:
- self.manager.handleStartupError(
- u_("Error while communicating with datasource.\n\n %s") % mesg)
+ raise StartupError, \
+ u_("Error while communicating with datasource.\n\n %s") % mesg
- except GDataObjects.Error, mesg:
- self.manager.handleStartupError(mesg)
+ self._uiinstance.initialize ()
-
- #
- # Construct an instance of the UI driver
- self._uiinstance = self._uimodule.GFUserInterface(self.eventController,
disableSplash=self._disableSplash, parentContainer=self._parentContainer)
- self._uiinstance.initialize()
-
- #
# Build the UIs for all the forms
- #
- for dialog in self._formsDictionary.keys():
- self.buildForm(dialog)
+ for dialog in self._formsDictionary.keys ():
+ self.buildForm (dialog)
- #
# Bring up the main form
- #
- self.activateForm('__main__')
- self._uiinstance.mainLoop()
+ self.activateForm ('__main__')
+ self._uiinstance.mainLoop ()
- #
- # Builds a UI based upon a specific form and
- # sets that form to active status
- #
+
+
+ # ---------------------------------------------------------------------------
+ # Activate a given form
+ # ---------------------------------------------------------------------------
+
def activateForm (self, formName = '__main__', parameters = {}, modal = 0):
- form = self._formsDictionary[formName]
- if parameters != {}:
- form._parameters=parameters
+ form = self._formsDictionary [formName]
+ if len (parameters.keys ()):
+ form._parameters = parameters
+
if not form._currentEntry:
- raise _("There are no navigable widgets in this form. "
- "Unable to display.")
+ raise errors.ApplicationError, \
+ _("There are no navigable widgets in this form. Unable to display.")
- form.processTrigger('On-Activation')
+ form.processTrigger ('On-Activation')
self._uiinstance.activateForm (formName, modal)
@@ -336,474 +340,612 @@
form.refreshDisplay (form)
self.updateStatus (form)
- #
- # buildForm
- #
- # Requests that the ui driver build a user interface
- # for a form tree.
- #
- def buildForm(self,formName='__main__'):
- form = self._formsDictionary[formName]
- self._uiinstance.buildForm(form, formName)
+ # ---------------------------------------------------------------------------
+ # Build a user interface for a form tree
+ # ---------------------------------------------------------------------------
- #
- #
+ def buildForm (self, formName = '__main__'):
+
+ form = self._formsDictionary [formName]
+ self._uiinstance.buildForm (form, formName)
+
+
+ # ===========================================================================
# UI FUNCTIONS
- #
- # Routines to update parts of the UI's status bar
- #
- def updateInsertMode(self, form):
- self.updateStatusBar(insertMode=form._insertMode, form=form)
+ # ===========================================================================
- def updateRecordCounter(self,form):
- self.updateStatusBar(currentRecord=form._currentBlock._currentRecord+1,
- maxRecord=form._currentBlock._recordCount, form=form)
+ # ---------------------------------------------------------------------------
+ # Update Statusbar: Insert Mode flag
+ # ---------------------------------------------------------------------------
- def updatePageCounter(self, form):
- maxPages = len(form._layout._pageList)
- count = form._layout._pageList.index(form._currentPage)
- self.updateStatusBar(currentPage=count+1,maxPage=maxPages, form=form)
+ def updateInsertMode (self, form):
- def updateTip(self, form):
+ self.updateStatusBar (insertMode = form._insertMode, form = form)
+
+
+ # ---------------------------------------------------------------------------
+ # Update Statusbar: Record counter
+ # ---------------------------------------------------------------------------
+
+ def updateRecordCounter (self, form):
+
+ self.updateStatusBar (currentRecord = form._currentBlock._currentRecord +1,
+ maxRecord = form._currentBlock._recordCount, form = form)
+
+
+ # ---------------------------------------------------------------------------
+ # Update Statusbar: Page counter
+ # ---------------------------------------------------------------------------
+
+ def updatePageCounter (self, form):
+
+ maxPages = len (form._layout._pageList)
+ count = form._layout._pageList.index (form._currentPage)
+ self.updateStatusBar (currentPage = count + 1, maxPage = maxPages,
+ form = form)
+
+
+ # ---------------------------------------------------------------------------
+ # Update Statusbar: Tip
+ # ---------------------------------------------------------------------------
+
+ def updateTip (self, form):
+
tip = ''
if form._currentEntry:
- if form._currentEntry.getOption('tip'):
- tip = form._currentEntry.getOption('tip')
- self.updateStatusBar(tip=tip, form=form)
+ if form._currentEntry.getOption ('tip'):
+ tip = form._currentEntry.getOption ('tip')
+ self.updateStatusBar (tip = tip, form = form)
- #
- # updateRecordStatus
- #
- # Determine the status of the current record
- # in the current block.
- #
+
+ # ---------------------------------------------------------------------------
+ # Update Statusbar: Record status
+ # ---------------------------------------------------------------------------
+
def updateRecordStatus(self, form):
- if form._currentBlock._resultSet.current.isDeleted():
+
+ if form._currentBlock._resultSet.current.isDeleted ():
status = 'deleted'
- elif form._currentBlock._resultSet.current.isPending():
+ elif form._currentBlock._resultSet.current.isPending ():
status = 'modified'
elif form._currentBlock.mode == 'query':
status = 'query'
else:
status = 'saved'
- self.updateStatusBar(recordStatus=status, form= form)
- #
- # updateStatus
- #
- # Calls all the various update status bar
- # functions to ensure everything is refreshed
- #
- def updateStatus(self, form):
- self.updateTip(form=form)
- self.updateInsertMode(form=form)
- self.updateRecordCounter(form=form)
- self.updateRecordStatus(form=form)
- self.updatePageCounter(form=form)
+ self.updateStatusBar (recordStatus = status, form = form)
+
+ # ---------------------------------------------------------------------------
+ # Update Statusbar: all fields of the status bar
+ # ---------------------------------------------------------------------------
+
+ def updateStatus (self, form):
+ self.updateTip (form = form)
+ self.updateInsertMode (form = form)
+ self.updateRecordCounter (form = form)
+ self.updateRecordStatus (form = form)
+ self.updatePageCounter (form = form)
+
+
#
# updateStatusBar
#
# generates the event to the UI that
# tells it to update it's status bar
- #
- def updateStatusBar(self, tip=None, recordStatus=None, insertMode=None,
- currentRecord=None,maxRecord=None, currentPage=None,
- maxPage=None, form=None):
- try:
- if not tip:
- tip = self.__lasttip
- except:
- pass
+
+ # ---------------------------------------------------------------------------
+ # Update the status bar
+ # ---------------------------------------------------------------------------
+
+ def updateStatusBar (self, tip = None, recordStatus = None,
+ insertMode = None, currentRecord = None, maxRecord = None,
+ currentPage = None, maxPage = None, form = None):
+
+ if tip is None and hasattr (self, '__lasttip'):
+ tip = self.__lasttip
+
self.__lasttip = tip
- self.dispatchEvent('uiUPDATESTATUS',tip=tip, recordStatus=recordStatus,
- insertMode=insertMode, currentRecord=currentRecord,
- maxRecord=maxRecord, currentPage=currentPage,
- maxPage=maxPage, _form=form)
+ self.dispatchEvent ('uiUPDATESTATUS',
+ tip = tip,
+ recordStatus = recordStatus,
+ insertMode = insertMode,
+ currentRecord = currentRecord,
+ maxRecord = maxRecord,
+ currentPage = currentPage,
+ maxPage = maxPage,
+ _form = form)
- #
- #
+
+ # ===========================================================================
# EVENT FUNCTIONS
- #
- # From here down should be nothing but eventListeners listed
- # in the __init__ above.
- #
+ # ===========================================================================
+
+ # From here down should be nothing but eventListeners listed in the __init__
+ # above.
- #
- # _entryUpdated
- #
- # Common code snipped called when something has changed with an
- # entry and it has to update the stat bar. Used to cut down on
- # repeated code.
- #
- def _entryUpdated(self, form):
- self.dispatchEvent('gotoENTRY',object=form._currentEntry, _form=form)
- self.updateRecordCounter(form)
- self.updateRecordStatus(form)
+ # ---------------------------------------------------------------------------
+ # Update status bar due to changes in an entry
+ # ---------------------------------------------------------------------------
- def __beforeEvent(self, event):
+ def _entryUpdated (self, form):
"""
+ Common code snipped called when something has changed with an entry and it
+ has to update the status bar. Used to cut down on repeated code.
+ """
+ self.dispatchEvent ('gotoENTRY', object = form._currentEntry, _form = form)
+ self.updateRecordCounter (form)
+ self.updateRecordStatus (form)
+
+
+ # ---------------------------------------------------------------------------
+ # Handle an event before it's sent to usual event processing
+ # ---------------------------------------------------------------------------
+
+ def __beforeEvent (self, event):
+ """
This is called before any normal event processing is done. This method
passes the event to the current focus widget and sees if that widget wants
to handle that event.
@param event: The event currently being processed.
"""
+
if hasattr (event, '_form') and event._form._currentEntry:
- # If the display will need to be refreshed,
- # then the proxied event should set this to 1
+ # If the display will need to be refreshed, then the proxied event should
+ # set this to 1
event.refreshDisplay = 0
# Pass off the event to the current entry's event handler
- event._form._currentEntry.subEventHandler.dispatchEvent(event)
+ event._form._currentEntry.subEventHandler.dispatchEvent (event)
# Refresh entry display if appropriate
if event.refreshDisplay:
# FIXME: This is not clean. Maybe the event should set event.__after__?
if hasattr (event._form._currentEntry, '_displayHandler'):
- event._form._currentEntry._displayHandler.generateRefreshEvent()
- event._form.refreshUIEvents()
+ event._form._currentEntry._displayHandler.generateRefreshEvent ()
- # If the entry needs an error message displayed,
- # then the proxied event should set this to the
- # message text
+ event._form.refreshUIEvents ()
+
+ # If the entry needs an error message displayed, then the proxied event
+ # should set this to the message text
if event.__errortext__:
self.displayMessageBox (event.__errortext__, 'Error')
- def nextEntry(self, event):
+
+ # ---------------------------------------------------------------------------
+ # Move focus to the next entry
+ # ---------------------------------------------------------------------------
+
+ def nextEntry (self, event):
"""
- Called whenever an event source has requested that the
- focus change to the next data entry object
+ Called whenever an event source has requested that the focus change to the
+ next data entry object
@param event: The event currently being processed.
"""
- if not event._form.endEditing():
+
+ if not event._form.endEditing ():
return
+
origEntry = event._form._currentEntry
- event._form._currentEntry.processTrigger('ON-NEXT-ENTRY',
ignoreAbort=False)
+ event._form._currentEntry.processTrigger ('ON-NEXT-ENTRY',
+ ignoreAbort = False)
+
# If the trigger changed focus, no need in us doing it too...
if origEntry == event._form._currentEntry:
- message = event._form.nextEntry()
+ message = event._form.nextEntry ()
if message:
self.displayMessageBox (message)
return
- self.dispatchEvent('gotoENTRY',object=event._form._currentEntry,
_form=event._form)
- self.updateRecordStatus(event._form)
- self.updateTip(event._form)
- def previousEntry(self, event):
+ self.dispatchEvent ('gotoENTRY', object = event._form._currentEntry,
+ _form = event._form)
+
+ self.updateRecordStatus (event._form)
+ self.updateTip (event._form)
+
+
+ # ---------------------------------------------------------------------------
+ # Move focus to the previous entry
+ # ---------------------------------------------------------------------------
+
+ def previousEntry (self, event):
"""
- Called whenever an event source has requested that the
- focus change to the next data entry object
+ Called whenever an event source has requested that the focus change to the
+ next data entry object
param event: The event that requested the previous entry.
"""
- if not event._form.endEditing():
+ if not event._form.endEditing ():
return
origEntry = event._form._currentEntry
- event._form._currentEntry.processTrigger('ON-PREVIOUS-ENTRY',
ignoreAbort=False)
+ event._form._currentEntry.processTrigger ('ON-PREVIOUS-ENTRY',
+ ignoreAbort = False)
+
# If the trigger changed focus, no need in us doing it too...
if origEntry == event._form._currentEntry:
- event._form.previousEntry()
- self.dispatchEvent('gotoENTRY',object=event._form._currentEntry,
_form=event._form)
+ event._form.previousEntry ()
+ self.dispatchEvent ('gotoENTRY', object = event._form._currentEntry,
+ _form = event._form)
- self.updateRecordStatus(event._form)
- self.updateTip(event._form)
+ self.updateRecordStatus (event._form)
+ self.updateTip (event._form)
- #
- # nextBlock
- #
- # Called whenever an event source has requested that the
- # focus change to the next data entry block
- #
- def nextBlock(self,event):
- if not event._form.endEditing():
+
+ # ---------------------------------------------------------------------------
+ # Move focus to the next block
+ # ---------------------------------------------------------------------------
+
+ def nextBlock (self,event):
+ """
+ Called whenever an event source has requested that the focus change to the
+ next data entry block
+ """
+
+ if not event._form.endEditing ():
return
- event._form.nextBlock()
- self.dispatchEvent('gotoENTRY',object=event._form._currentEntry,
_form=event._form)
- self.updateStatus(event._form)
- #
- # previousBlock
- #
- # Called whenever an event source has requested that the
- # focus change to the next data entry block
- #
- def previousBlock(self, event):
- if not event._form.endEditing():
+ event._form.nextBlock ()
+ self.dispatchEvent ('gotoENTRY', object = event._form._currentEntry,
+ _form = event._form)
+ self.updateStatus (event._form)
+
+
+ # ---------------------------------------------------------------------------
+ # Move focus to the previous block
+ # ---------------------------------------------------------------------------
+
+ def previousBlock (self, event):
+ """
+ Called whenever an event source has requested that the focus change to the
+ next data entry block
+ """
+
+ if not event._form.endEditing ():
return
- event._form.previousBlock()
- self.dispatchEvent('gotoENTRY',object=event._form._currentEntry,
_form=event._form)
- self.updateStatus(event._form)
+ event._form.previousBlock ()
+ self.dispatchEvent ('gotoENTRY', object = event._form._currentEntry,
+ _form = event._form)
+ self.updateStatus (event._form)
- #
- # nextPage
- #
- # Called to make the form jump to the next page
- #
- def nextPage(self,event):
- if not event._form.endEditing():
+
+ # ---------------------------------------------------------------------------
+ # Jump to the next page
+ # ---------------------------------------------------------------------------
+
+ def nextPage (self, event):
+ """
+ Called to make the form jump to the next page
+ """
+
+ if not event._form.endEditing ():
return
+
currentIndex =
event._form._layout._pageList.index(event._form._currentPage)
- if currentIndex == len(event._form._layout._pageList)-1:
+ if currentIndex == len (event._form._layout._pageList) - 1:
nextIndex = 0
else:
- nextIndex = currentIndex+1
- event._form.findAndChangeFocus(event._form._layout._pageList[nextIndex])
- self.dispatchEvent('gotoENTRY',object=event._form._currentEntry,
_form=event._form)
- self.updateStatus(event._form)
+ nextIndex = currentIndex + 1
- #
- # previousPage
- #
- # Called to make the form jump to the previous page
- #
- def previousPage(self,event):
- if not event._form.endEditing():
+ event._form.findAndChangeFocus (event._form._layout._pageList [nextIndex])
+ self.dispatchEvent ('gotoENTRY', object = event._form._currentEntry,
+ _form = event._form)
+ self.updateStatus (event._form)
+
+
+ # ---------------------------------------------------------------------------
+ # Jump to the previous page
+ # ---------------------------------------------------------------------------
+
+ def previousPage (self, event):
+ """
+ Called to make the form jump to the previous page
+ """
+
+ if not event._form.endEditing ():
return
- currentIndex =
event._form._layout._pageList.index(event._form._currentPage)
-
event._form.findAndChangeFocus(event._form._layout._pageList[currentIndex-1])
- self.dispatchEvent('gotoENTRY',object=event._form._currentEntry,
_form=event._form)
- self.updateStatus(event._form)
- #
- # gotoPage
- #
- # Called to make the form jump to a specific page
- #
- def gotoPage(self,event):
- if not event._form.endEditing():
+ pageList = event._form._layout._pageList
+ currentIndex = pageList.index (event._form._currentPage)
+ event._form.findAndChangeFocus (pageList [currentIndex - 1])
+
+ self.dispatchEvent ('gotoENTRY', object = event._form._currentEntry,
+ _form = event._form)
+ self.updateStatus (event._form)
+
+ # ---------------------------------------------------------------------------
+ # Jump to a specific page
+ # ---------------------------------------------------------------------------
+
+ def gotoPage (self, event):
+ """
+ Jump to a specific page of the form
+ """
+
+ if not event._form.endEditing ():
return
- newpage = event._form._layout._pageList[event.data]
- event._form.findAndChangeFocus(newpage)
- self.dispatchEvent('gotoENTRY',object=event._form._currentEntry,
_form=event._form)
- self.updateStatus(event._form)
- #
- # previousRecord
- #
- # Called enever an event source has requested that the
- # form advance to the next record in memory
- #
- def prevRecord(self, event):
- if not event._form.endEditing():
+ newpage = event._form._layout._pageList [event.data]
+ event._form.findAndChangeFocus (newpage)
+
+ self.dispatchEvent ('gotoENTRY', object = event._form._currentEntry,
+ _form = event._form)
+ self.updateStatus (event._form)
+
+
+ # ---------------------------------------------------------------------------
+ # Jump to the previous record
+ # ---------------------------------------------------------------------------
+
+ def prevRecord (self, event):
+ """
+ Called whenever an event source has requested that the form moves to the
+ previous record in memory
+ """
+
+ if not event._form.endEditing ():
return
- message = event._form.prevRecord()
+
+ message = event._form.prevRecord ()
if message:
self.displayMessageBox (message)
+ return
+ self._entryUpdated (event._form)
+
+
+ # ---------------------------------------------------------------------------
+ # Jump to the next record
+ # ---------------------------------------------------------------------------
+
+ def nextRecord (self, event):
+ """
+ Called whenever an event source has requested that the form advance to the
+ next record in memory
+ """
+
+ if not event._form.endEditing ():
return
- self._entryUpdated(event._form)
- #
- # nextRecord
- #
- # Called whenever an event source has requested that the
- # form advance to the next record in memory
- #
- def nextRecord(self, event):
- if not event._form.endEditing():
- return
- message = event._form.nextRecord()
+ message = event._form.nextRecord ()
if message:
self.displayMessageBox (message)
+ return
+ self._entryUpdated (event._form)
+
+
+ # ---------------------------------------------------------------------------
+ # Jump to the first record
+ # ---------------------------------------------------------------------------
+
+ def firstRecord (self, event):
+ """
+ Called whenever an event source has requested that the form advance to the
+ first record in memory
+ """
+
+ if not event._form.endEditing ():
return
- self._entryUpdated(event._form)
- #
- # firstRecord
- #
- # Called enever an event source has requested that the
- # form advance to the first record in memory
- #
- def firstRecord(self, event):
- if not event._form.endEditing():
- return
- message = event._form.firstRecord()
+ message = event._form.firstRecord ()
if message:
self.displayMessageBox (message)
+ return
+ self._entryUpdated (event._form)
+
+
+ # ---------------------------------------------------------------------------
+ # Jump to the last record
+ # ---------------------------------------------------------------------------
+
+ def lastRecord (self, event):
+ """
+ Called enever an event source has requested that the form advance to the
+ last record in memory
+ """
+
+ if not event._form.endEditing ():
return
- self._entryUpdated(event._form)
- #
- # lastRecord
- #
- # Called enever an event source has requested that the
- # form advance to the last record in memory
- #
- def lastRecord(self, event):
- if not event._form.endEditing():
- return
- message = event._form.lastRecord()
+ message = event._form.lastRecord ()
if message:
self.displayMessageBox (message)
-
return
- self._entryUpdated(event._form)
+ self._entryUpdated (event._form)
+
+
#
- # jumpToRecord
- #
- # Called whenever an event source has requested that the
- # form move a specific record
- #
- def jumpToRecord(self,event):
+ # ---------------------------------------------------------------------------
+ # Jump to a specific record
+ # ---------------------------------------------------------------------------
+
+ def jumpToRecord (self, event):
+ """
+ Called whenever an event source has requested that the form move to a
+ specific record
+ """
+
if event._form._currentBlock.mode == 'query':
- event._form.triggerSetStatusText(_('You cannot do that in query mode.'))
+ event._form.triggerSetStatusText (_('You cannot do that in query mode.'))
return
- if not event._form.endEditing():
+ if not event._form.endEditing ():
return
try:
- count = abs(int(event.data))-1
+ count = abs (int (event.data)) - 1
+
except ValueError:
message = _("Invalid numeric value entered.")
+
else:
- message = event._form.jumpRecord(count)
+ message = event._form.jumpRecord (count)
if message:
self.displayMessageBox (message, 'Error')
-
return
- self._entryUpdated(event._form)
+ self._entryUpdated (event._form)
- #
- # jumpRecords
- #
- # jump a specified number of records
- # forward or backward.
- #
- def jumpRecords(self,event):
- if not event._form.endEditing():
+
+ # ---------------------------------------------------------------------------
+ # Jump records forward or backward
+ # ---------------------------------------------------------------------------
+
+ def jumpRecords (self, event):
+ """
+ Jump a specified number of records forward or backward.
+ """
+
+ if not event._form.endEditing ():
return
# Manipulate event and redirect to jumpToRecord
- rows = event.data
- curRec = event._form._currentBlock._currentRecord + 1
+ rows = event.data
+ curRec = event._form._currentBlock._currentRecord + 1
recCount = event._form._currentBlock._recordCount
- if curRec+rows < 1:
- event.data = 1
- elif curRec+rows > recCount:
- event.data = recCount
- else:
- event.data = curRec+rows
- self.jumpToRecord(event)
- self._entryUpdated(event._form)
+ newValue = max (1, curRec + rows)
+ event.data = min (recCount, newValue)
- #
- # jumpRowsUp
- #
- # jump a rows="xx" number of records
- # backward.
- #
- def jumpRowsUp(self,event):
- if not event._form.endEditing():
+ self.jumpToRecord (event)
+ self._entryUpdated (event._form)
+
+
+ # ---------------------------------------------------------------------------
+ # Jump a number of records backward
+ # ---------------------------------------------------------------------------
+
+ def jumpRowsUp (self, event):
+
+ if not event._form.endEditing ():
return
# Manipulate event and redirect to jumpToRecord
if event._form._currentEntry._rows > 1:
event.data = -event._form._currentEntry._rows + 1
+
elif event._form._currentBlock._rows >1:
event.data = -event._form._currentBlock._rows + 1
+
else:
event.data = 0
+
if event.data:
- self.jumpRecords(event)
+ self.jumpRecords (event)
- # jumpRowsDown
- #
- # jump a rows="xx" number of records
- # forward.
- #
- def jumpRowsDown(self,event):
- if not event._form.endEditing():
+
+ # ---------------------------------------------------------------------------
+ # Jump a number of records forward
+ # ---------------------------------------------------------------------------
+
+ def jumpRowsDown (self, event):
+
+ if not event._form.endEditing ():
return
# Manipulate event and redirect to jumpToRecord
if event._form._currentEntry._rows > 1:
event.data = event._form._currentEntry._rows - 1
+
elif event._form._currentBlock._rows >1:
event.data = event._form._currentBlock._rows - 1
+
else:
event.data = 0
+
if event.data:
- self.jumpRecords(event)
+ self.jumpRecords (event)
- #
- # executeExit
- #
- # When exit is requested verify that the data
- # has been saved
- #
+
+ # ---------------------------------------------------------------------------
+ # Verify state of data and exit form
+ # ---------------------------------------------------------------------------
+
def executeExit(self, event):
+ """
+ When exit is requested verify that the data has been saved
+ """
+
try:
- event._form.processTrigger('Pre-Exit', ignoreAbort=False)
+ event._form.processTrigger ('Pre-Exit', ignoreAbort = False)
# TODO: WTF? This isn't saving a currently edited field
if event._form._currentBlock.autoCommit:
- event._form.endEditing()
- event._form.commit()
+ event._form.endEditing ()
+ event._form.commit ()
-
- if not event._form.isSaved():
+ if not event._form.isSaved ():
self.displayMessageBox (_("Data not saved. Save changes or clear "
"the form to proceed."), 'Error')
- event._form.refreshUIEvents()
+ event._form.refreshUIEvents ()
else:
- event._form.processTrigger('On-Exit')
- self.dispatchEvent('exitApplication',
- _('Current data is saved'),
- _formName=event._form.name)
+ event._form.processTrigger ('On-Exit')
+ self.dispatchEvent ('exitApplication', _('Current data is saved'),
+ _formName = event._form.name)
+
except AbortRequest, t:
self.displayMessageBox (t, 'Warning')
- event._form.refreshUIEvents()
+ event._form.refreshUIEvents ()
- #
- # deleteRecord
- #
- # Tells the form to mark a record for delete
- #
+
+ # ---------------------------------------------------------------------------
+ # Mark a record for deletion
+ # ---------------------------------------------------------------------------
+
def deleteRecord(self, event):
+ """
+ Tells the form to mark a record for delete
+ """
+
if event._form.readonly:
- self.dispatchEvent('formALERT',u_('Form is readonly'),_form=event._form)
+ self.dispatchEvent ('formALERT', _('Form is readonly'),
+ _form = event._form)
elif not event._form._currentBlock.deletable:
- self.dispatchEvent('formALERT',u_('Block does not allow
delete'),_form=event._form)
+ self.dispatchEvent ('formALERT', _('Block does not allow delete'),
+ _form = event._form)
else:
- event._form.deleteRecord()
- self.updateRecordStatus(event._form)
+ event._form.deleteRecord ()
+ self.updateRecordStatus (event._form)
- #
- # newRecord
- #
+
+ # ---------------------------------------------------------------------------
# Tells the form to create a new record
- #
+ # ---------------------------------------------------------------------------
+
def newRecord(self, event):
- if not event._form.endEditing():
+ """
+ Tells the form to create a new record
+ """
+
+ if not event._form.endEditing ():
return
+
if event._form.readonly:
- self.dispatchEvent('formALERT',u_('Form is readonly'),_form=event._form)
- elif event._form._currentBlock.editable not in ('Y','new'):
- self.dispatchEvent('formALERT',u_('Block does not allow
insert'),_form=event._form)
+ self.dispatchEvent ('formALERT', _('Form is readonly'),
+ _form = event._form)
+ elif event._form._currentBlock.editable not in ('Y', 'new'):
+ self.dispatchEvent ('formALERT', _('Block does not allow insert'),
+ _form = event._form)
else:
- event._form.newRecord()
- self._entryUpdated(event._form)
+ event._form.newRecord ()
+ self._entryUpdated (event._form)
- #
- # executeAbout
- #
- # Displays the about dialog
- #
+
+ # ---------------------------------------------------------------------------
+ # Display the about dialog
+ # ---------------------------------------------------------------------------
+
def executeAbout (self, event):
parameters = {
'appversion' : VERSION,
@@ -817,14 +959,13 @@
if hasattr (self._uiinstance, 'aboutBox'):
self._uiinstance.aboutBox (parameters, event._form)
else:
- self.activateForm('_about', parameters, modal=1)
+ self.activateForm ('_about', parameters, modal = True)
- #
- # displayMessageBox
- #
- # Displays a generic message box
- #
+ # ---------------------------------------------------------------------------
+ # Display a generic message box
+ # ---------------------------------------------------------------------------
+
def displayMessageBox (self, message = '', kind = 'Info', cancel = False,
caption = 'GNUe Message', title = None):
self._uiinstance.showMessage (message, kind, title, cancel)
@@ -833,10 +974,17 @@
#
# requestJumpTo
#
- # Displays a dialog box prompting for record to jump to
- # then jumps to the requested record
#
+ # ---------------------------------------------------------------------------
+ # Display a dialog box prompting for a record number to jump to
+ # ---------------------------------------------------------------------------
+
def requestJumpTo(self,event):
+ """
+ Displays a dialog box prompting for record to jump to then jumps to the
+ requested record
+ """
+
parameters = {'recordnumber': ''}
self.activateForm ('_jumpto', parameters, modal = True)
@@ -857,218 +1005,278 @@
self.displayMessageBox (message, 'Error')
return
- self._entryUpdated(event._form)
+ self._entryUpdated (event._form)
- #
- #
- # toggleInsertMode(self):
- #
- # tells the form to toggle mode
- #
- def toggleInsertMode(self, event):
- event._form.toggleInsertMode()
- self.updateInsertMode(event._form)
- #
- # executePrintout
- #
- # If the form has a trigger named process-printout then fire it
- #
- def executePrintout(self,event):
- if event._form._triggerDictionary.has_key('process-printout'):
- event._form.fireTrigger('process-printout')
+ # ---------------------------------------------------------------------------
+ # Toggle insert mode
+ # ---------------------------------------------------------------------------
+
+ def toggleInsertMode (self, event):
+ """
+ Tells the form to toggle mode
+ """
+
+ event._form.toggleInsertMode ()
+ self.updateInsertMode (event._form)
+
+
+ # ---------------------------------------------------------------------------
+ # Fire a trigger named 'process-printout' (if it exists)
+ # ---------------------------------------------------------------------------
+
+ def executePrintout (self, event):
+ """
+ If the form has a trigger named process-printout then fire it
+ """
+
+ if event._form._triggerDictionary.has_key ('process-printout'):
+ event._form.fireTrigger ('process-printout')
else:
- # TODO: should probably do something else as a default if trigger not
available
- # TODO: like a screen print
- self.dispatchEvent('uiPRINTOUT', _form=event._form)
+ # TODO: should probably do something else as a default if trigger not
+ # available like a screen print
+ self.dispatchEvent ('uiPRINTOUT', _form = event._form)
- #
- # executeRollback
- #
- # Tells the form to rollback everything it contains
- #
- def executeRollback(self,event):
- event._form.rollback()
- self._entryUpdated(event._form)
-## #
-## # activateDialog
-## #
-## def activateDialog(self,event):
-## pass
-## #self.activateForm(event.dialogName)
+ # ---------------------------------------------------------------------------
+ # Perform a rollback
+ # ---------------------------------------------------------------------------
+ def executeRollback (self, event):
+ """
+ Tells the form to rollback everything it contains
+ """
+ event._form.rollback ()
+ self._entryUpdated (event._form)
- #
- # changeFocus
- #
- # changes to the requested entry object requested by
- # an event source
- #
+
+ # ---------------------------------------------------------------------------
+ # Change the focus to an entry object
+ # ---------------------------------------------------------------------------
+
def changeFocus(self, event):
- GDebug.printMesg (2, "GFInstance.ChangeFocus: %s" % event.data.name)
+ """
+ Change the focus to the entry object requested by the event source
+ """
- if not event._form.endEditing():
+ if not event._form.endEditing ():
return False
- if event.data._type=='GFEntry' or event.data._type=='GFImage':
- if not event.data.isNavigable(event._form.getCurrentMode()):
+
+ if event.data._type in ['GFEntry', 'GFImage']:
+ if not event.data.isNavigable (event._form.getCurrentMode ()):
return False
newEntry = event.data
- GDebug.printMesg (2, "Calling _form.changeFocus () on %s" % event._form)
- message = event._form.changeFocus(newEntry)
+ message = event._form.changeFocus (newEntry)
if message:
self.displayMessageBox (message)
return False
- self.dispatchEvent('gotoENTRY',object=event._form._currentEntry,
_form=event._form)
- self.updateRecordStatus(event._form)
- self.updateTip(event._form)
+ self.dispatchEvent ('gotoENTRY', object = event._form._currentEntry,
+ _form = event._form)
- GDebug.printMesg (2, "Leaving GFInstance.ChangeFocus: %s" % \
- event._form._currentEntry)
+ self.updateRecordStatus (event._form)
+ self.updateTip (event._form)
+
return True
- #
- # requestQuery
- #
- def requestQuery(self, event):
- if not event._form.endEditing():
+
+ # ---------------------------------------------------------------------------
+ # Initialize a query
+ # ---------------------------------------------------------------------------
+
+ def requestQuery (self, event):
+
+ if not event._form.endEditing ():
return
- message = event._form.initQuery()
-
+ message = event._form.initQuery ()
if message:
self.displayMessageBox (message, 'Error')
-
return
- event._form.refreshDisplay(event._form)
- self.dispatchEvent('gotoENTRY',object=event._form._currentEntry,
_form=event._form)
- self.updateStatus(event._form)
+ event._form.refreshDisplay (event._form)
+ self.dispatchEvent ('gotoENTRY', object = event._form._currentEntry,
+ _form = event._form)
+ self.updateStatus (event._form)
- #
- # cancelQuery
- #
- def cancelQuery(self, event):
- if not event._form.endEditing():
+
+ # ---------------------------------------------------------------------------
+ # Cancel current query
+ # ---------------------------------------------------------------------------
+
+ def cancelQuery (self, event):
+
+ if not event._form.endEditing ():
return
- message = event._form.cancelQuery()
-
+ message = event._form.cancelQuery ()
if message:
self.displayMessageBox (message, 'Error')
-
return
- event._form.refreshDisplay(event._form)
- self.dispatchEvent('gotoENTRY',object=event._form._currentEntry,
_form=event._form)
- self.updateStatus(event._form)
+ event._form.refreshDisplay (event._form)
+ self.dispatchEvent ('gotoENTRY', object = event._form._currentEntry,
+ _form = event._form)
+ self.updateStatus (event._form)
- #
- # copyQuery
- #
- def copyQuery(self, event):
- if not event._form.endEditing():
+
+ # ---------------------------------------------------------------------------
+ # Copy the current query
+ # ---------------------------------------------------------------------------
+
+ def copyQuery (self, event):
+ if not event._form.endEditing ():
return
- message = event._form.copyQuery()
-
+ message = event._form.copyQuery ()
if message:
self.displayMessageBox (message, 'Error')
-
return
- event._form.refreshDisplay(event._form)
- self.dispatchEvent('gotoENTRY',object=event._form._currentEntry,
_form=event._form)
- self.updateStatus(event._form)
+ event._form.refreshDisplay (event._form)
+ self.dispatchEvent ('gotoENTRY', object = event._form._currentEntry,
+ _form = event._form)
+ self.updateStatus (event._form)
- #
- # executeQuery
- #
- def executeQuery(self, event):
- if not event._form.endEditing():
+
+ # ---------------------------------------------------------------------------
+ # Execute the current query
+ # ---------------------------------------------------------------------------
+
+ def executeQuery (self, event):
+
+ if not event._form.endEditing ():
return
- message = event._form.executeQuery()
+
+ message = event._form.executeQuery ()
if message:
self.displayMessageBox (message, 'Error')
- self.dispatchEvent('gotoENTRY',object=event._form._currentEntry,
_form=event._form)
- event._form.refreshDisplay(event._form._currentBlock)
- self._entryUpdated(event._form)
+ self.dispatchEvent ('gotoENTRY', object = event._form._currentEntry,
+ _form = event._form)
+ event._form.refreshDisplay (event._form._currentBlock)
+ self._entryUpdated (event._form)
- #
- # executeCommit
- #
- def executeCommit(self, event):
- if not event._form.endEditing():
+
+ # ---------------------------------------------------------------------------
+ # Perform a commit
+ # ---------------------------------------------------------------------------
+
+ def executeCommit (self, event):
+
+ if not event._form.endEditing ():
return
- message = event._form.commit()
+
+ message = event._form.commit ()
if message:
self.displayMessageBox (message, 'Error')
-
return
- self._entryUpdated(event._form)
- event._form.refreshDisplay(event._form._currentBlock)
+ self._entryUpdated (event._form)
+ event._form.refreshDisplay (event._form._currentBlock)
- def preCommit(self, event):
- self._handlePreCommit(event, 'PRE-COMMIT')
- def preInsert(self, event):
- self._handlePreCommit(event, 'PRE-INSERT')
+ # ---------------------------------------------------------------------------
+ # Execute block-trigger: Pre-Commit
+ # ---------------------------------------------------------------------------
+ def preCommit (self, event):
- def preUpdate(self, event):
- self._handlePreCommit(event, 'PRE-UPDATE')
+ self._handlePreCommit (event, 'PRE-COMMIT')
- def preDelete(self, event):
- self._handlePreCommit(event, 'PRE-DELETE')
+ # ---------------------------------------------------------------------------
+ # Execute block-trigger: Pre-Insert
+ # ---------------------------------------------------------------------------
+ def preInsert (self, event):
- def onRecordTouched(self, event):
- self._handlePreCommit(event, 'PRE-CHANGE')
+ self._handlePreCommit (event, 'PRE-INSERT')
- def _handlePreCommit(self, event, trigger):
+ # ---------------------------------------------------------------------------
+ # Execute block-trigger: Pre-Update
+ # ---------------------------------------------------------------------------
+
+ def preUpdate (self, event):
+
+ self._handlePreCommit (event, 'PRE-UPDATE')
+
+
+ # ---------------------------------------------------------------------------
+ # Execute block-trigger: Pre-Delete
+ # ---------------------------------------------------------------------------
+
+ def preDelete (self, event):
+
+ self._handlePreCommit (event, 'PRE-DELETE')
+
+
+ # ---------------------------------------------------------------------------
+ # Execute block-trigger: Pre-Change
+ # ---------------------------------------------------------------------------
+
+ def onRecordTouched (self, event):
+
+ self._handlePreCommit (event, 'PRE-CHANGE')
+
+
+ # ---------------------------------------------------------------------------
+ # Process a trigger for a given block and all it's fields
+ # ---------------------------------------------------------------------------
+
+ def _handlePreCommit (self, event, trigger):
+
try:
block = event.record._parent._block
+
except AttributeError:
return
saveMode = block.mode
block._preCommitWorkingRecord = event.record
block.mode = 'precommit'
- block.processTrigger(trigger)
+ block.processTrigger (trigger)
+
for child in block._fieldList:
- child.processTrigger(trigger)
+ child.processTrigger (trigger)
+
block.mode = saveMode
- def onQueryNewRecord(self, event):
+ # ---------------------------------------------------------------------------
+ #
+ # ---------------------------------------------------------------------------
+
+ def onQueryNewRecord (self, event):
+
try:
block = event.record._parent._block
+
except AttributeError:
return
- #
- # TODO: Running this here causes the trigger
- # TODO: to fire prior to all blocks being filled
- #
+ # TODO: Running this here causes the trigger to fire prior to all blocks
+ # being filled
#block.processTrigger('POST-QUERY')
#for child in block._fieldList:
# child.processTrigger('POST-QUERY')
- #
- # fireTrigger
- #
- def fireTrigger(self, event):
- event._form.fireTrigger(event.data)
- #
- # fireButton
- #
- def fireButton(self, event):
- event.data.processTrigger('On-Action')
+ # ---------------------------------------------------------------------------
+ # Fire a trigger of the form
+ # ---------------------------------------------------------------------------
+ def fireTrigger (self, event):
+
+ event._form.fireTrigger (event.data)
+
+
+ # ---------------------------------------------------------------------------
+ # Fire the action-trigger bound to a button
+ # ---------------------------------------------------------------------------
+
+ def fireButton (self, event):
+
+ event.data.processTrigger ('On-Action')
Property changes on: trunk/gnue-forms/src/GFInstance.py
___________________________________________________________________
Name: svn:keywords
+ Id
Modified: trunk/gnue-forms/src/uidrivers/_base/UIdriver.py
===================================================================
--- trunk/gnue-forms/src/uidrivers/_base/UIdriver.py 2004-09-13 17:21:34 UTC
(rev 6278)
+++ trunk/gnue-forms/src/uidrivers/_base/UIdriver.py 2004-09-14 13:47:28 UTC
(rev 6279)
@@ -91,48 +91,24 @@
def __init__(self, eventHandler, name = "Undefined", disableSplash = None,
parentContainer = None):
+ """
+ Constructors of descendants must bring their UI into a state where it can
+ perform simple tasks like showMessage () or showException ().
+ """
GRootObj.__init__(self, 'uiDriver', None, None)
- self.name = name
- self._type = 'UIDriver'
+ self.name = name
+ self._type = 'UIDriver'
self._disableSplash = disableSplash
- # Used when forms are embedded in navigator.
- # What parentContainer is depends on the
- # individual UIdriver and Navigator.
+ # Used when forms are embedded in navigator. What parentContainer is
+ # depends on the individual UIdriver and Navigator.
self._parentContainer = parentContainer
events.EventAware.__init__(self, eventHandler)
- #
- # Incomming events
- #
- self.registerEventListeners( {
- 'gotoENTRY' : self.switchFocus,
- 'updateENTRY' : self.updateEntry,
- 'updateEntryEditor': self.updateEntryEditor,
- 'gotoPAGE' : self.gotoPage,
- 'exitApplication' : self.exitApplication,
- 'setTitle' : self.setTitle,
-
- # User feedback events from the virtual form to the UI
- 'beginWAIT' : self.beginWait,
- 'endWAIT' : self.endWait,
- 'formALERT' : self.formAlert,
- 'uiUPDATESTATUS' : self.updateStatusBar,
-
- # Clipboard contents
- 'setCLIPBOARD' : self.setClipboardContents,
- 'getCLIPBOARD' : self.getClipboardContents,
-
- # Printout
- 'uiPRINTOUT' : self.printout,
- })
-
- #
# Mapping - internal record status : displayed on status bar
- #
self.statusValues = {'saved' :'OK',
'modified' :'MOD',
'deleted' :'DEL',
@@ -142,9 +118,7 @@
# So other modules can get to the ui
__builtins__ ['forms_ui'] = self
- #
# Multi-form support
- #
self._formNameToUIForm = {} # Holds links the to the top level
# UIForm objects held in memory
self._formNameToGFForm = {} # Holds links the to the top level
@@ -156,14 +130,10 @@
self._gfObjToToolkitWidgets = {} # the GFObj to UI widget cross ref
- #
# Our local "clipboard"
- #
self.__clipboard = None
- #
# Import and register supported widgets in UI driver
- #
self._supportedWidgets = {}
basedir = os.path.dirname (sys.modules [self.__module__].__file__)
@@ -196,22 +166,65 @@
self._uiFocusWidget = None
- ############################################################
- #
- # Things you may need to adjust in the individual UI drivers
- #
- ############################################################
-
- #
# Dialogs required by base
#
- # TODO: Once <dialog> works we may be able to
- # do away with these
- #
+ # TODO: Once <dialog> works we may be able to do away with these
self._DIALOGS = {}
# ---------------------------------------------------------------------------
+ # Initialize
+ # ---------------------------------------------------------------------------
+
+ def initialize (self):
+ """
+ This function gets called on activation of a GFInstance. It performs the
+ last steps needed for handling forms. Descendants of this class must put
+ their special init stuff into _initialize (), which gets called
+ automatically from this function.
+ """
+
+ # register incomming events
+ self.registerEventListeners ({
+ 'gotoENTRY' : self.switchFocus,
+ 'updateENTRY' : self.updateEntry,
+ 'updateEntryEditor': self.updateEntryEditor,
+ 'gotoPAGE' : self.gotoPage,
+ 'exitApplication' : self.exitApplication,
+ 'setTitle' : self.setTitle,
+
+ # User feedback events from the virtual form to the UI
+ 'beginWAIT' : self.beginWait,
+ 'endWAIT' : self.endWait,
+ 'formALERT' : self.formAlert,
+ 'uiUPDATESTATUS' : self.updateStatusBar,
+
+ # Clipboard contents
+ 'setCLIPBOARD' : self.setClipboardContents,
+ 'getCLIPBOARD' : self.getClipboardContents,
+
+ # Printout
+ 'uiPRINTOUT' : self.printout,
+ })
+
+ # now call the implementation specific initialization
+ self._initialize ()
+
+
+ # ---------------------------------------------------------------------------
+ # Driver-specific initializations
+ # ---------------------------------------------------------------------------
+
+ def _initialize (self):
+ """
+ Descendants of this class will override this function to do all
+ initializations.
+ """
+ pass
+
+
+
+ # ---------------------------------------------------------------------------
# Build the user interface
# ---------------------------------------------------------------------------
@@ -500,12 +513,14 @@
# Show the last exception
# ---------------------------------------------------------------------------
- def showException (self):
+ def showException (self, group = None, name = None, message = None,
+ detail = None):
"""
This function shows the last exception raised. Exceptions of the user group
are delegated to the showMessage-function.
"""
- (group, name, message, detail) = errors.getException ()
+ if (group, name, message, detail) == (None, None, None, None):
+ (group, name, message, detail) = errors.getException ()
if group == 'user':
self.showMessage (message, kind = 'Error', title = _("GNUe Message"))
else:
Modified: trunk/gnue-forms/src/uidrivers/curses/UIdriver.py
===================================================================
--- trunk/gnue-forms/src/uidrivers/curses/UIdriver.py 2004-09-13 17:21:34 UTC
(rev 6278)
+++ trunk/gnue-forms/src/uidrivers/curses/UIdriver.py 2004-09-14 13:47:28 UTC
(rev 6279)
@@ -39,7 +39,7 @@
# Initialize user interface
# ---------------------------------------------------------------------------
- def initialize (self):
+ def _initialize (self):
self.widgetWidth = 1
self.widgetHeight = 1
Modified: trunk/gnue-forms/src/uidrivers/gtk2/UIdriver.py
===================================================================
--- trunk/gnue-forms/src/uidrivers/gtk2/UIdriver.py 2004-09-13 17:21:34 UTC
(rev 6278)
+++ trunk/gnue-forms/src/uidrivers/gtk2/UIdriver.py 2004-09-14 13:47:28 UTC
(rev 6279)
@@ -107,7 +107,7 @@
# Initialize user interface
# ---------------------------------------------------------------------------
- def initialize (self):
+ def _initialize (self):
self.app = getApp ()
@@ -127,6 +127,7 @@
+
#############################################################################
#
# Private UIBase support functions
Modified: trunk/gnue-forms/src/uidrivers/win32/UIdriver.py
===================================================================
--- trunk/gnue-forms/src/uidrivers/win32/UIdriver.py 2004-09-13 17:21:34 UTC
(rev 6278)
+++ trunk/gnue-forms/src/uidrivers/win32/UIdriver.py 2004-09-14 13:47:28 UTC
(rev 6279)
@@ -127,7 +127,7 @@
return x
- def initialize(self):
+ def _initialize(self):
self._disabledColour = afxres.AFX_IDC_COLOR_LIGHTGRAY
self._win32app = getWin32App()
Modified: trunk/gnue-forms/src/uidrivers/wx/UIdriver.py
===================================================================
--- trunk/gnue-forms/src/uidrivers/wx/UIdriver.py 2004-09-13 17:21:34 UTC
(rev 6278)
+++ trunk/gnue-forms/src/uidrivers/wx/UIdriver.py 2004-09-14 13:47:28 UTC
(rev 6279)
@@ -78,7 +78,7 @@
wxID_NO : False,
wxID_CANCEL: None}
- def initialize(self):
+ def _initialize(self):
################################################################
# WX Specifics
[Prev in Thread] |
Current Thread |
[Next in Thread] |
- r6279 - in trunk/gnue-forms/src: . uidrivers/_base uidrivers/curses uidrivers/gtk2 uidrivers/win32 uidrivers/wx,
johannes <=