[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[gnue] r8344 - in trunk/gnue-designer/src: . base base/tools forms forms
From: |
jcater |
Subject: |
[gnue] r8344 - in trunk/gnue-designer/src: . base base/tools forms forms/LayoutEditor forms/LayoutEditor/renderers/Base forms/LayoutEditor/renderers/curses forms/LayoutEditor/renderers/native forms/PagePainter forms/PagePainter/skins forms/events forms/wizards navigator projects reports reports/Char reports/Default reports/Labels reports/MailMerge reports/SimpleTabulation reports/Standard schema schema/DiaEditor schema/wizards templates templates/forms templates/reports templates/schema ui/wx ui/wx/startup ui/wx/uihelpers ui/wx/uihelpers/doccanvas |
Date: |
Mon, 3 Apr 2006 18:25:28 -0500 (CDT) |
Author: jcater
Date: 2006-04-03 14:56:14 -0500 (Mon, 03 Apr 2006)
New Revision: 8344
Modified:
trunk/gnue-designer/src/Designer.py
trunk/gnue-designer/src/__init__.py
trunk/gnue-designer/src/base/Document.py
trunk/gnue-designer/src/base/EditorBase.py
trunk/gnue-designer/src/base/Goat.py
trunk/gnue-designer/src/base/Icons.py
trunk/gnue-designer/src/base/Incubator.py
trunk/gnue-designer/src/base/MRUManager.py
trunk/gnue-designer/src/base/MenuBar.py
trunk/gnue-designer/src/base/ModuleSupport.py
trunk/gnue-designer/src/base/MultiObjectGridEditor.py
trunk/gnue-designer/src/base/ObjectList.py
trunk/gnue-designer/src/base/PopupMenu.py
trunk/gnue-designer/src/base/PrimaryToolBar.py
trunk/gnue-designer/src/base/TemplateBase.py
trunk/gnue-designer/src/base/TemplateChooser.py
trunk/gnue-designer/src/base/TemplateParser.py
trunk/gnue-designer/src/base/ToolBar.py
trunk/gnue-designer/src/base/ToolBase.py
trunk/gnue-designer/src/base/UndoManager.py
trunk/gnue-designer/src/base/tools/DataSourceEditor.py
trunk/gnue-designer/src/base/tools/EventEditor.py
trunk/gnue-designer/src/base/tools/PropertyEditor.py
trunk/gnue-designer/src/base/tools/SchemaNavigator.py
trunk/gnue-designer/src/base/tools/SchemaViewer.py
trunk/gnue-designer/src/base/tools/TreeView.py
trunk/gnue-designer/src/base/tools/TriggerEditor.py
trunk/gnue-designer/src/forms/BlockEditor.py
trunk/gnue-designer/src/forms/Debugger.py
trunk/gnue-designer/src/forms/Document.py
trunk/gnue-designer/src/forms/EventEditor.py
trunk/gnue-designer/src/forms/Incubator.py
trunk/gnue-designer/src/forms/LayoutEditor/DisplayDropTarget.py
trunk/gnue-designer/src/forms/LayoutEditor/LayoutEditor.py
trunk/gnue-designer/src/forms/LayoutEditor/LayoutEditorTools.py
trunk/gnue-designer/src/forms/LayoutEditor/PopupEditor.py
trunk/gnue-designer/src/forms/LayoutEditor/PropertyBar.py
trunk/gnue-designer/src/forms/LayoutEditor/ReorderFocus.py
trunk/gnue-designer/src/forms/LayoutEditor/Utils.py
trunk/gnue-designer/src/forms/LayoutEditor/WidgetFocusTab.py
trunk/gnue-designer/src/forms/LayoutEditor/WidgetHandler.py
trunk/gnue-designer/src/forms/LayoutEditor/WidgetHighlighter.py
trunk/gnue-designer/src/forms/LayoutEditor/Workspace.py
trunk/gnue-designer/src/forms/LayoutEditor/renderers/Base/Driver.py
trunk/gnue-designer/src/forms/LayoutEditor/renderers/Base/GridPane.py
trunk/gnue-designer/src/forms/LayoutEditor/renderers/curses/Driver.py
trunk/gnue-designer/src/forms/LayoutEditor/renderers/native/Driver.py
trunk/gnue-designer/src/forms/LayoutEditor/renderers/native/WidgetHandler.py
trunk/gnue-designer/src/forms/PagePainter/PagePainter.py
trunk/gnue-designer/src/forms/PagePainter/skins/common.py
trunk/gnue-designer/src/forms/PagePainter/skins/default.py
trunk/gnue-designer/src/forms/PagePainter/skins/term.py
trunk/gnue-designer/src/forms/PropertyEditor.py
trunk/gnue-designer/src/forms/TemplateSupport.py
trunk/gnue-designer/src/forms/TreeView.py
trunk/gnue-designer/src/forms/WizardRunner.py
trunk/gnue-designer/src/forms/__init__.py
trunk/gnue-designer/src/forms/events/Arrange.py
trunk/gnue-designer/src/forms/events/Events.py
trunk/gnue-designer/src/forms/events/Resize.py
trunk/gnue-designer/src/forms/wizards/AddBlock.py
trunk/gnue-designer/src/forms/wizards/AddBox.py
trunk/gnue-designer/src/forms/wizards/AddButton.py
trunk/gnue-designer/src/forms/wizards/AddCheckbox.py
trunk/gnue-designer/src/forms/wizards/AddDataSource.py
trunk/gnue-designer/src/forms/wizards/AddDropDown.py
trunk/gnue-designer/src/forms/wizards/AddEntry.py
trunk/gnue-designer/src/forms/wizards/AddLabel.py
trunk/gnue-designer/src/forms/wizards/AddPage.py
trunk/gnue-designer/src/forms/wizards/CreateSchema.py
trunk/gnue-designer/src/forms/wizards/CreateWebForm.py
trunk/gnue-designer/src/navigator/Document.py
trunk/gnue-designer/src/navigator/Incubator.py
trunk/gnue-designer/src/navigator/LayoutEditor.py
trunk/gnue-designer/src/navigator/TemplateSupport.py
trunk/gnue-designer/src/navigator/__init__.py
trunk/gnue-designer/src/projects/Objects.py
trunk/gnue-designer/src/projects/Parser.py
trunk/gnue-designer/src/projects/Project.py
trunk/gnue-designer/src/reports/Char/FilterSupport.py
trunk/gnue-designer/src/reports/Char/Incubator.py
trunk/gnue-designer/src/reports/Char/LayoutEditor.py
trunk/gnue-designer/src/reports/Default/FilterSupport.py
trunk/gnue-designer/src/reports/Document.py
trunk/gnue-designer/src/reports/FilterSupport.py
trunk/gnue-designer/src/reports/Incubator.py
trunk/gnue-designer/src/reports/Labels/FilterSupport.py
trunk/gnue-designer/src/reports/MailMerge/FilterSupport.py
trunk/gnue-designer/src/reports/SimpleTabulation/FilterSupport.py
trunk/gnue-designer/src/reports/Standard/FilterSupport.py
trunk/gnue-designer/src/reports/Standard/GroupEditor.py
trunk/gnue-designer/src/reports/Standard/Incubator.py
trunk/gnue-designer/src/reports/Standard/LayoutEditor.py
trunk/gnue-designer/src/reports/TemplateSupport.py
trunk/gnue-designer/src/reports/TreeView.py
trunk/gnue-designer/src/reports/__init__.py
trunk/gnue-designer/src/schema/DiaEditor/VisualEditor.py
trunk/gnue-designer/src/schema/DiaEditor/VisualTable.py
trunk/gnue-designer/src/schema/Document.py
trunk/gnue-designer/src/schema/Incubator.py
trunk/gnue-designer/src/schema/LayoutEditor.py
trunk/gnue-designer/src/schema/TableEditor.py
trunk/gnue-designer/src/schema/TemplateSupport.py
trunk/gnue-designer/src/schema/TreeView.py
trunk/gnue-designer/src/schema/__init__.py
trunk/gnue-designer/src/schema/wizards/AddTable.py
trunk/gnue-designer/src/schema/wizards/WriteSchema.py
trunk/gnue-designer/src/templates/__init__.py
trunk/gnue-designer/src/templates/forms/FormBuilder.py
trunk/gnue-designer/src/templates/forms/Simple.py
trunk/gnue-designer/src/templates/forms/__init__.py
trunk/gnue-designer/src/templates/reports/CharReport.py
trunk/gnue-designer/src/templates/reports/Labels.py
trunk/gnue-designer/src/templates/reports/MailMerge.py
trunk/gnue-designer/src/templates/reports/SimpleReport.py
trunk/gnue-designer/src/templates/reports/__init__.py
trunk/gnue-designer/src/templates/schema/Introspection.py
trunk/gnue-designer/src/ui/wx/Base.py
trunk/gnue-designer/src/ui/wx/Instance.py
trunk/gnue-designer/src/ui/wx/MenuBar.py
trunk/gnue-designer/src/ui/wx/startup/Startup.py
trunk/gnue-designer/src/ui/wx/startup/__init__.py
trunk/gnue-designer/src/ui/wx/uihelpers/AdvancedSplash.py
trunk/gnue-designer/src/ui/wx/uihelpers/GridCellEditors.py
trunk/gnue-designer/src/ui/wx/uihelpers/NotebookCtrl.py
trunk/gnue-designer/src/ui/wx/uihelpers/PyAUI.py
trunk/gnue-designer/src/ui/wx/uihelpers/PythonEditor.py
trunk/gnue-designer/src/ui/wx/uihelpers/doccanvas/canvas.py
trunk/gnue-designer/src/ui/wx/uihelpers/doccanvas/colors.py
trunk/gnue-designer/src/ui/wx/uihelpers/doccanvas/dnd.py
trunk/gnue-designer/src/ui/wx/uihelpers/doccanvas/widget.py
Log:
misc code cleanup (trying to make the style consistent)
Modified: trunk/gnue-designer/src/Designer.py
===================================================================
--- trunk/gnue-designer/src/Designer.py 2006-04-03 19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/Designer.py 2006-04-03 19:56:14 UTC (rev 8344)
@@ -42,399 +42,398 @@
import time
try:
- from xml.sax import saxlib
+ from xml.sax import saxlib
except ImportError:
- print """
- This GNUe tool requires PyXML package to be installed.
- Typically this is the case, however some GNU/Linux distro's
- like Debian distribute this in another seperate package
+ print """
+ This GNUe tool requires PyXML package to be installed.
+ Typically this is the case, however some GNU/Linux distro's
+ like Debian distribute this in another seperate package
- To install this package...
- On Debian: apt-get install python-xml
+ To install this package...
+ On Debian: apt-get install python-xml
-"""
- sys.exit()
+ """
+ sys.exit()
class Designer(GClientApp):
- # GClientApp stuff...
- NAME = PACKAGE
- VERSION = VERSION
- COMMAND = "gnue-designer"
- SUMMARY = u_("A graphical tool for the rapid deployment of GNU Enterprise
forms and reports.")
- COMMAND_OPTIONS = [
- [ 'new', 'n', 'new', 1, None, 'module',
- u_('Starts up opening a new instance of <module>, where module can
be forms, reports, schema, etc.') ],
- ]
- USAGE = GClientApp.USAGE + " [file] [file] ..."
- USE_DATABASE_OPTIONS = 1
+ # GClientApp stuff...
+ NAME = PACKAGE
+ VERSION = VERSION
+ COMMAND = "gnue-designer"
+ SUMMARY = u_("A graphical tool for the rapid deployment of GNU Enterprise
forms and reports.")
+ COMMAND_OPTIONS = [
+ [ 'new', 'n', 'new', 1, None, 'module',
+ u_('Starts up opening a new instance of <module>, where module can
be forms, reports, schema, etc.') ],
+ ]
+ USAGE = GClientApp.USAGE + " [file] [file] ..."
+ USE_DATABASE_OPTIONS = 1
- def __init__(self):
- GClientApp.__init__(self, application="forms",defaults=ConfigOptions)
+ def __init__(self):
+ GClientApp.__init__(self, application="forms",defaults=ConfigOptions)
- self._instances = []
+ self._instances = []
- # Load the configuration information
-
self.configurationManager.loadApplicationConfig(section="designer",defaults=DesignerConfigOptions)
- self.configurationManager.registerAlias('gConfigNav', 'navigator')
- self.configurationManager.registerAlias('gConfigForms', 'forms')
- self.configurationManager.registerAlias('gConfigReports', 'reports')
+ # Load the configuration information
+
self.configurationManager.loadApplicationConfig(section="designer",defaults=DesignerConfigOptions)
+ self.configurationManager.registerAlias('gConfigNav', 'navigator')
+ self.configurationManager.registerAlias('gConfigForms', 'forms')
+ self.configurationManager.registerAlias('gConfigReports', 'reports')
- # ==========================================================================
- # Startup functions
- # ==========================================================================
- def run(self):
- """
- Startup logic for Designer.
- """
- print "Running"
+ #
==========================================================================
+ # Startup functions
+ #
==========================================================================
+ def run(self):
+ """
+ Startup logic for Designer.
+ """
+ print "Running"
- # TODO: make a startup/GConfig parameter, and/or do auto-detection
- from gnue.designer.ui.wx.Base import UIBase
+ # TODO: make a startup/GConfig parameter, and/or do auto-detection
+ from gnue.designer.ui.wx.Base import UIBase
- self.ui = UIBase(self)
+ self.ui = UIBase(self)
- # Setup the Most Recently Used URL manager
- self.mru = MRUManager.MRUManager(self)
+ # Setup the Most Recently Used URL manager
+ self.mru = MRUManager.MRUManager(self)
- # get list of available modules
- self.loadModuleInformation()
+ # get list of available modules
+ self.loadModuleInformation()
- self.ui.run()
+ self.ui.run()
- def init(self):
- """
- Called by the UI Driver after the graphics subsystem is ready.
- At this point, we can start loading/drawing.
- """
+ def init(self):
+ """
+ Called by the UI Driver after the graphics subsystem is ready.
+ At this point, we can start loading/drawing.
+ """
- print "Init'ing"
- # Init the splashscreen
+ print "Init'ing"
+ # Init the splashscreen
# self.ui.createStartupSplash()
- gStartupStatus(u_('Initializing Client Library'))
- print gStartupStatus
+ gStartupStatus(u_('Initializing Client Library'))
+ print gStartupStatus
- # Load the specified file, a requested new instance, or the default empty
instance
- if len(self.ARGUMENTS):
- for arg in self.ARGUMENTS:
- #self.SetTopWindow(self.load(arg))
- self.load(arg)
+ # Load the specified file, a requested new instance, or the default
empty instance
+ if len(self.ARGUMENTS):
+ for arg in self.ARGUMENTS:
+ #self.SetTopWindow(self.load(arg))
+ self.load(arg)
- elif self.OPTIONS['new']:
- try:
- #self.SetTopWindow(self.newDocument(self.OPTIONS['new']))
- self.newDocument(self.OPTIONS['new'])
- except ImportError:
- raise
- self.handleStartupError('"%s" is not a valid option for --new' % (
- self.OPTIONS['new']))
+ elif self.OPTIONS['new']:
+ try:
+ #self.SetTopWindow(self.newDocument(self.OPTIONS['new']))
+ self.newDocument(self.OPTIONS['new'])
+ except ImportError:
+ raise
+ self.handleStartupError('"%s" is not a valid option for --new'
% (
+ self.OPTIONS['new']))
- else:
- # TODO: What to do when no object is specified on command line?
- # TODO: jcater thinks of some task selector like kword uses,
- # TODO: or, restore the session to the way it was (same files, etc)
+ else:
+ # TODO: What to do when no object is specified on command line?
+ # TODO: jcater thinks of some task selector like kword uses,
+ # TODO: or, restore the session to the way it was (same files, etc)
- #self.SetTopWindow(self.newDocument('forms'))
- self.newDocument('forms')
+ #self.SetTopWindow(self.newDocument('forms'))
+ self.newDocument('forms')
- # Close startup screen
+ # Close startup screen
# self.ui.closeStartupSplash()
- return True
+ return True
- def loadModuleInformation(self):
- """
- Loads all the available editor modules into memory and
- extracts from them a list of file types/extensions
- that they support
- """
- gStartupStatus(u_('Loading available tool modules'))
+ def loadModuleInformation(self):
+ """
+ Loads all the available editor modules into memory and
+ extracts from them a list of file types/extensions
+ that they support
+ """
+ gStartupStatus(u_('Loading available tool modules'))
- self.supportedModuleObjects = [] # A list of supported modules along with
their "nickname"
- self.supportedOpenWildcard = "" #
- self.moduleExtensionMapping = {} # A dictionary of {file extension:
designer module}
+ self.supportedModuleObjects = [] # A list of supported modules along
with their "nickname"
+ self.supportedOpenWildcard = "" #
+ self.moduleExtensionMapping = {} # A dictionary of {file extension:
designer module}
- wildcard = []
- alltypes = []
+ wildcard = []
+ alltypes = []
- # TODO: wxWidgets currently doesn't consistently support multiple file
- # TODO: extension wildcards (e.g., "All GNUe Form Files (*.gfd,*.gfl)").
- # TODO: However, the code is left commented out in case some day it does.
+ # TODO: wxWidgets currently doesn't consistently support multiple file
+ # TODO: extension wildcards (e.g., "All GNUe Form Files
(*.gfd,*.gfl)").
+ # TODO: However, the code is left commented out in case some day it
does.
- for module in SupportedModules:
- self.supportedModuleObjects.append((module.properties.nickname, module))
+ for module in SupportedModules:
+ self.supportedModuleObjects.append((module.properties.nickname,
module))
- ## if len(module.properties.fileExtensions.keys()) > 1:
- ##
- ## wildcard += "%s Files (*.%s)|*.%s|" % \
- ## ( module.properties.application,
- ##
string.join(module.properties.fileExtensions.keys(),',*.'),
- ##
string.join(module.properties.fileExtensions.keys(),';*.') )
+ ## if len(module.properties.fileExtensions.keys()) > 1:
+ ##
+ ## wildcard += "%s Files (*.%s)|*.%s|" % \
+ ## ( module.properties.application,
+ ##
string.join(module.properties.fileExtensions.keys(),',*.'),
+ ##
string.join(module.properties.fileExtensions.keys(),';*.') )
- # Make the "default" file extension for a module
- # appear before the other extensions.
- wildcard += [
- ( module.properties.defaultFileExtension,
-
module.properties.fileExtensions[module.properties.defaultFileExtension]) ]
+ # Make the "default" file extension for a module
+ # appear before the other extensions.
+ wildcard += [
+ ( module.properties.defaultFileExtension,
+
module.properties.fileExtensions[module.properties.defaultFileExtension]) ]
- for type in module.properties.fileExtensions.keys():
- if type != module.properties.defaultFileExtension:
- wildcard += [
- ( type, module.properties.fileExtensions[type]) ]
- alltypes.append(type)
+ for type in module.properties.fileExtensions.keys():
+ if type != module.properties.defaultFileExtension:
+ wildcard += [
+ ( type, module.properties.fileExtensions[type]) ]
+ alltypes.append(type)
- # Keep a dict of Extension::Handler mappings
- self.moduleExtensionMapping[type] = module.properties.module
+ # Keep a dict of Extension::Handler mappings
+ self.moduleExtensionMapping[type] = module.properties.module
- ## self.supportedOpenWildcard = "All Supported Files (*.%s)|*.%s|" % \
- ## ( string.join(alltypes,',*.'),
- ## string.join(alltypes,';*.') ) \
- ## + wildcard \
- ## + "All Files (*.*)|*.*"
- self.supportedOpenWildcard = wildcard + [('*',"All Files")]
+ ## self.supportedOpenWildcard = "All Supported Files (*.%s)|*.%s|" % \
+ ## ( string.join(alltypes,',*.'),
+ ## string.join(alltypes,';*.') ) \
+ ## + wildcard \
+ ## + "All Files (*.*)|*.*"
+ self.supportedOpenWildcard = wildcard + [('*',"All Files")]
- # ==========================================================================
- # Document functions
- # ==========================================================================
- def load(self, file):
- """
- Loads the requested file into a new instance of the appropriate
- designer module if the extension is recognized.
+ #
==========================================================================
+ # Document functions
+ #
==========================================================================
+ def load(self, file):
+ """
+ Loads the requested file into a new instance of the appropriate
+ designer module if the extension is recognized.
- @type file: string
- @param file: The url of the file to open.
- @rtype: designer editor instance
- @return: An instance of the appropriate editor module or None if
- an error is encountered
- """
- gStartupStatus(u_('Loading document'))
+ @type file: string
+ @param file: The url of the file to open.
+ @rtype: designer editor instance
+ @return: An instance of the appropriate editor module or None if
+ an error is encountered
+ """
+ gStartupStatus(u_('Loading document'))
- extension = string.lower(os.path.splitext(file)[1][1:])
+ extension = string.lower(os.path.splitext(file)[1][1:])
- if not self.moduleExtensionMapping.has_key(extension):
+ if not self.moduleExtensionMapping.has_key(extension):
- # TODO: This should try to figure out what kind of file this is.
- # TODO: We maintain a list of opening xml elements in the
- # TODO: (gnue.designer.SupportedModules).properties object.
- # TODO: [gnue.designer.SupportedModules is a list]
+ # TODO: This should try to figure out what kind of file this is.
+ # TODO: We maintain a list of opening xml elements in the
+ # TODO: (gnue.designer.SupportedModules).properties object.
+ # TODO: [gnue.designer.SupportedModules is a list]
- # TODO: Shouldn't this display graphically?
- print "I do not know what to do with a .%s file!" % extension
- return None
+ # TODO: Shouldn't this display graphically?
+ print "I do not know what to do with a .%s file!" % extension
+ return None
- return self.newDocument(self.moduleExtensionMapping[extension], file)
+ return self.newDocument(self.moduleExtensionMapping[extension], file)
- def newDocument(self, module, *args, **parms):
- """
- Creates an instance of the appropriate designer editor module
- """
- c = dyn_import("gnue.designer.%s.Document" % module).Document(self, *args,
**parms)
- return c
+ def newDocument(self, module, *args, **parms):
+ """
+ Creates an instance of the appropriate designer editor module
+ """
+ c = dyn_import("gnue.designer.%s.Document" % module).Document(self,
*args, **parms)
+ return c
- def addDocument(self, instance):
- """
- Adds a newly created instance to the list of open instances
- Sets several event handlers in the instance to point back to
- this class so it can proxy the events for the instance.
+ def addDocument(self, instance):
+ """
+ Adds a newly created instance to the list of open instances
+ Sets several event handlers in the instance to point back to
+ this class so it can proxy the events for the instance.
- @type instance: Designer Editor Module
- @param instance: An instance of a designer module
- """
- self._instances.append(instance)
- instance.registerEventListeners({
- # Proxy for the main app
- 'RequestNew' : self.OnNew,
- 'RequestSaveAll' : self.OnSaveAll,
- 'RequestAbout' : self.OnAbout,
- 'RequestNewWizard' : self.OnWizard,
- 'RequestOpen' : self.OnOpen,
- 'RequestOpenRecent' : self.OnOpenRecent,
- 'RequestExit' : self.OnExit
- })
+ @type instance: Designer Editor Module
+ @param instance: An instance of a designer module
+ """
+ self._instances.append(instance)
+ instance.registerEventListeners({
+ # Proxy for the main app
+ 'RequestNew' : self.OnNew,
+ 'RequestSaveAll' : self.OnSaveAll,
+ 'RequestAbout' : self.OnAbout,
+ 'RequestNewWizard' : self.OnWizard,
+ 'RequestOpen' : self.OnOpen,
+ 'RequestOpenRecent' : self.OnOpenRecent,
+ 'RequestExit' : self.OnExit
+ })
- def removeDocument(self, instance):
- """
- Removes an instance from the list of open instances
+ def removeDocument(self, instance):
+ """
+ Removes an instance from the list of open instances
- @type instance: Designer Editor Module
- @param instance: An instance of a designer module
- """
- self._instances.remove(instance)
+ @type instance: Designer Editor Module
+ @param instance: An instance of a designer module
+ """
+ self._instances.remove(instance)
- # ==========================================================================
- # Proxy event functions
- # ==========================================================================
- def OnWizard(self, event):
- """
- Handles the request to display the wizard selection dialog
+ #
==========================================================================
+ # Proxy event functions
+ #
==========================================================================
+ def OnWizard(self, event):
+ """
+ Handles the request to display the wizard selection dialog
- type event: GNUe Event
- param event: The event request
- """
- wizard = TemplateChooser.TemplateChooser(self).run()
- if wizard != None:
- self.RunWizard(wizard)
+ type event: GNUe Event
+ param event: The event request
+ """
+ wizard = TemplateChooser.TemplateChooser(self).run()
+ if wizard != None:
+ self.RunWizard(wizard)
- def OnOpen(self, event):
- """
- Handles the request to open a file
+ def OnOpen(self, event):
+ """
+ Handles the request to open a file
- type event: GNUe Event
- param event: The event request
- """
+ type event: GNUe Event
+ param event: The event request
+ """
- path = self.ui.dialogOpenFile(u_("Open GNUe File..."),
- wildcards = self.supportedOpenWildcard)
+ path = self.ui.dialogOpenFile(u_("Open GNUe File..."),
+ wildcards = self.supportedOpenWildcard)
- if path:
- if self.isFileOpened(path):
- self.ui.dialogOk( u_("File is already opened."), u_("Notice"))
- else:
- self.load(path)
+ if path:
+ if self.isFileOpened(path):
+ self.ui.dialogOk( u_("File is already opened."), u_("Notice"))
+ else:
+ self.load(path)
- def OnOpenRecent(self, event):
- """
- Handles the request to open a recent opened URL
+ def OnOpenRecent(self, event):
+ """
+ Handles the request to open a recent opened URL
- type event: GNUe Event
- param event: The event request
- """
- location = self.mru.mruMenuMap[event.GetId()]
- if not self.isFileOpened(location):
- self.load(location )
+ type event: GNUe Event
+ param event: The event request
+ """
+ location = self.mru.mruMenuMap[event.GetId()]
+ if not self.isFileOpened(location):
+ self.load(location )
- def OnExit(self, event=None):
- """
- Handles the request for application exit
+ def OnExit(self, event=None):
+ """
+ Handles the request for application exit
- type event: GNUe Event
- param event: The event request
- """
- for instance in self._instances[:]:
- # TODO: this should be an event
- instance._OnClose(event)
- #
- # If this Close() causes issues you can replace
- # with the following.
- #
- #RuntimeSettings.saveRuntimeSettings(instance)
- #instance.Destroy()
+ type event: GNUe Event
+ param event: The event request
+ """
+ for instance in self._instances[:]:
+ # TODO: this should be an event
+ instance._OnClose(event)
+ #
+ # If this Close() causes issues you can replace
+ # with the following.
+ #
+ #RuntimeSettings.saveRuntimeSettings(instance)
+ #instance.Destroy()
- def OnSaveAll(self, event):
- """
- Handles the request for all instances to save their files
+ def OnSaveAll(self, event):
+ """
+ Handles the request for all instances to save their files
- type event: GNUe Event
- param event: The event request
- """
- for instance in self._instances:
- if instance.isDirty():
- instance.OnSave(event)
+ type event: GNUe Event
+ param event: The event request
+ """
+ for instance in self._instances:
+ if instance.isDirty():
+ instance.OnSave(event)
- def OnAbout(self, event):
- """
- Handles the request for an about box
+ def OnAbout(self, event):
+ """
+ Handles the request for an about box
- type event: GNUe Event
- param event: The event request
- """
+ type event: GNUe Event
+ param event: The event request
+ """
- imports = []
- for f in ('common','forms','reports','appserver','navigator'):
- try:
- v = {}
- exec 'from gnue.%s import __version__, PACKAGE' % f in v
- imports.append('%s Version %s' % (v['PACKAGE'], v['__version__']))
- except:
- pass
+ imports = []
+ for f in ('common','forms','reports','appserver','navigator'):
+ try:
+ v = {}
+ exec 'from gnue.%s import __version__, PACKAGE' % f in v
+ imports.append('%s Version %s' % (v['PACKAGE'],
v['__version__']))
+ except:
+ pass
- from wxPython import __version__ as v
- imports.append('wxPython Version %s' % v)
+ from wxPython import __version__ as v
+ imports.append('wxPython Version %s' % v)
- from sys import version as v
- imports.append('Python Version %s' % v.replace('\n','\n '))
+ from sys import version as v
+ imports.append('Python Version %s' % v.replace('\n','\n '))
- self.ui.dialogOk(self.NAME + " " +
- u_("Version ") + self.VERSION + "\n\n" +
- u_("Copyright 2001-2006 Free Software Foundation\n\n") +
- u_("Environment:\n %s\n\n") % string.join(imports,'\n
') +
- u_("For help, email address@hidden"),
- u_("About ") + self.NAME)
+ self.ui.dialogOk(self.NAME + " " +
+ u_("Version ") + self.VERSION + "\n\n" +
+ u_("Copyright 2001-2006 Free Software
Foundation\n\n") +
+ u_("Environment:\n %s\n\n") %
string.join(imports,'\n ') +
+ u_("For help, email address@hidden"),
+ u_("About ") + self.NAME)
- def OnNew(self, event):
- """
- Handles the request when for a new instance of a designer editor module
+ def OnNew(self, event):
+ """
+ Handles the request when for a new instance of a designer editor module
- type event: GNUe Event
- param event: The event request
- """
- self.newDocument(event.type)
+ type event: GNUe Event
+ param event: The event request
+ """
+ self.newDocument(event.type)
- # ==========================================================================
- # Support functions
- # ==========================================================================
+ #
==========================================================================
+ # Support functions
+ #
==========================================================================
- def isDirty(self):
- """
- Determines if all instances currently have unsaved edits.
+ def isDirty(self):
+ """
+ Determines if all instances currently have unsaved edits.
- @rtype: boolean
- @return: True if any instance contains unsaved information
- False if all instances are saved
- """
- isdirty = False
- for instance in self._instances:
- if instance.isDirty():
- isdirty = True
- break
- return isdirty
+ @rtype: boolean
+ @return: True if any instance contains unsaved information
+ False if all instances are saved
+ """
+ isdirty = False
+ for instance in self._instances:
+ if instance.isDirty():
+ isdirty = True
+ break
+ return isdirty
- def isFileOpened(self, location):
- """
- Determines if an instance already has the requested file open.
+ def isFileOpened(self, location):
+ """
+ Determines if an instance already has the requested file open.
- TODO: Currently this function is not implemented. It always
- returns False.
+ TODO: Currently this function is not implemented. It always
+ returns False.
- @rtype: boolean
- @return: True if any instance contains the requested file
- False if the file is not currently loaded
- """
+ @rtype: boolean
+ @return: True if any instance contains the requested file
+ False if the file is not currently loaded
+ """
- return False
+ return False
- def RunWizard(self, templateInformation):
- """
+ def RunWizard(self, templateInformation):
+ """
- """
- product = templateInformation['Product']
- templateSupport = dyn_import('gnue.designer.%s.TemplateSupport' % product)
+ """
+ product = templateInformation['Product']
+ templateSupport = dyn_import('gnue.designer.%s.TemplateSupport' %
product)
- try:
- style = templateInformation['ProductStyle']
- except:
- style = None
+ try:
+ style = templateInformation['ProductStyle']
+ except:
+ style = None
- instance = self.newDocument(product, style=style)
+ instance = self.newDocument(product, style=style)
- if not TemplateParser.TemplateParser(instance, instance.rootObject,
- instance.ui, templateInformation).run():
- instance.ui.close()
+ if not TemplateParser.TemplateParser(instance, instance.rootObject,
+ instance.ui, templateInformation).run():
+ instance.ui.close()
if __name__ == '__main__':
- Designer().run()
-
+ Designer().run()
Modified: trunk/gnue-designer/src/__init__.py
===================================================================
--- trunk/gnue-designer/src/__init__.py 2006-04-03 19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/__init__.py 2006-04-03 19:56:14 UTC (rev 8344)
@@ -36,14 +36,14 @@
# Version will be of the form "1.1.2" if a release or "1.1.1.99" if in CVS
if _release:
- VERSION="%s.%s.%s" % _version
+ VERSION="%s.%s.%s" % _version
else:
- _t = (("%08d" % (int("%02d%02d%02d00" % _version)-1) ).replace('99','') +
'99') + '0000000'
- if _t[6:8] != '00':
- extra = '.99'
- else:
- extra = ''
- VERSION = "%s.%s.%s%s" % (int(_t[:2]), int(_t[2:4]), int(_t[4:6]), extra)
+ _t = (("%08d" % (int("%02d%02d%02d00" % _version)-1) ).replace('99','') +
'99') + '0000000'
+ if _t[6:8] != '00':
+ extra = '.99'
+ else:
+ extra = ''
+ VERSION = "%s.%s.%s%s" % (int(_t[:2]), int(_t[2:4]), int(_t[4:6]), extra)
# Hex Version will be an integer in which version 1.2.15 is represented
# as 0x010215FF (for a release) or 0x01021500 (for a CVS snapshot)
@@ -59,5 +59,3 @@
PACKAGE='GNUe-Designer'
TITLE = 'GNUe Designer'
-
-
Modified: trunk/gnue-designer/src/base/Document.py
===================================================================
--- trunk/gnue-designer/src/base/Document.py 2006-04-03 19:53:03 UTC (rev
8343)
+++ trunk/gnue-designer/src/base/Document.py 2006-04-03 19:56:14 UTC (rev
8344)
@@ -64,771 +64,770 @@
class BaseDocument(EventController):
- #==========================================================================
- # Virtual functions (Override these functions in your Instance)
- #==========================================================================
- wizardRunner = WizardRunner
+ #==========================================================================
+ # Virtual functions (Override these functions in your Instance)
+ #==========================================================================
+ wizardRunner = WizardRunner
- def init(self):
- """
- initialize the instance (called at the
- beginning of the __init__ process)
- """
+ def init(self):
+ """
+ initialize the instance (called at the
+ beginning of the __init__ process)
+ """
- def init(self):
- """
- Finalize the instance (called at the
- end of the __init__ process)
- """
+ def init(self):
+ """
+ Finalize the instance (called at the
+ end of the __init__ process)
+ """
- def loadFile(self, buffer):
- """
- Called to load the object from a file buffer/handle
- """
- return None
+ def loadFile(self, buffer):
+ """
+ Called to load the object from a file buffer/handle
+ """
+ return None
- def loadEmpty(self, style=None):
- """
- Called to load an "empty" (new) object. Create the root object
- and any initial child objects (if appropriate)
- """
- return None
+ def loadEmpty(self, style=None):
+ """
+ Called to load an "empty" (new) object. Create the root object
+ and any initial child objects (if appropriate)
+ """
+ return None
- def inventoryObject(self, object):
- """
- Called in a tree-like fashion for every object
- whether loaded in the beginning or later added.
- """
- pass
+ def inventoryObject(self, object):
+ """
+ Called in a tree-like fashion for every object
+ whether loaded in the beginning or later added.
+ """
+ pass
- def preSave(self):
- """
- Called just before saving the file using GObject's dumpTree
- You might do some sanity checks, etc.
- """
- return
+ def preSave(self):
+ """
+ Called just before saving the file using GObject's dumpTree
+ You might do some sanity checks, etc.
+ """
+ return
- def createTools(self):
- """
- Add any ToolBase instances
- """
- pass
+ def createTools(self):
+ """
+ Add any ToolBase instances
+ """
+ pass
- def createEditors(self):
- """
- Add any EditorComponent instances
- """
- pass
+ def createEditors(self):
+ """
+ Add any EditorComponent instances
+ """
+ pass
- def createWizards(self):
- """
- Add any runtime-loadable wizards/tools
- """
- pass
+ def createWizards(self):
+ """
+ Add any runtime-loadable wizards/tools
+ """
+ pass
- def initMenu(self):
- """
- Add any tool-specific functions to the menu bar
- """
- pass
+ def initMenu(self):
+ """
+ Add any tool-specific functions to the menu bar
+ """
+ pass
- def initToolBar(self):
- """
- Add any tool-specific functions to the tool bar
- """
- pass
+ def initToolBar(self):
+ """
+ Add any tool-specific functions to the tool bar
+ """
+ pass
- def buildWizardCurrentDict(self):
- """
- Used by TemplateParser to build a wizard.current dict
- """
- return {'object': self._currentObject}
+ def buildWizardCurrentDict(self):
+ """
+ Used by TemplateParser to build a wizard.current dict
+ """
+ return {'object': self._currentObject}
- #==========================================================================
- # Public Functions
- #==========================================================================
+ #==========================================================================
+ # Public Functions
+ #==========================================================================
- #--------------------------------------------------------------------------
- # Register interface elements
- #--------------------------------------------------------------------------
- def addTool(self, id, title, baseclass, hotkey=None, menuGroup=499):
- """
- Add a ToolBase instance
- """
- self._toolCache.append( (id, title, baseclass, hotkey, menuGroup) )
+ #--------------------------------------------------------------------------
+ # Register interface elements
+ #--------------------------------------------------------------------------
+ def addTool(self, id, title, baseclass, hotkey=None, menuGroup=499):
+ """
+ Add a ToolBase instance
+ """
+ self._toolCache.append( (id, title, baseclass, hotkey, menuGroup) )
- def registerEditor(self, baseclass, gtype, filter=None):
- """
- Register an editor class
+ def registerEditor(self, baseclass, gtype, filter=None):
+ """
+ Register an editor class
- Parameters:
+ Parameters:
- baseclass: An EditorComponent class
+ baseclass: An EditorComponent class
- gtype: A string indicating a GObject._type identifier,
- or a list of such strings.
+ gtype: A string indicating a GObject._type identifier,
+ or a list of such strings.
- filter: A function that is passed a GObject and should
- return True/False indicating if an editor instance
- should be created.
+ filter: A function that is passed a GObject and should
+ return True/False indicating if an editor instance
+ should be created.
- """
- if isinstance(gtype,basestring):
- gtype = [gtype]
- for gtype1 in gtype:
- self._editorMapping[gtype1] = (filter, baseclass)
+ """
+ if isinstance(gtype,basestring):
+ gtype = [gtype]
+ for gtype1 in gtype:
+ self._editorMapping[gtype1] = (filter, baseclass)
- #--------------------------------------------------------------------------
- # Set the saved/unsaved status
- #--------------------------------------------------------------------------
+ #--------------------------------------------------------------------------
+ # Set the saved/unsaved status
+ #--------------------------------------------------------------------------
- def save(self):
+ def save(self):
- if self.preSave():
- print "Not saving definition"
- return
+ if self.preSave():
+ print "Not saving definition"
+ return
- location = self._path
- fileHandle = None
- fileHandle2 = None
- if self._makeBackup:
- try:
- fileHandle = open(location,'r')
- fileHandle2 = open(location + "~",'w')
- fileHandle2.writelines(fileHandle.readlines())
- except:
- pass
- else:
- if fileHandle != None:
- fileHandle.close()
- if fileHandle2 != None:
- fileHandle2.close()
+ location = self._path
+ fileHandle = None
+ fileHandle2 = None
+ if self._makeBackup:
+ try:
+ fileHandle = open(location,'r')
+ fileHandle2 = open(location + "~",'w')
+ fileHandle2.writelines(fileHandle.readlines())
+ except:
+ pass
+ else:
+ if fileHandle != None:
+ fileHandle.close()
+ if fileHandle2 != None:
+ fileHandle2.close()
- self._makeBackup = 0
+ self._makeBackup = 0
- fileHandle = open(location,'w')
+ fileHandle = open(location,'w')
- fileHandle.write('<?xml version="1.0" encoding="%s"?>\n\n' % \
- gConfig('textEncoding'))
+ fileHandle.write('<?xml version="1.0" encoding="%s"?>\n\n' % \
+ gConfig('textEncoding'))
- for comment in self.rootObject._rootComments:
- if comment.find(TITLE) > 0:
- self.rootObject._rootComments.remove(comment)
+ for comment in self.rootObject._rootComments:
+ if comment.find(TITLE) > 0:
+ self.rootObject._rootComments.remove(comment)
- # Place a timestamp in the XML as a comment
- # TODO: Replace with Dublin Core?
- fileHandle.write('<!-- %s (%s)\n%s Saved on: %s -->\n\n' \
- % (TITLE, VERSION, (len(self.wizardName) and (" Created by " +
self.wizardName + "\n") or ""),\
- time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))))
+ # Place a timestamp in the XML as a comment
+ # TODO: Replace with Dublin Core?
+ fileHandle.write('<!-- %s (%s)\n%s Saved on: %s -->\n\n' \
+ % (TITLE, VERSION, (len(self.wizardName) and (" Created by " +
self.wizardName + "\n") or ""),\
+ time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))))
- fileHandle.write(''.join(["<!--%s-->\n\n" %
comment.encode(gConfig('textEncoding')) \
- for comment in self.rootObject._rootComments]))
+ fileHandle.write(''.join(["<!--%s-->\n\n" %
comment.encode(gConfig('textEncoding')) \
+ for comment in self.rootObject._rootComments]))
-
fileHandle.write(self.rootObject.dumpXML(treeDump=True).encode(gConfig('textEncoding')))
- fileHandle.close()
+
fileHandle.write(self.rootObject.dumpXML(treeDump=True).encode(gConfig('textEncoding')))
+ fileHandle.close()
- self.app.mru.addLocation(location)
- self.makeClean()
+ self.app.mru.addLocation(location)
+ self.makeClean()
- # Mark our form as "dirty" (unsaved changes)
- def makeDirty(self):
- if not self._isdirty:
- self._isdirty = True
- if self._path == "":
- self.ui.setTitle( u_("Untitled %s*") % self.properties.nickname)
- else:
- self.ui.setTitle(self._path + "*")
- self.dispatchEvent('MakeDirty')
+ # Mark our form as "dirty" (unsaved changes)
+ def makeDirty(self):
+ if not self._isdirty:
+ self._isdirty = True
+ if self._path == "":
+ self.ui.setTitle( u_("Untitled %s*") %
self.properties.nickname)
+ else:
+ self.ui.setTitle(self._path + "*")
+ self.dispatchEvent('MakeDirty')
- # Mark our form as "clean" (no unsaved changes)
- def makeClean(self):
- self._isdirty = 0
- self._isnew = 0
- if self._path == "":
- self.ui.setTitle( u_("Untitled %s") % self.properties.nickname)
- else:
- self.ui.setTitle( self._path)
- self.dispatchEvent('MakeClean')
+ # Mark our form as "clean" (no unsaved changes)
+ def makeClean(self):
+ self._isdirty = 0
+ self._isnew = 0
+ if self._path == "":
+ self.ui.setTitle( u_("Untitled %s") % self.properties.nickname)
+ else:
+ self.ui.setTitle( self._path)
+ self.dispatchEvent('MakeClean')
- #--------------------------------------------------------------------------
- # GObject convenience methods
- #--------------------------------------------------------------------------
- def getNextGenericName (self, type):
- return self.getUniqueName(type.capitalize() + '1')
+ #--------------------------------------------------------------------------
+ # GObject convenience methods
+ #--------------------------------------------------------------------------
+ def getNextGenericName (self, type):
+ return self.getUniqueName(type.capitalize() + '1')
- def getUniqueName(self, name, limitingObject=None):
+ def getUniqueName(self, name, limitingObject=None):
- try:
- usedNames = limitingObject.usedNames
- except:
- usedNames = self.usedNames
+ try:
+ usedNames = limitingObject.usedNames
+ except:
+ usedNames = self.usedNames
- if name.lower() not in usedNames:
- usedNames.append(name.lower())
- return name
+ if name.lower() not in usedNames:
+ usedNames.append(name.lower())
+ return name
- index = len(name) - 1
+ index = len(name) - 1
- while index > 0 and '0' <= name[index] <= '9':
- index -= 1
+ while index > 0 and '0' <= name[index] <= '9':
+ index -= 1
- index += 1
- if index >= len(name):
- start = 1
- base = name
- else:
- start = int(name[index:])
- base = name[:index]
+ index += 1
+ if index >= len(name):
+ start = 1
+ base = name
+ else:
+ start = int(name[index:])
+ base = name[:index]
- while ("%s%s" % (base, start)).lower() in usedNames:
- start += 1
+ while ("%s%s" % (base, start)).lower() in usedNames:
+ start += 1
- rv = "%s%s" % (base, start)
- usedNames.append(rv.lower())
- if rv.lower() not in self.usedNames:
- self.usedNames.append(rv.lower())
- return rv
+ rv = "%s%s" % (base, start)
+ usedNames.append(rv.lower())
+ if rv.lower() not in self.usedNames:
+ self.usedNames.append(rv.lower())
+ return rv
- #--------------------------------------------------------------------------
- # Return, or create, an ObjectList based on the xml tag
- #--------------------------------------------------------------------------
- def getObjectList(self, tag):
- try:
- return self.objectLists[tag]
- except KeyError:
- defin = self.incubator.elements[tag]
- baseClass = defin['BaseClass']
+ #--------------------------------------------------------------------------
+ # Return, or create, an ObjectList based on the xml tag
+ #--------------------------------------------------------------------------
+ def getObjectList(self, tag):
+ try:
+ return self.objectLists[tag]
+ except KeyError:
+ defin = self.incubator.elements[tag]
+ baseClass = defin['BaseClass']
- # Determine the "name" attribute"
- nameAttr = None
- try:
- if defin['Attributes'].has_key('name'):
- nameAttr = 'name'
- else:
- for attribute, props in defin['Attributes'].items():
+ # Determine the "name" attribute"
+ nameAttr = None
try:
- if props['Unique']:
- nameAttr = attribute
- break
+ if defin['Attributes'].has_key('name'):
+ nameAttr = 'name'
+ else:
+ for attribute, props in defin['Attributes'].items():
+ try:
+ if props['Unique']:
+ nameAttr = attribute
+ break
+ except KeyError:
+ pass
except KeyError:
- pass
- except KeyError:
- pass
+ pass
- list = ObjectList(self, baseClass, nameAttr)
- self.objectLists[tag] = list
- return list
+ list = ObjectList(self, baseClass, nameAttr)
+ self.objectLists[tag] = list
+ return list
- #==========================================================================
- # Private functions
- #==========================================================================
+ #==========================================================================
+ # Private functions
+ #==========================================================================
- def __init__(self, app, location=None, buffer=None, style=None):
- EventController.__init__(self)
+ def __init__(self, app, location=None, buffer=None, style=None):
+ EventController.__init__(self)
- self.app = app
- self.ui = app.ui.createInstance(self)
+ self.app = app
+ self.ui = app.ui.createInstance(self)
- # During startup, we will cache all events
- # so we can execute them when everything has
- # been initialized.
- self.startCachingEvents()
+ # During startup, we will cache all events
+ # so we can execute them when everything has
+ # been initialized.
+ self.startCachingEvents()
- # Local variables
- self.wizardName = ""
- self._isdirty = False
- self._makeBackup = True
- self._isNew = True
- self.connections = app.connections
- self.nameMappings = {}
- self.usedNames = []
+ # Local variables
+ self.wizardName = ""
+ self._isdirty = False
+ self._makeBackup = True
+ self._isNew = True
+ self.connections = app.connections
+ self.nameMappings = {}
+ self.usedNames = []
- # Create the supplemental tools
- self._toolCache = []
- self._editorMapping = {}
- self._pages = []
- self.objectLists = {}
- self._path = ""
+ # Create the supplemental tools
+ self._toolCache = []
+ self._editorMapping = {}
+ self._pages = []
+ self.objectLists = {}
+ self._path = ""
- self.globalAccelerators = []
- self.globalAcceleratorListeners = []
+ self.globalAccelerators = []
+ self.globalAcceleratorListeners = []
- self._nameMappers = {} # {GDataSource: {'name': [(GFBlock,'name')]}}
+ self._nameMappers = {} # {GDataSource: {'name': [(GFBlock,'name')]}}
- self.registerEventListeners({
- # Menu/Toolbar stuff
- 'RequestSave' : self._OnSave,
- 'RequestSaveAs' : self._OnSaveAs,
- 'RequestClose' : self._OnClose,
+ self.registerEventListeners({
+ # Menu/Toolbar stuff
+ 'RequestSave' : self._OnSave,
+ 'RequestSaveAs' : self._OnSaveAs,
+ 'RequestClose' : self._OnClose,
- # Object stuff
- 'ObjectSelected' : self.__onSetCurrentObject,
- 'ObjectCreated' : self.__onCreateObject,
- 'ObjectModified' : self.__onModifyObject,
- 'ObjectDeleted' : self.__onDeleteObject,
- })
+ # Object stuff
+ 'ObjectSelected' : self.__onSetCurrentObject,
+ 'ObjectCreated' : self.__onCreateObject,
+ 'ObjectModified' : self.__onModifyObject,
+ 'ObjectDeleted' : self.__onDeleteObject,
+ })
- # Call the document-specific init method
- self.init()
+ # Call the document-specific init method
+ self.init()
- # Register ourself with RuntimeSettings
- RuntimeSettings.init(configFilename="gnue-des.ini", homeConfigDir=".gnue")
- RuntimeSettings.registerInstance(self)
+ # Register ourself with RuntimeSettings
+ RuntimeSettings.init(configFilename="gnue-des.ini",
homeConfigDir=".gnue")
+ RuntimeSettings.registerInstance(self)
- # Tell RuntimeSettings that we have information to save
- self.runtime_section = self.properties.nickname + 'Layout'
- RuntimeSettings.registerRuntimeSettingHandler(self, self)
+ # Tell RuntimeSettings that we have information to save
+ self.runtime_section = self.properties.nickname + 'Layout'
+ RuntimeSettings.registerRuntimeSettingHandler(self, self)
- # And the "Most Recenty Used" manager
- RuntimeSettings.registerRuntimeSettingHandler(self, app.mru)
+ # And the "Most Recenty Used" manager
+ RuntimeSettings.registerRuntimeSettingHandler(self, app.mru)
- # Set up the Undo/Redo Manager
- UndoManager(self)
+ # Set up the Undo/Redo Manager
+ UndoManager(self)
- # Load any files specified on the command line, or create a new document
- if location == None:
+ # Load any files specified on the command line, or create a new
document
+ if location == None:
- if buffer != None:
- self.__loadFromBuffer(buffer)
- self.makeDirty()
- else:
- self.__createEmptyInstance(style)
+ if buffer != None:
+ self.__loadFromBuffer(buffer)
+ self.makeDirty()
+ else:
+ self.__createEmptyInstance(style)
- else:
- if not os.access (location, os.R_OK):
- self.show()
- if not self.ui.dialogYesNo(
- u_('The requested file does not exist.\n') +
- u_('Do you want to create this file?') +
- u_('\n\nFile: %s') \
- % location, u_("File Not Found"), self.ui):
- # TODO: Is this right?
- sys.exit()
- self.hide()
- self.__createEmptyInstance(style)
- self._path = location
- self.makeDirty()
+ else:
+ if not os.access (location, os.R_OK):
+ self.show()
+ if not self.ui.dialogYesNo(
+ u_('The requested file does not exist.\n') +
+ u_('Do you want to create this file?') +
+ u_('\n\nFile: %s') \
+ % location, u_("File Not Found"), self.ui):
+ # TODO: Is this right?
+ sys.exit()
+ self.hide()
+ self.__createEmptyInstance(style)
+ self._path = location
+ self.makeDirty()
- elif not os.access (location, os.W_OK):
- self.show()
- if not self.ui.dialogCancel(
- u_('The requested file is Read Only.\n') +
- u_('To save any changes, you will \n') +
- u_('be required to do a "Save As..."\n\nFile: %s') \
- % location, u_("Read Only Warning"), self.ui) :
- # TODO: Is this right?
- sys.exit()
- self.hide()
- self.__loadFromFile(location)
- else:
- self.__loadFromFile(location)
+ elif not os.access (location, os.W_OK):
+ self.show()
+ if not self.ui.dialogCancel(
+ u_('The requested file is Read Only.\n') +
+ u_('To save any changes, you will \n') +
+ u_('be required to do a "Save As..."\n\nFile: %s') \
+ % location, u_("Read Only Warning"), self.ui) :
+ # TODO: Is this right?
+ sys.exit()
+ self.hide()
+ self.__loadFromFile(location)
+ else:
+ self.__loadFromFile(location)
- self.menubar = MenuBar(self)
+ self.menubar = MenuBar(self)
- gStartupStatus(u_('Creating User Interface'))
+ gStartupStatus(u_('Creating User Interface'))
- # Set up the menu system
- # ... our common menu
- self._initMenu()
- # ... and the document-centric menu
- self.initMenu()
+ # Set up the menu system
+ # ... our common menu
+ self._initMenu()
+ # ... and the document-centric menu
+ self.initMenu()
- self.createWizards()
+ self.createWizards()
- # Set up the editor components...
- # ... common
- self.registerEditor(TriggerEditor.TriggerEditor, 'GCTrigger',
- TriggerEditor.EditorFilter)
- # ... and document-centric
- self.createEditors()
+ # Set up the editor components...
+ # ... common
+ self.registerEditor(TriggerEditor.TriggerEditor, 'GCTrigger',
+ TriggerEditor.EditorFilter)
+ # ... and document-centric
+ self.createEditors()
- # Create the document-centric tools
- self.createTools()
+ # Create the document-centric tools
+ self.createTools()
- # And tell the UI driver to create the UI portions
- self.ui.initTools()
+ # And tell the UI driver to create the UI portions
+ self.ui.initTools()
- # Finalize menu bar
- self.menubar.finalize()
- self.app.mru.addMenu(self.menubar.getMenu('File|Open Recent|'), self)
+ # Finalize menu bar
+ self.menubar.finalize()
+ self.app.mru.addMenu(self.menubar.getMenu('File|Open Recent|'), self)
- self.toolbar = self.ui.toolbar
- self.initToolBar()
+ self.toolbar = self.ui.toolbar
+ self.initToolBar()
- # TODO: This is a hack to disable any menu items
- # TODO: for actions we've yet to implement
- for action in ('RequestRevert','RequestRedo','RequestCopy',
- 'RequestPaste','RequestPasteSpecial','RequestCut'):
- self.dispatchEvent('Disable:%s' % action)
+ # TODO: This is a hack to disable any menu items
+ # TODO: for actions we've yet to implement
+ for action in ('RequestRevert','RequestRedo','RequestCopy',
+ 'RequestPaste','RequestPasteSpecial','RequestCut'):
+ self.dispatchEvent('Disable:%s' % action)
- # Add ourselve to the main app's instance list
- self.app.addDocument(self)
+ # Add ourselve to the main app's instance list
+ self.app.addDocument(self)
- self.dispatchEvent('ObjectSelected', originator=self,
- object=self.rootObject)
+ self.dispatchEvent('ObjectSelected', originator=self,
+ object=self.rootObject)
- # Inventory the objects
- gStartupStatus(u_('Inventorying Document Objects'))
- self.rootObject.walk(self.__inventory)
+ # Inventory the objects
+ gStartupStatus(u_('Inventorying Document Objects'))
+ self.rootObject.walk(self.__inventory)
- self.finalize()
- self.ui.finalize()
+ self.finalize()
+ self.ui.finalize()
- self.stopCachingEvents()
+ self.stopCachingEvents()
- def _initMenu(self):
- # Add the [sub]menus
- for location, text, grouping in (
- ('File', u_('&File'), 100),
- ('File|New', u_('&New'), 100),
- ('File|Open Recent', u_('&Open Recent'), 200.1),
- ('File|Connect To', u_('&Connect To'), 400),
- ('Edit', u_('&Edit'), 200),
- ('Insert',u_('&Insert'), 300),
- ('Modify',u_('&Modify'), 400),
- ('Tools',u_('&Tools'), 500),
- ('View',u_('&View'), 800),
- ('Help',u_('&Help'), 999)):
+ def _initMenu(self):
+ # Add the [sub]menus
+ for location, text, grouping in (
+ ('File', u_('&File'), 100),
+ ('File|New', u_('&New'), 100),
+ ('File|Open Recent', u_('&Open Recent'), 200.1),
+ ('File|Connect To', u_('&Connect To'), 400),
+ ('Edit', u_('&Edit'), 200),
+ ('Insert',u_('&Insert'), 300),
+ ('Modify',u_('&Modify'), 400),
+ ('Tools',u_('&Tools'), 500),
+ ('View',u_('&View'), 800),
+ ('Help',u_('&Help'), 999)):
- self.menubar.addMenu(location, text, grouping)
+ self.menubar.addMenu(location, text, grouping)
- for location, event, text, hotkey, help, grouping in (
- ('File', 'RequestOpen', u_('&Open'), 'Ctrl+O', u_("Open an existing
document"), 200.1),
- ('File|Open Recent', 'XXXX', u_('&Foo'), None, u_("This is a
placeholder for the Open Recent menu"), 200.1),
- ('File|New', 'RequestNewWizard', u_('From &Wizard...'), None,
u_("Create a new document using a wizard"), 900.1),
- ('File', 'RequestSave', u_("&Save"), 'Ctrl+S', u_("Save the current
document"),300.1),
- ('File', 'RequestSaveAs', u_("Save &As..."),None, u_("Save the current
document under a new name"), 300.2),
- ('File', 'RequestSaveAll', u_("Save A&ll"),None,u_("Save all open
document"),300.3),
- ('File', 'RequestRevert', u_("Reload"), None, u_("Reload the current
document as of its last save (abandoning any changes)"), 500),
- ('File', 'RequestClose', u_("&Close"), 'Ctrl+W', u_("Close the current
document"), 990),
- ('File', 'RequestExit', u_("E&xit"), None, u_("Exit GNUe Designer"),
995),
- ('Edit', 'RequestUndo', u_("&Undo"), 'Ctrl+Z', u_("Undo the last
action"), 100.1),
- ('Edit', 'RequestRedo', u_("&Redo"), 'Ctrl+Y', u_("Redo the last undo
action"), 100.2),
- ('Edit', 'RequestCut', u_("Cu&t"), 'Ctrl+X', u_("Cut the current object
and move to the clipboard"), 200.1),
- ('Edit', 'RequestCopy', u_("&Copy"), 'Ctrl+C', u_("Copy the current
object to the clipboard"), 200.2),
- ('Edit', 'RequestPaste', u_("&Paste"), 'Ctrl+V', u_("Paste the current
object on the clipboard"), 200.3),
- ('Edit', 'RequestPasteSpecial', u_("Paste &Special..."), None,
u_("Paste the current object on the clipboard with special attributes"), 200.4),
- ('Modify','RequestDelete', u_("&Delete Item"), 'Delete', u_("Delete the
current object"),100),
- ('Help', 'RequestAbout', u_("&About GNUe Designer"), None, u_("More
information about GNUe Designer"), 900),
- ):
- self.menubar.addAction(location, text, event,
- grouping, canDisable=True,
- icon=None, hotkey=hotkey, help=help)
+ for location, event, text, hotkey, help, grouping in (
+ ('File', 'RequestOpen', u_('&Open'), 'Ctrl+O', u_("Open an existing
document"), 200.1),
+ ('File|Open Recent', 'XXXX', u_('&Foo'), None, u_("This is a
placeholder for the Open Recent menu"), 200.1),
+ ('File|New', 'RequestNewWizard', u_('From &Wizard...'), None,
u_("Create a new document using a wizard"), 900.1),
+ ('File', 'RequestSave', u_("&Save"), 'Ctrl+S', u_("Save the current
document"),300.1),
+ ('File', 'RequestSaveAs', u_("Save &As..."),None, u_("Save the
current document under a new name"), 300.2),
+ ('File', 'RequestSaveAll', u_("Save A&ll"),None,u_("Save all open
document"),300.3),
+ ('File', 'RequestRevert', u_("Reload"), None, u_("Reload the
current document as of its last save (abandoning any changes)"), 500),
+ ('File', 'RequestClose', u_("&Close"), 'Ctrl+W', u_("Close the
current document"), 990),
+ ('File', 'RequestExit', u_("E&xit"), None, u_("Exit GNUe
Designer"), 995),
+ ('Edit', 'RequestUndo', u_("&Undo"), 'Ctrl+Z', u_("Undo the last
action"), 100.1),
+ ('Edit', 'RequestRedo', u_("&Redo"), 'Ctrl+Y', u_("Redo the last
undo action"), 100.2),
+ ('Edit', 'RequestCut', u_("Cu&t"), 'Ctrl+X', u_("Cut the current
object and move to the clipboard"), 200.1),
+ ('Edit', 'RequestCopy', u_("&Copy"), 'Ctrl+C', u_("Copy the current
object to the clipboard"), 200.2),
+ ('Edit', 'RequestPaste', u_("&Paste"), 'Ctrl+V', u_("Paste the
current object on the clipboard"), 200.3),
+ ('Edit', 'RequestPasteSpecial', u_("Paste &Special..."), None,
u_("Paste the current object on the clipboard with special attributes"), 200.4),
+ ('Modify','RequestDelete', u_("&Delete Item"), 'Delete', u_("Delete
the current object"),100),
+ ('Help', 'RequestAbout', u_("&About GNUe Designer"), None, u_("More
information about GNUe Designer"), 900),
+ ):
+ self.menubar.addAction(location, text, event,
+ grouping, canDisable=True,
+ icon=None, hotkey=hotkey, help=help)
- # Add supported tools to File|New
- for tool in SupportedModules:
- self.menubar.addAction('File|New', '&%s' % tool.properties.nickname,
- 'RequestNew', 100,
- help=u_('Create a new %s') % tool.properties.nickname.lower(),
eventdata={'type': tool.properties.module })
+ # Add supported tools to File|New
+ for tool in SupportedModules:
+ self.menubar.addAction('File|New', '&%s' %
tool.properties.nickname,
+ 'RequestNew', 100,
+ help=u_('Create a new %s') % tool.properties.nickname.lower(),
eventdata={'type': tool.properties.module })
- # Add connections
- for conn in self.connections.getAllConnectionParameters().keys():
- self.menubar.addAction('File|Connect To', conn, 'Connect:%s' % conn,
- help=u_("Login to %s connection") % conn,
- eventdata={'connection': conn})
- self.registerEventListeners({'Connect:%s' % conn:self.__OnConnectTo})
+ # Add connections
+ for conn in self.connections.getAllConnectionParameters().keys():
+ self.menubar.addAction('File|Connect To', conn, 'Connect:%s' %
conn,
+ help=u_("Login to %s connection") % conn,
+ eventdata={'connection': conn})
+ self.registerEventListeners({'Connect:%s' %
conn:self.__OnConnectTo})
- def __loadFromFile(self, location):
- try:
- self._path = location
- fileHandle = open(location,'r')
- self.__loadFromBuffer(fileHandle)
- fileHandle.close()
- self.makeClean()
- self._isNew = 0
- except IOError, msg:
- print "\n%s %s\n\nUnable to open file '%s'. \nUnexpected read error:\n
%s.\n" % (TITLE, VERSION, location, msg)
- sys.exit()
- self.app.mru.addLocation(location)
+ def __loadFromFile(self, location):
+ try:
+ self._path = location
+ fileHandle = open(location,'r')
+ self.__loadFromBuffer(fileHandle)
+ fileHandle.close()
+ self.makeClean()
+ self._isNew = 0
+ except IOError, msg:
+ print "\n%s %s\n\nUnable to open file '%s'. \nUnexpected read
error:\n %s.\n" % (TITLE, VERSION, location, msg)
+ sys.exit()
+ self.app.mru.addLocation(location)
- def addNameMapper(self, instance, attribute, childinst, childattr):
- try:
- instm = self._nameMappers[instance]
- except KeyError:
- instm = {}
- self._nameMappers[instance] = instm
- try:
- attrm = instm[attribute]
- except KeyError:
- attrm = []
- instm[attribute] = attrm
- attrm.append ( (childinst, childattr) )
+ def addNameMapper(self, instance, attribute, childinst, childattr):
+ try:
+ instm = self._nameMappers[instance]
+ except KeyError:
+ instm = {}
+ self._nameMappers[instance] = instm
+ try:
+ attrm = instm[attribute]
+ except KeyError:
+ attrm = []
+ instm[attribute] = attrm
+ attrm.append ( (childinst, childattr) )
- def __loadFromBuffer(self, fileHandle):
- self.rootObject = self.loadBuffer(fileHandle)
+ def __loadFromBuffer(self, fileHandle):
+ self.rootObject = self.loadBuffer(fileHandle)
- def __createEmptyInstance(self, style):
- self.rootObject = self.loadEmpty(style)
- self.makeClean()
- self._isNew = True
+ def __createEmptyInstance(self, style):
+ self.rootObject = self.loadEmpty(style)
+ self.makeClean()
+ self._isNew = True
- #--------------------------------------------------------------------------
- #
- #--------------------------------------------------------------------------
- #
- # Used by RuntimeSettings
- #
- def saveRuntimeSettings(self):
- return ( self.runtime_section, self.ui.getRuntimeSettings() )
+ #--------------------------------------------------------------------------
+ #
+ #--------------------------------------------------------------------------
+ #
+ # Used by RuntimeSettings
+ #
+ def saveRuntimeSettings(self):
+ return ( self.runtime_section, self.ui.getRuntimeSettings() )
- #--------------------------------------------------------------------------
- #
- #--------------------------------------------------------------------------
- # Do we need to be saved?
- def isDirty(self):
- return self._isdirty
+ #--------------------------------------------------------------------------
+ #
+ #--------------------------------------------------------------------------
+ # Do we need to be saved?
+ def isDirty(self):
+ return self._isdirty
- #--------------------------------------------------------------------------
- #
- #--------------------------------------------------------------------------
- # Take an object and mangle it all up
- # until it is useful to us
- def __inventory (self, object):
+ #--------------------------------------------------------------------------
+ #
+ #--------------------------------------------------------------------------
+ # Take an object and mangle it all up
+ # until it is useful to us
+ def __inventory (self, object):
- # Add a GObjectHelper to intercept __getitem__ calls on GObject
- GObjectHelper(self, object)
+ # Add a GObjectHelper to intercept __getitem__ calls on GObject
+ GObjectHelper(self, object)
- if object != self.rootObject:
+ if object != self.rootObject:
- # Assign an ID if none exists
- # TODO: in the future, I want to change these to id=".." instead of
name=".."
- if hasattr(object, 'name'):
- if object.name == None or object.name[:3] == "__G":
- object.name = self.getNextGenericName(object._type[2:])
- self.nameMappings[object.name.lower()] = object
- self.usedNames.append(object.name.lower())
+ # Assign an ID if none exists
+ # TODO: in the future, I want to change these to id=".." instead
of name=".."
+ if hasattr(object, 'name'):
+ if object.name == None or object.name[:3] == "__G":
+ object.name = self.getNextGenericName(object._type[2:])
+ self.nameMappings[object.name.lower()] = object
+ self.usedNames.append(object.name.lower())
- # Do we create an EditorComponent instance?
- if object._type in self._editorMapping.keys():
- filter = self._editorMapping[object._type][0]
- if filter is None or filter(object):
- self.ui.createEditor(object, *self._editorMapping[object._type][1:])
+ # Do we create an EditorComponent instance?
+ if object._type in self._editorMapping.keys():
+ filter = self._editorMapping[object._type][0]
+ if filter is None or filter(object):
+ self.ui.createEditor(object,
*self._editorMapping[object._type][1:])
- # Now, give the tool-specific instances a chance
- self.inventoryObject(object)
+ # Now, give the tool-specific instances a chance
+ self.inventoryObject(object)
- def __onSetCurrentObject (self, event):
- object = event.object
- handler = event.originator
- self._currentObject = object
+ def __onSetCurrentObject (self, event):
+ object = event.object
+ handler = event.originator
+ self._currentObject = object
- def __onCreateObject (self, event):
- self.__inventory(event.object)
- self.makeDirty()
+ def __onCreateObject (self, event):
+ self.__inventory(event.object)
+ self.makeDirty()
- def __onModifyObject (self, event):
- object = event.object
- # Check for any name dependencies
- # (i.e., GFEntry is dependent on GFBlock.name and GFField.name)
- # Automatically create any change events for the child objects
- if hasattr(object, '_nameDependencies'):
- for key in object._nameDependencies.keys():
- masterattr, slaveattr = object._nameDependencies[key]
- if masterattr in event.new.keys():
- oa = {slaveattr: key[slaveattr]}
- na = {slaveattr: object[masterattr]}
- key.__dict__.update(na)
- self.dispatchEvent( 'ObjectModified',
- object=key,
- originator=self,
- old=oa, new=na )
- self.makeDirty()
+ def __onModifyObject (self, event):
+ object = event.object
+ # Check for any name dependencies
+ # (i.e., GFEntry is dependent on GFBlock.name and GFField.name)
+ # Automatically create any change events for the child objects
+ if hasattr(object, '_nameDependencies'):
+ for key in object._nameDependencies.keys():
+ masterattr, slaveattr = object._nameDependencies[key]
+ if masterattr in event.new.keys():
+ oa = {slaveattr: key[slaveattr]}
+ na = {slaveattr: object[masterattr]}
+ key.__dict__.update(na)
+ self.dispatchEvent( 'ObjectModified',
+ object=key,
+ originator=self,
+ old=oa, new=na )
+ self.makeDirty()
- def __onDeleteObject (self, event):
- object = event.object
+ def __onDeleteObject (self, event):
+ object = event.object
- # Delete the actual object from its parent
- object.getParent ()._children.remove(object)
- ##object.getParent ()._children.pop(object.getParent
()._children.index(object))
+ # Delete the actual object from its parent
+ object.getParent ()._children.remove(object)
+ ##object.getParent ()._children.pop(object.getParent
()._children.index(object))
- self.makeDirty()
+ self.makeDirty()
- def __OnConnectTo(self, event):
- conn = event.connection
- try:
- tempDO = self.connections.getConnection(conn, 'object')
- self.dispatchEvent('ConnectionEstablished',connection=conn)
- self.dispatchEvent('Disable:Connect:%s' % conn)
- except:
- print u_("Unable to connect to %s") % conn
+ def __OnConnectTo(self, event):
+ conn = event.connection
+ try:
+ tempDO = self.connections.getConnection(conn, 'object')
+ self.dispatchEvent('ConnectionEstablished',connection=conn)
+ self.dispatchEvent('Disable:Connect:%s' % conn)
+ except:
+ print u_("Unable to connect to %s") % conn
- #--------------------------------------------------------------------------
- #
- #--------------------------------------------------------------------------
- def _OnSave(self, event):
- if not len(self._path):
- self.OnSaveAs(event)
- else:
- self.save()
+ #--------------------------------------------------------------------------
+ #
+ #--------------------------------------------------------------------------
+ def _OnSave(self, event):
+ if not len(self._path):
+ self.OnSaveAs(event)
+ else:
+ self.save()
- def _OnSaveAs(self, event):
- wildcards = []
- # Make the "default" file extension for a tool
- # appear before the other extensions.
- filterIndex = [self.properties.defaultFileExtension]
- wildcards += [
- ( self.properties.defaultFileExtension,
- self.properties.fileExtensions[self.properties.defaultFileExtension]) ]
-
- for type in self.properties.fileExtensions.keys():
- if type != self.properties.defaultFileExtension:
+ def _OnSaveAs(self, event):
+ wildcards = []
+ # Make the "default" file extension for a tool
+ # appear before the other extensions.
+ filterIndex = [self.properties.defaultFileExtension]
wildcards += [
- ( type, self.properties.fileExtensions[type]) ]
- filterIndex.append(type)
+ ( self.properties.defaultFileExtension,
+
self.properties.fileExtensions[self.properties.defaultFileExtension]) ]
- path = self.ui.dialogSaveFile(u_("Save %s As...") %
self.properties.description,
- wildcards = wildcards,
- parentWindow=self.ui)
+ for type in self.properties.fileExtensions.keys():
+ if type != self.properties.defaultFileExtension:
+ wildcards += [
+ ( type, self.properties.fileExtensions[type]) ]
+ filterIndex.append(type)
- if path:
+ path = self.ui.dialogSaveFile(u_("Save %s As...") %
self.properties.description,
+ wildcards = wildcards,
+ parentWindow=self.ui)
+
+ if path:
# if len(path) < 4 or not (path[-4] == '.' and path[-3:].lower() in
self.properties.fileExtensions.keys()):
# path += "." + filterIndex[dlg.GetFilterIndex()]
- if os.path.isfile(path):
- overwrite = self.ui.dialogYesNo(
- u_('The file "%s".\n' % path) +
- u_("exists. Overwrite?"),
- u_("Unsaved Changes"), icon="warn", parentWindow=self.ui)
- if not overwrite:
- self.OnSaveAs(event)
- return
+ if os.path.isfile(path):
+ overwrite = self.ui.dialogYesNo(
+ u_('The file "%s".\n' % path) +
+ u_("exists. Overwrite?"),
+ u_("Unsaved Changes"), icon="warn", parentWindow=self.ui)
+ if not overwrite:
+ self.OnSaveAs(event)
+ return
- self._path = path
- self.ui.setTitle (self._path)
- self.save()
+ self._path = path
+ self.ui.setTitle (self._path)
+ self.save()
- def _OnClose(self, event):
- if self.isDirty():
- save = self.ui.dialogYesNoCancel(
- u_("This document has unsaved changes.\n") +
- u_("Save changes before closing?"),
- u_("Unsaved Changes"), icon="warn", parentWindow=self.ui)
- if save == True:
- self.OnSave(event)
- elif save == -1:
- event.Veto()
- return
+ def _OnClose(self, event):
+ if self.isDirty():
+ save = self.ui.dialogYesNoCancel(
+ u_("This document has unsaved changes.\n") +
+ u_("Save changes before closing?"),
+ u_("Unsaved Changes"), icon="warn", parentWindow=self.ui)
+ if save == True:
+ self.OnSave(event)
+ elif save == -1:
+ event.Veto()
+ return
- RuntimeSettings.saveRuntimeSettings(self)
- self.app.mru.removeMenu(self.menubar.getMenu('File|Open Recent|'), self)
- self.app.removeDocument(self)
- self.ui.close()
+ RuntimeSettings.saveRuntimeSettings(self)
+ self.app.mru.removeMenu(self.menubar.getMenu('File|Open Recent|'),
self)
+ self.app.removeDocument(self)
+ self.ui.close()
- #--------------------------------------------------------------------------
- #
- #--------------------------------------------------------------------------
- def loadWizards(self, package):
- templates = []
+ #--------------------------------------------------------------------------
+ #
+ #--------------------------------------------------------------------------
+ def loadWizards(self, package):
+ templates = []
- basedir = os.path.dirname(package.__file__)
- processed = [] # Base file names processed (e.g., base of Simple.py*
- # is Simple) This will keep us from importing Simple
- # three times if Simple.py, Simple.pyc, and Simple.lib
- # all exist.
+ basedir = os.path.dirname(package.__file__)
+ processed = [] # Base file names processed (e.g., base of Simple.py*
+ # is Simple) This will keep us from importing Simple
+ # three times if Simple.py, Simple.pyc, and Simple.lib
+ # all exist.
- for dir in dircache.listdir(basedir):
- base = dir.split('.')[0]
- if not dir[0] in ('.','_') and not base in processed:
- processed.append(base)
- try:
- templates.append(dyn_import(
- '%s.%s' % (package.__name__,base)).TemplateInformation)
- except ImportError, mesg:
- assert gDebug(2,"%s.%s doesn't appear to be a valid wizard" %
(package.__name__, base))
- assert gDebug(5,' --> %s' % (mesg))
- except AttributeError:
- assert gDebug(2,'Wizard %s for package %s is missing'
- ' an \'TemplateInformation\' attribute.' %
- (base,package.__name__))
+ for dir in dircache.listdir(basedir):
+ base = dir.split('.')[0]
+ if not dir[0] in ('.','_') and not base in processed:
+ processed.append(base)
+ try:
+ templates.append(dyn_import(
+ '%s.%s' % (package.__name__,base)).TemplateInformation)
+ except ImportError, mesg:
+ assert gDebug(2,"%s.%s doesn't appear to be a valid
wizard" % (package.__name__, base))
+ assert gDebug(5,' --> %s' % (mesg))
+ except AttributeError:
+ assert gDebug(2,'Wizard %s for package %s is missing'
+ ' an \'TemplateInformation\' attribute.' %
+ (base,package.__name__))
- for template in templates:
- try:
- location = template['MenuLocation']
- try:
- location, translation, grouping = location
- grouping = float(grouping)
- except:
- location, translation = location
- grouping = 499.0
+ for template in templates:
+ try:
+ location = template['MenuLocation']
+ try:
+ location, translation, grouping = location
+ grouping = float(grouping)
+ except:
+ location, translation = location
+ grouping = 499.0
- if location:
- self.wizardRunner(template, self)
- self.menubar.addAction(location=location, text=translation,
- event='Wizard:%s' % template['BaseID'],
- grouping=grouping, canDisable=True,
- eventdata={'template':template},
help=template['Description'])
- except ValueError:
- continue
+ if location:
+ self.wizardRunner(template, self)
+ self.menubar.addAction(location=location, text=translation,
+ event='Wizard:%s' %
template['BaseID'],
+ grouping=grouping, canDisable=True,
+ eventdata={'template':template},
help=template['Description'])
+ except ValueError:
+ continue
# ===========================================================================
# Wrapper Class
# ===========================================================================
class GObjectHelper:
- def __init__(self, instance, object):
- self.document = instance
- self.object = object
- object._setItemHook = self._setItemHook
+ def __init__(self, instance, object):
+ self.document = instance
+ self.object = object
+ object._setItemHook = self._setItemHook
- # Replace the getitem hooks from GObject
- # This is for the wizards, so they can do
- # entry['Char:x']-type calls and get back
- # what they expected.
+ # Replace the getitem hooks from GObject
+ # This is for the wizards, so they can do
+ # entry['Char:x']-type calls and get back
+ # what they expected.
- def _setItemHook(self, key, value):
- ek = key.replace(':','__')
- object = self.object
- try:
- ov = {key: object.__dict__[ek]}
- except KeyError:
- ov = {}
- object.__dict__[key.replace(':','__')] = value
- self.document.dispatchEvent('ObjectModified',
- object = object, new={key:value}, old=ov, originator = '__inline__')
+ def _setItemHook(self, key, value):
+ ek = key.replace(':','__')
+ object = self.object
+ try:
+ ov = {key: object.__dict__[ek]}
+ except KeyError:
+ ov = {}
+ object.__dict__[key.replace(':','__')] = value
+ self.document.dispatchEvent('ObjectModified',
+ object = object, new={key:value}, old=ov, originator = '__inline__')
- def setStatus(self, text):
- self.ui.setStatus(text)
+ def setStatus(self, text):
+ self.ui.setStatus(text)
# ===========================================================================
# Helper class used by the tool-specific packages
# ===========================================================================
class ModuleProperties:
- xmlOpeningTag = 'undefined'
- short = 'undefined'
- application = 'GNUe Tool'
- description = 'undefined'
- fileExtensions = {}
- defaultFileExtension = 'undefined'
-
+ xmlOpeningTag = 'undefined'
+ short = 'undefined'
+ application = 'GNUe Tool'
+ description = 'undefined'
+ fileExtensions = {}
+ defaultFileExtension = 'undefined'
Modified: trunk/gnue-designer/src/base/EditorBase.py
===================================================================
--- trunk/gnue-designer/src/base/EditorBase.py 2006-04-03 19:53:03 UTC (rev
8343)
+++ trunk/gnue-designer/src/base/EditorBase.py 2006-04-03 19:56:14 UTC (rev
8344)
@@ -37,40 +37,40 @@
#
# ===========================================================================
class EditorBase(wx.Panel, events.EventAware):
- """
- An "Editor Component" is presented usually as an editor to the user
- and is considered a "primary window".
- """
- default_dock = 'primary'
- icon = 'painter'
+ """
+ An "Editor Component" is presented usually as an editor to the user
+ and is considered a "primary window".
+ """
+ default_dock = 'primary'
+ icon = 'painter'
- def __init__(self, object, document, parentWindow):
- wx.Panel.__init__(self, parentWindow, -1)
- events.EventAware.__init__(self, document)
+ def __init__(self, object, document, parentWindow):
+ wx.Panel.__init__(self, parentWindow, -1)
+ events.EventAware.__init__(self, document)
- self.document = document
+ self.document = document
- # TODO: Phase out this
- self.rootObject = document.rootObject
+ # TODO: Phase out this
+ self.rootObject = document.rootObject
- self.document.globalAcceleratorListeners.append(self)
+ self.document.globalAcceleratorListeners.append(self)
- self.init(object)
+ self.init(object)
- RuntimeSettings.registerRuntimeSettingHandler(self.document, self)
+ RuntimeSettings.registerRuntimeSettingHandler(self.document, self)
- def saveRuntimeSettings(self):
- return (self.runtime_section, {})
+ def saveRuntimeSettings(self):
+ return (self.runtime_section, {})
- def setFeedback(self, text):
- print "TODO: setFeedback"
+ def setFeedback(self, text):
+ print "TODO: setFeedback"
- def setCaption(self, caption):
- self._caption = caption
- # TODO: tell the ui instance to update, if necessary
+ def setCaption(self, caption):
+ self._caption = caption
+ # TODO: tell the ui instance to update, if necessary
- def destroy(self):
- self.Destroy()
+ def destroy(self):
+ self.Destroy()
- def setFeedback(self, text):
- print "TODO: setFeedback"
+ def setFeedback(self, text):
+ print "TODO: setFeedback"
Modified: trunk/gnue-designer/src/base/Goat.py
===================================================================
--- trunk/gnue-designer/src/base/Goat.py 2006-04-03 19:53:03 UTC (rev
8343)
+++ trunk/gnue-designer/src/base/Goat.py 2006-04-03 19:56:14 UTC (rev
8344)
@@ -88,7 +88,7 @@
\x8d\x8e\xf0\xe04\x02\x13\xa6L\xa5\x90\x12L\x1d\xe1\rL\xbc\x19\xc9\xbb\xdf\
\xfa\xb2\xd3\xfe2{\xdc;\x00\xa1`\x88\xfa\xba\xda\xdbm\xadm\x9c}dF\x87\xb8q\
\xf5\nJz\xc6\x19\x84tL&E\x05X\xc5\x18\x8e|w\xdb\xf2\xa3M\xd16\xff\xffo\x95\
-\xf7\xd9\xfe\x07 \xf45f\x18k\x97o\x00\x00\x00\x00IEND\xaeB`\x82'
+\xf7\xd9\xfe\x07 \xf45f\x18k\x97o\x00\x00\x00\x00IEND\xaeB`\x82'
def getGoatBitmap():
return BitmapFromImage(getGoatImage())
@@ -101,4 +101,3 @@
icon = EmptyIcon()
icon.CopyFromBitmap(getGoatBitmap())
return icon
-
Modified: trunk/gnue-designer/src/base/Icons.py
===================================================================
--- trunk/gnue-designer/src/base/Icons.py 2006-04-03 19:53:03 UTC (rev
8343)
+++ trunk/gnue-designer/src/base/Icons.py 2006-04-03 19:56:14 UTC (rev
8344)
@@ -33,8 +33,8 @@
# Nasty hack to get around wxPython bug (still in 2.3.1)
class myImageList(wx.ImageList):
- def __del__(self):
- pass
+ def __del__(self):
+ pass
treeIconMap = {}
treeIconList = myImageList(18,18,False)
@@ -42,22 +42,22 @@
iconlocation =
os.path.join(GConfig.getInstalledBase('designer_images','common_images'),'designer')
if sys.platform != 'win32':
- icontype = wx.BITMAP_TYPE_XPM
- iconextension = 'xpm'
+ icontype = wx.BITMAP_TYPE_XPM
+ iconextension = 'xpm'
else:
- icontype = wx.BITMAP_TYPE_ICO
- iconextension = 'ico'
+ icontype = wx.BITMAP_TYPE_ICO
+ iconextension = 'ico'
if __version__ < '2.3.0': # TODO: wxPython 2.2.x seems to segfault with icons
- iconextension = '' # this is a hack to make it not find icons
- # and thus not segfault. We should never
- # build a win version w/ that old a wxPython
+ iconextension = '' # this is a hack to make it not find icons
+ # and thus not segfault. We should never
+ # build a win version w/ that old a wxPython
for f in ('block','datasource','entry','import','pagewidget',
'page','trigger','properties'):
- if os.path.isfile('%s/destree_%s.%s' % (iconlocation, f,iconextension)):
- treeIconMap[f] = treeIconList.AddIcon(
- wx.Icon('%s/destree_%s.%s' % (iconlocation, f,iconextension),
- icontype))
- else:
- treeIconMap[f] = treeIconList.AddIcon(wx.NullIcon)
+ if os.path.isfile('%s/destree_%s.%s' % (iconlocation, f,iconextension)):
+ treeIconMap[f] = treeIconList.AddIcon(
+ wx.Icon('%s/destree_%s.%s' % (iconlocation, f,iconextension),
+ icontype))
+ else:
+ treeIconMap[f] = treeIconList.AddIcon(wx.NullIcon)
Modified: trunk/gnue-designer/src/base/Incubator.py
===================================================================
--- trunk/gnue-designer/src/base/Incubator.py 2006-04-03 19:53:03 UTC (rev
8343)
+++ trunk/gnue-designer/src/base/Incubator.py 2006-04-03 19:56:14 UTC (rev
8344)
@@ -31,133 +31,132 @@
from gnue.common.definitions import GParserHelpers
class BaseIncubator:
- elements = {}
+ elements = {}
- ##
- ## Reparent an object
- ##
- def reparentObject(self, rootObject, object, newParent):
- if object.getParent () == newParent:
- return
+ ##
+ ## Reparent an object
+ ##
+ def reparentObject(self, rootObject, object, newParent):
+ if object.getParent () == newParent:
+ return
- # TODO
+ # TODO
- ##
- ## Create a new object
- ##
- def createObject(self, rootObject, tag,
- parent, attributes={}, select=1):
+ ##
+ ## Create a new object
+ ##
+ def createObject(self, rootObject, tag,
+ parent, attributes={}, select=1):
- assert gDebug(3,'Creating a "%s" object' % tag)
- assert gDebug(6,"Object's parent is %s" % parent)
+ assert gDebug(3,'Creating a "%s" object' % tag)
+ assert gDebug(6,"Object's parent is %s" % parent)
- try:
- name = attributes['name']
- except KeyError:
- name = self.document.getNextGenericName(tag)
+ try:
+ name = attributes['name']
+ except KeyError:
+ name = self.document.getNextGenericName(tag)
- try:
- objclass = self.elements[tag]['BaseClass']
- if self.elements[tag].has_key('Attributes'):
- attrs = self.elements[tag]['Attributes']
- else:
- attrs = {}
- except KeyError:
- assert gDebug(1, "Attempted to create a '%s', "
- "but I don't know what to do!" % tag)
- return 1
+ try:
+ objclass = self.elements[tag]['BaseClass']
+ if self.elements[tag].has_key('Attributes'):
+ attrs = self.elements[tag]['Attributes']
+ else:
+ attrs = {}
+ except KeyError:
+ assert gDebug(1, "Attempted to create a '%s', "
+ "but I don't know what to do!" % tag)
+ return 1
- o = objclass(parent)
- assert gDebug(10, 'Created %s' % o)
+ o = objclass(parent)
+ assert gDebug(10, 'Created %s' % o)
- # Add any GContent
- try:
- GParserHelpers.GContent(o, attributes['_content_'])
- except KeyError:
- pass
+ # Add any GContent
+ try:
+ GParserHelpers.GContent(o, attributes['_content_'])
+ except KeyError:
+ pass
- # Pull default values for any attributes not supplied
- for attr in attrs.keys():
- if not attributes.has_key(attr):
- if attrs[attr].has_key('Default'):
- attributes[attr] = attrs[attr]['Typecast'](attrs[attr]['Default'])
+ # Pull default values for any attributes not supplied
+ for attr in attrs.keys():
+ if not attributes.has_key(attr):
+ if attrs[attr].has_key('Default'):
+ attributes[attr] =
attrs[attr]['Typecast'](attrs[attr]['Default'])
- for attr in attributes.keys():
- if attrs.has_key(attr):
- o.__dict__[attr] = attributes[attr]
- else:
- self._handleUnknownAttribute(tag, o, attr, attributes[attr])
+ for attr in attributes.keys():
+ if attrs.has_key(attr):
+ o.__dict__[attr] = attributes[attr]
+ else:
+ self._handleUnknownAttribute(tag, o, attr, attributes[attr])
- o.name = name
- self.document.nameMappings[o.name] = o
- o._buildObject()
- self.document.dispatchEvent('ObjectCreated',object=o, originator=__name__)
- if select:
- self.document.dispatchEvent('ObjectSelected',object=o,
originator=__name__)
- return o
+ o.name = name
+ self.document.nameMappings[o.name] = o
+ o._buildObject()
+ self.document.dispatchEvent('ObjectCreated',object=o,
originator=__name__)
+ if select:
+ self.document.dispatchEvent('ObjectSelected',object=o,
originator=__name__)
+ return o
- ##
- ## Delete an object
- ##
- def deleteObject(self, rootObject, object, newCurrentObject=None,
firstRun=1):
+ ##
+ ## Delete an object
+ ##
+ def deleteObject(self, rootObject, object, newCurrentObject=None,
firstRun=1):
- if firstRun:
- newCurrentObject = parent = object.getParent ()
+ if firstRun:
+ newCurrentObject = parent = object.getParent ()
- for child in object._children:
- if not child._type == '_content_':
- self.deleteObject(rootObject, child, firstRun=0)
+ for child in object._children:
+ if not child._type == '_content_':
+ self.deleteObject(rootObject, child, firstRun=0)
- self.document.dispatchEvent('ObjectDeleted',object=object,
originator=__name__)
+ self.document.dispatchEvent('ObjectDeleted',object=object,
originator=__name__)
- if firstRun:
- o = parent
- while o.getParent ():
- o._buildObject()
- o = o.getParent ()
+ if firstRun:
+ o = parent
+ while o.getParent ():
+ o._buildObject()
+ o = o.getParent ()
- if newCurrentObject:
- self.document.dispatchEvent('ObjectSelected',object=object,
originator=__name__)
+ if newCurrentObject:
+ self.document.dispatchEvent('ObjectSelected',object=object,
originator=__name__)
-
- ##
- ## Internal stuff
- ##
- def __init__(self, instance):
- self.document = instance
+ ##
+ ## Internal stuff
+ ##
- # Figure out tag dependencies
- self._calcDependencies()
+ def __init__(self, instance):
+ self.document = instance
+ # Figure out tag dependencies
+ self._calcDependencies()
- def _calcDependencies(self):
- self.elementMapping = elementMapping = {}
- elements = self.elements
- for tag in elements.keys():
- t = elements[tag]
+ def _calcDependencies(self):
+ self.elementMapping = elementMapping = {}
+ elements = self.elements
- try:
- cascade = t['UsableBySiblings']
- except KeyError:
- cascade = 0
+ for tag in elements.keys():
+ t = elements[tag]
- if t.has_key('ParentTags'):
- parents = t['ParentTags']
- else:
- parents = None
+ try:
+ cascade = t['UsableBySiblings']
+ except KeyError:
+ cascade = 0
- if parents != None:
- for parent in parents:
- try:
- elementMapping[parent].append(tag)
- except KeyError:
- elementMapping[parent] = [tag]
+ if t.has_key('ParentTags'):
+ parents = t['ParentTags']
+ else:
+ parents = None
- def _handleUnknownAttribute(self, tag, object, attr, value):
- return
+ if parents != None:
+ for parent in parents:
+ try:
+ elementMapping[parent].append(tag)
+ except KeyError:
+ elementMapping[parent] = [tag]
+ def _handleUnknownAttribute(self, tag, object, attr, value):
+ return
Modified: trunk/gnue-designer/src/base/MRUManager.py
===================================================================
--- trunk/gnue-designer/src/base/MRUManager.py 2006-04-03 19:53:03 UTC (rev
8343)
+++ trunk/gnue-designer/src/base/MRUManager.py 2006-04-03 19:56:14 UTC (rev
8344)
@@ -32,144 +32,144 @@
import wx
class MRUManager:
- """
- Most Recently Used (MRU) Manager
+ """
+ Most Recently Used (MRU) Manager
- Responsible for maintaining the menu that displays the most
- recently used items.
- """
- def __init__(self, app):
- self._menus = []
- self._locations = []
- self.menulist = []
- self.app = app
- self.mruMenuMap = {}
+ Responsible for maintaining the menu that displays the most
+ recently used items.
+ """
+ def __init__(self, app):
+ self._menus = []
+ self._locations = []
+ self.menulist = []
+ self.app = app
+ self.mruMenuMap = {}
- # TODO: Should this be user configurable?
- self._maxMRUs = 9
+ # TODO: Should this be user configurable?
+ self._maxMRUs = 9
- # Set ourselves up to be saved in the runtime settings file
- # Each instance will register for us
- self.runtime_section = "MRUList"
+ # Set ourselves up to be saved in the runtime settings file
+ # Each instance will register for us
+ self.runtime_section = "MRUList"
- # Load the saved MRU list
- for i in range(self._maxMRUs):
- location = RuntimeSettings.get(self.runtime_section, "%s" % i, None)
- if location is None:
- break
- self._locations.append (location)
+ # Load the saved MRU list
+ for i in range(self._maxMRUs):
+ location = RuntimeSettings.get(self.runtime_section, "%s" % i,
None)
+ if location is None:
+ break
+ self._locations.append (location)
- self._refreshMenuList()
+ self._refreshMenuList()
- def addLocation(self, location):
- """
- Adds a URL to the MRU list.
- @type location: string
- @param location: URL to be added
- """
+ def addLocation(self, location):
+ """
+ Adds a URL to the MRU list.
+ @type location: string
+ @param location: URL to be added
+ """
- # Remove entry from old position
- absloc = os.path.normcase(os.path.abspath(location))
- try:
- self._locations.remove(absloc)
- except ValueError:
- pass
+ # Remove entry from old position
+ absloc = os.path.normcase(os.path.abspath(location))
+ try:
+ self._locations.remove(absloc)
+ except ValueError:
+ pass
- # Add to top of list
- self._locations.insert(0, absloc)
+ # Add to top of list
+ self._locations.insert(0, absloc)
- # Truncate list if necessary
- if len(self._locations) >= self._maxMRUs:
- self._locations = self._locations[:self._maxMRUs]
+ # Truncate list if necessary
+ if len(self._locations) >= self._maxMRUs:
+ self._locations = self._locations[:self._maxMRUs]
- self._refreshMenuList()
+ self._refreshMenuList()
- def _refreshMenuList(self):
- """
- This figures out the common prefix of all the forms and reduces
appropriately.
- i.e., if you have /usr/home/me/form1.gfd, /usr/home/you/form2.gfd then
- this will reduce to me/form1.gfd and you/form2.gfd.. This is to keep the
- MRU menu list from being too wide!
- """
- commonpos=len(os.path.commonprefix(
- map(lambda x: os.path.join(os.path.split(x)[0],''),self._locations)))
+ def _refreshMenuList(self):
+ """
+ This figures out the common prefix of all the forms and reduces
appropriately.
+ i.e., if you have /usr/home/me/form1.gfd, /usr/home/you/form2.gfd then
+ this will reduce to me/form1.gfd and you/form2.gfd.. This is to keep
the
+ MRU menu list from being too wide!
+ """
+ commonpos=len(os.path.commonprefix(
+ map(lambda x:
os.path.join(os.path.split(x)[0],''),self._locations)))
- if commonpos > 2:
- self.menulist = map(lambda x, pos=commonpos: x[pos:], self._locations)
- else:
- self.menulist = self._locations[:]
+ if commonpos > 2:
+ self.menulist = map(lambda x, pos=commonpos: x[pos:],
self._locations)
+ else:
+ self.menulist = self._locations[:]
- self.refreshMenus()
+ self.refreshMenus()
- def addMenu(self, menu, instance):
- """
- Adds a link to a wx.Menu that needs maintained.
+ def addMenu(self, menu, instance):
+ """
+ Adds a link to a wx.Menu that needs maintained.
- @type menu: wx.Menu instance
- @param menu: A menu that needs maintained
- @type instance: BaseInstance or child
- @param instance: A designer instance to which this menu belongs. Designer
creates
- an instance for every file it currently has
open.
- """
- self._menus.append(menu)
- menu.__instance = instance
- self.refreshMenu(menu)
+ @type menu: wx.Menu instance
+ @param menu: A menu that needs maintained
+ @type instance: BaseInstance or child
+ @param instance: A designer instance to which this menu belongs.
Designer creates
+ an instance for every file it currently
has open.
+ """
+ self._menus.append(menu)
+ menu.__instance = instance
+ self.refreshMenu(menu)
- def removeMenu(self, menu, instance):
- """
- Removes a wx.Menu from the list of wx.Menus that
- contain recently opened files.
+ def removeMenu(self, menu, instance):
+ """
+ Removes a wx.Menu from the list of wx.Menus that
+ contain recently opened files.
- @type menu: wx.Menu instance
- @param menu: Menu that needs removed
- @type instance: BaseInstance
- @param instance: A designer instance to which this menu belongs. Designer
creates
- an instance for every file it currently has
open. NOT USED?
+ @type menu: wx.Menu instance
+ @param menu: Menu that needs removed
+ @type instance: BaseInstance
+ @param instance: A designer instance to which this menu belongs.
Designer creates
+ an instance for every file it currently
has open. NOT USED?
- """
- self._menus.remove(menu)
+ """
+ self._menus.remove(menu)
- def refreshMenus(self):
- """
- Iterates through all the wx.Menus under management and refreshes
- their list.
- """
- map(self.refreshMenu, self._menus)
+ def refreshMenus(self):
+ """
+ Iterates through all the wx.Menus under management and refreshes
+ their list.
+ """
+ map(self.refreshMenu, self._menus)
- def refreshMenu(self, menu):
- """
- Resets and updates the wx.Menu that displays the MRU list.
- """
- # Purge all entries from the existing wx.Menu and
- # reset the menu mapping
- self.mruMenuMap = {}
- for i in menu.GetMenuItems():
- menu.Delete(i.GetId())
+ def refreshMenu(self, menu):
+ """
+ Resets and updates the wx.Menu that displays the MRU list.
+ """
+ # Purge all entries from the existing wx.Menu and
+ # reset the menu mapping
+ self.mruMenuMap = {}
+ for i in menu.GetMenuItems():
+ menu.Delete(i.GetId())
- # Rebuild the menu with the current items.
- i = 0
- for location in self.menulist:
- tid = wx.NewId()
- menu.Append ( tid, '&%s %s' % (i+1, location),
- u_('Open "%s" in a new window') % self._locations[i] )
+ # Rebuild the menu with the current items.
+ i = 0
+ for location in self.menulist:
+ tid = wx.NewId()
+ menu.Append ( tid, '&%s %s' % (i+1, location),
+ u_('Open "%s" in a new window') % self._locations[i]
)
- wx.EVT_MENU(menu.__instance.ui, tid, self.app.OnOpenRecent)
- self.mruMenuMap[tid] = self._locations[i]
- i += 1
+ wx.EVT_MENU(menu.__instance.ui, tid, self.app.OnOpenRecent)
+ self.mruMenuMap[tid] = self._locations[i]
+ i += 1
- def saveRuntimeSettings(self):
- """
- Returns a dictionary used by Designer's instance of RuntimeSettings
- to save the recently used urls
+ def saveRuntimeSettings(self):
+ """
+ Returns a dictionary used by Designer's instance of RuntimeSettings
+ to save the recently used urls
- @rtype: dict of {position:URL}
- @return: The recently used files.
- """
- results = {}
+ @rtype: dict of {position:URL}
+ @return: The recently used files.
+ """
+ results = {}
- for i in range(len(self._locations)):
- results["%s" % i] = self._locations[i]
+ for i in range(len(self._locations)):
+ results["%s" % i] = self._locations[i]
- return ( self.runtime_section, results )
+ return ( self.runtime_section, results )
Modified: trunk/gnue-designer/src/base/MenuBar.py
===================================================================
--- trunk/gnue-designer/src/base/MenuBar.py 2006-04-03 19:53:03 UTC (rev
8343)
+++ trunk/gnue-designer/src/base/MenuBar.py 2006-04-03 19:56:14 UTC (rev
8344)
@@ -35,114 +35,112 @@
#
class MenuBar:
- def __init__(self, instance):
- self.document = instance
+ def __init__(self, instance):
+ self.document = instance
- self._menus = {}
- self._menuItems = {'':[]}
+ self._menus = {}
+ self._menuItems = {'':[]}
- print instance
- self.uimenu = instance.ui.createMenuBar()
+ print instance
+ self.uimenu = instance.ui.createMenuBar()
- # Locations can be <loc>|<loc> where <loc> is <location>/<translation>@group
- def addMenu(self, location, translation=None, grouping=499):
+ # Locations can be <loc>|<loc> where <loc> is
<location>/<translation>@group
+ def addMenu(self, location, translation=None, grouping=499):
- loc = ''
- if translation:
- location += '/' + translation
- if grouping:
- location += '@' + str(grouping)
+ loc = ''
+ if translation:
+ location += '/' + translation
+ if grouping:
+ location += '@' + str(grouping)
- for part in location.split('|'):
- try:
- part, group = part.split('@')
- group = float(group)
- except:
- group = 500.0
- try:
- part, trans = part.split('/')
- except:
- trans = part
- nloc = loc + part + '|'
- if not self._menuItems.has_key(nloc):
- self._menuItems[nloc] = []
- self._menuItems[loc].append((int(grouping),grouping, trans, 1, nloc,
- 0, 0, None, None, None, None))
- loc = nloc
- return loc
+ for part in location.split('|'):
+ try:
+ part, group = part.split('@')
+ group = float(group)
+ except:
+ group = 500.0
+ try:
+ part, trans = part.split('/')
+ except:
+ trans = part
+ nloc = loc + part + '|'
+ if not self._menuItems.has_key(nloc):
+ self._menuItems[nloc] = []
+ self._menuItems[loc].append((int(grouping),grouping, trans, 1,
nloc,
+ 0, 0, None, None, None, None))
+ loc = nloc
+ return loc
- def addAction(self, location, text, event,
- grouping=499, canToggle=0, canDisable=0,
- icon=None, hotkey=None, eventdata={}, help=""):
+ def addAction(self, location, text, event,
+ grouping=499, canToggle=0, canDisable=0,
+ icon=None, hotkey=None, eventdata={}, help=""):
- location = self.addMenu(location)
- self._menuItems[location].append((int(grouping), grouping, text, 0, event,
- canToggle, canDisable, icon, hotkey,
- eventdata, help))
+ location = self.addMenu(location)
+ self._menuItems[location].append((int(grouping), grouping, text, 0,
event,
+ canToggle, canDisable, icon, hotkey,
+ eventdata, help))
- #
- # Called by Instance.py when the menu can finally be built
- #
- def finalize(self):
- for group, order, text, isMenu, action, canToggle, canDisable, \
- icon, hotkey, eventdata, help in self._menuItems['']:
- self.__setupMenu(None, action, text)
+ #
+ # Called by Instance.py when the menu can finally be built
+ #
+ def finalize(self):
+ for group, order, text, isMenu, action, canToggle, canDisable, \
+ icon, hotkey, eventdata, help in self._menuItems['']:
+ self.__setupMenu(None, action, text)
- #
- # Recursively build (sub)menus
- #
- def __setupMenu(self, parent, location, text):
- items = self._menuItems[location]
+ #
+ # Recursively build (sub)menus
+ #
+ def __setupMenu(self, parent, location, text):
+ items = self._menuItems[location]
- # Don't add empty menus (???)
- if not items:
- return
+ # Don't add empty menus (???)
+ if not items:
+ return
- if parent:
- menu = self.uimenu.createSubMenu(text, location, parent)
- else:
- menu = self.uimenu.createMenu(text, location)
+ if parent:
+ menu = self.uimenu.createSubMenu(text, location, parent)
+ else:
+ menu = self.uimenu.createMenu(text, location)
- items.sort()
- lastgroup = items[0][0]
+ items.sort()
+ lastgroup = items[0][0]
- for group, order, text, isMenu, action, canToggle, canDisable, \
- icon, hotkey, eventdata, help in self._menuItems[location]:
- if group != lastgroup:
- self.uimenu.createSeparator(menu)
- lastgroup = group
-
- if isMenu:
- self.__setupMenu(menu, action, text)
- else:
- self.uimenu.createMenuItem(menu, text, canToggle, canDisable, icon,
hotkey, eventdata, help, action)
-
-
- def getEventHelp(self, handle):
- """
- Return the help string of a menu event,
- so that it could be used for toolbar icon tooltips too.
- (Two to two too...)
- """
- try:
- for menuItems in self._menuItems.values():
for group, order, text, isMenu, action, canToggle, canDisable, \
- icon, hotkey, eventdata, help in menuItems:
- if action == handle:
- return (text, help)
- except:
- pass
+ icon, hotkey, eventdata, help in self._menuItems[location]:
+ if group != lastgroup:
+ self.uimenu.createSeparator(menu)
+ lastgroup = group
- return None
+ if isMenu:
+ self.__setupMenu(menu, action, text)
+ else:
+ self.uimenu.createMenuItem(menu, text, canToggle, canDisable,
icon, hotkey, eventdata, help, action)
- #
- # Return the wx.Menu(Item) associated with a location
- def getMenu(self, location):
- return self.uimenu.getMenu(location)
+ def getEventHelp(self, handle):
+ """
+ Return the help string of a menu event,
+ so that it could be used for toolbar icon tooltips too.
+ (Two to two too...)
+ """
+ try:
+ for menuItems in self._menuItems.values():
+ for group, order, text, isMenu, action, canToggle, canDisable,
\
+ icon, hotkey, eventdata, help in menuItems:
+ if action == handle:
+ return (text, help)
+ except:
+ pass
+ return None
+
+ #
+ # Return the wx.Menu(Item) associated with a location
+ def getMenu(self, location):
+ return self.uimenu.getMenu(location)
Modified: trunk/gnue-designer/src/base/ModuleSupport.py
===================================================================
--- trunk/gnue-designer/src/base/ModuleSupport.py 2006-04-03 19:53:03 UTC
(rev 8343)
+++ trunk/gnue-designer/src/base/ModuleSupport.py 2006-04-03 19:56:14 UTC
(rev 8344)
@@ -22,12 +22,12 @@
# ModuleSupport.py
#
# DESCRIPTION:
-#
+#
# NOTES:
#
"""
-Loads all modules available to designer.
-Modules are only loaded once
+Loads all modules available to designer.
+Modules are only loaded once
"""
from gnue.common.apps import GDebug as _GDebug
from gnue.common.utils.FileUtils import dyn_import
@@ -41,10 +41,10 @@
)
for module in Modules:
- try:
- SupportedModules.append(dyn_import("gnue.designer.%s" % module))
- _GDebug.printMesg(1,'Loaded Designer support for %s' % module)
- except ImportError, mesg:
- UnsupportedModules.append(module)
- _GDebug.printMesg(1,'Cannot load Designer support for %s' % module)
- _GDebug.printMesg(2,' Error: %s' % mesg)
+ try:
+ SupportedModules.append(dyn_import("gnue.designer.%s" % module))
+ _GDebug.printMesg(1,'Loaded Designer support for %s' % module)
+ except ImportError, mesg:
+ UnsupportedModules.append(module)
+ _GDebug.printMesg(1,'Cannot load Designer support for %s' % module)
+ _GDebug.printMesg(2,' Error: %s' % mesg)
Modified: trunk/gnue-designer/src/base/MultiObjectGridEditor.py
===================================================================
--- trunk/gnue-designer/src/base/MultiObjectGridEditor.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/base/MultiObjectGridEditor.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -39,319 +39,317 @@
class MultiObjectGridEditor(Grid):
- ##
- ## Stuff that needs to be implemented by the subclasses
- ##
+ ##
+ ## Stuff that needs to be implemented by the subclasses
+ ##
- base_gobject = None # GObject
+ base_gobject = None # GObject
- # Any initialization stuff
- def init(self):
- pass
+ # Any initialization stuff
+ def init(self):
+ pass
- # Should return a tuple of columns
- def getColumnDefinitions(self):
- return ()
+ # Should return a tuple of columns
+ def getColumnDefinitions(self):
+ return ()
- ##
- ## Internal Stuff
- ##
- def __init__(self, parent, instance):
- Grid.__init__(self, parent, -1)
+ ##
+ ## Internal Stuff
+ ##
+ def __init__(self, parent, instance):
+ Grid.__init__(self, parent, -1)
- self.document = instance
- self.objects = []
- self.rows = []
- self.current = None
- self.lastSort = -1
- self.lastReverse = 0
+ self.document = instance
+ self.objects = []
+ self.rows = []
+ self.current = None
+ self.lastSort = -1
+ self.lastReverse = 0
- # Set up our grid
+ # Set up our grid
- # Register the Designer event handlers
- instance.registerEventListeners({
- 'ObjectSelected' : self._objectSelected,
- 'ObjectCreated' : self._objectCreated,
- 'ObjectModified' : self._objectModified,
- 'ObjectDeleted' : self._objectDeleted,
- })
+ # Register the Designer event handlers
+ instance.registerEventListeners({
+ 'ObjectSelected' : self._objectSelected,
+ 'ObjectCreated' : self._objectCreated,
+ 'ObjectModified' : self._objectModified,
+ 'ObjectDeleted' : self._objectDeleted,
+ })
- #
- # Register the wx event handlers
- #
- EVT_GRID_CELL_CHANGE(self, self.__OnCellChange)
- EVT_GRID_SELECT_CELL(self, self.__OnSelectCell)
- EVT_GRID_LABEL_LEFT_CLICK(self, self.__OnLabelLeftClick)
+ #
+ # Register the wx event handlers
+ #
+ EVT_GRID_CELL_CHANGE(self, self.__OnCellChange)
+ EVT_GRID_SELECT_CELL(self, self.__OnSelectCell)
+ EVT_GRID_LABEL_LEFT_CLICK(self, self.__OnLabelLeftClick)
- self.init()
- self.columns = columns = self.getColumnDefinitions()
+ self.init()
+ self.columns = columns = self.getColumnDefinitions()
- #
- # Create the grid
- #
+ #
+ # Create the grid
+ #
- self.CreateGrid(1,len(columns))
+ self.CreateGrid(1,len(columns))
# self.SetEditable(1)
# self.SetSelectionMode(GridSelectRows)
- self.BeginBatch()
+ self.BeginBatch()
- self.SetRowLabelSize(0)
+ self.SetRowLabelSize(0)
- index = 0
- for column in columns:
- attr = GridCellAttr()
- try:
- readonly = column['ReadOnly']
- attr.SetReadOnly(column['ReadOnly'])
- except KeyError:
- pass
+ index = 0
+ for column in columns:
+ attr = GridCellAttr()
+ try:
+ readonly = column['ReadOnly']
+ attr.SetReadOnly(column['ReadOnly'])
+ except KeyError:
+ pass
- self.SetColLabelValue(index, column['Label'])
- self.SetColAttr(index, attr)
+ self.SetColLabelValue(index, column['Label'])
+ self.SetColAttr(index, attr)
- index += 1
+ index += 1
- # Initial inventory
- instance.rootObject.walk (self.inventoryObject)
+ # Initial inventory
+ instance.rootObject.walk (self.inventoryObject)
- self.__rebuildGrid()
- self.EndBatch()
+ self.__rebuildGrid()
+ self.EndBatch()
- #
- # Rebuild an individual row in the visible grid
- #
- def __rebuildRow(self, ri):
- self.BeginBatch()
+ #
+ # Rebuild an individual row in the visible grid
+ #
+ def __rebuildRow(self, ri):
+ self.BeginBatch()
- # Add any necessary rows
- if ri + 1 > self.GetNumberRows():
- self.AppendRows(ri - self.GetNumberRows() + 1)
+ # Add any necessary rows
+ if ri + 1 > self.GetNumberRows():
+ self.AppendRows(ri - self.GetNumberRows() + 1)
- row = self.rows[ri]
- ci = 0
- for column in self.columns:
- v = column['Attribute']
- if type(v) == types.MethodType:
- value = v(row)
- else:
- try:
- value = str(row.__dict__[v])
- except KeyError:
- value = ""
- self.SetCellValue(ri, ci, value)
- ci += 1
- self.EndBatch()
+ row = self.rows[ri]
+ ci = 0
+ for column in self.columns:
+ v = column['Attribute']
+ if type(v) == types.MethodType:
+ value = v(row)
+ else:
+ try:
+ value = str(row.__dict__[v])
+ except KeyError:
+ value = ""
+ self.SetCellValue(ri, ci, value)
+ ci += 1
+ self.EndBatch()
- #
- # Rebuild the visible grid.
- # If sort != -1, then sort is
- # the column # to sort by.
- #
- def __rebuildGrid(self, sort=-1, reverse=0):
+ #
+ # Rebuild the visible grid.
+ # If sort != -1, then sort is
+ # the column # to sort by.
+ #
+ def __rebuildGrid(self, sort=-1, reverse=0):
- # Save the sorting preference
- self.lastSort = sort
- self.lastReverse = reverse
+ # Save the sorting preference
+ self.lastSort = sort
+ self.lastReverse = reverse
- # Sort, if appropriate
- if sort >= 0:
- column = self.columns[sort]['Attribute']
- rows = []
- for object in self.objects:
- # If key is dynamically created, create it
- if type(column) == types.MethodType:
- key = column(object)
+ # Sort, if appropriate
+ if sort >= 0:
+ column = self.columns[sort]['Attribute']
+ rows = []
+ for object in self.objects:
+ # If key is dynamically created, create it
+ if type(column) == types.MethodType:
+ key = column(object)
+ else:
+ # Otherwise get the value, if available
+ try:
+ key = object.__dict__[column]
+ except KeyError:
+ key = None
+ try:
+ # If the key is a string, lowercase it
+ key = key.lower()
+ except AttributeError:
+ pass
+ rows.append ( (key, object) )
+ rows.sort()
+ if reverse:
+ rows.reverse()
+ self.rows = []
+ for key, object in rows:
+ self.rows.append(object)
else:
- # Otherwise get the value, if available
- try:
- key = object.__dict__[column]
- except KeyError:
- key = None
- try:
- # If the key is a string, lowercase it
- key = key.lower()
- except AttributeError:
- pass
- rows.append ( (key, object) )
- rows.sort()
- if reverse:
- rows.reverse()
- self.rows = []
- for key, object in rows:
- self.rows.append(object)
- else:
- self.rows = self.objects[:]
+ self.rows = self.objects[:]
- # .. and update the visible grid
- num = len(self.rows)
- self.BeginBatch()
+ # .. and update the visible grid
+ num = len(self.rows)
+ self.BeginBatch()
- # Create or delete any excess rows
- existing = self.GetNumberRows()
- if num < existing:
- self.DeleteRows(0, existing - num)
- elif num > existing:
- self.AppendRows(num - existing)
+ # Create or delete any excess rows
+ existing = self.GetNumberRows()
+ if num < existing:
+ self.DeleteRows(0, existing - num)
+ elif num > existing:
+ self.AppendRows(num - existing)
- # And update each individual row
- for i in range(len(self.rows)):
- self.__rebuildRow(i)
+ # And update each individual row
+ for i in range(len(self.rows)):
+ self.__rebuildRow(i)
- if self.current in self.rows:
- self.SelectRow(self.rows.index(self.current))
- else:
- try:
- self.current = self.rows[0]
- except IndexError:
- self.current = None
+ if self.current in self.rows:
+ self.SelectRow(self.rows.index(self.current))
+ else:
+ try:
+ self.current = self.rows[0]
+ except IndexError:
+ self.current = None
- self.EndBatch()
+ self.EndBatch()
- #
- #
- #
- def saveRuntimeSettings(self):
- settings = {}
+ #
+ #
+ #
+ def saveRuntimeSettings(self):
+ settings = {}
- # Save the top-level list column sizes
- for i in range(3): # Should be the number of columns in the list
- settings["col%s" % i] = self.list.GetColumnWidth(i)
+ # Save the top-level list column sizes
+ for i in range(3): # Should be the number of columns in the list
+ settings["col%s" % i] = self.list.GetColumnWidth(i)
- # Save the reference viewer column sizes
- for i in range(REF_COLUMNS):
- settings["refCol%s" % i] = self.referencesPanel.list.GetColumnWidth(i)
+ # Save the reference viewer column sizes
+ for i in range(REF_COLUMNS):
+ settings["refCol%s" % i] =
self.referencesPanel.list.GetColumnWidth(i)
- # Save the schema viewer column sizes
- for i in range(SCH_COLUMNS):
- settings["schemaCol%s" % i] = self.schemaPanel.list.GetColumnWidth(i)
+ # Save the schema viewer column sizes
+ for i in range(SCH_COLUMNS):
+ settings["schemaCol%s" % i] =
self.schemaPanel.list.GetColumnWidth(i)
- return ( self.runtime_section,
- settings )
+ return ( self.runtime_section,
+ settings )
- #
- # Add the object to our inventory, if applicable
- # If rebuild=1, then the visible grid is rebuilt
- #
- def inventoryObject(self, object, rebuild=0):
- if isinstance(object, self.base_gobject):
- self.objects.append(object)
- if rebuild:
- if self.lastSort > 0:
- self.__rebuildGrid(sort=self.lastSort, reverse=self.lastReverse)
- else:
- self.rows.append(object)
- self.__rebuildRow(len(self.rows)-1)
+ #
+ # Add the object to our inventory, if applicable
+ # If rebuild=1, then the visible grid is rebuilt
+ #
+ def inventoryObject(self, object, rebuild=0):
+ if isinstance(object, self.base_gobject):
+ self.objects.append(object)
+ if rebuild:
+ if self.lastSort > 0:
+ self.__rebuildGrid(sort=self.lastSort,
reverse=self.lastReverse)
+ else:
+ self.rows.append(object)
+ self.__rebuildRow(len(self.rows)-1)
- #
- # ObjectSelected event
- #
- def _objectSelected(self, event):
- if event.originator == self:
- return
- object = event.object
- if object in self.objects:
- self.current = object
- self.SelectRow(self.rows.index(object))
- index = self.objects.index(object)
+ #
+ # ObjectSelected event
+ #
+ def _objectSelected(self, event):
+ if event.originator == self:
+ return
+ object = event.object
+ if object in self.objects:
+ self.current = object
+ self.SelectRow(self.rows.index(object))
+ index = self.objects.index(object)
- #
- # ObjectModified event
- #
- def _objectModified(self, event):
- if event.originator == self:
- return
- if event.object in self.objects:
- if self.lastSort > 0:
- self.__rebuildGrid(sort=self.lastSort, reverse=self.lastReverse)
- else:
- self.__rebuildRow(self.rows.index(event.object))
+ #
+ # ObjectModified event
+ #
+ def _objectModified(self, event):
+ if event.originator == self:
+ return
+ if event.object in self.objects:
+ if self.lastSort > 0:
+ self.__rebuildGrid(sort=self.lastSort,
reverse=self.lastReverse)
+ else:
+ self.__rebuildRow(self.rows.index(event.object))
- #
- # ObjectCreated event
- #
- def _objectCreated(self, event):
- self.inventoryObject(event.object, 1)
+ #
+ # ObjectCreated event
+ #
+ def _objectCreated(self, event):
+ self.inventoryObject(event.object, 1)
- #
- # ObjectDeleted event
- #
- def _objectDeleted(self, event):
- object = event.object
- if object in self.objects:
- self.BeginBatch()
- self.objects.remove(object)
- index = self.rows.index(object)
- self.rows.remove(object)
- self.DeleteRows(index,1)
- self.EndBatch()
+ #
+ # ObjectDeleted event
+ #
+ def _objectDeleted(self, event):
+ object = event.object
+ if object in self.objects:
+ self.BeginBatch()
+ self.objects.remove(object)
+ index = self.rows.index(object)
+ self.rows.remove(object)
+ self.DeleteRows(index,1)
+ self.EndBatch()
- #
- # Called by the subclass to notify us that
- # a valid set has changed
- #
- def updateValidSet(self, column):
- i = 0
- while i < len(self.columns):
- if self.columns[i]['Name'] == column:
- break
- i += 1
- values = self.columns[i]['ValidSet']
- if type(values) == types.MethodType:
- values = values()
- print "TODO: UPDATING VALID SET"
+ #
+ # Called by the subclass to notify us that
+ # a valid set has changed
+ #
+ def updateValidSet(self, column):
+ i = 0
+ while i < len(self.columns):
+ if self.columns[i]['Name'] == column:
+ break
+ i += 1
+ values = self.columns[i]['ValidSet']
+ if type(values) == types.MethodType:
+ values = values()
+ print "TODO: UPDATING VALID SET"
- ##
- ## Wx event handlers
- ##
- def __OnCellChange(self, event):
- r = event.GetRow()
- c = event.GetCol()
- val = self.GetCellValue(r,c)
- object = self.rows[r]
- column = self.columns[c]
- attribute = column['Attribute']
- try:
- old = {attribute: object.__dict__[attribute] }
- except KeyError:
- old = {}
+ ##
+ ## Wx event handlers
+ ##
+ def __OnCellChange(self, event):
+ r = event.GetRow()
+ c = event.GetCol()
+ val = self.GetCellValue(r,c)
+ object = self.rows[r]
+ column = self.columns[c]
+ attribute = column['Attribute']
+ try:
+ old = {attribute: object.__dict__[attribute] }
+ except KeyError:
+ old = {}
- self.document.dispatchEvent('ObjectModified',
- object=object, originator=self,
- old=old, new = {attribute: val})
+ self.document.dispatchEvent('ObjectModified',
+ object=object, originator=self,
+ old=old, new = {attribute: val})
- #
- # User selected a new cell (row)
- #
- def __OnSelectCell(self, event):
- # Fire an ObjectSelected event
- object = self.rows[event.GetRow()]
- if object != self.current:
- self.document.dispatchEvent('ObjectSelected',
- object=self.rows[event.GetRow()],
- originator = self)
- self.current = object
- event.Skip()
+ #
+ # User selected a new cell (row)
+ #
+ def __OnSelectCell(self, event):
+ # Fire an ObjectSelected event
+ object = self.rows[event.GetRow()]
+ if object != self.current:
+ self.document.dispatchEvent('ObjectSelected',
+ object=self.rows[event.GetRow()],
+ originator = self)
+ self.current = object
+ event.Skip()
- #
- # User clicked the top label; resort by that column
- #
- def __OnLabelLeftClick(self, event):
- sort = event.GetCol()
- reverse = (sort == self.lastSort) and not self.lastReverse
- self.__rebuildGrid(sort=sort, reverse=reverse)
-
-
+ #
+ # User clicked the top label; resort by that column
+ #
+ def __OnLabelLeftClick(self, event):
+ sort = event.GetCol()
+ reverse = (sort == self.lastSort) and not self.lastReverse
+ self.__rebuildGrid(sort=sort, reverse=reverse)
Modified: trunk/gnue-designer/src/base/ObjectList.py
===================================================================
--- trunk/gnue-designer/src/base/ObjectList.py 2006-04-03 19:53:03 UTC (rev
8343)
+++ trunk/gnue-designer/src/base/ObjectList.py 2006-04-03 19:56:14 UTC (rev
8344)
@@ -36,82 +36,81 @@
class ObjectList:
- def __init__(self, instance, base, nameAttr, updateMethod=None):
- self.base = base
- self.name = nameAttr
- self.listeners = updateMethod and [updateMethod] or []
- self.objects = []
- instance.registerEventListeners({
- 'ObjectCreated' : self.__objectCreated,
- 'ObjectModified' : self.__objectModified,
- 'ObjectDeleted' : self.__objectDeleted,
- })
- instance.rootObject.walk(self.__inventory)
+ def __init__(self, instance, base, nameAttr, updateMethod=None):
+ self.base = base
+ self.name = nameAttr
+ self.listeners = updateMethod and [updateMethod] or []
+ self.objects = []
+ instance.registerEventListeners({
+ 'ObjectCreated' : self.__objectCreated,
+ 'ObjectModified' : self.__objectModified,
+ 'ObjectDeleted' : self.__objectDeleted,
+ })
+ instance.rootObject.walk(self.__inventory)
- def addListener(self, listener):
- self.listeners.append(listener)
+ def addListener(self, listener):
+ self.listeners.append(listener)
- def removeListener(self, listener):
- self.listeners.remove(listener)
+ def removeListener(self, listener):
+ self.listeners.remove(listener)
- def __inventory(self, object):
- if isinstance(object, self.base):
- self.objects.append(object)
+ def __inventory(self, object):
+ if isinstance(object, self.base):
+ self.objects.append(object)
- def __objectModified (self, event):
- if isinstance(event.object, self.base) and \
- self.name in event.old.keys() or \
- self.name in event.new.keys():
- for listener in self.listeners:
- listener()
+ def __objectModified (self, event):
+ if isinstance(event.object, self.base) and \
+ self.name in event.old.keys() or \
+ self.name in event.new.keys():
+ for listener in self.listeners:
+ listener()
- def __objectCreated (self, event):
- if isinstance(event.object, self.base):
- self.objects.append(event.object)
- for listener in self.listeners:
- listener()
+ def __objectCreated (self, event):
+ if isinstance(event.object, self.base):
+ self.objects.append(event.object)
+ for listener in self.listeners:
+ listener()
- def __objectDeleted (self, event):
- try:
- self.objects.remove(event.object)
- except ValueError:
- return
- for listener in self.listeners:
- listener()
+ def __objectDeleted (self, event):
+ try:
+ self.objects.remove(event.object)
+ except ValueError:
+ return
+ for listener in self.listeners:
+ listener()
- def getDict(self):
- rs = {}
- for object in self.objects:
- try:
- rs[object.__dict__[self.name]] = object
- except KeyError:
- pass
- return rs
+ def getDict(self):
+ rs = {}
+ for object in self.objects:
+ try:
+ rs[object.__dict__[self.name]] = object
+ except KeyError:
+ pass
+ return rs
- def getList(self):
- return tuple(self.objects)
+ def getList(self):
+ return tuple(self.objects)
- def __getitem__(self, name):
+ def __getitem__(self, name):
- # Name can either be the object's "name", or an index value
- try:
- name = name.lower()
- except AttributeError:
- # Index reference, not name reference
- return self.objects[name]
+ # Name can either be the object's "name", or an index value
+ try:
+ name = name.lower()
+ except AttributeError:
+ # Index reference, not name reference
+ return self.objects[name]
- # Name reference
- for object in self.objects:
- try:
- if object.__dict__[self.name].lower() == name:
- return object
- except KeyError:
- pass
- raise KeyError
+ # Name reference
+ for object in self.objects:
+ try:
+ if object.__dict__[self.name].lower() == name:
+ return object
+ except KeyError:
+ pass
+ raise KeyError
- def __getslice__(self, i, j):
- return self.objects[i:j]
+ def __getslice__(self, i, j):
+ return self.objects[i:j]
- def __len__(self):
- return len(self.objects)
-
+ def __len__(self):
+ return len(self.objects)
Modified: trunk/gnue-designer/src/base/PopupMenu.py
===================================================================
--- trunk/gnue-designer/src/base/PopupMenu.py 2006-04-03 19:53:03 UTC (rev
8343)
+++ trunk/gnue-designer/src/base/PopupMenu.py 2006-04-03 19:56:14 UTC (rev
8344)
@@ -35,236 +35,232 @@
class ActionMenu(wx.Menu):
- def __init__(self, instance, object, parent=None, text=None,
parentText=None):
- wx.Menu.__init__(self, text)
- self.document = instance
- self.__parent = parent
- self._object = object
- self._newMap = {}
- if parent:
- parent.AppendMenu(wx.NewId(), parentText, self)
+ def __init__(self, instance, object, parent=None, text=None,
parentText=None):
+ wx.Menu.__init__(self, text)
+ self.document = instance
+ self.__parent = parent
+ self._object = object
+ self._newMap = {}
+ if parent:
+ parent.AppendMenu(wx.NewId(), parentText, self)
- if object == None:
+ if object == None:
- self.addCreateTag(u_('datasource'),u_('New Data Source'))
- self.addCreateTag(u_('trigger'),u_('New Shared Trigger'))
- self.addCreateTag(u_('page'),u_('New Page'))
+ self.addCreateTag(u_('datasource'),u_('New Data Source'))
+ self.addCreateTag(u_('trigger'),u_('New Shared Trigger'))
+ self.addCreateTag(u_('page'),u_('New Page'))
- else:
+ else:
- # New >
- CreateObjectMenu(instance, object, self)
+ # New >
+ CreateObjectMenu(instance, object, self)
- # Properties
- id = wx.NewId()
- self.Append(id, u_("&Properties..."))
- wx.EVT_MENU(self, id, self.OnEditProperties)
+ # Properties
+ id = wx.NewId()
+ self.Append(id, u_("&Properties..."))
+ wx.EVT_MENU(self, id, self.OnEditProperties)
- if not isinstance (object, GFForm.GFForm):
- # Delete
- id = wx.NewId()
- self.Append(id, u_("&Delete %s") % object._type[2:])
- wx.EVT_MENU(self, id, self.OnDeleteObject)
+ if not isinstance (object, GFForm.GFForm):
+ # Delete
+ id = wx.NewId()
+ self.Append(id, u_("&Delete %s") % object._type[2:])
+ wx.EVT_MENU(self, id, self.OnDeleteObject)
- self.AppendSeparator()
+ self.AppendSeparator()
- # Events >
- if isinstance (object, GTrigger.GTriggerExtension):
- menu = wx.Menu(u_("Events..."))
- self._triggerMap = {}
- keys = object._validTriggers.keys()
- keys.sort()
- for trigger in (keys):
- tid = wx.NewId()
- self._triggerMap[tid] = trigger
- menu.Append(tid, object._validTriggers[trigger] + "...")
- wx.EVT_MENU(menu, tid, self.OnEditEvent)
- self.AppendMenu(wx.NewId(), u_("&Events"), menu)
+ # Events >
+ if isinstance (object, GTrigger.GTriggerExtension):
+ menu = wx.Menu(u_("Events..."))
+ self._triggerMap = {}
+ keys = object._validTriggers.keys()
+ keys.sort()
+ for trigger in (keys):
+ tid = wx.NewId()
+ self._triggerMap[tid] = trigger
+ menu.Append(tid, object._validTriggers[trigger] + "...")
+ wx.EVT_MENU(menu, tid, self.OnEditEvent)
+ self.AppendMenu(wx.NewId(), u_("&Events"), menu)
- if isinstance(object, GFObjects.GFPage) or \
- isinstance(object, GFObjects.GFBlock):
- self.AppendSeparator()
- # Reorder
- id = wx.NewId()
- self.Append(id, u_("&Reorder by Location"))
- wx.EVT_MENU(self, id, self.OnReorderLayout)
+ if isinstance(object, GFObjects.GFPage) or \
+ isinstance(object, GFObjects.GFBlock):
+ self.AppendSeparator()
+ # Reorder
+ id = wx.NewId()
+ self.Append(id, u_("&Reorder by Location"))
+ wx.EVT_MENU(self, id, self.OnReorderLayout)
- def addChildObjectMenu(self):
- object = self._object
- if len(object._children):
- self.AppendSeparator()
- for child in object._children:
- if isinstance (child, GObjects.GObj):
- self.AppendMenu(wx.NewId(), hasattr(child,'name') and child.name or \
- string.upper(child._type[2]) + \
- string.lower(child._type[3:]),
- PageMenu(self.document, child, self.x, self.y))
+ def addChildObjectMenu(self):
+ object = self._object
+ if len(object._children):
+ self.AppendSeparator()
+ for child in object._children:
+ if isinstance (child, GObjects.GObj):
+ self.AppendMenu(wx.NewId(), hasattr(child,'name') and
child.name or \
+ string.upper(child._type[2]) + \
+ string.lower(child._type[3:]),
+ PageMenu(self.document, child, self.x, self.y))
- def addCreateTag(self, tag, text):
- tid = wx.NewId()
- self._newMap[tid] = tag
- self.Append(tid, text)
- wx.EVT_MENU(self.document.ui, tid, self.OnCreateObject)
+ def addCreateTag(self, tag, text):
+ tid = wx.NewId()
+ self._newMap[tid] = tag
+ self.Append(tid, text)
+ wx.EVT_MENU(self.document.ui, tid, self.OnCreateObject)
- def OnEditProperties(self, event):
- self.document.propertyEditorWindow.Show(1)
- self.document.propertyEditorWindow.Raise()
- self.document.propertyEditorWindow.SetFocus()
+ def OnEditProperties(self, event):
+ self.document.propertyEditorWindow.Show(1)
+ self.document.propertyEditorWindow.Raise()
+ self.document.propertyEditorWindow.SetFocus()
- def OnEditEvent(self, event):
- pass
+ def OnEditEvent(self, event):
+ pass
- def OnCreateObject(self, event):
- tag = self._newMap[event.GetId()]
- assert gDebug(4,'Creating object %s with id %s'%(tag, event.GetId()))
- attributes=hasattr(self,'Char__x') and {'Char:x': self.Char__x, 'Char:y':
self.Char__y} or {}
- if tag == 'trigger':
- attributes['type']='named'
+ def OnCreateObject(self, event):
+ tag = self._newMap[event.GetId()]
+ assert gDebug(4,'Creating object %s with id %s'%(tag, event.GetId()))
+ attributes=hasattr(self,'Char__x') and {'Char:x': self.Char__x,
'Char:y': self.Char__y} or {}
+ if tag == 'trigger':
+ attributes['type']='named'
- self.document.incubator.createObject(self.document.rootObject, tag,
- self._object, attributes)
+ self.document.incubator.createObject(self.document.rootObject, tag,
+ self._object, attributes)
- def OnCreateDataSource(self, event):
- self.document.incubator.createObject(self.document.rootObject,
'datasource')
+ def OnCreateDataSource(self, event):
+ self.document.incubator.createObject(self.document.rootObject,
'datasource')
- def OnCreateNamedTrigger(self, event):
- self.document.incubator.createObject(self.document.rootObject, 'trigger')
+ def OnCreateNamedTrigger(self, event):
+ self.document.incubator.createObject(self.document.rootObject,
'trigger')
- def OnCreatePage(self, event):
- self.document.incubator.createObject(self.document.rootObject, 'page')
+ def OnCreatePage(self, event):
+ self.document.incubator.createObject(self.document.rootObject, 'page')
- def OnDeleteObject(self, event):
- self.document.dispatchEvent('ObjectDeleted', object=self._object,
- originator=self)
+ def OnDeleteObject(self, event):
+ self.document.dispatchEvent('ObjectDeleted', object=self._object,
+ originator=self)
- def OnReorderLayout(self, event):
- unqId = 0
- triggerObjects = []
- hiddenObjects = []
- boxObjects = {}
- navObjects = {}
- blockObjects = {}
- self._object._upperX = 99999
- self._object._upperY = 99999
+ def OnReorderLayout(self, event):
+ unqId = 0
+ triggerObjects = []
+ hiddenObjects = []
+ boxObjects = {}
+ navObjects = {}
+ blockObjects = {}
+ self._object._upperX = 99999
+ self._object._upperY = 99999
- # Handle each child (note we are working from a copy
- # because self.oject._children will be morphing
- for object in self._object._children[:]:
- if hasattr(object, 'hidden') and object.hidden:
- hiddenObjects.append(object)
- elif object._type == 'GCTrigger':
- triggerObjects.append(object)
- elif object._type == 'GFBlock':
- object._popupMenu.OnReorderLayout(event)
- object.__savedChildren = object._children[:]
- for o2 in object.__savedChildren:
- self.document.onDeleteObject(o2, __name__)
+ # Handle each child (note we are working from a copy
+ # because self.oject._children will be morphing
+ for object in self._object._children[:]:
+ if hasattr(object, 'hidden') and object.hidden:
+ hiddenObjects.append(object)
+ elif object._type == 'GCTrigger':
+ triggerObjects.append(object)
+ elif object._type == 'GFBlock':
+ object._popupMenu.OnReorderLayout(event)
+ object.__savedChildren = object._children[:]
+ for o2 in object.__savedChildren:
+ self.document.onDeleteObject(o2, __name__)
- oid = "%5d.%5d.%5d" % (object._upperY, object._upperX, unqId)
- unqId = unqId + 1
- blockObjects[oid] = object
+ oid = "%5d.%5d.%5d" % (object._upperY, object._upperX, unqId)
+ unqId = unqId + 1
+ blockObjects[oid] = object
- else:
- if hasattr(object,'Char__y') and object.Char__y < self._object._upperY:
- self._object._upperY = object.Char__y
- if hasattr(object,'Char__x') and object.Char__x < self._object._upperX:
- self._object._upperX = object.Char__x
+ else:
+ if hasattr(object,'Char__y') and object.Char__y <
self._object._upperY:
+ self._object._upperY = object.Char__y
+ if hasattr(object,'Char__x') and object.Char__x <
self._object._upperX:
+ self._object._upperX = object.Char__x
- oid = "%5d.%5d.%5d" % (object.y, object.x, unqId)
- unqId = unqId + 1
- if object._type == 'GFBox':
- boxObjects[oid] = object
- else:
- navObjects[oid] = object
+ oid = "%5d.%5d.%5d" % (object.y, object.x, unqId)
+ unqId = unqId + 1
+ if object._type == 'GFBox':
+ boxObjects[oid] = object
+ else:
+ navObjects[oid] = object
- # Notify everyone that this object was deleted
- self.document.onDeleteObject(object, __name__)
+ # Notify everyone that this object was deleted
+ self.document.onDeleteObject(object, __name__)
- self._object._children = []
+ self._object._children = []
- # First, add back triggers
- for object in triggerObjects:
- self._object._children.append(object)
- self.document.onCreateObject(object, __name__)
+ # First, add back triggers
+ for object in triggerObjects:
+ self._object._children.append(object)
+ self.document.onCreateObject(object, __name__)
- # Next, add back hidden objects
- for object in hiddenObjects:
- self._object._children.append(object)
- self.document.onCreateObject(object, __name__)
+ # Next, add back hidden objects
+ for object in hiddenObjects:
+ self._object._children.append(object)
+ self.document.onCreateObject(object, __name__)
- # Now, add hidden objects
- boxes = boxObjects.keys()
- boxes.sort()
- for box in boxes:
- self._object._children.append(boxObjects[box])
- self.document.onCreateObject(boxObjects[box], __name__)
+ # Now, add hidden objects
+ boxes = boxObjects.keys()
+ boxes.sort()
+ for box in boxes:
+ self._object._children.append(boxObjects[box])
+ self.document.onCreateObject(boxObjects[box], __name__)
- # The rest of the objects (other than blocks) go here
- nav = navObjects.keys()
- nav.sort()
- for n in nav:
- self._object._children.append(navObjects[n])
- self.document.onCreateObject(navObjects[n], __name__)
+ # The rest of the objects (other than blocks) go here
+ nav = navObjects.keys()
+ nav.sort()
+ for n in nav:
+ self._object._children.append(navObjects[n])
+ self.document.onCreateObject(navObjects[n], __name__)
- # And, finally, any child blocks
- blocks = blockObjects.keys()
- blocks.sort()
- for block in blocks:
- children = blockObjects[block].__savedChildren[:]
- self._object._children.append(blockObjects[block])
- self.document.onCreateObject(blockObjects[block], __name__)
- for child in children:
- blockObjects[block]._children.append(child)
- self.document.onCreateObject(child,__name__)
+ # And, finally, any child blocks
+ blocks = blockObjects.keys()
+ blocks.sort()
+ for block in blocks:
+ children = blockObjects[block].__savedChildren[:]
+ self._object._children.append(blockObjects[block])
+ self.document.onCreateObject(blockObjects[block], __name__)
+ for child in children:
+ blockObjects[block]._children.append(child)
+ self.document.onCreateObject(child,__name__)
class CreateObjectMenu(ActionMenu):
- def __init__(self, instance, object, parent):
- ActionMenu.__init__(self, instance, None, parent, u_('New...'),u_('&New'))
+ def __init__(self, instance, object, parent):
+ ActionMenu.__init__(self, instance, None, parent,
u_('New...'),u_('&New'))
- self._object = object
+ self._object = object
- self.AppendSeparator()
- tag = string.lower(object._type[2:])
- if self.document.incubator.elementMapping.has_key(tag):
- self.document.incubator.elementMapping[tag].sort()
- for element in self.document.incubator.elementMapping[tag]:
- descr = string.upper(element[0])+string.lower(element[1:])
- if descr == 'Import':
- descr = 'Import Library'
- elif len(descr) > 7 and descr[:7] == 'Import-':
- descr = 'Imported ' + string.upper(descr[7])+ \
- string.lower(descr[8:])
+ self.AppendSeparator()
+ tag = string.lower(object._type[2:])
+ if self.document.incubator.elementMapping.has_key(tag):
+ self.document.incubator.elementMapping[tag].sort()
+ for element in self.document.incubator.elementMapping[tag]:
+ descr = string.upper(element[0])+string.lower(element[1:])
+ if descr == 'Import':
+ descr = 'Import Library'
+ elif len(descr) > 7 and descr[:7] == 'Import-':
+ descr = 'Imported ' + string.upper(descr[7])+ \
+ string.lower(descr[8:])
- self.addCreateTag(element, descr)
+ self.addCreateTag(element, descr)
# This menu is the popup menu on the object tree
class ObjectMenu(ActionMenu):
- def __init__(self, instance, object):
- ActionMenu.__init__(self, instance, object, None, u_("Object Tasks..."))
+ def __init__(self, instance, object):
+ ActionMenu.__init__(self, instance, object, None, u_("Object
Tasks..."))
# This menu is the popup menu on the layout screen
class PageMenu(ActionMenu):
- def __init__(self, instance, object, x, y):
- ActionMenu.__init__(self, instance, object, None, hasattr(object,'name')
and \
- object.name or string.upper(object._type[2]) + \
- string.lower(object._type[3:]) )
+ def __init__(self, instance, object, x, y):
+ ActionMenu.__init__(self, instance, object, None,
hasattr(object,'name') and \
+ object.name or string.upper(object._type[2]) + \
+ string.lower(object._type[3:]) )
- self.x = x
- self.y = y
+ self.x = x
+ self.y = y
- self.addChildObjectMenu()
-
-
-
-
+ self.addChildObjectMenu()
Modified: trunk/gnue-designer/src/base/PrimaryToolBar.py
===================================================================
--- trunk/gnue-designer/src/base/PrimaryToolBar.py 2006-04-03 19:53:03 UTC
(rev 8343)
+++ trunk/gnue-designer/src/base/PrimaryToolBar.py 2006-04-03 19:56:14 UTC
(rev 8344)
@@ -47,36 +47,35 @@
# Tool Bar class
#----------------------------------------------------------------------------
class PrimaryToolBar(BaseToolBar):
- """
- The primary tool bar that is common to all documents
- (includes New, Open, Save, Exit, etc)
- """
+ """
+ The primary tool bar that is common to all documents
+ (includes New, Open, Save, Exit, etc)
+ """
- def init(self):
- # Register our icons
- self.addToolbarMapping(ToolbarMapping)
-
- # Listen for document-level "saved/unsaved" events
- # So we can enable/disable the Save icon
- self.registerEventListeners( {'MakeDirty' : self._onDirty,
- 'MakeClean' : self._onClean, } )
+ def init(self):
+ # Register our icons
+ self.addToolbarMapping(ToolbarMapping)
+ # Listen for document-level "saved/unsaved" events
+ # So we can enable/disable the Save icon
+ self.registerEventListeners( {'MakeDirty' : self._onDirty,
+ 'MakeClean' : self._onClean, } )
- def _onDirty(self, event):
- """
- Enable the Save icon
- """
- try:
- self.EnableTool(self.mapping['RequestSave'],1)
- except KeyError:
- pass
- def _onClean(self, event):
- """
- Disable the Save icon
- """
- try:
- self.EnableTool(self.mapping['RequestSave'],0)
- except KeyError:
- pass
+ def _onDirty(self, event):
+ """
+ Enable the Save icon
+ """
+ try:
+ self.EnableTool(self.mapping['RequestSave'],1)
+ except KeyError:
+ pass
+ def _onClean(self, event):
+ """
+ Disable the Save icon
+ """
+ try:
+ self.EnableTool(self.mapping['RequestSave'],0)
+ except KeyError:
+ pass
Modified: trunk/gnue-designer/src/base/TemplateBase.py
===================================================================
--- trunk/gnue-designer/src/base/TemplateBase.py 2006-04-03 19:53:03 UTC
(rev 8343)
+++ trunk/gnue-designer/src/base/TemplateBase.py 2006-04-03 19:56:14 UTC
(rev 8344)
@@ -79,158 +79,158 @@
#
class TemplateBase:
- ##########################################
- #
- # The following few methods should be
- # subclassed by the template developer.
+ ##########################################
+ #
+ # The following few methods should be
+ # subclassed by the template developer.
- # The first step in our wizard
- FIRST_STEP = '0'
+ # The first step in our wizard
+ FIRST_STEP = '0'
- # Stores all the variables
- # entered by the wizard user.
- variables = {}
+ # Stores all the variables
+ # entered by the wizard user.
+ variables = {}
- def Start(self, object, current={}):
- return 0
+ def Start(self, object, current={}):
+ return 0
- # Verify contents of current step
- # Return None if no problems, otherwise
- # return a tuple of error message strings
- def ValidateStep(self, stepCode):
- return None
+ # Verify contents of current step
+ # Return None if no problems, otherwise
+ # return a tuple of error message strings
+ def ValidateStep(self, stepCode):
+ return None
- # Get a step
- def GetStep(self, stepCode):
- return None
+ # Get a step
+ def GetStep(self, stepCode):
+ return None
- # We have all the data, so generate our object
- def Finalize(self):
- return 1
+ # We have all the data, so generate our object
+ def Finalize(self):
+ return 1
- ##########################################
- #
- # The following methods are convenience
- # methods.
+ ##########################################
+ #
+ # The following methods are convenience
+ # methods.
- def AddElement(self, tag, parent, attributes={}, content=""):
- instance = self.parser.document
- if content:
- attr = {'_content_': content}
- else:
- attr = {}
- attr.update(attributes)
- return instance.incubator.createObject(instance.rootObject,
- tag, parent, attributes=attr, select=0)
+ def AddElement(self, tag, parent, attributes={}, content=""):
+ instance = self.parser.document
+ if content:
+ attr = {'_content_': content}
+ else:
+ attr = {}
+ attr.update(attributes)
+ return instance.incubator.createObject(instance.rootObject,
+ tag, parent, attributes=attr, select=0)
- def SetContent(self, element, content):
- i = 0
- while i < len(element._children):
- if element._children[i]._type == '_content_':
- element._children.pop(i)
- else:
- i += 1
- content = GContent(element, content)
+ def SetContent(self, element, content):
+ i = 0
+ while i < len(element._children):
+ if element._children[i]._type == '_content_':
+ element._children.pop(i)
+ else:
+ i += 1
+ content = GContent(element, content)
- def ModifyElement(self, element, **modifications):
- oldMods = {}
- for attr in modifications.keys():
- try:
- oldMods[attr] = element.__dict__[attr]
- except KeyError:
- oldMods[attr] = None
+ def ModifyElement(self, element, **modifications):
+ oldMods = {}
+ for attr in modifications.keys():
+ try:
+ oldMods[attr] = element.__dict__[attr]
+ except KeyError:
+ oldMods[attr] = None
- element.__dict__.update(modifications)
+ element.__dict__.update(modifications)
- self.parser.document.dispatchEvent('ObjectModified',
- object=element, originator=__name__,
- new=modifications, old=oldMods)
+ self.parser.document.dispatchEvent('ObjectModified',
+ object=element, originator=__name__,
+ new=modifications, old=oldMods)
- def GetAvailableConnections(self):
- rv = []
- p = self._connections.getAllConnectionParameters()
- for conn in p.keys():
- if p[conn].has_key('comment'):
- rv.append((conn, '%s [%s]' % (p[conn]['comment'], conn)))
- else:
- rv.append((conn, '%s [%s]' % (conn, p[conn]['provider'])))
- return rv
+ def GetAvailableConnections(self):
+ rv = []
+ p = self._connections.getAllConnectionParameters()
+ for conn in p.keys():
+ if p[conn].has_key('comment'):
+ rv.append((conn, '%s [%s]' % (p[conn]['comment'], conn)))
+ else:
+ rv.append((conn, '%s [%s]' % (conn, p[conn]['provider'])))
+ return rv
- def GetTemporaryConnection(self, connection_name):
-
- return self._connections.getConnection(connection_name, 1)
+ def GetTemporaryConnection(self, connection_name):
+ return self._connections.getConnection(connection_name, 1)
- def GetAvailableSources (self, connection_name):
- try:
- tables = self.__cachedSources[connection_name]
- except KeyError:
- self.__cachedSources [connection_name] = tables = \
- self.GetTemporaryConnection (connection_name).readSchema ()
+ def GetAvailableSources (self, connection_name):
- result = []
+ try:
+ tables = self.__cachedSources[connection_name]
+ except KeyError:
+ self.__cachedSources [connection_name] = tables = \
+ self.GetTemporaryConnection (connection_name).readSchema ()
- if tables is not None:
- for table in tables.findChildrenOfType ('GSTable', False, True):
- result.append ((table.name, hasattr (table, 'description') and
- table.description or table.name))
- return result
+ result = []
+ if tables is not None:
+ for table in tables.findChildrenOfType ('GSTable', False, True):
+ result.append ((table.name, hasattr (table, 'description') and
+ table.description or table.name))
+ return result
- def GetSourceSchema (self, connection_name, source_name):
- if not connection_name in self.__cachedSources:
- self.__cachedSources [connection_name] = \
- self.GetTemporaryConnection (connection_name).readSchema ()
+ def GetSourceSchema (self, connection_name, source_name):
- schema = self.__cachedSources [connection_name]
- if schema is not None:
- for table in schema.findChildrenOfType ('GSTable', False, True):
- if table.name.lower () == source_name.lower ():
- return table
- else:
- return None
+ if not connection_name in self.__cachedSources:
+ self.__cachedSources [connection_name] = \
+ self.GetTemporaryConnection (connection_name).readSchema ()
+ schema = self.__cachedSources [connection_name]
+ if schema is not None:
+ for table in schema.findChildrenOfType ('GSTable', False, True):
+ if table.name.lower () == source_name.lower ():
+ return table
+ else:
+ return None
- def GetAvailableFields (self, connection_name, source_name):
- result = []
- source = self.GetSourceSchema (connection_name, source_name)
- if source is not None:
- for field in source.findChildrenOfType ('GSField', False, True):
- result.append ((field.name, hasattr (field, 'description') \
- and field.description or field.name))
- return result
+ def GetAvailableFields (self, connection_name, source_name):
+ result = []
+ source = self.GetSourceSchema (connection_name, source_name)
+ if source is not None:
+ for field in source.findChildrenOfType ('GSField', False, True):
+ result.append ((field.name, hasattr (field, 'description') \
+ and field.description or field.name))
+ return result
- def GetUniqueName(self, name, limitingObject=None):
- return self.document.getUniqueName(name, limitingObject)
+ def GetUniqueName(self, name, limitingObject=None):
+ return self.document.getUniqueName(name, limitingObject)
- ##########################################
- #
- # The following methods are of no concern
- # to the wizard/template developer and
- # may/will be changed later on.
- def __init__(self, parser):
- self.parser = parser
- self.document = parser.document
- self._connections = parser.document.app.connections
- self.__cachedConnections = {}
- self.__cachedSources = {}
+ ##########################################
+ #
+ # The following methods are of no concern
+ # to the wizard/template developer and
+ # may/will be changed later on.
+ def __init__(self, parser):
+ self.parser = parser
+ self.document = parser.document
+ self._connections = parser.document.app.connections
+ self.__cachedConnections = {}
+ self.__cachedSources = {}
+
###########################################################
#
# Wizard elements
@@ -247,37 +247,37 @@
class WizardItem:
- pass
+ pass
class WizardText (WizardItem):
- def __init__(self, text):
- self.text = text
+ def __init__(self, text):
+ self.text = text
class WizardInput (WizardItem):
- def __init__(self, variable, label, typecast=text,
- set=None, size=10, lowerbound=None, upperbound=None,
- forceupper=0, forcelower=0, required=0, lines=1,
- maxSelections=1, orderable=0):
+ def __init__(self, variable, label, typecast=text,
+ set=None, size=10, lowerbound=None, upperbound=None,
+ forceupper=0, forcelower=0, required=0, lines=1,
+ maxSelections=1, orderable=0):
- self.variable = variable
- self.label = label
- self.typecast = typecast
- self.set = set
- self.size = size
- self.lowerbound = lowerbound
- self.upperbound = upperbound
- self.forceupper = forceupper
- self.required = required
- self.forcelower = forcelower
- self.lines = lines
+ self.variable = variable
+ self.label = label
+ self.typecast = typecast
+ self.set = set
+ self.size = size
+ self.lowerbound = lowerbound
+ self.upperbound = upperbound
+ self.forceupper = forceupper
+ self.required = required
+ self.forcelower = forcelower
+ self.lines = lines
- # The following only have an effect is set != None
- self.maxSelections = maxSelections
- self.orderable = orderable
+ # The following only have an effect is set != None
+ self.maxSelections = maxSelections
+ self.orderable = orderable
# A wizard can raise this if not enough information
# is provided or if the root object is not in a
# sufficient state.
class InsufficientInformation(StandardError):
- pass
+ pass
Modified: trunk/gnue-designer/src/base/TemplateChooser.py
===================================================================
--- trunk/gnue-designer/src/base/TemplateChooser.py 2006-04-03 19:53:03 UTC
(rev 8343)
+++ trunk/gnue-designer/src/base/TemplateChooser.py 2006-04-03 19:56:14 UTC
(rev 8344)
@@ -32,41 +32,41 @@
from gnue.designer.templates import GetAvailablePackages, GetAvailableTemplates
class TemplateChooser:
- def __init__(self, parent):
- self.parent = parent
+ def __init__(self, parent):
+ self.parent = parent
- self.packages = GetAvailablePackages()
+ self.packages = GetAvailablePackages()
- def run(self):
+ def run(self):
- self.chooser = wx.Dialog(None, -1, u_('Choose Wizard to Run...'),
- style=wx.DEFAULT_DIALOG_STYLE|wx.DIALOG_MODAL)
+ self.chooser = wx.Dialog(None, -1, u_('Choose Wizard to Run...'),
+ style=wx.DEFAULT_DIALOG_STYLE|wx.DIALOG_MODAL)
- self.panel = wx.Panel(self.chooser, -1, wx.Point(0,0), wx.Size(400,340))
- self.notebook = wx.Notebook(self.panel, -1)
- self.chooser.SetClientSize(wx.Size(400,340))
+ self.panel = wx.Panel(self.chooser, -1, wx.Point(0,0),
wx.Size(400,340))
+ self.notebook = wx.Notebook(self.panel, -1)
+ self.chooser.SetClientSize(wx.Size(400,340))
- self.chooseButton = wx.Button(self.panel, -1, u_('Run Wizard'))
- self.cancelButton = wx.Button(self.panel, -1, u_('Cancel'))
+ self.chooseButton = wx.Button(self.panel, -1, u_('Run Wizard'))
+ self.cancelButton = wx.Button(self.panel, -1, u_('Cancel'))
- self.chooseButton.SetDefault()
+ self.chooseButton.SetDefault()
- self.cancelButton.SetSize(self.chooseButton.GetSize())
+ self.cancelButton.SetSize(self.chooseButton.GetSize())
- y = self.panel.GetClientSize().y - 6 - self.chooseButton.GetSize().y
- dx = self.chooseButton.GetSize().x + 6
- x = self.panel.GetClientSize().x - 9 - self.chooseButton.GetSize().x
+ y = self.panel.GetClientSize().y - 6 - self.chooseButton.GetSize().y
+ dx = self.chooseButton.GetSize().x + 6
+ x = self.panel.GetClientSize().x - 9 - self.chooseButton.GetSize().x
- self.cancelButton.SetPosition( (x, y) )
- self.chooseButton.SetPosition( (x - dx, y) )
+ self.cancelButton.SetPosition( (x, y) )
+ self.chooseButton.SetPosition( (x - dx, y) )
- wx.EVT_BUTTON(self.chooser,self.chooseButton.GetId(), self.OnSelected)
- wx.EVT_BUTTON(self.chooser,self.cancelButton.GetId(), self.OnCancel)
+ wx.EVT_BUTTON(self.chooser,self.chooseButton.GetId(), self.OnSelected)
+ wx.EVT_BUTTON(self.chooser,self.cancelButton.GetId(), self.OnCancel)
- wx.EVT_CLOSE(self.chooser, self.OnCancel)
+ wx.EVT_CLOSE(self.chooser, self.OnCancel)
# self.title = wx.StaticText(self.panel, -1, "Wizard Header",
pos=wx.Point(10,10))
# font = self.title.GetFont()
@@ -78,13 +78,13 @@
# self.title2.SetForegroundColour(wx.Colour(0,0,102))
# self.title2.SetFont(font)
- self.chooser.Fit()
+ self.chooser.Fit()
- self.notebook.SetPosition((10, 10))
- w,h = self.chooser.GetClientSizeTuple()
- w = w - 21
- h = h - 46 - self.chooseButton.GetSize().y
- self.notebook.SetSize((w,h))
+ self.notebook.SetPosition((10, 10))
+ w,h = self.chooser.GetClientSizeTuple()
+ w = w - 21
+ h = h - 46 - self.chooseButton.GetSize().y
+ self.notebook.SetSize((w,h))
# self.chooserPage.SetSize((w,h))
# self.chooserPage.SetBackgroundColour(
@@ -93,86 +93,86 @@
# self.panel.GetBackgroundColour().Green() + 32,
# self.panel.GetBackgroundColour().Blue() + 32) )
- assert gDebug(2,"Packages=%s" % self.packages)
- notebookIndex = 0
- lookupIndex = 0
- self.lookup = {}
- for package in self.packages:
+ assert gDebug(2,"Packages=%s" % self.packages)
+ notebookIndex = 0
+ lookupIndex = 0
+ self.lookup = {}
+ for package in self.packages:
# page = wx.Panel(self.notebook, -1, wx.Point(0,0), \
# self.notebook.GetClientSize())
# w,h = page.GetClientSizeTuple()
# ctrl = wx.ListCtrl(page, -1,wx.Point(5,5), wx.Size(w-10,h-10),
# style=wx.LC_REPORT|wx.LC_SINGLE_SEL|wx.STATIC_BORDER)
#wx.LC_HRULES|wx.LC_VRULES|)
- ctrl = wx.ListCtrl(self.notebook, -1,wx.Point(5,5), wx.Size(w-10,h-10),
- style=wx.LC_REPORT|wx.LC_SINGLE_SEL|wx.STATIC_BORDER)
#wx.LC_HRULES|wx.LC_VRULES|)
- ctrl.InsertColumn(0, u_("Name"), format=wx.LIST_FORMAT_LEFT, width=-1)
- ctrl.InsertColumn(1, u_("Description"), format=wx.LIST_FORMAT_LEFT,
width=-1)
- ctrl.InsertColumn(2, u_("Type"), format=wx.LIST_FORMAT_LEFT, width=-1)
- ctrl.InsertColumn(3, u_("Author"), format=wx.LIST_FORMAT_LEFT, width=-1)
- ctrl.InsertColumn(4, u_("Version"), format=wx.LIST_FORMAT_LEFT, width=-1)
+ ctrl = wx.ListCtrl(self.notebook, -1,wx.Point(5,5),
wx.Size(w-10,h-10),
+ style=wx.LC_REPORT|wx.LC_SINGLE_SEL|wx.STATIC_BORDER)
#wx.LC_HRULES|wx.LC_VRULES|)
+ ctrl.InsertColumn(0, u_("Name"), format=wx.LIST_FORMAT_LEFT,
width=-1)
+ ctrl.InsertColumn(1, u_("Description"),
format=wx.LIST_FORMAT_LEFT, width=-1)
+ ctrl.InsertColumn(2, u_("Type"), format=wx.LIST_FORMAT_LEFT,
width=-1)
+ ctrl.InsertColumn(3, u_("Author"), format=wx.LIST_FORMAT_LEFT,
width=-1)
+ ctrl.InsertColumn(4, u_("Version"), format=wx.LIST_FORMAT_LEFT,
width=-1)
- wx.EVT_LIST_ITEM_SELECTED(self.chooser, ctrl.GetId(), self.OnSelect)
- wx.EVT_LIST_ITEM_ACTIVATED(self.chooser, ctrl.GetId(), self.OnSelected)
+ wx.EVT_LIST_ITEM_SELECTED(self.chooser, ctrl.GetId(),
self.OnSelect)
+ wx.EVT_LIST_ITEM_ACTIVATED(self.chooser, ctrl.GetId(),
self.OnSelected)
# self.notebook.AddPage(page, package.PACKAGE)
- self.notebook.AddPage(ctrl, package.PACKAGE)
- self.lookup[notebookIndex] = {}
+ self.notebook.AddPage(ctrl, package.PACKAGE)
+ self.lookup[notebookIndex] = {}
- i = 0
- for template in GetAvailableTemplates(package):
- ctrl.InsertStringItem(i, template['Name'])
- if template.has_key('Description'):
- ctrl.SetStringItem(i, 1, template['Description'])
- else:
- ctrl.SetStringItem(i, 1, u_('Unknown'))
+ i = 0
+ for template in GetAvailableTemplates(package):
+ ctrl.InsertStringItem(i, template['Name'])
+ if template.has_key('Description'):
+ ctrl.SetStringItem(i, 1, template['Description'])
+ else:
+ ctrl.SetStringItem(i, 1, u_('Unknown'))
- if template['Product'] == TemplateBase.TEMPLATE:
- ctrl.SetStringItem(i, 2, 'Template')
- elif template['Product'] == TemplateBase.WIZARD:
- ctrl.SetStringItem(i, 2, u_('Wizard'))
+ if template['Product'] == TemplateBase.TEMPLATE:
+ ctrl.SetStringItem(i, 2, 'Template')
+ elif template['Product'] == TemplateBase.WIZARD:
+ ctrl.SetStringItem(i, 2, u_('Wizard'))
- if template.has_key('Author'):
- ctrl.SetStringItem(i, 3, template['Author'])
- else:
- ctrl.SetStringItem(i, 3, u_('Unknown'))
+ if template.has_key('Author'):
+ ctrl.SetStringItem(i, 3, template['Author'])
+ else:
+ ctrl.SetStringItem(i, 3, u_('Unknown'))
- if template.has_key('Version'):
- ctrl.SetStringItem(i, 4, template['Version'])
- else:
- ctrl.SetStringItem(i, 4, u_('Unknown'))
- ctrl.SetItemData(i, lookupIndex)
+ if template.has_key('Version'):
+ ctrl.SetStringItem(i, 4, template['Version'])
+ else:
+ ctrl.SetStringItem(i, 4, u_('Unknown'))
+ ctrl.SetItemData(i, lookupIndex)
- self.lookup[notebookIndex][lookupIndex] = template
+ self.lookup[notebookIndex][lookupIndex] = template
- i += 1
- lookupIndex += 1
+ i += 1
+ lookupIndex += 1
- if i:
- ctrl.SetColumnWidth(0,wx.LIST_AUTOSIZE)
+ if i:
+ ctrl.SetColumnWidth(0,wx.LIST_AUTOSIZE)
- lookupIndex = 0
- notebookIndex += 1
+ lookupIndex = 0
+ notebookIndex += 1
- self.selection = 0
- completed = self.chooser.ShowModal()
- results = None
+ self.selection = 0
+ completed = self.chooser.ShowModal()
+ results = None
- if completed:
- results = self.lookup[self.notebook.GetSelection()][self.selection]
+ if completed:
+ results = self.lookup[self.notebook.GetSelection()][self.selection]
- self.chooser.Destroy()
- return results
+ self.chooser.Destroy()
+ return results
- # When user highlights a wizard from the list...
- def OnSelect(self, event):
- self.selection = event.GetIndex()
+ # When user highlights a wizard from the list...
+ def OnSelect(self, event):
+ self.selection = event.GetIndex()
- # When user clicks the "Select" button...
- def OnSelected(self, event):
- self.chooser.EndModal(1)
+ # When user clicks the "Select" button...
+ def OnSelected(self, event):
+ self.chooser.EndModal(1)
- # When user clicks the "Cancel" button...
- def OnCancel(self, event):
- self.chooser.EndModal(0)
+ # When user clicks the "Cancel" button...
+ def OnCancel(self, event):
+ self.chooser.EndModal(0)
Modified: trunk/gnue-designer/src/base/TemplateParser.py
===================================================================
--- trunk/gnue-designer/src/base/TemplateParser.py 2006-04-03 19:53:03 UTC
(rev 8343)
+++ trunk/gnue-designer/src/base/TemplateParser.py 2006-04-03 19:56:14 UTC
(rev 8344)
@@ -34,651 +34,651 @@
from gnue.common.events import Event
class TemplateParser:
- def __init__(self, instance, rootObject, parent,
- templateInformation, currentObject=None):
- self.parent = parent
- self.document = instance
- self.templateInformation = templateInformation
- self.rootObject = rootObject
- self.currentObject = currentObject
+ def __init__(self, instance, rootObject, parent,
+ templateInformation, currentObject=None):
+ self.parent = parent
+ self.document = instance
+ self.templateInformation = templateInformation
+ self.rootObject = rootObject
+ self.currentObject = currentObject
- self.elements = instance.incubator.elements
+ self.elements = instance.incubator.elements
- def run(self, **params):
+ def run(self, **params):
- self.template = self.templateInformation['BaseClass'](self)
+ self.template = self.templateInformation['BaseClass'](self)
- completed = 0
+ completed = 0
- try:
- # Clear out any old variables
- self.template.variables = {}
- self.template.Start(self.rootObject,
- self.document.buildWizardCurrentDict(),
- **params)
+ try:
+ # Clear out any old variables
+ self.template.variables = {}
+ self.template.Start(self.rootObject,
+ self.document.buildWizardCurrentDict(),
+ **params)
- # If this is simply a template and not a wizard,
- # generate the results and get out of Dodge.
- if self.templateInformation['Behavior'] == TemplateBase.TEMPLATE:
- return self.template.Finalize()
+ # If this is simply a template and not a wizard,
+ # generate the results and get out of Dodge.
+ if self.templateInformation['Behavior'] == TemplateBase.TEMPLATE:
+ return self.template.Finalize()
- self.wizard = wx.Dialog(self.parent, -1,
self.templateInformation['Name'],
- style=wx.DEFAULT_DIALOG_STYLE|wx.DIALOG_MODAL)
+ self.wizard = wx.Dialog(self.parent, -1,
self.templateInformation['Name'],
+ style=wx.DEFAULT_DIALOG_STYLE|wx.DIALOG_MODAL)
- self.panel = wx.Panel(self.wizard, -1, wx.Point(0,0), wx.Size(400,400))
- self.wizard.SetClientSize(wx.Size(400,400))
+ self.panel = wx.Panel(self.wizard, -1, wx.Point(0,0),
wx.Size(400,400))
+ self.wizard.SetClientSize(wx.Size(400,400))
- self.wizardPage = WizardPage(self, self.panel)
+ self.wizardPage = WizardPage(self, self.panel)
- self.prevButton = wx.Button(self.panel, -1, u_('< Back'))
- self.nextButton = wx.Button(self.panel, -1, u_('Continue >'))
- self.cancelButton = wx.Button(self.panel, -1, u_('Cancel'))
+ self.prevButton = wx.Button(self.panel, -1, u_('< Back'))
+ self.nextButton = wx.Button(self.panel, -1, u_('Continue >'))
+ self.cancelButton = wx.Button(self.panel, -1, u_('Cancel'))
- self.nextButton.SetDefault()
+ self.nextButton.SetDefault()
- self.prevButton.SetSize(self.nextButton.GetSize())
- self.cancelButton.SetSize(self.nextButton.GetSize())
+ self.prevButton.SetSize(self.nextButton.GetSize())
+ self.cancelButton.SetSize(self.nextButton.GetSize())
- y = self.panel.GetClientSize().y - 9 - self.nextButton.GetSize().y
- dx = self.nextButton.GetSize().x + 6
- x = self.panel.GetClientSize().x - 9 - self.nextButton.GetSize().x
+ y = self.panel.GetClientSize().y - 9 - self.nextButton.GetSize().y
+ dx = self.nextButton.GetSize().x + 6
+ x = self.panel.GetClientSize().x - 9 - self.nextButton.GetSize().x
- self.cancelButton.SetPosition( (x, y) )
- self.nextButton.SetPosition( (x - dx, y) )
- self.prevButton.SetPosition( (x - dx*2, y) )
+ self.cancelButton.SetPosition( (x, y) )
+ self.nextButton.SetPosition( (x - dx, y) )
+ self.prevButton.SetPosition( (x - dx*2, y) )
- wx.EVT_BUTTON(self.wizard,self.prevButton.GetId(),
self.wizardPage.OnPrevStep)
- wx.EVT_BUTTON(self.wizard,self.nextButton.GetId(),
self.wizardPage.OnNextStep)
- wx.EVT_BUTTON(self.wizard,self.cancelButton.GetId(),
self.wizardPage.OnCancel)
+ wx.EVT_BUTTON(self.wizard,self.prevButton.GetId(),
self.wizardPage.OnPrevStep)
+ wx.EVT_BUTTON(self.wizard,self.nextButton.GetId(),
self.wizardPage.OnNextStep)
+ wx.EVT_BUTTON(self.wizard,self.cancelButton.GetId(),
self.wizardPage.OnCancel)
- wx.EVT_CLOSE(self.wizard, self.wizardPage.OnCancel)
+ wx.EVT_CLOSE(self.wizard, self.wizardPage.OnCancel)
- self.title = wx.StaticText(self.panel, -1, u_("Wizard Header"),
pos=wx.Point(10,10))
- font = self.title.GetFont()
- font.SetPointSize(int(self.title.GetFont().GetPointSize()*1.5))
- font.SetStyle(wx.ITALIC)
+ self.title = wx.StaticText(self.panel, -1, u_("Wizard Header"),
pos=wx.Point(10,10))
+ font = self.title.GetFont()
+ font.SetPointSize(int(self.title.GetFont().GetPointSize()*1.5))
+ font.SetStyle(wx.ITALIC)
# font.SetWeight(wx.BOLD)
- self.title.SetForegroundColour(wx.Colour(255,255,255))
- self.title.SetFont(font)
- self.title2 = wx.StaticText(self.panel, -1, u_("Wizard Header"),
pos=wx.Point(11,11))
- self.title2.SetForegroundColour(wx.Colour(0,0,102))
- self.title2.SetFont(font)
+ self.title.SetForegroundColour(wx.Colour(255,255,255))
+ self.title.SetFont(font)
+ self.title2 = wx.StaticText(self.panel, -1, u_("Wizard Header"),
pos=wx.Point(11,11))
+ self.title2.SetForegroundColour(wx.Colour(0,0,102))
+ self.title2.SetFont(font)
- self.wizard.Fit()
+ self.wizard.Fit()
- self.wizardPage.SetPosition((20, 20 + self.title.GetSize().y))
- w,h = self.wizard.GetClientSizeTuple()
- w = w - 50
- h = h - 56 - self.title.GetSize().y - self.nextButton.GetSize().y
- self.wizardPage.SetSize((w,h))
+ self.wizardPage.SetPosition((20, 20 + self.title.GetSize().y))
+ w,h = self.wizard.GetClientSizeTuple()
+ w = w - 50
+ h = h - 56 - self.title.GetSize().y - self.nextButton.GetSize().y
+ self.wizardPage.SetSize((w,h))
- r = self.panel.GetBackgroundColour().Red()
- g = self.panel.GetBackgroundColour().Green()
- b = self.panel.GetBackgroundColour().Blue()
+ r = self.panel.GetBackgroundColour().Red()
+ g = self.panel.GetBackgroundColour().Green()
+ b = self.panel.GetBackgroundColour().Blue()
- self.wizardPage.SetBackgroundColour(
- wx.Colour(
- (r <= 223 and r or 223) + 32,
- (g <= 223 and g or 223) + 32,
- (b <= 223 and b or 223) + 32) )
+ self.wizardPage.SetBackgroundColour(
+ wx.Colour(
+ (r <= 223 and r or 223) + 32,
+ (g <= 223 and g or 223) + 32,
+ (b <= 223 and b or 223) + 32) )
- self.wizardPage.setStep(self.template.FIRST_STEP)
- completed = self.wizard.ShowModal()
- if completed:
- completed = self.template.Finalize()
+ self.wizardPage.setStep(self.template.FIRST_STEP)
+ completed = self.wizard.ShowModal()
+ if completed:
+ completed = self.template.Finalize()
- except TemplateBase.InsufficientInformation, msg:
- # Give feedback if the wizard raised an exception
- if str(msg):
- msg = "\n\n" + TextUtils.lineWrap(str(msg),40)
- else:
- msg = ""
+ except TemplateBase.InsufficientInformation, msg:
+ # Give feedback if the wizard raised an exception
+ if str(msg):
+ msg = "\n\n" + TextUtils.lineWrap(str(msg),40)
+ else:
+ msg = ""
- dlg = wx.MessageDialog(None,
- u_("Unable to perform the requested action.") + msg,
- u_("Wizard Error"), style=wx.OK|wx.ICON_WARNING)
- dlg.ShowModal()
- dlg.Destroy()
+ dlg = wx.MessageDialog(None,
+ u_("Unable to perform the requested action.") + msg,
+ u_("Wizard Error"), style=wx.OK|wx.ICON_WARNING)
+ dlg.ShowModal()
+ dlg.Destroy()
- # Cleanup...
- try: self.wizardPage.Destroy()
- except: pass
- try: self.wizard.Destroy()
- except: pass
+ # Cleanup...
+ try: self.wizardPage.Destroy()
+ except: pass
+ try: self.wizard.Destroy()
+ except: pass
- return completed
+ return completed
- def cancel(self):
- self.wizard.EndModal(0)
+ def cancel(self):
+ self.wizard.EndModal(0)
class WizardPage(wx.Panel):
- def __init__(self, parser, parent):
- wx.Panel.__init__(self, parent, -1, pos=wx.Point(0,0),
size=wx.Size(400,250), style=wx.SIMPLE_BORDER)
- self.parser = parser
- self.parent = parent
- self.panel = None
+ def __init__(self, parser, parent):
+ wx.Panel.__init__(self, parent, -1, pos=wx.Point(0,0),
size=wx.Size(400,250), style=wx.SIMPLE_BORDER)
+ self.parser = parser
+ self.parent = parent
+ self.panel = None
- def GetPrev(self, parent):
- if self.prevStep != None:
- return self
- else:
- return None
+ def GetPrev(self, parent):
+ if self.prevStep != None:
+ return self
+ else:
+ return None
- def GetNext(self, parent):
- if self.nextStep != None:
- self.setStep(self.stepInfo['next'])
- return self
- else:
- return None
+ def GetNext(self, parent):
+ if self.nextStep != None:
+ self.setStep(self.stepInfo['next'])
+ return self
+ else:
+ return None
- def setStep(self, step):
- self.step = step
- self.stepInfo = self.parser.template.GetStep(step)
- self.nextStep = self.stepInfo['next']
- self.prevStep = self.stepInfo['prev']
- self.buildPage()
+ def setStep(self, step):
+ self.step = step
+ self.stepInfo = self.parser.template.GetStep(step)
+ self.nextStep = self.stepInfo['next']
+ self.prevStep = self.stepInfo['prev']
+ self.buildPage()
- # User clicked the "Next >" (or "Finish") button
- def OnNextStep(self, event):
+ # User clicked the "Next >" (or "Finish") button
+ def OnNextStep(self, event):
- validation = []
+ validation = []
- # Save the variables from current step
- for o in self.editorMappings.keys():
- value = o.get()
- if o.source.required and (value == None or not o.source.set and
- o.source.typecast == TemplateBase.text and not len(value)):
- validation.append('A required value is missing for "%s"' % (
- hasattr(o.source,'label') and o.source.label or o.source.variable))
+ # Save the variables from current step
+ for o in self.editorMappings.keys():
+ value = o.get()
+ if o.source.required and (value == None or not o.source.set and
+ o.source.typecast == TemplateBase.text and not
len(value)):
+ validation.append('A required value is missing for "%s"' % (
+ hasattr(o.source,'label') and o.source.label or
o.source.variable))
- ## TODO: Add the various other validation checks
+ ## TODO: Add the various other validation checks
- self.parser.template.variables[self.editorMappings[o].variable] = value
+ self.parser.template.variables[self.editorMappings[o].variable] =
value
- # Ask the template instance if it validates or not
- if not validation:
- validation = self.parser.template.ValidateStep(self.step)
+ # Ask the template instance if it validates or not
+ if not validation:
+ validation = self.parser.template.ValidateStep(self.step)
- # Whoop! The user forgot something... inform them
- if validation:
- # Give feedback
- dlg = wx.MessageDialog(self.parser.wizard,
- u_("Please correct the following mistakes before continuing:\n\n
- ") + \
- string.join(validation,'\n - '),
- u_("Wizard Error"), style=wx.OK|wx.ICON_WARNING)
- dlg.ShowModal()
- dlg.Destroy()
+ # Whoop! The user forgot something... inform them
+ if validation:
+ # Give feedback
+ dlg = wx.MessageDialog(self.parser.wizard,
+ u_("Please correct the following mistakes before
continuing:\n\n - ") + \
+ string.join(validation,'\n - '),
+ u_("Wizard Error"), style=wx.OK|wx.ICON_WARNING)
+ dlg.ShowModal()
+ dlg.Destroy()
- return
+ return
- # Life is good and we have our info.... High-tail it out of here
- else:
- if self.nextStep == None:
- self.parser.wizard.EndModal(1)
- else:
- self.setStep(self.nextStep)
- event.Skip()
+ # Life is good and we have our info.... High-tail it out of here
+ else:
+ if self.nextStep == None:
+ self.parser.wizard.EndModal(1)
+ else:
+ self.setStep(self.nextStep)
+ event.Skip()
- # User clicked the "< Prev" button
- def OnPrevStep(self, event):
- # Save the variables from current step
- for o in self.editorMappings.keys():
- self.parser.template.variables[self.editorMappings[o].variable] = o.get()
+ # User clicked the "< Prev" button
+ def OnPrevStep(self, event):
+ # Save the variables from current step
+ for o in self.editorMappings.keys():
+ self.parser.template.variables[self.editorMappings[o].variable] =
o.get()
- self.setStep(self.prevStep)
+ self.setStep(self.prevStep)
- # User clicked the "Cancel" button
- def OnCancel(self, event):
- self.parser.wizard.EndModal(0)
+ # User clicked the "Cancel" button
+ def OnCancel(self, event):
+ self.parser.wizard.EndModal(0)
- # Build all the widgets and position them
- def buildPage(self):
- for child in self.GetChildren():
- child.Destroy()
+ # Build all the widgets and position them
+ def buildPage(self):
+ for child in self.GetChildren():
+ child.Destroy()
- xMargin = 6
- xMarginInput = xMargin * 3
- yMargin = 6
+ xMargin = 6
+ xMarginInput = xMargin * 3
+ yMargin = 6
- xSpacing = 10
- ySpacing = 6
- nextY = yMargin
+ xSpacing = 10
+ ySpacing = 6
+ nextY = yMargin
- if self.nextStep == None:
- self.parser.nextButton.SetLabel(u_('Finished'))
- else:
- self.parser.nextButton.SetLabel(u_('Continue >'))
+ if self.nextStep == None:
+ self.parser.nextButton.SetLabel(u_('Finished'))
+ else:
+ self.parser.nextButton.SetLabel(u_('Continue >'))
- if self.prevStep == None:
- self.parser.prevButton.Enable(0)
- else:
- self.parser.prevButton.Enable(1)
+ if self.prevStep == None:
+ self.parser.prevButton.Enable(0)
+ else:
+ self.parser.prevButton.Enable(1)
- self.parser.title.SetLabel(self.stepInfo['title'])
- self.parser.title2.SetLabel(self.stepInfo['title'])
+ self.parser.title.SetLabel(self.stepInfo['title'])
+ self.parser.title2.SetLabel(self.stepInfo['title'])
- xMargin = xMargin
- nextY = yMargin
+ xMargin = xMargin
+ nextY = yMargin
- self.editorMappings = {}
- self.textctrlList = []
+ self.editorMappings = {}
+ self.textctrlList = []
- for object in self.stepInfo['content']:
+ for object in self.stepInfo['content']:
- if isinstance(object, TemplateBase.WizardText):
+ if isinstance(object, TemplateBase.WizardText):
- width = self.GetSize().x - xMargin * 2
+ width = self.GetSize().x - xMargin * 2
- o = WrappedStaticText(self, -1, object.text, width,
- pos=wx.Point(xMargin, nextY))
+ o = WrappedStaticText(self, -1, object.text, width,
+ pos=wx.Point(xMargin, nextY))
- nextY = nextY + ySpacing + o.GetSize().y
+ nextY = nextY + ySpacing + o.GetSize().y
- elif isinstance(object, TemplateBase.WizardInput):
+ elif isinstance(object, TemplateBase.WizardInput):
- x = xMarginInput
- if object.label != None:
- o = wx.StaticText(self, -1, object.label, pos=wx.Point(x, nextY+3))
- x = x + xSpacing + o.GetSize().x
+ x = xMarginInput
+ if object.label != None:
+ o = wx.StaticText(self, -1, object.label, pos=wx.Point(x,
nextY+3))
+ x = x + xSpacing + o.GetSize().x
- size = (self.GetClientSize().x - x - xMarginInput,-1)
+ size = (self.GetClientSize().x - x - xMarginInput,-1)
- if object.set != None and len(object.set):
- if object.maxSelections != 1 and object.orderable:
- x = xMarginInput
- nextY = nextY + ySpacing + o.GetSize().y
- size = (self.GetClientSize().x - x - xMarginInput,-1)
- o = SortableListField(object, self, pos=wx.Point(x, nextY),
size=size)
- elif object.lines > 1 or object.maxSelections != 1:
- o = ListField(object, self, pos=wx.Point(x, nextY), size=size)
- else:
- o = ComboField(object, self, pos=wx.Point(x, nextY), size=size)
- else:
- o = TextField(object, self, pos=wx.Point(x, nextY), size=size)
+ if object.set != None and len(object.set):
+ if object.maxSelections != 1 and object.orderable:
+ x = xMarginInput
+ nextY = nextY + ySpacing + o.GetSize().y
+ size = (self.GetClientSize().x - x - xMarginInput,-1)
+ o = SortableListField(object, self, pos=wx.Point(x,
nextY), size=size)
+ elif object.lines > 1 or object.maxSelections != 1:
+ o = ListField(object, self, pos=wx.Point(x, nextY),
size=size)
+ else:
+ o = ComboField(object, self, pos=wx.Point(x, nextY),
size=size)
+ else:
+ o = TextField(object, self, pos=wx.Point(x, nextY),
size=size)
- self.editorMappings[o] = object
- MyId = len(self.textctrlList)
- self.textctrlList.append(o)
+ self.editorMappings[o] = object
+ MyId = len(self.textctrlList)
+ self.textctrlList.append(o)
- nextY = nextY + ySpacing + o.GetSize().y
+ nextY = nextY + ySpacing + o.GetSize().y
- wx.EVT_CHAR(o, FieldHandler(self, MyId).fieldEventTrap)
+ wx.EVT_CHAR(o, FieldHandler(self, MyId).fieldEventTrap)
- if self.parser.template.variables.has_key(object.variable):
- o.set(self.parser.template.variables[object.variable])
+ if self.parser.template.variables.has_key(object.variable):
+ o.set(self.parser.template.variables[object.variable])
- # Add our buttons to the focus list
- if self.prevStep:
- self.textctrlList.append(self.parser.prevButton)
- self.textctrlList.append(self.parser.nextButton)
- self.textctrlList.append(self.parser.cancelButton)
+ # Add our buttons to the focus list
+ if self.prevStep:
+ self.textctrlList.append(self.parser.prevButton)
+ self.textctrlList.append(self.parser.nextButton)
+ self.textctrlList.append(self.parser.cancelButton)
- # Set focus to be the first input widget
- self.textctrlList[0].SetFocus()
+ # Set focus to be the first input widget
+ self.textctrlList[0].SetFocus()
class TextField(wx.TextCtrl):
- def __init__(self, source, parent,
- pos=wx.DefaultPosition, size=wx.DefaultSize):
- wx.TextCtrl.__init__(self, parent, -1, pos=pos, size=size)
- self.source = source
- self.parent = parent
+ def __init__(self, source, parent,
+ pos=wx.DefaultPosition, size=wx.DefaultSize):
+ wx.TextCtrl.__init__(self, parent, -1, pos=pos, size=size)
+ self.source = source
+ self.parent = parent
- self.forceupper = self.source.forceupper
- self.forcelower = self.source.forcelower
+ self.forceupper = self.source.forceupper
+ self.forcelower = self.source.forcelower
- if self.forceupper:
- wx.EVT_CHAR(wx.TextCtrl, self.OnCharUpper)
- if self.forcelower:
- wx.EVT_CHAR(wx.TextCtrl, self.OnCharLower)
+ if self.forceupper:
+ wx.EVT_CHAR(wx.TextCtrl, self.OnCharUpper)
+ if self.forcelower:
+ wx.EVT_CHAR(wx.TextCtrl, self.OnCharLower)
- def get(self):
- return self.GetValue()
+ def get(self):
+ return self.GetValue()
- def set(self, value):
- self.SetValue(value)
+ def set(self, value):
+ self.SetValue(value)
- # TODO: This wx.EVT_CHAR should convert the text to uppercase
- def OnCharUpper(self, event):
- event.Skip()
+ # TODO: This wx.EVT_CHAR should convert the text to uppercase
+ def OnCharUpper(self, event):
+ event.Skip()
- # TODO: This wx.EVT_CHAR should convert the text to lowercase
- def OnCharLower(self, event):
- event.Skip()
+ # TODO: This wx.EVT_CHAR should convert the text to lowercase
+ def OnCharLower(self, event):
+ event.Skip()
class ComboField(wx.ComboBox):
- def __init__(self, source, parent, pos=wx.DefaultPosition,
size=wx.DefaultSize):
- wx.ComboBox.__init__(self, parent, -1, pos=pos, size=size)
- self.source = source
- self.parent = parent
- self.mapping = {}
- self.lookup = []
+ def __init__(self, source, parent, pos=wx.DefaultPosition,
size=wx.DefaultSize):
+ wx.ComboBox.__init__(self, parent, -1, pos=pos, size=size)
+ self.source = source
+ self.parent = parent
+ self.mapping = {}
+ self.lookup = []
- i = 0
- for choice in source.set:
- key, descr = choice
- self.mapping[key] = i
- self.lookup.append(key)
- self.Append(descr)
- i = i + 1
+ i = 0
+ for choice in source.set:
+ key, descr = choice
+ self.mapping[key] = i
+ self.lookup.append(key)
+ self.Append(descr)
+ i = i + 1
- def get(self):
- return self.lookup[self.GetSelection()]
+ def get(self):
+ return self.lookup[self.GetSelection()]
- def set(self, value):
- self.SetSelection(self.mapping[value])
+ def set(self, value):
+ self.SetSelection(self.mapping[value])
class ListField(wx.ListBox):
- def __init__(self, source, parent, pos=wx.DefaultPosition,
size=wx.DefaultSize):
- if source.maxSelections != 1:
- style = wx.LB_MULTIPLE
- else:
- style = wx.LB_SINGLE
+ def __init__(self, source, parent, pos=wx.DefaultPosition,
size=wx.DefaultSize):
+ if source.maxSelections != 1:
+ style = wx.LB_MULTIPLE
+ else:
+ style = wx.LB_SINGLE
- wx.ListBox.__init__(self, parent, -1, pos=pos, size=size, \
- style=style|wx.LB_HSCROLL|wx.LB_NEEDED_SB)
+ wx.ListBox.__init__(self, parent, -1, pos=pos, size=size, \
+ style=style|wx.LB_HSCROLL|wx.LB_NEEDED_SB)
- self.source = source
- self.parent = parent
- self.mapping = {}
- self.lookup = []
+ self.source = source
+ self.parent = parent
+ self.mapping = {}
+ self.lookup = []
- #print source.set
+ #print source.set
- i = 0
+ i = 0
- # TODO: This [:2000] is a temporary fix since GTK limits to 2000 entries
- for choice in source.set[:500]:
- key, descr = choice
- self.mapping[key] = i
- self.lookup.append(key)
- self.Append(descr)
- i = i + 1
+ # TODO: This [:2000] is a temporary fix since GTK limits to 2000
entries
+ for choice in source.set[:500]:
+ key, descr = choice
+ self.mapping[key] = i
+ self.lookup.append(key)
+ self.Append(descr)
+ i = i + 1
- def get(self):
- if self.source.maxSelections == 1:
- return self.lookup[self.GetSelection()]
- else:
- rv = []
- for i in self.GetSelections():
- rv.append(self.lookup[i])
+ def get(self):
+ if self.source.maxSelections == 1:
+ return self.lookup[self.GetSelection()]
+ else:
+ rv = []
+ for i in self.GetSelections():
+ rv.append(self.lookup[i])
- def set(self, value):
- if type(value) in ( type([]), type(()) ) :
- set = []
- for v in value:
- set.append(self.mapping[v])
- self.SetSelections(set)
- else:
- try:
- self.SetSelection(self.mapping[value])
- except KeyError:
- pass
+ def set(self, value):
+ if type(value) in ( type([]), type(()) ) :
+ set = []
+ for v in value:
+ set.append(self.mapping[v])
+ self.SetSelections(set)
+ else:
+ try:
+ self.SetSelection(self.mapping[value])
+ except KeyError:
+ pass
class SortableListField(wx.Panel):
- def __init__(self, source, parent, pos=wx.DefaultPosition,
- size=wx.DefaultSize):
+ def __init__(self, source, parent, pos=wx.DefaultPosition,
+ size=wx.DefaultSize):
- wx.Panel.__init__(self, parent, -1, pos=pos, size=size,
- style=wx.SIMPLE_BORDER)
+ wx.Panel.__init__(self, parent, -1, pos=pos, size=size,
+ style=wx.SIMPLE_BORDER)
- self.source = source
- self.parent = parent
+ self.source = source
+ self.parent = parent
- self.addButton = wx.Button(self, -1, u_(" Add >"))
- self.delButton = wx.Button(self, -1, u_("< Remove "))
- self.upButton = wx.Button(self, -1, u_("Move Up"))
- self.downButton = wx.Button(self, -1, u_("Move Down"))
- self.selectAllButton = wx.Button(self, -1, u_("Select All"))
+ self.addButton = wx.Button(self, -1, u_(" Add >"))
+ self.delButton = wx.Button(self, -1, u_("< Remove "))
+ self.upButton = wx.Button(self, -1, u_("Move Up"))
+ self.downButton = wx.Button(self, -1, u_("Move Down"))
+ self.selectAllButton = wx.Button(self, -1, u_("Select All"))
- self.addButton.SetSize(self.downButton.GetSize())
- self.delButton.SetSize(self.downButton.GetSize())
- self.upButton.SetSize(self.downButton.GetSize())
- self.selectAllButton.SetSize(self.downButton.GetSize())
+ self.addButton.SetSize(self.downButton.GetSize())
+ self.delButton.SetSize(self.downButton.GetSize())
+ self.upButton.SetSize(self.downButton.GetSize())
+ self.selectAllButton.SetSize(self.downButton.GetSize())
- self.addButton.Enable(0)
- self.delButton.Enable(0)
- self.upButton.Enable(0)
- self.downButton.Enable(0)
- self.selectAllButton.Enable(1)
+ self.addButton.Enable(0)
+ self.delButton.Enable(0)
+ self.upButton.Enable(0)
+ self.downButton.Enable(0)
+ self.selectAllButton.Enable(1)
- self.list1 = wx.ListBox(self, -1, wx.Point(6,6), \
- style=wx.LB_MULTIPLE|wx.LB_HSCROLL|wx.LB_NEEDED_SB)
+ self.list1 = wx.ListBox(self, -1, wx.Point(6,6), \
+ style=wx.LB_MULTIPLE|wx.LB_HSCROLL|wx.LB_NEEDED_SB)
- self.list2 = wx.ListBox(self, -1, \
- style=wx.LB_MULTIPLE|wx.LB_HSCROLL|wx.LB_NEEDED_SB)
+ self.list2 = wx.ListBox(self, -1, \
+ style=wx.LB_MULTIPLE|wx.LB_HSCROLL|wx.LB_NEEDED_SB)
- self.included = []
- self.excluded = []
+ self.included = []
+ self.excluded = []
- self.includedMap = {}
- self.excludedMap = {}
+ self.includedMap = {}
+ self.excludedMap = {}
- bw, bh = self.delButton.GetSizeTuple()
- lw, lh = self.list1.GetSizeTuple()
+ bw, bh = self.delButton.GetSizeTuple()
+ lw, lh = self.list1.GetSizeTuple()
- self.addButton.SetPosition(wx.Point(lw + 12, 12))
- self.delButton.SetPosition(wx.Point(lw + 12, 16 + bh))
- self.upButton.SetPosition(wx.Point(lw + 12, 26 + bh*2))
- self.downButton.SetPosition(wx.Point(lw + 12, 30 + bh*3))
- self.selectAllButton.SetPosition(wx.Point(lw + 12, 34 + bh*4))
+ self.addButton.SetPosition(wx.Point(lw + 12, 12))
+ self.delButton.SetPosition(wx.Point(lw + 12, 16 + bh))
+ self.upButton.SetPosition(wx.Point(lw + 12, 26 + bh*2))
+ self.downButton.SetPosition(wx.Point(lw + 12, 30 + bh*3))
+ self.selectAllButton.SetPosition(wx.Point(lw + 12, 34 + bh*4))
- self.list1.SetSize(wx.Size(self.list1.GetSizeTuple()[0],
- 50 + bh*4))
- self.list2.SetSize(self.list1.GetSize())
+ self.list1.SetSize(wx.Size(self.list1.GetSizeTuple()[0],
+ 50 + bh*4))
+ self.list2.SetSize(self.list1.GetSize())
- self.list2.SetPosition(wx.Point(lw+bw+18,6))
- lw, lh = self.list1.GetSizeTuple()
+ self.list2.SetPosition(wx.Point(lw+bw+18,6))
+ lw, lh = self.list1.GetSizeTuple()
- self.SetSize(wx.Size(lw*2+bw+25, lh + 13))
+ self.SetSize(wx.Size(lw*2+bw+25, lh + 13))
- wx.EVT_BUTTON(self, self.addButton.GetId(), self.OnAdd)
- wx.EVT_BUTTON(self, self.delButton.GetId(), self.OnRemove)
- wx.EVT_BUTTON(self, self.upButton.GetId(), self.OnMoveUp)
- wx.EVT_BUTTON(self, self.downButton.GetId(), self.OnMoveDown)
- wx.EVT_BUTTON(self, self.selectAllButton.GetId(), self.OnSelectAll)
+ wx.EVT_BUTTON(self, self.addButton.GetId(), self.OnAdd)
+ wx.EVT_BUTTON(self, self.delButton.GetId(), self.OnRemove)
+ wx.EVT_BUTTON(self, self.upButton.GetId(), self.OnMoveUp)
+ wx.EVT_BUTTON(self, self.downButton.GetId(), self.OnMoveDown)
+ wx.EVT_BUTTON(self, self.selectAllButton.GetId(), self.OnSelectAll)
- wx.EVT_LISTBOX(self, self.list1.GetId(), self.OnSelectLeft)
- wx.EVT_LISTBOX(self, self.list2.GetId(), self.OnSelectRight)
+ wx.EVT_LISTBOX(self, self.list1.GetId(), self.OnSelectLeft)
+ wx.EVT_LISTBOX(self, self.list2.GetId(), self.OnSelectRight)
- for choice in source.set:
- key, descr = choice
- self.excluded.append(key)
- self.list1.Append(descr)
+ for choice in source.set:
+ key, descr = choice
+ self.excluded.append(key)
+ self.list1.Append(descr)
- def get(self):
- return self.included[:]
+ def get(self):
+ return self.included[:]
- def set(self, value):
- map = {}
- self.included = []
- self.excluded = []
- self.list1.Clear()
- self.list2.Clear()
- for choice in self.source.set:
- key, descr = choice
- if key in value:
- map[key] = descr
- else:
- self.excluded.append(key)
- self.list1.Append(descr)
+ def set(self, value):
+ map = {}
+ self.included = []
+ self.excluded = []
+ self.list1.Clear()
+ self.list2.Clear()
+ for choice in self.source.set:
+ key, descr = choice
+ if key in value:
+ map[key] = descr
+ else:
+ self.excluded.append(key)
+ self.list1.Append(descr)
- for key in value:
- self.included.append(key)
- self.list2.Append(map[key])
+ for key in value:
+ self.included.append(key)
+ self.list2.Append(map[key])
- def OnSelectLeft(self, event):
- if len(self.list1.GetSelections()):
- self.addButton.Enable(1)
- else:
- self.addButton.Enable(0)
- self.delButton.Enable(0)
- self.upButton.Enable(0)
- self.downButton.Enable(0)
- for i in self.list2.GetSelections():
- self.list2.SetSelection(i,0)
+ def OnSelectLeft(self, event):
+ if len(self.list1.GetSelections()):
+ self.addButton.Enable(1)
+ else:
+ self.addButton.Enable(0)
+ self.delButton.Enable(0)
+ self.upButton.Enable(0)
+ self.downButton.Enable(0)
+ for i in self.list2.GetSelections():
+ self.list2.SetSelection(i,0)
- def OnSelectRight(self, event):
- sel = self.list2.GetSelections()
- if len(sel):
- self.delButton.Enable(1)
+ def OnSelectRight(self, event):
+ sel = self.list2.GetSelections()
+ if len(sel):
+ self.delButton.Enable(1)
- if 0 in sel:
- self.upButton.Enable(0)
- else:
- self.upButton.Enable(1)
+ if 0 in sel:
+ self.upButton.Enable(0)
+ else:
+ self.upButton.Enable(1)
- if self.list2.Number()-1 in sel:
- self.downButton.Enable(0)
- else:
- self.downButton.Enable(1)
- else:
- self.delButton.Enable(0)
- self.upButton.Enable(0)
- self.downButton.Enable(0)
+ if self.list2.Number()-1 in sel:
+ self.downButton.Enable(0)
+ else:
+ self.downButton.Enable(1)
+ else:
+ self.delButton.Enable(0)
+ self.upButton.Enable(0)
+ self.downButton.Enable(0)
- self.addButton.Enable(0)
- for i in self.list1.GetSelections():
- self.list1.SetSelection(i,0)
+ self.addButton.Enable(0)
+ for i in self.list1.GetSelections():
+ self.list1.SetSelection(i,0)
- def OnSelectAll(self, event):
+ def OnSelectAll(self, event):
- count = self.list1.GetCount()
- for count in range(count):
- self.list1.SetSelection(count)
- self.addButton.Enable(1)
+ count = self.list1.GetCount()
+ for count in range(count):
+ self.list1.SetSelection(count)
+ self.addButton.Enable(1)
- def OnAdd(self, event):
- sel = list(self.list1.GetSelections())
- sel.sort(lambda a,b : cmp (b,a))
- appendages1 = []
- appendages2 = []
- for i in sel:
- appendages1.insert(0,self.list1.GetString(i))
- appendages2.insert(0,self.excluded[i])
- self.excluded.pop(i)
- self.list1.Delete(i)
+ def OnAdd(self, event):
+ sel = list(self.list1.GetSelections())
+ sel.sort(lambda a,b : cmp (b,a))
+ appendages1 = []
+ appendages2 = []
+ for i in sel:
+ appendages1.insert(0,self.list1.GetString(i))
+ appendages2.insert(0,self.excluded[i])
+ self.excluded.pop(i)
+ self.list1.Delete(i)
- for a in appendages1:
- self.list2.Append(a)
+ for a in appendages1:
+ self.list2.Append(a)
- for a in appendages2:
- self.included.append(a)
+ for a in appendages2:
+ self.included.append(a)
- self.OnSelectRight(None)
+ self.OnSelectRight(None)
- def OnRemove(self, event):
- sel = list(self.list2.GetSelections())
- sel.sort(lambda a,b : cmp (b,a))
- appendages1 = []
- appendages2 = []
- for i in sel:
- appendages1.insert(0,self.list2.GetString(i))
- appendages2.insert(0,self.included[i])
- self.included.pop(i)
- self.list2.Delete(i)
+ def OnRemove(self, event):
+ sel = list(self.list2.GetSelections())
+ sel.sort(lambda a,b : cmp (b,a))
+ appendages1 = []
+ appendages2 = []
+ for i in sel:
+ appendages1.insert(0,self.list2.GetString(i))
+ appendages2.insert(0,self.included[i])
+ self.included.pop(i)
+ self.list2.Delete(i)
- for a in appendages1:
- self.list1.Append(a)
+ for a in appendages1:
+ self.list1.Append(a)
- for a in appendages2:
- self.excluded.append(a)
+ for a in appendages2:
+ self.excluded.append(a)
- self.OnSelectLeft(None)
+ self.OnSelectLeft(None)
- def OnMoveUp(self, event):
- sel = self.list2.GetSelections()
- if 0 in sel:
- return
+ def OnMoveUp(self, event):
+ sel = self.list2.GetSelections()
+ if 0 in sel:
+ return
- for i in sel:
- k = i - 1
- prevKey = self.included[k]
- prevText = self.list2.GetString(k)
- self.included.pop(k)
- self.included.insert(i,prevKey)
- self.list2.Delete(k)
- self.list2.InsertItems([prevText],i)
+ for i in sel:
+ k = i - 1
+ prevKey = self.included[k]
+ prevText = self.list2.GetString(k)
+ self.included.pop(k)
+ self.included.insert(i,prevKey)
+ self.list2.Delete(k)
+ self.list2.InsertItems([prevText],i)
- def OnMoveDown(self, event):
- sel = list(self.list2.GetSelections())
- if self.list2.Number()-1 in sel:
- return
+ def OnMoveDown(self, event):
+ sel = list(self.list2.GetSelections())
+ if self.list2.Number()-1 in sel:
+ return
- sel.sort(lambda a,b: cmp(b,a))
+ sel.sort(lambda a,b: cmp(b,a))
- for i in sel:
- k = i + 1
- prevKey = self.included[k]
- prevText = self.list2.GetString(k)
- self.included.pop(k)
- self.included.insert(i,prevKey)
- self.list2.Delete(k)
- self.list2.InsertItems([prevText],i)
+ for i in sel:
+ k = i + 1
+ prevKey = self.included[k]
+ prevText = self.list2.GetString(k)
+ self.included.pop(k)
+ self.included.insert(i,prevKey)
+ self.list2.Delete(k)
+ self.list2.InsertItems([prevText],i)
class WizardRunner:
- def __init__(self, template, instance):
- self.template = template
- self.document = instance
- instance.registerEventListeners(
- { 'Wizard:%s' % template['BaseID']: self.run,
- 'Cancel:Wizard:%s' % template['BaseID']: self.cancel } )
+ def __init__(self, template, instance):
+ self.template = template
+ self.document = instance
+ instance.registerEventListeners(
+ { 'Wizard:%s' % template['BaseID']: self.run,
+ 'Cancel:Wizard:%s' % template['BaseID']: self.cancel } )
- def run(self, event, *args, **parms):
- self.document.dispatchEvent('BeginWizard', template=self.template)
- self.document.dispatchEvent('BeginUndoGroup')
- self.parser = TemplateParser(self.document, self.document.rootObject,
- self.document.ui, self.template)
- self.parser.run(*args, **parms)
- self.document.dispatchEvent('EndUndoGroup')
- self.document.dispatchEvent('EndWizard', template=self.template)
+ def run(self, event, *args, **parms):
+ self.document.dispatchEvent('BeginWizard', template=self.template)
+ self.document.dispatchEvent('BeginUndoGroup')
+ self.parser = TemplateParser(self.document, self.document.rootObject,
+ self.document.ui, self.template)
+ self.parser.run(*args, **parms)
+ self.document.dispatchEvent('EndUndoGroup')
+ self.document.dispatchEvent('EndWizard', template=self.template)
- def cancel(self, event=None):
- self.parser.cancel()
+ def cancel(self, event=None):
+ self.parser.cancel()
- def finalize(self):
- pass
+ def finalize(self):
+ pass
class WrappedStaticText(wx.StaticText):
- def __init__(self, parent, id, label, width, *args, **params):
- wx.StaticText.__init__(self, parent, id, "bah!", *args, **params)
+ def __init__(self, parent, id, label, width, *args, **params):
+ wx.StaticText.__init__(self, parent, id, "bah!", *args, **params)
- textSoFar = ""
- thisLine = ""
- for part in string.split(label,'\n'):
- for word in string.split(part):
- self.SetLabel(thisLine + word)
- if self.GetSize().width > width:
- textSoFar += thisLine + " \n"
- thisLine = word + " "
- else:
- thisLine += word + " "
+ textSoFar = ""
+ thisLine = ""
+ for part in string.split(label,'\n'):
+ for word in string.split(part):
+ self.SetLabel(thisLine + word)
+ if self.GetSize().width > width:
+ textSoFar += thisLine + " \n"
+ thisLine = word + " "
+ else:
+ thisLine += word + " "
- textSoFar += thisLine + " \n"
- thisLine = ""
+ textSoFar += thisLine + " \n"
+ thisLine = ""
- if len(textSoFar):
- self.SetLabel(string.replace(textSoFar,' \n','\n')[:-1])
- else:
- self.SetLabel("")
+ if len(textSoFar):
+ self.SetLabel(string.replace(textSoFar,' \n','\n')[:-1])
+ else:
+ self.SetLabel("")
#
@@ -687,21 +687,20 @@
# enables the user to press tab/return and have it jump to the next box
#
class FieldHandler:
- def __init__(self, app, seq):
- self.app = app
- self.seq = seq
+ def __init__(self, app, seq):
+ self.app = app
+ self.seq = seq
- def fieldEventTrap(self, event):
- keycode = event.KeyCode()
- if keycode in (wx.WXK_RETURN,wx.WXK_TAB):
- if self.seq < len(self.app.textctrlList) - 1:
- self.app.textctrlList[self.seq+1].SetFocus()
- else:
- if keycode == wx.WXK_TAB:
- if event.ShiftDown():
- self.app.textctrlList[self.seq-1].SetFocus()
- elif keycode == wx.WXK_ESCAPE:
- self.app.OnCancel(None)
- else:
- event.Skip()
-
+ def fieldEventTrap(self, event):
+ keycode = event.KeyCode()
+ if keycode in (wx.WXK_RETURN,wx.WXK_TAB):
+ if self.seq < len(self.app.textctrlList) - 1:
+ self.app.textctrlList[self.seq+1].SetFocus()
+ else:
+ if keycode == wx.WXK_TAB:
+ if event.ShiftDown():
+ self.app.textctrlList[self.seq-1].SetFocus()
+ elif keycode == wx.WXK_ESCAPE:
+ self.app.OnCancel(None)
+ else:
+ event.Skip()
Modified: trunk/gnue-designer/src/base/ToolBar.py
===================================================================
--- trunk/gnue-designer/src/base/ToolBar.py 2006-04-03 19:53:03 UTC (rev
8343)
+++ trunk/gnue-designer/src/base/ToolBar.py 2006-04-03 19:56:14 UTC (rev
8344)
@@ -52,76 +52,76 @@
# TODO: This needs to be decoupled from wx
class BaseToolBar(wx.ToolBar, EventAware):
- ICON_SIZE = (24,24)
+ ICON_SIZE = (24,24)
- def getToolbarMapping(self):
- return ''
+ def getToolbarMapping(self):
+ return ''
- def init(self):
- pass
+ def init(self):
+ pass
- def __init__(self, parent, document):
- self.document = document
- wx.ToolBar.__init__(self, parent, -1, wx.DefaultPosition, wx.DefaultSize,
- wx.TB_FLAT | wx.TB_NODIVIDER)
- EventAware.__init__(self, document)
- self.mapping = {}
- self.SetToolBitmapSize(wx.Size(*self.ICON_SIZE))
- self.init()
- self.Realize()
-
+ def __init__(self, parent, document):
+ self.document = document
+ wx.ToolBar.__init__(self, parent, -1, wx.DefaultPosition,
wx.DefaultSize,
+ wx.TB_FLAT | wx.TB_NODIVIDER)
+ EventAware.__init__(self, document)
+ self.mapping = {}
+ self.SetToolBitmapSize(wx.Size(*self.ICON_SIZE))
+ self.init()
+ self.Realize()
- def addToolbarMapping(self, mapping):
- for type in string.split(mapping,';'):
- if not len(type):
- self.AddSeparator()
- else:
- try:
- handle, image, options = string.split(type,',',2)
- options = options.lower().split()
- except:
- handle, image = string.split(type,',',1)
- options = ()
- try:
- shortHelp, longHelp = self.document.menubar.getEventHelp(handle)
- shortHelp = shortHelp.replace('&','') #Menu entries can contain
shortcut keys
- longHelp = longHelp.replace('&','')
- except:
- print "Warning: No event tied to %s" % handle
- shortHelp = ""
- longHelp = ""
+ def addToolbarMapping(self, mapping):
+ for type in string.split(mapping,';'):
+ if not len(type):
+ self.AddSeparator()
+ else:
+ try:
+ handle, image, options = string.split(type,',',2)
+ options = options.lower().split()
+ except:
+ handle, image = string.split(type,',',1)
+ options = ()
- id = wx.NewId()
- self.mapping[id] = handle
- self.mapping[handle] = id
+ try:
+ shortHelp, longHelp =
self.document.menubar.getEventHelp(handle)
+ shortHelp = shortHelp.replace('&','') #Menu entries can
contain shortcut keys
+ longHelp = longHelp.replace('&','')
+ except:
+ print "Warning: No event tied to %s" % handle
+ shortHelp = ""
+ longHelp = ""
+ id = wx.NewId()
+ self.mapping[id] = handle
+ self.mapping[handle] = id
- if 'pulldown' in options:
- print "Erm, I don't yet support pulldown toolbar buttons (%s)" %
handle
- print self.document.__class__
- self.AddTool(id,
- self.document.app.ui.getIcon(image, *self.ICON_SIZE),
- isToggle=1,
- shortHelpString=shortHelp,
- longHelpString=longHelp)
+ if 'pulldown' in options:
+ print "Erm, I don't yet support pulldown toolbar buttons
(%s)" % handle
- self.SetToolClientData(id, handle)
+ print self.document.__class__
+ self.AddTool(id,
+ self.document.app.ui.getIcon(image, *self.ICON_SIZE),
+ isToggle=1,
+ shortHelpString=shortHelp,
+ longHelpString=longHelp)
- wx.EVT_TOOL(self, id, self.OnButtonSelected)
- self.Realize()
+ self.SetToolClientData(id, handle)
+ wx.EVT_TOOL(self, id, self.OnButtonSelected)
+ self.Realize()
- def resetTool(self, mode):
- if self.mapping.has_key(mode):
- self.ToggleTool(self.mapping[mode],0)
+ def resetTool(self, mode):
+ if self.mapping.has_key(mode):
+ self.ToggleTool(self.mapping[mode],0)
- def OnButtonSelected(self, event):
- #
- # Cheer up any previously depressed toolbuttons
- #
+
+ def OnButtonSelected(self, event):
+ #
+ # Cheer up any previously depressed toolbuttons
+ #
# for key in self.mapping.keys():
# try:
# self.ToggleTool(int(key),0)
@@ -129,12 +129,12 @@
# pass
- handle = self.mapping[event.GetId()]
- state = self.GetToolState(event.GetId())
- self.ToggleTool(event.GetId(),0)
- if not state:
- evt = 'Cancel:%s' % handle
- else:
- evt = handle
+ handle = self.mapping[event.GetId()]
+ state = self.GetToolState(event.GetId())
+ self.ToggleTool(event.GetId(),0)
+ if not state:
+ evt = 'Cancel:%s' % handle
+ else:
+ evt = handle
- self.document.dispatchEvent(evt)
+ self.document.dispatchEvent(evt)
Modified: trunk/gnue-designer/src/base/ToolBase.py
===================================================================
--- trunk/gnue-designer/src/base/ToolBase.py 2006-04-03 19:53:03 UTC (rev
8343)
+++ trunk/gnue-designer/src/base/ToolBase.py 2006-04-03 19:56:14 UTC (rev
8344)
@@ -39,80 +39,77 @@
# Basic Component
# ===========================================================================
class ToolBase (wx.Panel, events.EventAware):
- """
- The base of all tool interfaces
- """
- default_visible = 1
- default_dock = 'frame'
- runtime_section = ""
- uses_feedback_bar = 0
- uses_toolbar = 0
+ """
+ The base of all tool interfaces
+ """
+ default_visible = 1
+ default_dock = 'frame'
+ runtime_section = ""
+ uses_feedback_bar = 0
+ uses_toolbar = 0
- def __init__(self, id, title, document, rootObject, parentWindow):
- wx.Panel.__init__(self,parentWindow,-1)
- events.EventAware.__init__(self, document)
+ def __init__(self, id, title, document, rootObject, parentWindow):
+ wx.Panel.__init__(self,parentWindow,-1)
+ events.EventAware.__init__(self, document)
- self.id = id
- self.title = title
+ self.id = id
+ self.title = title
# self.dockpane = parentWindow
- self.document = document
- self.rootObject = rootObject
- self.document.globalAcceleratorListeners.append(self)
+ self.document = document
+ self.rootObject = rootObject
+ self.document.globalAcceleratorListeners.append(self)
- self._createOuterInterfaces()
+ self._createOuterInterfaces()
- self.init()
- document.registerEventListeners({'Show:Tool:%s' % id: self.__show,
- 'Hide:Tool:%s' % id: self.__hide})
+ self.init()
+ document.registerEventListeners({'Show:Tool:%s' % id: self.__show,
+ 'Hide:Tool:%s' % id: self.__hide})
- RuntimeSettings.registerRuntimeSettingHandler(document, self)
+ RuntimeSettings.registerRuntimeSettingHandler(document, self)
- def saveRuntimeSettings(self):
- return (self.runtime_section, {})
+ def saveRuntimeSettings(self):
+ return (self.runtime_section, {})
- def setFeedback(self, text):
- print "TODO: setFeedback"
+ def setFeedback(self, text):
+ print "TODO: setFeedback"
# self.dockpane.setFeedback(text)
- def __show(self, event):
- self._visible = True
+ def __show(self, event):
+ self._visible = True
# self.dockpane.show()
- def __hide(self, event):
- self._visible = False
+ def __hide(self, event):
+ self._visible = False
# self.dockpane.hide()
- # Used by UI-specific subclasses below
- def _createOuterInterfaces(self):
- pass
+ # Used by UI-specific subclasses below
+ def _createOuterInterfaces(self):
+ pass
# ===========================================================================
# Notebook-based Component
# ===========================================================================
class ToolNotebook(ToolBase):
- """
- Tool interfaces with a Notebook control as their outer component
- """
- def _createOuterInterfaces(self):
- notebook = self.notebook = NotebookCtrl.NotebookCtrl(self, -1,
- style=NotebookCtrl.NC_DEFAULT_STYLE|NotebookCtrl.NC_BOTTOM)
- notebook.HideOnSingleTab()
- notebook.EnableHiding()
- notebook.SetTabHeight(10)
- notebook.SetPadding(wx.Size(1,1))
+ """
+ Tool interfaces with a Notebook control as their outer component
+ """
+ def _createOuterInterfaces(self):
+ notebook = self.notebook = NotebookCtrl.NotebookCtrl(self, -1,
+ style=NotebookCtrl.NC_DEFAULT_STYLE|NotebookCtrl.NC_BOTTOM)
+ notebook.HideOnSingleTab()
+ notebook.EnableHiding()
+ notebook.SetTabHeight(10)
+ notebook.SetPadding(wx.Size(1,1))
- self.document.app.ui.autoSizer(self, notebook)
+ self.document.app.ui.autoSizer(self, notebook)
- ToolBase._createOuterInterfaces(self)
+ ToolBase._createOuterInterfaces(self)
- def addPage(self, page, text):
- self.notebook.AddPage(page, text)
- self.notebook.SetPageTextFont(self.notebook.GetPageCount()-1, wx.Font(9,
wx.DEFAULT, wx.NORMAL, wx.NORMAL, False))
- return page
+ def addPage(self, page, text):
+ self.notebook.AddPage(page, text)
+ self.notebook.SetPageTextFont(self.notebook.GetPageCount()-1,
wx.Font(9, wx.DEFAULT, wx.NORMAL, wx.NORMAL, False))
+ return page
- def deletePage(self, id):
- return self.notebook.DeletePage(id)
-
-
-
+ def deletePage(self, id):
+ return self.notebook.DeletePage(id)
Modified: trunk/gnue-designer/src/base/UndoManager.py
===================================================================
--- trunk/gnue-designer/src/base/UndoManager.py 2006-04-03 19:53:03 UTC (rev
8343)
+++ trunk/gnue-designer/src/base/UndoManager.py 2006-04-03 19:56:14 UTC (rev
8344)
@@ -31,136 +31,135 @@
import types
class UndoManager:
- def __init__(self, instance):
- self.objects = []
+ def __init__(self, instance):
+ self.objects = []
- self.history = []
- self.future = []
- self.document = instance
+ self.history = []
+ self.future = []
+ self.document = instance
- self.deleteMap = {}
+ self.deleteMap = {}
- # True if we are in the middle of a REDO action
- self.redo = 0
+ # True if we are in the middle of a REDO action
+ self.redo = 0
- # Non-zero if we are in the middle of an UndoGroup
- self.groupCount = 0
- self.group = []
+ # Non-zero if we are in the middle of an UndoGroup
+ self.groupCount = 0
+ self.group = []
- instance.registerEventListeners({
- 'ObjectDeleted' : self.catchEvent,
- 'ObjectCreated' : self.catchEvent,
- 'ObjectModified' : self.catchEvent,
- 'BeginUndoGroup' : self.beginGroup,
- 'EndUndoGroup' : self.endGroup,
- 'RequestUndo' : self.undo,
- 'RequestRedo' : self.redo,
- })
+ instance.registerEventListeners({
+ 'ObjectDeleted' : self.catchEvent,
+ 'ObjectCreated' : self.catchEvent,
+ 'ObjectModified' : self.catchEvent,
+ 'BeginUndoGroup' : self.beginGroup,
+ 'EndUndoGroup' : self.endGroup,
+ 'RequestUndo' : self.undo,
+ 'RequestRedo' : self.redo,
+ })
- def catchEvent(self, event):
- if not self.redo:
- history = History(self, event)
- if self.groupCount:
- self.group.append(history)
- else:
- self.history.append ([history])
- self.future = []
- self.history = self.history[-50:]
- self.updateEvents()
+ def catchEvent(self, event):
+ if not self.redo:
+ history = History(self, event)
+ if self.groupCount:
+ self.group.append(history)
+ else:
+ self.history.append ([history])
+ self.future = []
+ self.history = self.history[-50:]
+ self.updateEvents()
- def beginGroup(self, event):
- self.groupCount += 1
- self.future = []
+ def beginGroup(self, event):
+ self.groupCount += 1
+ self.future = []
- def endGroup(self, event):
- self.groupCount -= 1
- if not self.groupCount:
- self.history.append(self.group)
- self.history = self.history[-50:]
- self.group = []
+ def endGroup(self, event):
+ self.groupCount -= 1
+ if not self.groupCount:
+ self.history.append(self.group)
+ self.history = self.history[-50:]
+ self.group = []
- def undo(self, event):
- self.redo = 1
- if self.history:
- events = self.history.pop()
- events.reverse()
- for event in events:
- event.reverse(self)
+ def undo(self, event):
+ self.redo = 1
+ if self.history:
+ events = self.history.pop()
+ events.reverse()
+ for event in events:
+ event.reverse(self)
- self.updateEvents()
- self.redo = 0
+ self.updateEvents()
+ self.redo = 0
- def redo(self, event):
- self.redo = 1
+ def redo(self, event):
+ self.redo = 1
- # TODO
+ # TODO
- self.updateEvents()
- self.redo = 0
+ self.updateEvents()
+ self.redo = 0
- def updateEvents(self):
- if self.history:
- self.document.dispatchEvent('Enable:RequestUndo')
- else:
- self.document.dispatchEvent('Disable:RequestUndo')
+ def updateEvents(self):
+ if self.history:
+ self.document.dispatchEvent('Enable:RequestUndo')
+ else:
+ self.document.dispatchEvent('Disable:RequestUndo')
- if 0: #TODO# self.future:
- self.document.dispatchEvent('Enable:RequestRedo')
- else:
- self.document.dispatchEvent('Disable:RequestRedo')
+ if 0: #TODO# self.future:
+ self.document.dispatchEvent('Enable:RequestRedo')
+ else:
+ self.document.dispatchEvent('Disable:RequestRedo')
- # Return the current instance of this object
- def getCurrObject(self, object):
- print "Finding current version of %s" % object
- while 1:
- try:
- object = self.deleteMap[id(object)]
- except KeyError:
- print "Found %s" % object
- return object
+ # Return the current instance of this object
+ def getCurrObject(self, object):
+ print "Finding current version of %s" % object
+ while 1:
+ try:
+ object = self.deleteMap[id(object)]
+ except KeyError:
+ print "Found %s" % object
+ return object
class History:
- def __init__(self, manager, event):
- self.event = event
- if event.__event__ == 'ObjectDeleted':
- self.parentindex = event.object.getParent
()._children.index(event.object)
- self.parent = id(event.object.getParent ())
+ def __init__(self, manager, event):
+ self.event = event
+ if event.__event__ == 'ObjectDeleted':
+ self.parentindex = event.object.getParent
()._children.index(event.object)
+ self.parent = id(event.object.getParent ())
- def reverse(self, manager):
- orig = self.event
- print "-----"
- print orig.object
- object = manager.getCurrObject(orig.object)
- print object
- if orig.__event__ == 'ObjectCreated':
- manager.document.dispatchEvent('ObjectDeleted',
- object=orig.object, originator=__name__)
- elif orig.__event__ == 'ObjectModified':
- for key in orig.new.keys():
- del object.__dict__[key.replace(':','__')]
- for key, value in orig.old.items():
- object.__dict__[key.replace(':','__')] = value
- manager.document.dispatchEvent('ObjectModified',
- object=orig.object, originator=__name__,
- new=orig.old, old=orig.new)
- elif orig.__event__ == 'ObjectDeleted':
- attrs = {}
- for key, val in object.__dict__.items():
- if key[0] != '_' and type(val) != types.MethodType:
- attrs[key] = val
- parent = manager.getCurrObject(object.getParent ())
- obj = object.__class__(parent)
- obj.__dict__.update(attrs)
- obj._buildObject()
- manager.deleteMap[id(object)] = obj
+ def reverse(self, manager):
+ orig = self.event
+ print "-----"
+ print orig.object
+ object = manager.getCurrObject(orig.object)
+ print object
+ if orig.__event__ == 'ObjectCreated':
+ manager.document.dispatchEvent('ObjectDeleted',
+ object=orig.object, originator=__name__)
+ elif orig.__event__ == 'ObjectModified':
+ for key in orig.new.keys():
+ del object.__dict__[key.replace(':','__')]
+ for key, value in orig.old.items():
+ object.__dict__[key.replace(':','__')] = value
+ manager.document.dispatchEvent('ObjectModified',
+ object=orig.object, originator=__name__,
+ new=orig.old, old=orig.new)
+ elif orig.__event__ == 'ObjectDeleted':
+ attrs = {}
+ for key, val in object.__dict__.items():
+ if key[0] != '_' and type(val) != types.MethodType:
+ attrs[key] = val
+ parent = manager.getCurrObject(object.getParent ())
+ obj = object.__class__(parent)
+ obj.__dict__.update(attrs)
+ obj._buildObject()
+ manager.deleteMap[id(object)] = obj
- # Move the child to its old, relative position
- # in the parent's child list
- obj.getParent ()._children.pop()
- obj.getParent ()._children.insert(self.parentindex, obj)
+ # Move the child to its old, relative position
+ # in the parent's child list
+ obj.getParent ()._children.pop()
+ obj.getParent ()._children.insert(self.parentindex, obj)
- # Notify our peeps...
- manager.document.dispatchEvent('ObjectCreated', originator=__name__,
- object=obj)
-
+ # Notify our peeps...
+ manager.document.dispatchEvent('ObjectCreated',
originator=__name__,
+ object=obj)
Modified: trunk/gnue-designer/src/base/tools/DataSourceEditor.py
===================================================================
--- trunk/gnue-designer/src/base/tools/DataSourceEditor.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/base/tools/DataSourceEditor.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -36,320 +36,320 @@
class DataSourceEditor(ToolBase):
- runtime_section = "DataSourceEditor"
+ runtime_section = "DataSourceEditor"
- def init(self):
- self.connections = self.document.app.connections
+ def init(self):
+ self.connections = self.document.app.connections
- self.combopanel = wx.Panel(self, -1, pos=wx.Point(0,0))
- self.splitter = wx.SplitterWindow(self, -1, style=wx.SP_3D)
+ self.combopanel = wx.Panel(self, -1, pos=wx.Point(0,0))
+ self.splitter = wx.SplitterWindow(self, -1, style=wx.SP_3D)
## self.toolBar = ToolBar(self, parentWindow)
- self.list = wx.ListCtrl(self.splitter, -1, pos=wx.Point(0,0),
- style=wx.LC_REPORT| # wx.LC_EDIT_LABELS|
- wx.LC_HRULES|wx.LC_VRULES|wx.LC_SINGLE_SEL)
+ self.list = wx.ListCtrl(self.splitter, -1, pos=wx.Point(0,0),
+ style=wx.LC_REPORT| # wx.LC_EDIT_LABELS|
+ wx.LC_HRULES|wx.LC_VRULES|wx.LC_SINGLE_SEL)
- self.list.InsertColumn(0,u_('Name'))
- self.list.InsertColumn(1,u_('Source'))
- self.list.InsertColumn(2,u_('Connection'))
+ self.list.InsertColumn(0,u_('Name'))
+ self.list.InsertColumn(1,u_('Source'))
+ self.list.InsertColumn(2,u_('Connection'))
- self.notebook = wx.Notebook(self.splitter, -1, style=wx.NB_BOTTOM)
+ self.notebook = wx.Notebook(self.splitter, -1, style=wx.NB_BOTTOM)
- self.propertyPanel = PropertyViewer(self, self.notebook)
- self.referencesPanel = ReferencesViewer(self, self.notebook)
- self.schemaPanel = SchemaViewer(self, self.notebook)
+ self.propertyPanel = PropertyViewer(self, self.notebook)
+ self.referencesPanel = ReferencesViewer(self, self.notebook)
+ self.schemaPanel = SchemaViewer(self, self.notebook)
- self.notebook.AddPage(self.propertyPanel, u_('Properties'))
- self.notebook.AddPage(self.referencesPanel, u_('References'))
- self.notebook.AddPage(self.schemaPanel, u_('Schema'))
+ self.notebook.AddPage(self.propertyPanel, u_('Properties'))
+ self.notebook.AddPage(self.referencesPanel, u_('References'))
+ self.notebook.AddPage(self.schemaPanel, u_('Schema'))
- self.splitter.SplitHorizontally(self.list, self.notebook,200)
+ self.splitter.SplitHorizontally(self.list, self.notebook,200)
- wx.EVT_SIZE(self, self.OnSize)
+ wx.EVT_SIZE(self, self.OnSize)
- self.datasourceMap = {}
- self.datasources = []
+ self.datasourceMap = {}
+ self.datasources = []
- self.current = None
+ self.current = None
- self.document.rootObject.walk (self.initialInventory)
- self.document.rootObject.walk (self.inventoryObject)
- self.fillList()
+ self.document.rootObject.walk (self.initialInventory)
+ self.document.rootObject.walk (self.inventoryObject)
+ self.fillList()
- # EventAware provided by ToolBase
- self.registerEventListeners({
- 'ObjectSelected' : self.onSetCurrentObject,
- 'ObjectCreated' : self.onCreateObject,
- 'ObjectModified' : self.onModifyObject,
- 'ObjectDeleted' : self.onDeleteObject,
- })
+ # EventAware provided by ToolBase
+ self.registerEventListeners({
+ 'ObjectSelected' : self.onSetCurrentObject,
+ 'ObjectCreated' : self.onCreateObject,
+ 'ObjectModified' : self.onModifyObject,
+ 'ObjectDeleted' : self.onDeleteObject,
+ })
- wx.EVT_LIST_ITEM_SELECTED(self, self.list.GetId(), self.OnDSSelected)
- self._setCurrent(self.current)
+ wx.EVT_LIST_ITEM_SELECTED(self, self.list.GetId(), self.OnDSSelected)
+ self._setCurrent(self.current)
- self.finalized = 0
- self.splitter.SetSize(self.GetSize())
+ self.finalized = 0
+ self.splitter.SetSize(self.GetSize())
- def fillList(self):
+ def fillList(self):
- self.list.DeleteAllItems()
+ self.list.DeleteAllItems()
- for datasource in self.datasources:
- if not datasource.__master:
- self._fillList(datasource, 0)
+ for datasource in self.datasources:
+ if not datasource.__master:
+ self._fillList(datasource, 0)
- def _fillList(self, object, indent):
+ def _fillList(self, object, indent):
- index = self.list.GetItemCount()
- self.list.InsertStringItem(index, " * " * indent + object.name)
- self.list.SetStringItem(index, 1,
- hasattr(object,'table') and object.table or '')
- self.list.SetStringItem(index, 2,
- hasattr(object,'database') and object.database or '')
- self.list.SetItemData(index, id(object))
+ index = self.list.GetItemCount()
+ self.list.InsertStringItem(index, " * " * indent + object.name)
+ self.list.SetStringItem(index, 1,
+ hasattr(object,'table') and object.table or '')
+ self.list.SetStringItem(index, 2,
+ hasattr(object,'database') and object.database or '')
+ self.list.SetItemData(index, id(object))
- object.__listIndex = index
+ object.__listIndex = index
- for detail in object._datasourceReferences:
- self._fillList(detail, indent + 1)
+ for detail in object._datasourceReferences:
+ self._fillList(detail, indent + 1)
- def initialInventory(self, object):
- if isinstance(object, GDataSource.GDataSource):
- self.datasourceMap[string.lower(object.name)] = object
- self.datasourceMap[id(object)] = object
- self.datasources.append(object)
- object._fieldFkReferences = {}
- object._blockReferences = []
- object._datasourceReferences = []
- if self.current is None:
- self.current = object
+ def initialInventory(self, object):
+ if isinstance(object, GDataSource.GDataSource):
+ self.datasourceMap[string.lower(object.name)] = object
+ self.datasourceMap[id(object)] = object
+ self.datasources.append(object)
+ object._fieldFkReferences = {}
+ object._blockReferences = []
+ object._datasourceReferences = []
+ if self.current is None:
+ self.current = object
- def inventoryObject(self, object):
- if isinstance(object, GDataSource.GDataSource):
- if hasattr(object,'master') and object.master:
- try:
- object.__master = self.datasourceMap[string.lower(object.master)]
- except KeyError:
- # TODO: Something better than this
- print "DataSource %s references non-existent master %s" % \
- (object.name, object.master)
- else:
- object.__master = None
+ def inventoryObject(self, object):
+ if isinstance(object, GDataSource.GDataSource):
+ if hasattr(object,'master') and object.master:
+ try:
+ object.__master =
self.datasourceMap[string.lower(object.master)]
+ except KeyError:
+ # TODO: Something better than this
+ print "DataSource %s references non-existent master %s" % \
+ (object.name, object.master)
+ else:
+ object.__master = None
- #
- # Create a cross-reference list of objects referring to datasources
- # These are used by the ReferencesViewer
- #
+ #
+ # Create a cross-reference list of objects referring to datasources
+ # These are used by the ReferencesViewer
+ #
- if object._type == 'GFEntry' and \
- hasattr(object,'foreign_key') and \
- len(object.foreign_key):
+ if object._type == 'GFEntry' and \
+ hasattr(object,'foreign_key') and \
+ len(object.foreign_key):
- ds, field = string.split(
- string.lower(object.foreign_key),'.')
+ ds, field = string.split(
+ string.lower(object.foreign_key),'.')
- try:
- self.datasourceMap[ds]._fieldFkReferences[field].append(object)
- except KeyError:
- self.datasourceMap[ds]._fieldFkReferences[field] = [object]
+ try:
+ self.datasourceMap[ds]._fieldFkReferences[field].append(object)
+ except KeyError:
+ self.datasourceMap[ds]._fieldFkReferences[field] = [object]
- elif object._type == 'GFBlock' and \
- hasattr(object,'datasource') and \
- len(object.datasource):
+ elif object._type == 'GFBlock' and \
+ hasattr(object,'datasource') and \
+ len(object.datasource):
- ds = self.datasourceMap[string.lower(object.datasource)]
+ ds = self.datasourceMap[string.lower(object.datasource)]
- if not object in ds._blockReferences:
- ds._blockReferences.append(object)
+ if not object in ds._blockReferences:
+ ds._blockReferences.append(object)
- elif isinstance(object,GDataSource.GDataSource) and \
- hasattr(object,'master') and \
- object.master:
+ elif isinstance(object,GDataSource.GDataSource) and \
+ hasattr(object,'master') and \
+ object.master:
- ds = self.datasourceMap[string.lower(object.master)]
+ ds = self.datasourceMap[string.lower(object.master)]
- if not object in ds._datasourceReferences:
- ds._datasourceReferences.append(object)
+ if not object in ds._datasourceReferences:
+ ds._datasourceReferences.append(object)
- def onSetCurrentObject (self, event):
- object = event.object
- handler = event.originator
- self._currentObject = object
- if object == None:
- return
+ def onSetCurrentObject (self, event):
+ object = event.object
+ handler = event.originator
+ self._currentObject = object
+ if object == None:
+ return
- if handler != __name__:
- self._setCurrent(object)
+ if handler != __name__:
+ self._setCurrent(object)
- def _setCurrent(self, object):
- if isinstance(object, GDataSource.GDataSource):
+ def _setCurrent(self, object):
+ if isinstance(object, GDataSource.GDataSource):
- self.current = object
- self.list.SetItemState ( object.__listIndex,
- wx.LIST_STATE_SELECTED,
- wx.LIST_STATE_SELECTED)
+ self.current = object
+ self.list.SetItemState ( object.__listIndex,
+ wx.LIST_STATE_SELECTED,
+ wx.LIST_STATE_SELECTED)
- self.list.EnsureVisible(object.__listIndex)
+ self.list.EnsureVisible(object.__listIndex)
- self.propertyPanel.setCurrent(object)
- self.referencesPanel.setCurrent(object)
- self.schemaPanel.setCurrent(object)
+ self.propertyPanel.setCurrent(object)
+ self.referencesPanel.setCurrent(object)
+ self.schemaPanel.setCurrent(object)
- def onCreateObject (self, event):
- object = event.object
- handler = event.originator
- self._currentSelection = {}
- if object == None:
- return
+ def onCreateObject (self, event):
+ object = event.object
+ handler = event.originator
+ self._currentSelection = {}
+ if object == None:
+ return
- if handler != __name__:
- self.initialInventory(object)
- self.inventoryObject(object)
+ if handler != __name__:
+ self.initialInventory(object)
+ self.inventoryObject(object)
- if isinstance(object, GDataSource.GDataSource):
- self.fillList()
+ if isinstance(object, GDataSource.GDataSource):
+ self.fillList()
- def onModifyObject (self, event):
- object = event.object
- handler = event.originator
- if object == None:
- return
+ def onModifyObject (self, event):
+ object = event.object
+ handler = event.originator
+ if object == None:
+ return
- if handler != __name__:
+ if handler != __name__:
- if isinstance(object, GDataSource.GDataSource):
- # TODO: Maintain self.datasourceMap
- self.fillList()
+ if isinstance(object, GDataSource.GDataSource):
+ # TODO: Maintain self.datasourceMap
+ self.fillList()
- # Dirty way to rebuild all our lists
- if object == self.current:
- self._setCurrent(object)
+ # Dirty way to rebuild all our lists
+ if object == self.current:
+ self._setCurrent(object)
- def onDeleteObject (self, event):
- object = event.object
- handler = event.originator
- if object == None:
- return
+ def onDeleteObject (self, event):
+ object = event.object
+ handler = event.originator
+ if object == None:
+ return
- if isinstance(object, GDataSource.GDataSource):
+ if isinstance(object, GDataSource.GDataSource):
- index = object.__listIndex
+ index = object.__listIndex
- i = j = 0
- for datasource in self.datasources:
- if datasource == object: j = i
- if datasource.__listIndex > index:
- datasource.__listIndex -= 1
- i += 1
+ i = j = 0
+ for datasource in self.datasources:
+ if datasource == object: j = i
+ if datasource.__listIndex > index:
+ datasource.__listIndex -= 1
+ i += 1
- self.datasources.pop(j)
- self.list.DeleteItem(index)
+ self.datasources.pop(j)
+ self.list.DeleteItem(index)
- del self.datasourceMap[string.lower(object.name)]
- del self.datasourceMap[id(object)]
+ del self.datasourceMap[string.lower(object.name)]
+ del self.datasourceMap[id(object)]
- def OnSize(self, event):
- if not self.finalized:
- self.finalize()
- self.splitter.SetSize(self.GetSize())
+ def OnSize(self, event):
+ if not self.finalized:
+ self.finalize()
+ self.splitter.SetSize(self.GetSize())
- # Runtime Setting Support
+ # Runtime Setting Support
- def finalize(self):
+ def finalize(self):
- self.finalized = 1
+ self.finalized = 1
- self.SetPosition((
- RuntimeSettings.getint(self.runtime_section, 'x', -1),
- RuntimeSettings.getint(self.runtime_section, 'y', -1)))
+ self.SetPosition((
+ RuntimeSettings.getint(self.runtime_section, 'x', -1),
+ RuntimeSettings.getint(self.runtime_section, 'y', -1)))
- self.splitter.SetSashPosition(
- RuntimeSettings.getint(
- self.runtime_section, 'sash', 100) or 100)
+ self.splitter.SetSashPosition(
+ RuntimeSettings.getint(
+ self.runtime_section, 'sash', 100) or 100)
- self.notebook.SetSelection(
- RuntimeSettings.getint(
- self.runtime_section, 'visibletab', 0))
+ self.notebook.SetSelection(
+ RuntimeSettings.getint(
+ self.runtime_section, 'visibletab', 0))
- for i in range(3): # Should be the number of columns in the list
- self.list.SetColumnWidth(i,
- RuntimeSettings.getint(
- self.runtime_section, "col%s" % i, -2))
+ for i in range(3): # Should be the number of columns in the list
+ self.list.SetColumnWidth(i,
+ RuntimeSettings.getint(
+ self.runtime_section, "col%s" % i, -2))
- for i in range(REF_COLUMNS):
- self.referencesPanel.list.SetColumnWidth(i,
- RuntimeSettings.getint(
- self.runtime_section, "refCol%s" % i, -2))
+ for i in range(REF_COLUMNS):
+ self.referencesPanel.list.SetColumnWidth(i,
+ RuntimeSettings.getint(
+ self.runtime_section, "refCol%s" % i, -2))
- for i in range(SCH_COLUMNS):
- self.schemaPanel.list.SetColumnWidth(i,
- RuntimeSettings.getint(
- self.runtime_section, "schemaCol%s" % i, -2))
+ for i in range(SCH_COLUMNS):
+ self.schemaPanel.list.SetColumnWidth(i,
+ RuntimeSettings.getint(
+ self.runtime_section, "schemaCol%s" % i, -2))
- self.list.Refresh()
- self.Refresh()
+ self.list.Refresh()
+ self.Refresh()
- def saveRuntimeSettings(self):
- sash = self.GetPositionTuple()
+ def saveRuntimeSettings(self):
+ sash = self.GetPositionTuple()
- settings = {
- 'sash': self.splitter.GetSashPosition(),
- 'visibletab': self.notebook.GetSelection()
- }
+ settings = {
+ 'sash': self.splitter.GetSashPosition(),
+ 'visibletab': self.notebook.GetSelection()
+ }
- # Save the top-level list column sizes
- for i in range(3): # Should be the number of columns in the list
- settings["col%s" % i] = self.list.GetColumnWidth(i)
+ # Save the top-level list column sizes
+ for i in range(3): # Should be the number of columns in the list
+ settings["col%s" % i] = self.list.GetColumnWidth(i)
- # Save the reference viewer column sizes
- for i in range(REF_COLUMNS):
- settings["refCol%s" % i] = self.referencesPanel.list.GetColumnWidth(i)
+ # Save the reference viewer column sizes
+ for i in range(REF_COLUMNS):
+ settings["refCol%s" % i] =
self.referencesPanel.list.GetColumnWidth(i)
- # Save the schema viewer column sizes
- for i in range(SCH_COLUMNS):
- settings["schemaCol%s" % i] = self.schemaPanel.list.GetColumnWidth(i)
+ # Save the schema viewer column sizes
+ for i in range(SCH_COLUMNS):
+ settings["schemaCol%s" % i] =
self.schemaPanel.list.GetColumnWidth(i)
- return ( self.runtime_section,
- settings )
+ return ( self.runtime_section,
+ settings )
- # A Datasource was selected in the menu
- def OnDSSelected(self, event):
- self.current = self.datasourceMap[event.GetData()]
-
self.document.dispatchEvent(events.Event('ObjectSelected',object=self.current,
originator=__name__))
+ # A Datasource was selected in the menu
+ def OnDSSelected(self, event):
+ self.current = self.datasourceMap[event.GetData()]
+
self.document.dispatchEvent(events.Event('ObjectSelected',object=self.current,
originator=__name__))
- def OnAddDSSelected(self, event):
+ def OnAddDSSelected(self, event):
- attributes = {}
- if self.current is not None:
- attributes['database'] = \
- hasattr(self.current,'database') and self.current.database or ''
+ attributes = {}
+ if self.current is not None:
+ attributes['database'] = \
+ hasattr(self.current,'database') and self.current.database or
''
- self.document.incubator.createObject(self.rootObject, 'datasource',
- parent=self.rootObject, attributes=attributes)
+ self.document.incubator.createObject(self.rootObject, 'datasource',
+ parent=self.rootObject, attributes=attributes)
- def OnDeleteDSSelected(self, event):
+ def OnDeleteDSSelected(self, event):
- if self.current is not None:
- self.dispatchEvent('ObjectDeleted',object=self.current,
originator=__name__)
+ if self.current is not None:
+ self.dispatchEvent('ObjectDeleted',object=self.current,
originator=__name__)
@@ -358,31 +358,31 @@
#
class ToolBar (wx.ToolBar):
- def __init__(self, editor, parent):
- wx.ToolBar.__init__(self, parent, -1, style=wx.TB_DOCKABLE)
- self.editor = editor
- parent.SetToolBar(self)
+ def __init__(self, editor, parent):
+ wx.ToolBar.__init__(self, parent, -1, style=wx.TB_DOCKABLE)
+ self.editor = editor
+ parent.SetToolBar(self)
- self.addButtonId = wx.NewId()
- self.deleteButtonId = wx.NewId()
+ self.addButtonId = wx.NewId()
+ self.deleteButtonId = wx.NewId()
- self.AddSimpleTool(self.addButtonId,
- wx.Image(images_dir+gConfig('tb_insert'),
- wx.BITMAP_TYPE_PNG).ConvertToBitmap(),
- u_("Create Data Source"),
- u_("Create a new data source"))
+ self.AddSimpleTool(self.addButtonId,
+ wx.Image(images_dir+gConfig('tb_insert'),
+ wx.BITMAP_TYPE_PNG).ConvertToBitmap(),
+ u_("Create Data Source"),
+ u_("Create a new data source"))
- self.AddSimpleTool(self.deleteButtonId,
- wx.Image(images_dir+gConfig('tb_delete'),
- wx.BITMAP_TYPE_PNG).ConvertToBitmap(),
- u_("Delete Data Source"),
- u_("Delete the currently selected data source"))
+ self.AddSimpleTool(self.deleteButtonId,
+ wx.Image(images_dir+gConfig('tb_delete'),
+ wx.BITMAP_TYPE_PNG).ConvertToBitmap(),
+ u_("Delete Data Source"),
+ u_("Delete the currently selected data source"))
- wx.EVT_TOOL(self, self.addButtonId, editor.OnAddDSSelected)
- wx.EVT_TOOL(self, self.deleteButtonId, editor.OnDeleteDSSelected)
+ wx.EVT_TOOL(self, self.addButtonId, editor.OnAddDSSelected)
+ wx.EVT_TOOL(self, self.deleteButtonId, editor.OnDeleteDSSelected)
- self.dblinks = []
+ self.dblinks = []
#############################################################################
@@ -391,20 +391,20 @@
#
class PropertyViewer(wx.Panel):
- def __init__(self, editor, parentWindow):
- wx.Panel.__init__(self, parentWindow, -1)
- self.editor = editor
+ def __init__(self, editor, parentWindow):
+ wx.Panel.__init__(self, parentWindow, -1)
+ self.editor = editor
- wx.EVT_SIZE(self, self.OnSize)
+ wx.EVT_SIZE(self, self.OnSize)
- def setCurrent(self, object):
- if isinstance(object, GDataSource.GDataSource):
- self.current = object
+ def setCurrent(self, object):
+ if isinstance(object, GDataSource.GDataSource):
+ self.current = object
- def OnSize(self, event):
- event.Skip()
+ def OnSize(self, event):
+ event.Skip()
@@ -419,99 +419,99 @@
REF_COLUMNS = REF_TYPE + 1
class ReferencesViewer(wx.Panel):
- def __init__(self, editor, parentWindow):
- wx.Panel.__init__(self, parentWindow, -1)
- self.editor = editor
+ def __init__(self, editor, parentWindow):
+ wx.Panel.__init__(self, parentWindow, -1)
+ self.editor = editor
- self.list = wx.ListCtrl(self, -1, pos=wx.Point(0,0),
- style=wx.LC_REPORT|wx.LC_HRULES|wx.LC_VRULES)
+ self.list = wx.ListCtrl(self, -1, pos=wx.Point(0,0),
+ style=wx.LC_REPORT|wx.LC_HRULES|wx.LC_VRULES)
- self.list.InsertColumn(REF_NAME, u_('Reference'))
- self.list.InsertColumn(REF_REFR, u_('Referrer'))
- self.list.InsertColumn(REF_TYPE, u_('Type'), wx.LIST_FORMAT_RIGHT)
+ self.list.InsertColumn(REF_NAME, u_('Reference'))
+ self.list.InsertColumn(REF_REFR, u_('Referrer'))
+ self.list.InsertColumn(REF_TYPE, u_('Type'), wx.LIST_FORMAT_RIGHT)
- wx.EVT_SIZE(self, self.OnSize)
+ wx.EVT_SIZE(self, self.OnSize)
- def setCurrent(self, object):
- if isinstance(object, GDataSource.GDataSource):
- self.current = object
- self.fillList()
+ def setCurrent(self, object):
+ if isinstance(object, GDataSource.GDataSource):
+ self.current = object
+ self.fillList()
- def OnSize(self, event):
- self.list.SetSize(self.GetSize())
+ def OnSize(self, event):
+ self.list.SetSize(self.GetSize())
- def fillList(self):
+ def fillList(self):
- if not hasattr(self.current,'table'):
- return
+ if not hasattr(self.current,'table'):
+ return
- mastertable = self.current.table
+ mastertable = self.current.table
- self.lines = {}
+ self.lines = {}
- def addLine(self, name, referrer, type):
- name = string.lower(name)
+ def addLine(self, name, referrer, type):
+ name = string.lower(name)
- if not self.lines.has_key(name):
- self.lines[name] = []
+ if not self.lines.has_key(name):
+ self.lines[name] = []
- self.lines[name].append((name, referrer, type))
+ self.lines[name].append((name, referrer, type))
- for item in self.current._datasourceReferences:
+ for item in self.current._datasourceReferences:
- mfields = string.split(item.masterlink,'.')
- dfields = string.split(item.detaillink,'.')
+ mfields = string.split(item.masterlink,'.')
+ dfields = string.split(item.detaillink,'.')
- for i in range(len(mfields)):
- addLine( self, "%s.%s" % (mastertable, mfields[i]),
- "%s.%s" % (item.name, dfields[i]),
- u_("Detail Datasource") )
+ for i in range(len(mfields)):
+ addLine( self, "%s.%s" % (mastertable, mfields[i]),
+ "%s.%s" % (item.name, dfields[i]),
+ u_("Detail Datasource") )
- for field in self.current._fieldFkReferences.keys():
- for item in self.current._fieldFkReferences[field]:
- addLine( self, "%s.%s" % (mastertable, field),
- "%s.%s" % (item.getParent ().name, item.name),
- u_("Dropdown Entry") )
+ for field in self.current._fieldFkReferences.keys():
+ for item in self.current._fieldFkReferences[field]:
+ addLine( self, "%s.%s" % (mastertable, field),
+ "%s.%s" % (item.getParent ().name, item.name),
+ u_("Dropdown Entry") )
- for block in self.current._blockReferences:
- addLine (self, mastertable, block.name, "Block")
+ for block in self.current._blockReferences:
+ addLine (self, mastertable, block.name, "Block")
- for item in block._children:
+ for item in block._children:
- if item._type == 'GFEntry' and \
- hasattr(item,'field') and \
- len(item.field):
+ if item._type == 'GFEntry' and \
+ hasattr(item,'field') and \
+ len(item.field):
- addLine( self, "%s.%s" % (mastertable, item.field),
- "%s.%s" % (block.name, item.name),
- u_("Entry"))
+ addLine( self, "%s.%s" % (mastertable, item.field),
+ "%s.%s" % (block.name, item.name),
+ u_("Entry"))
- index = 0
- self.list.DeleteAllItems()
- keys = self.lines.keys()
- keys.sort()
+ index = 0
+ self.list.DeleteAllItems()
+ keys = self.lines.keys()
+ keys.sort()
- index = 0
- for key in keys:
+ index = 0
+ for key in keys:
- newline = 0
- self.list.InsertStringItem(index, key)
+ newline = 0
+ self.list.InsertStringItem(index, key)
- for line in self.lines[key]:
- if newline:
- self.list.InsertStringItem(index, "")
- else:
- newline = 1
+ for line in self.lines[key]:
+ if newline:
+ self.list.InsertStringItem(index, "")
+ else:
+ newline = 1
- name, referrer, type = line
- self.list.SetStringItem(index, REF_REFR, referrer)
- self.list.SetStringItem(index, REF_TYPE, type)
- index += 1
+ name, referrer, type = line
+ self.list.SetStringItem(index, REF_REFR, referrer)
+ self.list.SetStringItem(index, REF_TYPE, type)
+ index += 1
@@ -531,156 +531,154 @@
SCH_COLUMNS = SCH_REQ + 1
class SchemaViewer(wx.Panel):
- def __init__(self, editor, parentWindow):
- wx.Panel.__init__(self, parentWindow, -1)
- self.editor = editor
+ def __init__(self, editor, parentWindow):
+ wx.Panel.__init__(self, parentWindow, -1)
+ self.editor = editor
- self.list = wx.ListCtrl(self, -1, pos=wx.Point(0,0),
- style=wx.LC_REPORT|wx.LC_HRULES|wx.LC_VRULES)
+ self.list = wx.ListCtrl(self, -1, pos=wx.Point(0,0),
+ style=wx.LC_REPORT|wx.LC_HRULES|wx.LC_VRULES)
- self.list.InsertColumn(SCH_FIELD, u_('Field'))
- self.list.InsertColumn(SCH_TYPE, u_('Base Type'))
- self.list.InsertColumn(SCH_SIZE, u_('Size'), wx.LIST_FORMAT_RIGHT)
- self.list.InsertColumn(SCH_NATIVE,u_('Native Type'))
- self.list.InsertColumn(SCH_REQ, u_('Required'))
+ self.list.InsertColumn(SCH_FIELD, u_('Field'))
+ self.list.InsertColumn(SCH_TYPE, u_('Base Type'))
+ self.list.InsertColumn(SCH_SIZE, u_('Size'), wx.LIST_FORMAT_RIGHT)
+ self.list.InsertColumn(SCH_NATIVE,u_('Native Type'))
+ self.list.InsertColumn(SCH_REQ, u_('Required'))
- self.schemaMap = []
+ self.schemaMap = []
- wx.EVT_SIZE(self, self.OnSize)
- wx.EVT_LIST_BEGIN_DRAG(self, self.list.GetId(), self.OnBeginDrag)
+ wx.EVT_SIZE(self, self.OnSize)
+ wx.EVT_LIST_BEGIN_DRAG(self, self.list.GetId(), self.OnBeginDrag)
- def fillList(self):
+ def fillList(self):
- try:
- conn = self.editor.current.database
+ try:
+ conn = self.editor.current.database
- if not self.editor.connections.isConnectionActive(conn) and \
- not int(gConfig("AutoConnect",section="designer")):
+ if not self.editor.connections.isConnectionActive(conn) and \
+ not int(gConfig("AutoConnect",section="designer")):
- # TODO: Some other form of feedback
- if not hasattr(self.editor,'_schemaMessageDisplayed'):
- print u_("You are not logged in to %s... not retrieving schema") %
(conn)
- self.editor._schemaMessageDisplayed = 1
+ # TODO: Some other form of feedback
+ if not hasattr(self.editor,'_schemaMessageDisplayed'):
+ print u_("You are not logged in to %s... not retrieving
schema") % (conn)
+ self.editor._schemaMessageDisplayed = 1
- return
+ return
- # TODO: Much error catching... any DB errors should be
- # TODO: trapped so the designing session can continue,
- # TODO: albeit without schema support.
+ # TODO: Much error catching... any DB errors should be
+ # TODO: trapped so the designing session can continue,
+ # TODO: albeit without schema support.
- c = self.editor.connections.getConnection (conn, True)
- schema = c.readSchema ()(name=self.editor.current.table)
- table = None
- if schema is not None:
- for item in schema.findChildrenOfType ('GSTable', False, True):
- if item.name.lower () == self.editor.current.table.lower ():
- table = item
- break
+ c = self.editor.connections.getConnection (conn, True)
+ schema = c.readSchema ()(name=self.editor.current.table)
+ table = None
+ if schema is not None:
+ for item in schema.findChildrenOfType ('GSTable', False, True):
+ if item.name.lower () == self.editor.current.table.lower
():
+ table = item
+ break
- index = 0
- self.list.DeleteAllItems()
- if table:
- for field in table.findChildrenOfType ('GSField', False, True):
- self.list.InsertStringItem(index, field.name)
- self.list.SetStringItem (index, SCH_TYPE, field.type.capitalize ())
- self.list.SetStringItem(index, SCH_NATIVE,
- hasattr(field, 'nativetype') and field.nativetype or '(unknown)')
- self.list.SetStringItem(index, SCH_REQ,
- field.nullable and "No" or "Yes")
- if hasattr(field,'length'):
- if hasattr(field,'precision') and field.precision > 0:
- self.list.SetStringItem(index, SCH_SIZE, "%s;%s" % (
- field.length, field.precision))
- else:
- self.list.SetStringItem(index, SCH_SIZE, "%s" % field.length)
- else:
- self.list.SetStringItem(index, SCH_SIZE,'-')
- self.list.SetItemData(index, index)
- self.schemaMap.append(field)
- index += 1
+ index = 0
+ self.list.DeleteAllItems()
+ if table:
+ for field in table.findChildrenOfType ('GSField', False, True):
+ self.list.InsertStringItem(index, field.name)
+ self.list.SetStringItem (index, SCH_TYPE,
field.type.capitalize ())
+ self.list.SetStringItem(index, SCH_NATIVE,
+ hasattr(field, 'nativetype') and field.nativetype or
'(unknown)')
+ self.list.SetStringItem(index, SCH_REQ,
+ field.nullable and "No" or "Yes")
+ if hasattr(field,'length'):
+ if hasattr(field,'precision') and field.precision > 0:
+ self.list.SetStringItem(index, SCH_SIZE, "%s;%s" %
(
+ field.length, field.precision))
+ else:
+ self.list.SetStringItem(index, SCH_SIZE, "%s" %
field.length)
+ else:
+ self.list.SetStringItem(index, SCH_SIZE,'-')
+ self.list.SetItemData(index, index)
+ self.schemaMap.append(field)
+ index += 1
- except:
+ except:
- buffer = StringIO.StringIO()
- traceback.print_exc(file=buffer)
+ buffer = StringIO.StringIO()
+ traceback.print_exc(file=buffer)
- assert gDebug(5,"Exception when retrieving schema (last 5 lines):")
- assert gDebug(5,"%s"%buffer.getvalue())
- buffer.close()
+ assert gDebug(5,"Exception when retrieving schema (last 5 lines):")
+ assert gDebug(5,"%s"%buffer.getvalue())
+ buffer.close()
- def setCurrent(self, object):
- if isinstance(object, GDataSource.GDataSource):
- self.current = object
- self.fillList()
+ def setCurrent(self, object):
+ if isinstance(object, GDataSource.GDataSource):
+ self.current = object
+ self.fillList()
- def OnSize(self, event):
- self.list.SetSize(self.GetSize())
+ def OnSize(self, event):
+ self.list.SetSize(self.GetSize())
- def OnBeginDrag(self, event):
+ def OnBeginDrag(self, event):
- data = []
+ data = []
- item = -1
- # Cycle through each selected item
- while 1:
- item = self.list.GetNextItem(item,
- wx.LIST_NEXT_ALL,
- wx.LIST_STATE_SELECTED);
- if item == -1:
- break
+ item = -1
+ # Cycle through each selected item
+ while 1:
+ item = self.list.GetNextItem(item,
+ wx.LIST_NEXT_ALL,
+ wx.LIST_STATE_SELECTED);
+ if item == -1:
+ break
- object = self.schemaMap[item]
+ object = self.schemaMap[item]
- attributes = {
- "datasource": self.current.name,
- "name": self.editor.document.getUniqueName(
- "fld%s" % (
- string.join(string.split(string.capwords( \
- string.replace(object.name,'_',' '))),''))),
- "field": object.name,
- "datatype": object.type,
- "required" : not object.nullable,
- }
+ attributes = {
+ "datasource": self.current.name,
+ "name": self.editor.document.getUniqueName(
+ "fld%s" % (
+ string.join(string.split(string.capwords( \
+ string.replace(object.name,'_',' '))),''))),
+ "field": object.name,
+ "datatype": object.type,
+ "required" : not object.nullable,
+ }
- if hasattr(object,'length') and object.length:
- attributes['max_length'] = object.length
- attributes['width'] = object.length < 30 and object.length or 30
+ if hasattr(object,'length') and object.length:
+ attributes['max_length'] = object.length
+ attributes['width'] = object.length < 30 and object.length or
30
- if hasattr(object, 'label') and len(object.label):
- label = object.label
- elif len(object.name) == 1:
- label = string.upper(object.name)
- else:
- label = string.join(string.split(string.capwords( \
- string.replace(object.name,'_',' '))),' ')
+ if hasattr(object, 'label') and len(object.label):
+ label = object.label
+ elif len(object.name) == 1:
+ label = string.upper(object.name)
+ else:
+ label = string.join(string.split(string.capwords( \
+ string.replace(object.name,'_',' '))),' ')
- data.append({ "Type" : "entry",
- "Attributes": attributes,
- "Label": label})
+ data.append({ "Type" : "entry",
+ "Attributes": attributes,
+ "Label": label})
- do =
wx.CustomDataObject(wx.CustomDataFormat("application/x-gnue-designer"))
- do.SetData(cPickle.dumps(data,1))
+ do =
wx.CustomDataObject(wx.CustomDataFormat("application/x-gnue-designer"))
+ do.SetData(cPickle.dumps(data,1))
- dropSource = wx.DropSource(self)
- dropSource.SetData(do)
- result = dropSource.DoDragDrop(False)
+ dropSource = wx.DropSource(self)
+ dropSource.SetData(do)
+ result = dropSource.DoDragDrop(False)
# Get around a few wx 2.2.x shortcomings:
try:
- wx.LC_HRULES
- wx.LC_VRULES
+ wx.LC_HRULES
+ wx.LC_VRULES
except NameError:
- wx.LC_HRULES=0
- wx.LC_VRULES=0
+ wx.LC_HRULES=0
+ wx.LC_VRULES=0
# Shortcut
images_dir =
os.path.join(GConfig.getInstalledBase('designer_images','common_images'),'designer')
-
-
Modified: trunk/gnue-designer/src/base/tools/EventEditor.py
===================================================================
--- trunk/gnue-designer/src/base/tools/EventEditor.py 2006-04-03 19:53:03 UTC
(rev 8343)
+++ trunk/gnue-designer/src/base/tools/EventEditor.py 2006-04-03 19:56:14 UTC
(rev 8344)
@@ -42,85 +42,85 @@
class EventEditor (ToolNotebook):
- runtime_section = 'EventEditor'
- uses_feedback_bar = True
- default_dock = 'left-2'
+ runtime_section = 'EventEditor'
+ uses_feedback_bar = True
+ default_dock = 'left-2'
- def init(self):
- self.object = None
+ def init(self):
+ self.object = None
- # EventAware provided by ToolBase
- self.registerEventListeners({
- 'ObjectSelected' : self.onSetCurrentObject,
- 'ObjectCreated' : self.onCreateObject,
- 'ObjectModified' : self.onModifyObject,
- 'ObjectDeleted' : self.onDeleteObject,
- })
+ # EventAware provided by ToolBase
+ self.registerEventListeners({
+ 'ObjectSelected' : self.onSetCurrentObject,
+ 'ObjectCreated' : self.onCreateObject,
+ 'ObjectModified' : self.onModifyObject,
+ 'ObjectDeleted' : self.onDeleteObject,
+ })
- self.supplemental = []
+ self.supplemental = []
- self.main = self.createMainPage()
- self.addInspector(self.main,'Properties')
+ self.main = self.createMainPage()
+ self.addInspector(self.main,'Properties')
- def createMainPage(self):
- return InspectorPanel(self, self.notebook)
+ def createMainPage(self):
+ return InspectorPanel(self, self.notebook)
- def onSetCurrentObject (self, event):
- object = event.object
- handler = event.originator
- if object == None:
- return
- if object != self.object:
- self.setCurrent(object)
+ def onSetCurrentObject (self, event):
+ object = event.object
+ handler = event.originator
+ if object == None:
+ return
+ if object != self.object:
+ self.setCurrent(object)
- def setCurrent(self, object):
- self.object = object
- self.reset()
- self.main.setCurrent(object)
- self.notebook.SetPageText(0, self.main.getPageText())
- i = 1
- for page in self.supplemental:
- page.setCurrent(object)
- self.notebook.SetPageText(i, page.getPageText())
- i += 1
+ def setCurrent(self, object):
+ self.object = object
+ self.reset()
+ self.main.setCurrent(object)
+ self.notebook.SetPageText(0, self.main.getPageText())
+ i = 1
+ for page in self.supplemental:
+ page.setCurrent(object)
+ self.notebook.SetPageText(i, page.getPageText())
+ i += 1
- def addInspector(self, inspector, label):
- self.supplemental.append(inspector)
- self.addPage(inspector, label)
+ def addInspector(self, inspector, label):
+ self.supplemental.append(inspector)
+ self.addPage(inspector, label)
- def reset(self):
- for i in range(len(self.supplemental[1:])):
- self.deletePage(1)
- self.supplemental = []
+ def reset(self):
+ for i in range(len(self.supplemental[1:])):
+ self.deletePage(1)
+ self.supplemental = []
- def onCreateObject (self, event):
- object = event.object
- handler = event.originator
- for insp in [self.main] + self.supplemental:
- insp.onCreateObject(event)
+ def onCreateObject (self, event):
+ object = event.object
+ handler = event.originator
+ for insp in [self.main] + self.supplemental:
+ insp.onCreateObject(event)
- def onModifyObject (self, event):
- object = event.object
- handler = event.originator
- if object == None:
- return
- if handler != __name__ and self.object == object:
- self.setCurrent(object)
- for insp in [self.main] + self.supplemental:
- insp.onModifyObject(event)
+ def onModifyObject (self, event):
+ object = event.object
+ handler = event.originator
+ if object == None:
+ return
+ if handler != __name__ and self.object == object:
+ self.setCurrent(object)
+ for insp in [self.main] + self.supplemental:
+ insp.onModifyObject(event)
- def onDeleteObject (self, event):
- object = event.object
- handler = event.originator
- if object == None:
- return
- if handler != __name__:
- pass
- for insp in [self.main] + self.supplemental:
- insp.onDeleteObject(event)
+ def onDeleteObject (self, event):
+ object = event.object
+ handler = event.originator
+ if object == None:
+ return
+ if handler != __name__:
+ pass
+ for insp in [self.main] + self.supplemental:
+ insp.onDeleteObject(event)
@@ -129,330 +129,329 @@
#
class InspectorPanel(wx.Panel):
- NAMESPACE = ""
+ NAMESPACE = ""
- def __init__(self, editor, parent):
+ def __init__(self, editor, parent):
- wx.Panel.__init__(self, parent, -1)
- self.editor = editor
+ wx.Panel.__init__(self, parent, -1)
+ self.editor = editor
- self.object = None
- self.objectList = []
- self.objectMap = {}
- self.triggerMap = {}
- self.rowList = []
+ self.object = None
+ self.objectList = []
+ self.objectMap = {}
+ self.triggerMap = {}
+ self.rowList = []
- # Set up our grid
- self.grid = Grid(self, -1, pos=wx.Point(0,0))
- self.grid.CreateGrid(1,1)
- self.grid.SetColLabelSize(0)
+ # Set up our grid
+ self.grid = Grid(self, -1, pos=wx.Point(0,0))
+ self.grid.CreateGrid(1,1)
+ self.grid.SetColLabelSize(0)
- self.namedMap = {}
+ self.namedMap = {}
- EVT_GRID_SELECT_CELL(self.grid, self.OnCellSelected)
- EVT_GRID_CELL_CHANGE(self.grid, self.OnCellChange)
- EVT_GRID_CELL_LEFT_DCLICK(self.grid, self.OnLeftDClick)
- wx.EVT_SIZE(self, self.onSize)
+ EVT_GRID_SELECT_CELL(self.grid, self.OnCellSelected)
+ EVT_GRID_CELL_CHANGE(self.grid, self.OnCellChange)
+ EVT_GRID_CELL_LEFT_DCLICK(self.grid, self.OnLeftDClick)
+ wx.EVT_SIZE(self, self.onSize)
- self.editor.rootObject.walk(self.inventoryObject)
+ self.editor.rootObject.walk(self.inventoryObject)
- def setCurrent(self, object):
- self._setCurrent(object)
+ def setCurrent(self, object):
+ self._setCurrent(object)
- def _setCurrent(self, object):
- self.object = object
- try:
- self.triggerList = object._validTriggers
- except AttributeError:
- self.triggerList = {}
+ def _setCurrent(self, object):
+ self.object = object
+ try:
+ self.triggerList = object._validTriggers
+ except AttributeError:
+ self.triggerList = {}
- # Speed up the process by not refreshing the grid yet
- self.grid.BeginBatch()
+ # Speed up the process by not refreshing the grid yet
+ self.grid.BeginBatch()
- # Delete any old rows from a previous object
- nr = self.grid.GetNumberRows()
- if nr:
- self.grid.DeleteRows(0,nr)
+ # Delete any old rows from a previous object
+ nr = self.grid.GetNumberRows()
+ if nr:
+ self.grid.DeleteRows(0,nr)
- self.rowList = self.triggerList.keys()
- self.rowList.sort()
+ self.rowList = self.triggerList.keys()
+ self.rowList.sort()
- # Create the number of rows we'll need
- self.grid.InsertRows(0,len(self.rowList))
+ # Create the number of rows we'll need
+ self.grid.InsertRows(0,len(self.rowList))
- self.triggerTypes = {'':u_('(None)'),
- '(Custom Trigger)':u_('(Custom Trigger)')}
- self.triggerMap = {}
+ self.triggerTypes = {'':u_('(None)'),
+ '(Custom Trigger)':u_('(Custom Trigger)')}
+ self.triggerMap = {}
- for name in self.namedMap.keys():
- self.triggerTypes[name] = name + ' (named)'
+ for name in self.namedMap.keys():
+ self.triggerTypes[name] = name + ' (named)'
- mappedTriggers = {}
- for child in object._children:
- if isinstance(child, GTrigger):
- if hasattr(child,'src') and child.src:
- mappedTriggers[child.type.upper()] = child.src
- else:
- mappedTriggers[child.type.upper()] = '(Custom Trigger)'
- self.triggerMap[child.type.upper()] = child
+ mappedTriggers = {}
+ for child in object._children:
+ if isinstance(child, GTrigger):
+ if hasattr(child,'src') and child.src:
+ mappedTriggers[child.type.upper()] = child.src
+ else:
+ mappedTriggers[child.type.upper()] = '(Custom Trigger)'
+ self.triggerMap[child.type.upper()] = child
- self.mappedTriggers = mappedTriggers
- i = 0
+ self.mappedTriggers = mappedTriggers
+ i = 0
- for key in self.rowList:
- self.grid.SetRowLabelValue(i,self.triggerList[key])
- self.grid.SetCellEditor(i, 0,
EventCellEditor(self.grid,self.triggerTypes))
- try:
- self.grid.SetCellValue(i,0, "%s" % mappedTriggers[key])
- except KeyError:
- self.grid.SetCellValue(i,0, "%s" % '')
- i += 1
+ for key in self.rowList:
+ self.grid.SetRowLabelValue(i,self.triggerList[key])
+ self.grid.SetCellEditor(i, 0,
EventCellEditor(self.grid,self.triggerTypes))
+ try:
+ self.grid.SetCellValue(i,0, "%s" % mappedTriggers[key])
+ except KeyError:
+ self.grid.SetCellValue(i,0, "%s" % '')
+ i += 1
- # Redraw the grid
- self.grid.EndBatch()
- try:
- self.grid.ForceRefresh() # Added in 2.3.1
- except AttributeError:
- pass
+ # Redraw the grid
+ self.grid.EndBatch()
+ try:
+ self.grid.ForceRefresh() # Added in 2.3.1
+ except AttributeError:
+ pass
- #
- # If the first cell has a trigger, select it
- #
- try:
- trigger=self.triggerMap[self.rowList[0]]
- if trigger.src:
-
self.editor.dispatchEvent('TriggerSelected',object=self.namedMap[trigger.src],
originator=__name__)
- else:
- self.editor.dispatchEvent('TriggerSelected',object=trigger,
originator=__name__)
- except KeyError:
- pass
- except IndexError:
- pass
+ #
+ # If the first cell has a trigger, select it
+ #
+ try:
+ trigger=self.triggerMap[self.rowList[0]]
+ if trigger.src:
+
self.editor.dispatchEvent('TriggerSelected',object=self.namedMap[trigger.src],
originator=__name__)
+ else:
+ self.editor.dispatchEvent('TriggerSelected',object=trigger,
originator=__name__)
+ except KeyError:
+ pass
+ except IndexError:
+ pass
- def getPageText(self):
- return self.object._type[2:]
+ def getPageText(self):
+ return self.object._type[2:]
- def onCreateObject (self, event):
- self.inventoryObject(event.object)
+ def onCreateObject (self, event):
+ self.inventoryObject(event.object)
- def onModifyObject (self, event):
- object = event.object
- handler = event.originator
- if object == None:
- return
- if isinstance(object,GTrigger) and \
- object.type.upper() == 'NAMED' and \
- event.new.has_key('name'):
- try:
- del self.namedMap[event.old['name']]
- except KeyError:
- pass
- self.namedMap[object.name] = object
- self._setCurrent(self.object)
+ def onModifyObject (self, event):
+ object = event.object
+ handler = event.originator
+ if object == None:
+ return
+ if isinstance(object,GTrigger) and \
+ object.type.upper() == 'NAMED' and \
+ event.new.has_key('name'):
+ try:
+ del self.namedMap[event.old['name']]
+ except KeyError:
+ pass
+ self.namedMap[object.name] = object
+ self._setCurrent(self.object)
- try:
- if handler != __name__ and self.object == object:
- self._setCurrent(object)
- except wx.PyDeadObjectError:
- pass
+ try:
+ if handler != __name__ and self.object == object:
+ self._setCurrent(object)
+ except wx.PyDeadObjectError:
+ pass
- def onDeleteObject (self, event):
- object = event.object
- handler = event.originator
- if object == None:
- return
- if handler != __name__:
- pass
+ def onDeleteObject (self, event):
+ object = event.object
+ handler = event.originator
+ if object == None:
+ return
+ if handler != __name__:
+ pass
- def inventoryObject(self, object):
- if isinstance(object,GTrigger) and object.type.upper() == 'NAMED':
- self.namedMap[object.name] = object
+ def inventoryObject(self, object):
+ if isinstance(object,GTrigger) and object.type.upper() == 'NAMED':
+ self.namedMap[object.name] = object
- def onSize(self, event):
- self.grid.SetSize(self.GetClientSizeTuple())
- w,h = self.grid.GetClientSizeTuple()
- self.grid.SetColSize(0, w - self.grid.GetRowLabelSize()-1)
- try:
- self.grid.ForceRefresh() # Added in 2.3.1
- except AttributeError:
- pass
+ def onSize(self, event):
+ self.grid.SetSize(self.GetClientSizeTuple())
+ w,h = self.grid.GetClientSizeTuple()
+ self.grid.SetColSize(0, w - self.grid.GetRowLabelSize()-1)
+ try:
+ self.grid.ForceRefresh() # Added in 2.3.1
+ except AttributeError:
+ pass
- # Force a grid cell into Edit mode when Double-Clicked
- def OnLeftDClick(self,evt):
- if self.grid.CanEnableCellControl():
- self.grid.EnableCellEditControl()
+ # Force a grid cell into Edit mode when Double-Clicked
+ def OnLeftDClick(self,evt):
+ if self.grid.CanEnableCellControl():
+ self.grid.EnableCellEditControl()
- def _generateName(self, object):
- parent = object.getParent ()
- name = '%s.%s (%s-Level Trigger)' % (parent.name,
parent._validTriggers[object.type.upper()], parent._type[2:].capitalize())
- return name
+ def _generateName(self, object):
+ parent = object.getParent ()
+ name = '%s.%s (%s-Level Trigger)' % (parent.name,
parent._validTriggers[object.type.upper()], parent._type[2:].capitalize())
+ return name
- # Fire a TriggerSelected event
- def OnCellSelected(self,evt):
- try:
- trigger=self.triggerMap[self.rowList[evt.GetRow()]]
- if trigger.src:
-
self.editor.dispatchEvent('TriggerSelected',object=self.namedMap[trigger.src],
originator=__name__)
- else:
- self.editor.dispatchEvent('TriggerSelected',object=trigger,
originator=__name__)
- except KeyError:
- pass
- except IndexError:
- pass
+ # Fire a TriggerSelected event
+ def OnCellSelected(self,evt):
+ try:
+ trigger=self.triggerMap[self.rowList[evt.GetRow()]]
+ if trigger.src:
+
self.editor.dispatchEvent('TriggerSelected',object=self.namedMap[trigger.src],
originator=__name__)
+ else:
+ self.editor.dispatchEvent('TriggerSelected',object=trigger,
originator=__name__)
+ except KeyError:
+ pass
+ except IndexError:
+ pass
- evt.Skip()
+ evt.Skip()
- def OnCellChange(self, evt):
- attr = self.rowList[evt.GetRow()]
- value = self.grid.GetCellValue(evt.GetRow(), evt.GetCol())
- try:
- oldvalue = self.mappedTriggers[attr]
- except:
- oldvalue = ""
+ def OnCellChange(self, evt):
+ attr = self.rowList[evt.GetRow()]
+ value = self.grid.GetCellValue(evt.GetRow(), evt.GetCol())
+ try:
+ oldvalue = self.mappedTriggers[attr]
+ except:
+ oldvalue = ""
- if oldvalue == value:
- return
+ if oldvalue == value:
+ return
- trigType = self.object._validTriggers[attr]
+ trigType = self.object._validTriggers[attr]
- try:
- trigger = self.triggerMap[attr]
- new = 0
- except KeyError:
- trigger = GTrigger(self.object, trigType)
- new = 1
+ try:
+ trigger = self.triggerMap[attr]
+ new = 0
+ except KeyError:
+ trigger = GTrigger(self.object, trigType)
+ new = 1
- oldStuff = {}
- newStuff = {}
+ oldStuff = {}
+ newStuff = {}
- # If custom trigger, save the text in case the user changes his mind
- if oldvalue == '(Custom Trigger)':
- try:
- self.object.__triggerHistory
- except:
- self.object.__triggerHistory = {}
- self.object.__triggerHistory[attr] = trigger.getChildrenAsContent()
- elif oldvalue:
- oldStuff[src] = oldvalue
- newStuff[src] = ""
+ # If custom trigger, save the text in case the user changes his mind
+ if oldvalue == '(Custom Trigger)':
+ try:
+ self.object.__triggerHistory
+ except:
+ self.object.__triggerHistory = {}
+ self.object.__triggerHistory[attr] = trigger.getChildrenAsContent()
+ elif oldvalue:
+ oldStuff[src] = oldvalue
+ newStuff[src] = ""
- # Clear any old content
- trigger._children = []
+ # Clear any old content
+ trigger._children = []
- if value:
- if value == '(Custom Trigger)':
- try:
- # Restore a previous life's custom trigger text...
- text = self.object.__triggerHistory[attr]
- except:
- # ... or not, and create a new blank trigger
- text = "##\n## %s\n##\n\nreturn\n\n" % (self._generateName(trigger))
- trigger.src = None
- GContent(trigger,text)
- elif value:
- # named trigger
- trigger.src = value
- if not oldStuff.has_key('src'):
- oldStuff['src'] = ''
- newStuff['src'] = value
+ if value:
+ if value == '(Custom Trigger)':
+ try:
+ # Restore a previous life's custom trigger text...
+ text = self.object.__triggerHistory[attr]
+ except:
+ # ... or not, and create a new blank trigger
+ text = "##\n## %s\n##\n\nreturn\n\n" %
(self._generateName(trigger))
+ trigger.src = None
+ GContent(trigger,text)
+ elif value:
+ # named trigger
+ trigger.src = value
+ if not oldStuff.has_key('src'):
+ oldStuff['src'] = ''
+ newStuff['src'] = value
- if new:
- self.editor.dispatchEvent('ObjectCreated',object=trigger,
originator=__name__)
- else:
- self.editor.dispatchEvent('ObjectModified',object=trigger,
originator=__name__,
- old=oldStuff, new=newStuff)
+ if new:
+ self.editor.dispatchEvent('ObjectCreated',object=trigger,
originator=__name__)
+ else:
+ self.editor.dispatchEvent('ObjectModified',object=trigger,
originator=__name__,
+ old=oldStuff, new=newStuff)
- if trigger.src:
-
self.editor.dispatchEvent('TriggerSelected',object=self.namedMap[trigger.src],
originator=__name__)
- else:
- self.editor.dispatchEvent('TriggerSelected',object=trigger,
originator=__name__)
- else:
- # No trigger
+ if trigger.src:
+
self.editor.dispatchEvent('TriggerSelected',object=self.namedMap[trigger.src],
originator=__name__)
+ else:
+ self.editor.dispatchEvent('TriggerSelected',object=trigger,
originator=__name__)
+ else:
+ # No trigger
## self.object._children.pop(self.object._children.index(trigger))
- self.editor.dispatchEvent('ObjectDeleted',object=trigger,
originator=__name__)
- self.editor.dispatchEvent('TriggerSelected',object=None,
originator=__name__)
+ self.editor.dispatchEvent('ObjectDeleted',object=trigger,
originator=__name__)
+ self.editor.dispatchEvent('TriggerSelected',object=None,
originator=__name__)
##
##
##
class EventCellEditor (CharCellEditor):
- def __init__(self, grid, attributes):
- CharCellEditor.__init__(self, grid, attributes)
- self.valueList = attributes.keys()
+ def __init__(self, grid, attributes):
+ CharCellEditor.__init__(self, grid, attributes)
+ self.valueList = attributes.keys()
- self.valueList.sort()
- self.selectionList = []
- self.valueMap = {}
+ self.valueList.sort()
+ self.selectionList = []
+ self.valueMap = {}
- i = 0
- for v in self.valueList:
- self.valueMap[v] = i
- self.selectionList.append("%s" % (attributes[v] or v))
- i = i + 1
+ i = 0
+ for v in self.valueList:
+ self.valueMap[v] = i
+ self.selectionList.append("%s" % (attributes[v] or v))
+ i = i + 1
## self.valueList.insert(0, '')
- def Create(self, parent, id, evtHandler):
- assert gDebug(10,'Creating CharCellEditor')
- self._tc = wx.ComboBox(parent, id, "", style=wx.CB_READONLY,
- choices=self.selectionList)
- self.SetControl(self._tc)
- if evtHandler:
- self._tc.PushEventHandler(evtHandler)
+ def Create(self, parent, id, evtHandler):
+ assert gDebug(10,'Creating CharCellEditor')
+ self._tc = wx.ComboBox(parent, id, "", style=wx.CB_READONLY,
+ choices=self.selectionList)
+ self.SetControl(self._tc)
+ if evtHandler:
+ self._tc.PushEventHandler(evtHandler)
- def BeginEdit(self, row, col, grid):
- self.startValue = grid.GetTable().GetValue(row, col)
- self._tc.SetSelection(self.valueMap[self.startValue])
- self._tc.SetFocus()
+ def BeginEdit(self, row, col, grid):
+ self.startValue = grid.GetTable().GetValue(row, col)
+ self._tc.SetSelection(self.valueMap[self.startValue])
+ self._tc.SetFocus()
- def EndEdit(self, row, col, grid):
- changed = False
+ def EndEdit(self, row, col, grid):
+ changed = False
- val = self.valueList[self._tc.GetSelection()]
- if val != self.startValue:
- changed = True
- grid.GetTable().SetValue(row, col, "%s" % val) # update the table
+ val = self.valueList[self._tc.GetSelection()]
+ if val != self.startValue:
+ changed = True
+ grid.GetTable().SetValue(row, col, "%s" % val) # update the table
- self.startValue = ''
- self._tc.SetSelection(0)
- return changed
+ self.startValue = ''
+ self._tc.SetSelection(0)
+ return changed
- def Reset(self):
- self._tc.SetSelection(self.valueMap[self.startValue])
- #self._tc.SetInsertionPointEnd()
+ def Reset(self):
+ self._tc.SetSelection(self.valueMap[self.startValue])
+ #self._tc.SetInsertionPointEnd()
- def StartingKey(self, evt):
- key = evt.GetKeyCode()
- ch = None
- if key in [wx.WXK_NUMPAD0, wx.WXK_NUMPAD1, wx.WXK_NUMPAD2, wx.WXK_NUMPAD3,
wx.WXK_NUMPAD4,
- wx.WXK_NUMPAD5, wx.WXK_NUMPAD6, wx.WXK_NUMPAD7, wx.WXK_NUMPAD8,
wx.WXK_NUMPAD9]:
- ch = ch = chr(ord('0') + key - wx.WXK_NUMPAD0)
+ def StartingKey(self, evt):
+ key = evt.GetKeyCode()
+ ch = None
+ if key in [wx.WXK_NUMPAD0, wx.WXK_NUMPAD1, wx.WXK_NUMPAD2,
wx.WXK_NUMPAD3, wx.WXK_NUMPAD4,
+ wx.WXK_NUMPAD5, wx.WXK_NUMPAD6, wx.WXK_NUMPAD7,
wx.WXK_NUMPAD8, wx.WXK_NUMPAD9]:
+ ch = ch = chr(ord('0') + key - wx.WXK_NUMPAD0)
- elif key < 256 and key >= 0 and chr(key):
- ch = chr(key)
- if not evt.ShiftDown():
- ch = string.lower(ch)
+ elif key < 256 and key >= 0 and chr(key):
+ ch = chr(key)
+ if not evt.ShiftDown():
+ ch = string.lower(ch)
- if ch is not None:
- # For this example, replace the text. Normally we would append it.
- #self._tc.AppendText(ch)
- pass
+ if ch is not None:
+ # For this example, replace the text. Normally we would append it.
+ #self._tc.AppendText(ch)
+ pass
# self._tc.SetValue(ch)
# self._tc.SetInsertionPointEnd()
- else:
- evt.Skip()
-
+ else:
+ evt.Skip()
Modified: trunk/gnue-designer/src/base/tools/PropertyEditor.py
===================================================================
--- trunk/gnue-designer/src/base/tools/PropertyEditor.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/base/tools/PropertyEditor.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -38,77 +38,77 @@
class PropertyEditor (ToolNotebook):
- runtime_section = 'PropertyEditor'
- default_dock = 'left-1'
+ runtime_section = 'PropertyEditor'
+ default_dock = 'left-1'
- def init(self):
+ def init(self):
- self.object = None
+ self.object = None
- # EventAware provided by ToolBase
- self.registerEventListeners({
- 'ObjectSelected' : self.onSetCurrentObject,
- 'ObjectCreated' : self.onCreateObject,
- 'ObjectModified' : self.onModifyObject,
- 'ObjectDeleted' : self.onDeleteObject,
- })
+ # EventAware provided by ToolBase
+ self.registerEventListeners({
+ 'ObjectSelected' : self.onSetCurrentObject,
+ 'ObjectCreated' : self.onCreateObject,
+ 'ObjectModified' : self.onModifyObject,
+ 'ObjectDeleted' : self.onDeleteObject,
+ })
- self.supplemental = []
- self.main = self.createMainPage()
- self.notebook.AddPage(self.main,'Properties')
+ self.supplemental = []
+ self.main = self.createMainPage()
+ self.notebook.AddPage(self.main,'Properties')
- def createMainPage(self):
- return InspectorPanel(self, self.notebook)
+ def createMainPage(self):
+ return InspectorPanel(self, self.notebook)
- def onSetCurrentObject (self, event):
- object = event.object
- handler = event.originator
- if object == None:
- return
- if object != self.object:
- self.setCurrent(object)
+ def onSetCurrentObject (self, event):
+ object = event.object
+ handler = event.originator
+ if object == None:
+ return
+ if object != self.object:
+ self.setCurrent(object)
- def setCurrent(self, object):
- self.object = object
- self.reset()
- self.main.setCurrent(object)
- self.notebook.SetPageText(0, self.main.getPageText())
- i = 1
- for page in self.supplemental:
- page.setCurrent(object)
- self.notebook.SetPageText(i, page.getPageText())
- i += 1
+ def setCurrent(self, object):
+ self.object = object
+ self.reset()
+ self.main.setCurrent(object)
+ self.notebook.SetPageText(0, self.main.getPageText())
+ i = 1
+ for page in self.supplemental:
+ page.setCurrent(object)
+ self.notebook.SetPageText(i, page.getPageText())
+ i += 1
- def addPage(self, inspector, label):
- self.supplemental.append(inspector)
- self.notebook.AddPage(inspector, label)
+ def addPage(self, inspector, label):
+ self.supplemental.append(inspector)
+ self.notebook.AddPage(inspector, label)
- def reset(self):
- for i in range(len(self.supplemental)):
- self.notebook.DeletePage(1)
- self.supplemental = []
+ def reset(self):
+ for i in range(len(self.supplemental)):
+ self.notebook.DeletePage(1)
+ self.supplemental = []
- def onCreateObject (self, event):
- object = event.object
- handler = event.originator
+ def onCreateObject (self, event):
+ object = event.object
+ handler = event.originator
- def onModifyObject (self, event):
- object = event.object
- if object == None:
- return
+ def onModifyObject (self, event):
+ object = event.object
+ if object == None:
+ return
- if event.originator != __name__:
- for page in [self.main] + self.supplemental:
- page.resetValues(object)
+ if event.originator != __name__:
+ for page in [self.main] + self.supplemental:
+ page.resetValues(object)
- def onDeleteObject (self, event):
- object = event.object
- handler = event.originator
- if object == None:
- return
- if handler != __name__:
- pass
+ def onDeleteObject (self, event):
+ object = event.object
+ handler = event.originator
+ if object == None:
+ return
+ if handler != __name__:
+ pass
#
@@ -116,380 +116,380 @@
#
class InspectorPanel(wx.ScrolledWindow):
- NAMESPACE = ""
+ NAMESPACE = ""
- def __init__(self, editor, parent):
- wx.ScrolledWindow.__init__(self, parent, -1, style = wx.HSCROLL)
- self.splitter = splitter = wx.SplitterWindow(self, -1, style=wx.SP_3DSASH
| wx.SP_NOBORDER)
- self.object = None
- self.editor = editor
- self.fields = []
- self.labels = []
+ def __init__(self, editor, parent):
+ wx.ScrolledWindow.__init__(self, parent, -1, style = wx.HSCROLL)
+ self.splitter = splitter = wx.SplitterWindow(self, -1,
style=wx.SP_3DSASH | wx.SP_NOBORDER)
+ self.object = None
+ self.editor = editor
+ self.fields = []
+ self.labels = []
- # These will be set in _setCurrent
- self.maxy = 0
- self.maxLabel = 0
+ # These will be set in _setCurrent
+ self.maxy = 0
+ self.maxLabel = 0
- self.labelPanel = wx.Panel(splitter, -1)
- self.fieldPanel = wx.Panel(splitter, -1)
- splitter.SplitVertically(self.labelPanel, self.fieldPanel)
- wx.EVT_SPLITTER_SASH_POS_CHANGED(self, self.splitter.GetId(),self.__onSize)
- wx.EVT_SIZE(self, self.__onSize)
+ self.labelPanel = wx.Panel(splitter, -1)
+ self.fieldPanel = wx.Panel(splitter, -1)
+ splitter.SplitVertically(self.labelPanel, self.fieldPanel)
+ wx.EVT_SPLITTER_SASH_POS_CHANGED(self,
self.splitter.GetId(),self.__onSize)
+ wx.EVT_SIZE(self, self.__onSize)
- def getAttributes(self, object):
- elements = self.editor.document.incubator.elements
- try:
- return elements[(object._type[2:]).lower()]['Attributes']
- except KeyError:
- return {}
+ def getAttributes(self, object):
+ elements = self.editor.document.incubator.elements
+ try:
+ return elements[(object._type[2:]).lower()]['Attributes']
+ except KeyError:
+ return {}
- def setCurrent(self, object):
- self._setCurrent(object)
+ def setCurrent(self, object):
+ self._setCurrent(object)
- def _setCurrent(self, object):
- self.object = object
- self.attributes = self.getAttributes(object)
+ def _setCurrent(self, object):
+ self.object = object
+ self.attributes = self.getAttributes(object)
- # Define our rows
- self.rowList = []
- for key, attributes in self.attributes.items():
- try:
- label = attributes['Label']
- except KeyError:
- # This little tidbit does mixed case w/'_' as separators
- words = string.split(key.split(':',1)[-1],'_')
- for j in range(len(words)):
- words[j] = words[j].capitalize()
- label = string.join(words)
- self.rowList.append((label, key))
- self.rowList.sort()
+ # Define our rows
+ self.rowList = []
+ for key, attributes in self.attributes.items():
+ try:
+ label = attributes['Label']
+ except KeyError:
+ # This little tidbit does mixed case w/'_' as separators
+ words = string.split(key.split(':',1)[-1],'_')
+ for j in range(len(words)):
+ words[j] = words[j].capitalize()
+ label = string.join(words)
+ self.rowList.append((label, key))
+ self.rowList.sort()
- # Get rid of any old fields
- for i in range(len(self.fields)):
- field = self.fields.pop()
- field.Destroy()
- label = self.labels.pop()
- label.Destroy()
+ # Get rid of any old fields
+ for i in range(len(self.fields)):
+ field = self.fields.pop()
+ field.Destroy()
+ label = self.labels.pop()
+ label.Destroy()
- # Only show properties for nondeprecated values (unless set)
- i = 0
- while i < len(self.rowList):
- label, key = self.rowList[i]
- xkey = key.replace(':','__')
- if self.attributes[key].has_key ('Deprecated') and \
- self.attributes[key]['Deprecated'] and \
- (not hasattr(object, xkey) or \
- (self.attributes[key].has_key('Default') and \
- object.__dict__[xkey] == self.attributes[key]['Default'] ) ):
- self.rowList.pop(i)
- else:
- i = i + 1
+ # Only show properties for nondeprecated values (unless set)
+ i = 0
+ while i < len(self.rowList):
+ label, key = self.rowList[i]
+ xkey = key.replace(':','__')
+ if self.attributes[key].has_key ('Deprecated') and \
+ self.attributes[key]['Deprecated'] and \
+ (not hasattr(object, xkey) or \
+ (self.attributes[key].has_key('Default') and \
+ object.__dict__[xkey] == self.attributes[key]['Default'] )
):
+ self.rowList.pop(i)
+ else:
+ i = i + 1
- y = 2
- maxLabel = 0
- for text, key in self.rowList:
+ y = 2
+ maxLabel = 0
+ for text, key in self.rowList:
- xkey = key.replace(':','__')
+ xkey = key.replace(':','__')
- # If an attribute has a "Label", use it;
- # otherwise create one from its name.
+ # If an attribute has a "Label", use it;
+ # otherwise create one from its name.
- if self.attributes[key]['Typecast'] == GTypecast.boolean:
- text += u_('?')
- else:
- text += ':'
+ if self.attributes[key]['Typecast'] == GTypecast.boolean:
+ text += u_('?')
+ else:
+ text += ':'
- try:
- label = wx.StaticText (self.labelPanel, -1, text)
- except:
- pass
+ try:
+ label = wx.StaticText (self.labelPanel, -1, text)
+ except:
+ pass
- # Determine the type of Cell Editor we want
- # (Integer, Boolean, Dropdown, Char)
- if self.attributes[key].has_key('ValueSet'):
- field = LimitedSetEditor(self.fieldPanel,self.attributes[key])
- wx.EVT_COMBOBOX(field, field.GetId(), self.__valueModified)
- elif self.attributes[key].has_key('References'):
- tag, attr = self.attributes[key]['References'].split('.')
- objectList = self.editor.document.getObjectList(tag)
- field = LinkedTextEditor(self.fieldPanel, self.attributes[key],
objectList, attr)
- wx.EVT_COMBOBOX(field, field.GetId(), self.__valueModified)
- elif self.attributes[key]['Typecast'] == GTypecast.boolean:
- field = BoolEditor(self.fieldPanel,self.attributes[key])
- wx.EVT_COMBOBOX(field, field.GetId(), self.__valueModified)
- elif self.attributes[key]['Typecast'] in (GTypecast.integer,
- GTypecast.number, GTypecast.whole):
- field = IntEditor(self.fieldPanel,self.attributes[key])
- wx.EVT_SPINCTRL(field, field.GetId(), self.__valueModified)
- else:
- field = TextEditor(self.fieldPanel,self.attributes[key])
- wx.EVT_TEXT(field, field.GetId(), self.__valueModified)
+ # Determine the type of Cell Editor we want
+ # (Integer, Boolean, Dropdown, Char)
+ if self.attributes[key].has_key('ValueSet'):
+ field = LimitedSetEditor(self.fieldPanel,self.attributes[key])
+ wx.EVT_COMBOBOX(field, field.GetId(), self.__valueModified)
+ elif self.attributes[key].has_key('References'):
+ tag, attr = self.attributes[key]['References'].split('.')
+ objectList = self.editor.document.getObjectList(tag)
+ field = LinkedTextEditor(self.fieldPanel,
self.attributes[key], objectList, attr)
+ wx.EVT_COMBOBOX(field, field.GetId(), self.__valueModified)
+ elif self.attributes[key]['Typecast'] == GTypecast.boolean:
+ field = BoolEditor(self.fieldPanel,self.attributes[key])
+ wx.EVT_COMBOBOX(field, field.GetId(), self.__valueModified)
+ elif self.attributes[key]['Typecast'] in (GTypecast.integer,
+ GTypecast.number, GTypecast.whole):
+ field = IntEditor(self.fieldPanel,self.attributes[key])
+ wx.EVT_SPINCTRL(field, field.GetId(), self.__valueModified)
+ else:
+ field = TextEditor(self.fieldPanel,self.attributes[key])
+ wx.EVT_TEXT(field, field.GetId(), self.__valueModified)
- # Generate a tooltip from the description.
- # Note that tooltips can have {Name} tokens
- try:
- tt = self.attributes[key]['Description']
- try:
- for v, l in self.attributes[key]['ValueSet'].items():
- tt = tt.replace('{%s}' % v, '"%s"' % l['Label'])
- except KeyError:
- pass
- tt = tt.replace('{Y}','"True"')
- tt = tt.replace('{N}','"False"')
- tt = tt.replace('{','"')
- tt = tt.replace('}','"')
- field.SetToolTip(wx.ToolTip(tt))
- except KeyError:
- pass
+ # Generate a tooltip from the description.
+ # Note that tooltips can have {Name} tokens
+ try:
+ tt = self.attributes[key]['Description']
+ try:
+ for v, l in self.attributes[key]['ValueSet'].items():
+ tt = tt.replace('{%s}' % v, '"%s"' % l['Label'])
+ except KeyError:
+ pass
+ tt = tt.replace('{Y}','"True"')
+ tt = tt.replace('{N}','"False"')
+ tt = tt.replace('{','"')
+ tt = tt.replace('}','"')
+ field.SetToolTip(wx.ToolTip(tt))
+ except KeyError:
+ pass
- # Align the centers of the field and label
- fx, fy = field.GetSizeTuple()
- lx, ly = label.GetSizeTuple()
- maxy = max(fy, ly)
- maxLabel = max(maxLabel, lx+4)
- field.SetPosition((2, int((maxy - fy)/2) + y))
- label.SetPosition((4, int((maxy - ly)/2) + y))
+ # Align the centers of the field and label
+ fx, fy = field.GetSizeTuple()
+ lx, ly = label.GetSizeTuple()
+ maxy = max(fy, ly)
+ maxLabel = max(maxLabel, lx+4)
+ field.SetPosition((2, int((maxy - fy)/2) + y))
+ label.SetPosition((4, int((maxy - ly)/2) + y))
- # Next y...
- y += maxy
+ # Next y...
+ y += maxy
- # Set the initial value of the cells to the current property values
- if hasattr(object, xkey):
- field.SetValue(object.__dict__[xkey])
+ # Set the initial value of the cells to the current property values
+ if hasattr(object, xkey):
+ field.SetValue(object.__dict__[xkey])
- self.fields.append(field)
- self.labels.append(label)
+ self.fields.append(field)
+ self.labels.append(label)
- self.splitter.SetSashPosition(maxLabel+2)
- self.maxy = y
- self.maxLabel = maxLabel
- self.__onSize(None)
+ self.splitter.SetSashPosition(maxLabel+2)
+ self.maxy = y
+ self.maxLabel = maxLabel
+ self.__onSize(None)
- # Reset the values displayed based on the values on the object
- def resetValues(self, object):
- if object != self.object:
- return
- for i in range(len(self.fields)):
- xkey = self.rowList[i][1].replace(':','__')
- field = self.fields[i]
- # Set the initial value of the cells to the current property values
- if hasattr(object, xkey):
- field.SetValue(object.__dict__[xkey])
- else:
- try:
- field.Clear()
- except AttributeError:
- print 'TODO: IntEditor has no Clear()'
+ # Reset the values displayed based on the values on the object
+ def resetValues(self, object):
+ if object != self.object:
+ return
+ for i in range(len(self.fields)):
+ xkey = self.rowList[i][1].replace(':','__')
+ field = self.fields[i]
+ # Set the initial value of the cells to the current property values
+ if hasattr(object, xkey):
+ field.SetValue(object.__dict__[xkey])
+ else:
+ try:
+ field.Clear()
+ except AttributeError:
+ print 'TODO: IntEditor has no Clear()'
- def getPageText(self):
- return self.object._type[2:]
+ def getPageText(self):
+ return self.object._type[2:]
- def __onSize(self, event):
- x, y = self.GetClientSizeTuple()
- my = max(y, self.maxy)
- self.splitter.SetSize((x, my ))
- self.splitter.SetSashPosition(self.maxLabel+2)
- self.SetVirtualSize((x, my))
- if my > y:
- self.SetScrollRate(0,10)
- #fw = self.fieldPanel.GetSize().x - 4
- #for field in self.fields:
- # field.SetSize((fw, field.GetSize().y))
+ def __onSize(self, event):
+ x, y = self.GetClientSizeTuple()
+ my = max(y, self.maxy)
+ self.splitter.SetSize((x, my ))
+ self.splitter.SetSashPosition(self.maxLabel+2)
+ self.SetVirtualSize((x, my))
+ if my > y:
+ self.SetScrollRate(0,10)
+ #fw = self.fieldPanel.GetSize().x - 4
+ #for field in self.fields:
+ # field.SetSize((fw, field.GetSize().y))
- # Notify system that the object has been modified
- def __valueModified(self, event):
- field = event.GetEventObject()
- try:
- attr = self.rowList[self.fields.index(field)][1]
- except ValueError:
- return
+ # Notify system that the object has been modified
+ def __valueModified(self, event):
+ field = event.GetEventObject()
+ try:
+ attr = self.rowList[self.fields.index(field)][1]
+ except ValueError:
+ return
- value = field.GetValue()
+ value = field.GetValue()
- xkey = attr.replace(':','__')
- try:
- try:
- ov = self.object.__dict__[xkey]
- except KeyError:
- ov = None
+ xkey = attr.replace(':','__')
+ try:
+ try:
+ ov = self.object.__dict__[xkey]
+ except KeyError:
+ ov = None
- oldVal = {attr: ov}
+ oldVal = {attr: ov}
- # We only care if user actually changed the current value...
- if ov != value and not (ov == None and value in (0,'')):
- # If value is None, then user basically selected "No value"
- if value != None:
- # Typecast the value, then store in the object's dictionary
- value = self.attributes[attr]['Typecast'](value)
- else:
- # No value... try to set value as "default" value
- try:
- value = self.attributes[attr]['Default']
- except KeyError:
- # Otherwise leave as None
- pass
+ # We only care if user actually changed the current value...
+ if ov != value and not (ov == None and value in (0,'')):
+ # If value is None, then user basically selected "No value"
+ if value != None:
+ # Typecast the value, then store in the object's dictionary
+ value = self.attributes[attr]['Typecast'](value)
+ else:
+ # No value... try to set value as "default" value
+ try:
+ value = self.attributes[attr]['Default']
+ except KeyError:
+ # Otherwise leave as None
+ pass
- self.object.__dict__[xkey] = value
- newVal = {attr: value}
-
- self.editor.dispatchEvent('ObjectModified',
- object=self.object,
- originator=__name__,
- old=oldVal,
- new=newVal)
+ self.object.__dict__[xkey] = value
+ newVal = {attr: value}
- except ValueError:
- wx.Bell()
+ self.editor.dispatchEvent('ObjectModified',
+ object=self.object,
+ originator=__name__,
+ old=oldVal,
+ new=newVal)
- event.Skip()
+ except ValueError:
+ wx.Bell()
+ event.Skip()
+
#
# Property Editor derived from an attribute's ValueSet
#
class LimitedSetEditor(wx.ComboBox):
- def __init__(self, parent, attributes):
- wx.ComboBox.__init__(self, parent, -1,
- style=wx.TE_PROCESS_ENTER|wx.CB_DROPDOWN|wx.CB_READONLY)
- self.attributes = attributes
- self.selectionList = []
+ def __init__(self, parent, attributes):
+ wx.ComboBox.__init__(self, parent, -1,
+ style=wx.TE_PROCESS_ENTER|wx.CB_DROPDOWN|wx.CB_READONLY)
+ self.attributes = attributes
+ self.selectionList = []
- try:
- default = self.attributes['Default']
- except KeyError:
- default = None
+ try:
+ default = self.attributes['Default']
+ except KeyError:
+ default = None
- if not (attributes.has_key('Required') and attributes['Required'] ):
- self.selectionList.append(None)
- self.Append('')
+ if not (attributes.has_key('Required') and attributes['Required'] ):
+ self.selectionList.append(None)
+ self.Append('')
- # Sort the attribute names...
- keys = attributes['ValueSet'].keys()
- keys.sort()
+ # Sort the attribute names...
+ keys = attributes['ValueSet'].keys()
+ keys.sort()
- # .. but make the default always come first
- if default:
- keys.remove(default)
- keys.insert(0, default)
+ # .. but make the default always come first
+ if default:
+ keys.remove(default)
+ keys.insert(0, default)
- # Add attributes to the combo box
- for v in keys:
- self.selectionList.append(v)
- try:
- text = attributes['ValueSet'][v]['Label']
- except KeyError:
- text = v
- self.Append("%s%s" % (text, v == default and '*' or '' ))
+ # Add attributes to the combo box
+ for v in keys:
+ self.selectionList.append(v)
+ try:
+ text = attributes['ValueSet'][v]['Label']
+ except KeyError:
+ text = v
+ self.Append("%s%s" % (text, v == default and '*' or '' ))
- def GetValue(self):
- return self.selectionList[self.GetSelection()]
+ def GetValue(self):
+ return self.selectionList[self.GetSelection()]
- def SetValue(self, value):
- self.SetSelection(self.selectionList.index(value))
+ def SetValue(self, value):
+ self.SetSelection(self.selectionList.index(value))
#
# Property Editor whose selections are linked to lists of other objects
#
class LinkedTextEditor(wx.ComboBox):
- def __init__(self, parent, attributes, objectList, attr):
- wx.ComboBox.__init__(self, parent, -1,
- style=wx.TE_PROCESS_ENTER|wx.CB_DROPDOWN|wx.CB_SORT)
- self.attributes = attributes
- self.objectList = objectList
- self.attr = attr
- self.updateList()
- objectList.addListener(self.updateList)
+ def __init__(self, parent, attributes, objectList, attr):
+ wx.ComboBox.__init__(self, parent, -1,
+ style=wx.TE_PROCESS_ENTER|wx.CB_DROPDOWN|wx.CB_SORT)
+ self.attributes = attributes
+ self.objectList = objectList
+ self.attr = attr
+ self.updateList()
+ objectList.addListener(self.updateList)
- def Destroy(self):
- self.objectList.removeListener(self.updateList)
- wx.ComboBox.Destroy(self)
+ def Destroy(self):
+ self.objectList.removeListener(self.updateList)
+ wx.ComboBox.Destroy(self)
- def GetValue(self):
- return wx.ComboBox.GetValue(self) or None
+ def GetValue(self):
+ return wx.ComboBox.GetValue(self) or None
- def SetValue(self, value):
- if value in self.list:
- self.SetSelection(self.list.index(value))
- elif value is None:
- wx.ComboBox.SetValue(self, "")
- else:
- wx.ComboBox.SetValue(self, value)
+ def SetValue(self, value):
+ if value in self.list:
+ self.SetSelection(self.list.index(value))
+ elif value is None:
+ wx.ComboBox.SetValue(self, "")
+ else:
+ wx.ComboBox.SetValue(self, value)
- def updateList(self):
- try:
- self.Clear()
- self.list = []
- if not (self.attributes.has_key('Required') and
self.attributes['Required'] ):
- self.list.append(None)
- self.Append('')
- for v in self.objectList:
- self.list.append(v[self.attr])
- self.Append("%s" % v[self.attr])
- except wx.PyDeadObjectError:
- # TODO: why are we getting this exception?
- # TODO: Destroy() is being explicitly called. :(
- pass
+ def updateList(self):
+ try:
+ self.Clear()
+ self.list = []
+ if not (self.attributes.has_key('Required') and
self.attributes['Required'] ):
+ self.list.append(None)
+ self.Append('')
+ for v in self.objectList:
+ self.list.append(v[self.attr])
+ self.Append("%s" % v[self.attr])
+ except wx.PyDeadObjectError:
+ # TODO: why are we getting this exception?
+ # TODO: Destroy() is being explicitly called. :(
+ pass
#
# Property editor for boolean types
#
class BoolEditor(wx.ComboBox):
- def __init__(self, parent, attributes):
- wx.ComboBox.__init__(self, parent, -1,
- style=wx.TE_PROCESS_ENTER|wx.CB_DROPDOWN|wx.CB_READONLY|wx.CB_SORT)
- self.attributes = attributes
+ def __init__(self, parent, attributes):
+ wx.ComboBox.__init__(self, parent, -1,
+ style=wx.TE_PROCESS_ENTER|wx.CB_DROPDOWN|wx.CB_READONLY|wx.CB_SORT)
+ self.attributes = attributes
- if not (self.attributes.has_key('Required') and
self.attributes['Required'] ):
- self.Append('')
+ if not (self.attributes.has_key('Required') and
self.attributes['Required'] ):
+ self.Append('')
- try:
- default = self.attributes['Default']
- except KeyError:
- default = None
+ try:
+ default = self.attributes['Default']
+ except KeyError:
+ default = None
- self.True = u_('Yes') + (default and '*' or '')
- self.False = u_('No') + (not default and '*' or '')
+ self.True = u_('Yes') + (default and '*' or '')
+ self.False = u_('No') + (not default and '*' or '')
- self.Append(self.True)
- self.Append(self.False)
+ self.Append(self.True)
+ self.Append(self.False)
- def GetValue(self):
- v = wx.ComboBox.GetValue(self)
- if v == '':
- return None
- else:
- return v == self.True
+ def GetValue(self):
+ v = wx.ComboBox.GetValue(self)
+ if v == '':
+ return None
+ else:
+ return v == self.True
- def SetValue(self, value):
- if value == None:
- wx.ComboBox.SetValue(self,'')
- elif value:
- wx.ComboBox.SetValue(self,self.True)
- else:
- wx.ComboBox.SetValue(self,self.False)
+ def SetValue(self, value):
+ if value == None:
+ wx.ComboBox.SetValue(self,'')
+ elif value:
+ wx.ComboBox.SetValue(self,self.True)
+ else:
+ wx.ComboBox.SetValue(self,self.False)
#
#
#
class IntEditor(wx.SpinCtrl):
- def __init__(self, parent, attributes):
- wx.SpinCtrl.__init__(self, parent, -1, style=wx.TE_PROCESS_ENTER)
- self.attributes = attributes
+ def __init__(self, parent, attributes):
+ wx.SpinCtrl.__init__(self, parent, -1, style=wx.TE_PROCESS_ENTER)
+ self.attributes = attributes
#
#
#
class TextEditor(wx.TextCtrl):
- def __init__(self, parent, attributes):
- wx.TextCtrl.__init__(self, parent, -1, style=wx.TE_PROCESS_ENTER)
- self.attributes = attributes
+ def __init__(self, parent, attributes):
+ wx.TextCtrl.__init__(self, parent, -1, style=wx.TE_PROCESS_ENTER)
+ self.attributes = attributes
- def SetValue(self, value):
- if value == None:
- value = ""
- wx.TextCtrl.SetValue(self, wxEncode(value))
+ def SetValue(self, value):
+ if value == None:
+ value = ""
+ wx.TextCtrl.SetValue(self, wxEncode(value))
Modified: trunk/gnue-designer/src/base/tools/SchemaNavigator.py
===================================================================
--- trunk/gnue-designer/src/base/tools/SchemaNavigator.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/base/tools/SchemaNavigator.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -60,35 +60,35 @@
class SchemaNavigator(ToolBase):
- runtime_section = "SchemaNavigator"
- default_dock = 'left-5'
- uses_toolbar = 1
- uses_feedback_bar = 1
+ runtime_section = "SchemaNavigator"
+ default_dock = 'left-5'
+ uses_toolbar = 1
+ uses_feedback_bar = 1
- def init(self):
- self.connections = self.document.app.connections
+ def init(self):
+ self.connections = self.document.app.connections
- self.connectionName = None
- self.connectionNames = self.connections.getConnectionNames()
- self.connectionNames.sort()
- self.connectionCache = {}
+ self.connectionName = None
+ self.connectionNames = self.connections.getConnectionNames()
+ self.connectionNames.sort()
+ self.connectionCache = {}
- self.current = None
+ self.current = None
- self.tree = tree = TreeCtrl(self, self)
- root = tree.AddRoot('Schema')
- tree.SetItemHasChildren(root, 1)
- for connection in self.connectionNames:
- ConnectionNode(self, tree, root, connection=connection)
+ self.tree = tree = TreeCtrl(self, self)
+ root = tree.AddRoot('Schema')
+ tree.SetItemHasChildren(root, 1)
+ for connection in self.connectionNames:
+ ConnectionNode(self, tree, root, connection=connection)
## tree.Expand(root)
- sizer = wx.BoxSizer(wx.VERTICAL)
- sizer.Add(tree, 1, wx.EXPAND|wx.ALL, 6)
- self.SetAutoLayout(True)
- self.SetSizer(sizer)
+ sizer = wx.BoxSizer(wx.VERTICAL)
+ sizer.Add(tree, 1, wx.EXPAND|wx.ALL, 6)
+ self.SetAutoLayout(True)
+ self.SetSizer(sizer)
- # EventAware provided by ToolBase
+ # EventAware provided by ToolBase
## self.registerEventListeners({
## 'ObjectSelected' : self.onSetCurrentObject,
## 'ObjectCreated' : self.onCreateObject,
@@ -96,130 +96,130 @@
## 'ObjectDeleted' : self.onDeleteObject,
## })
- self.expanded = 1
- wx.EVT_TREE_SEL_CHANGED(self, self.tree.GetId(), self.OnSelectionChange)
- wx.EVT_TREE_BEGIN_DRAG(self, self.tree.GetId(), self.OnBeginDrag)
- wx.EVT_TREE_BEGIN_RDRAG(self, self.tree.GetId(), self.OnBeginRDrag)
+ self.expanded = 1
+ wx.EVT_TREE_SEL_CHANGED(self, self.tree.GetId(),
self.OnSelectionChange)
+ wx.EVT_TREE_BEGIN_DRAG(self, self.tree.GetId(), self.OnBeginDrag)
+ wx.EVT_TREE_BEGIN_RDRAG(self, self.tree.GetId(), self.OnBeginRDrag)
- self.Layout()
+ self.Layout()
- def createToolbar(self, parent):
- return _SchemaToolbar(parent, self.document)
+ def createToolbar(self, parent):
+ return _SchemaToolbar(parent, self.document)
- # Since this class is the root node, we need to
- # emulate part of the Node class
- def getColumn(self, i=0):
- return ""
+ # Since this class is the root node, we need to
+ # emulate part of the Node class
+ def getColumn(self, i=0):
+ return ""
- def OnBeginDrag(self, event, right=0):
- do =
wx.CustomDataObject(wx.CustomDataFormat("application/x-gnue-designer"))
- do.SetData(cPickle.dumps(self.buildDataObject(right),1))
+ def OnBeginDrag(self, event, right=0):
+ do =
wx.CustomDataObject(wx.CustomDataFormat("application/x-gnue-designer"))
+ do.SetData(cPickle.dumps(self.buildDataObject(right),1))
- dropSource = wx.DropSource(self)
- dropSource.SetData(do)
- self.document.dispatchEvent('BeginUndoGroup')
- # win32 needs wx.Drag_AllowMove to really enable DnD...
- result = dropSource.DoDragDrop(wx.Drag_CopyOnly | wx.Drag_AllowMove)
- self.document.dispatchEvent('EndUndoGroup')
+ dropSource = wx.DropSource(self)
+ dropSource.SetData(do)
+ self.document.dispatchEvent('BeginUndoGroup')
+ # win32 needs wx.Drag_AllowMove to really enable DnD...
+ result = dropSource.DoDragDrop(wx.Drag_CopyOnly | wx.Drag_AllowMove)
+ self.document.dispatchEvent('EndUndoGroup')
- def OnBeginRDrag(self, event):
- self.OnBeginDrag(event, right=1)
+ def OnBeginRDrag(self, event):
+ self.OnBeginDrag(event, right=1)
- def OnSelectionChange(self, event):
- try:
- o = self.tree.GetPyData(event.GetItem())
- if o.getColumn():
- self.setFeedback(o.getLabel() + ': ' + o.getColumn())
- else:
- self.setFeedback('')
- except:
- pass
+ def OnSelectionChange(self, event):
+ try:
+ o = self.tree.GetPyData(event.GetItem())
+ if o.getColumn():
+ self.setFeedback(o.getLabel() + ': ' + o.getColumn())
+ else:
+ self.setFeedback('')
+ except:
+ pass
- def __addTable(self, object):
- # Find the "connection" node
- parent = self.tree.GetPyData(self.tree.GetItemParent(object.node))
- while not isinstance(parent, ConnectionNode):
- parent = self.tree.GetPyData(self.tree.GetItemParent(parent.node))
+ def __addTable(self, object):
+ # Find the "connection" node
+ parent = self.tree.GetPyData(self.tree.GetItemParent(object.node))
+ while not isinstance(parent, ConnectionNode):
+ parent = self.tree.GetPyData(self.tree.GetItemParent(parent.node))
- rs = {}
- for attr, val in object.schema.__dict__.items():
- if attr[0] != '_' and type(val) != types.MethodType:
- rs[attr] = val
+ rs = {}
+ for attr, val in object.schema.__dict__.items():
+ if attr[0] != '_' and type(val) != types.MethodType:
+ rs[attr] = val
- rs['connection'] = parent.connection
- return rs
+ rs['connection'] = parent.connection
+ return rs
- def __addField(self, object):
- rs = {}
- for attr, val in object.field.__dict__.items():
- if attr[0] != '_' and type(val) != types.MethodType:
- rs[attr] = val
- return rs
+ def __addField(self, object):
+ rs = {}
+ for attr, val in object.field.__dict__.items():
+ if attr[0] != '_' and type(val) != types.MethodType:
+ rs[attr] = val
+ return rs
- def buildDataObject(self, right=0):
- rs = []
- tableCache = {}
+ def buildDataObject(self, right=0):
+ rs = []
+ tableCache = {}
- # Add all our tables/fields to a list
- # in the format [ (table, [field, field]),
- # (table, [field, field]) ]
- for tid in self.tree.GetSelections():
- node = self.tree.GetPyData(tid)
- if isinstance(node, TableNode):
- tn = tableCache[node] = []
- rs.append((self.__addTable(node), tn))
- elif isinstance(node, FieldNode):
- table = self.tree.GetPyData(self.tree.GetItemParent(tid))
- try:
- tn = tableCache[table]
- except KeyError:
- tn = tableCache[table] = []
- rs.append((self.__addTable(table), tn))
- tn.append(self.__addField(node))
+ # Add all our tables/fields to a list
+ # in the format [ (table, [field, field]),
+ # (table, [field, field]) ]
+ for tid in self.tree.GetSelections():
+ node = self.tree.GetPyData(tid)
+ if isinstance(node, TableNode):
+ tn = tableCache[node] = []
+ rs.append((self.__addTable(node), tn))
+ elif isinstance(node, FieldNode):
+ table = self.tree.GetPyData(self.tree.GetItemParent(tid))
+ try:
+ tn = tableCache[table]
+ except KeyError:
+ tn = tableCache[table] = []
+ rs.append((self.__addTable(table), tn))
+ tn.append(self.__addField(node))
- # If a table was selected, but no fields,
- # then add all the fields to the cache
- for table, fields in tableCache.items():
- if not fields:
- if not table.expanded:
- table.expand()
- cookie = 0
- if wxversion[:3] == '2.6':
- child, cookie = self.tree.GetFirstChild(table.node)
- else:
- child, cookie = self.tree.GetFirstChild(table.node, cookie)
- while child.IsOk():
- fields.append(self.__addField(self.tree.GetPyData(child)))
- child, cookie = self.tree.GetNextChild(table.node, cookie)
+ # If a table was selected, but no fields,
+ # then add all the fields to the cache
+ for table, fields in tableCache.items():
+ if not fields:
+ if not table.expanded:
+ table.expand()
+ cookie = 0
+ if wxversion[:3] == '2.6':
+ child, cookie = self.tree.GetFirstChild(table.node)
+ else:
+ child, cookie = self.tree.GetFirstChild(table.node, cookie)
+ while child.IsOk():
+ fields.append(self.__addField(self.tree.GetPyData(child)))
+ child, cookie = self.tree.GetNextChild(table.node, cookie)
- return [{'Type': 'SchemaDrop', 'Data': rs, 'ShowMenu': right}]
+ return [{'Type': 'SchemaDrop', 'Data': rs, 'ShowMenu': right}]
class TreeCtrl(wx.TreeCtrl):
- def __init__(self, parent, tool):
- wx.TreeCtrl.__init__(self, parent, -1,
-## style=wx.TR_HAS_BUTTONS|wx.TR_NO_LINES| wx.TR_HIDE_ROOT|
-## wx.NO_BORDER|wx.TR_MULTIPLE|wx.TR_ROW_LINES)
- style=wx.TR_HAS_BUTTONS|wx.TR_HIDE_ROOT|wx.TR_LINES_AT_ROOT|
- wx.SIMPLE_BORDER|wx.TR_MULTIPLE|wx.TR_FULL_ROW_HIGHLIGHT )
+ def __init__(self, parent, tool):
+ wx.TreeCtrl.__init__(self, parent, -1,
+ ## style=wx.TR_HAS_BUTTONS|wx.TR_NO_LINES| wx.TR_HIDE_ROOT|
+ ## wx.NO_BORDER|wx.TR_MULTIPLE|wx.TR_ROW_LINES)
+ style=wx.TR_HAS_BUTTONS|wx.TR_HIDE_ROOT|wx.TR_LINES_AT_ROOT|
+ wx.SIMPLE_BORDER|wx.TR_MULTIPLE|wx.TR_FULL_ROW_HIGHLIGHT )
- self.tool = tool
- wx.EVT_TREE_ITEM_EXPANDING(self, self.GetId(), self.__OnExpand)
+ self.tool = tool
+ wx.EVT_TREE_ITEM_EXPANDING(self, self.GetId(), self.__OnExpand)
- def __OnExpand(self, event):
- parent = event.GetItem()
- if self.GetChildrenCount(parent) > 0:
- return
+ def __OnExpand(self, event):
+ parent = event.GetItem()
+ if self.GetChildrenCount(parent) > 0:
+ return
- node = self.GetPyData(parent)
- if node and not node.expanded:
- node.expand()
+ node = self.GetPyData(parent)
+ if node and not node.expanded:
+ node.expand()
- event.Skip()
+ event.Skip()
@@ -230,92 +230,92 @@
#
class Node:
- isleaf = 0
- def __init__(self, navigator, tree, parent, **params):
- self.__dict__.update(params)
- self.expanded = 0
- self.navigator = navigator
- self.tree = tree
- self.node = node = tree.AppendItem(parent, self.getLabel())
- tree.SetItemHasChildren(node, not self.isleaf)
- tree.SetPyData(node, self)
+ isleaf = 0
+ def __init__(self, navigator, tree, parent, **params):
+ self.__dict__.update(params)
+ self.expanded = 0
+ self.navigator = navigator
+ self.tree = tree
+ self.node = node = tree.AppendItem(parent, self.getLabel())
+ tree.SetItemHasChildren(node, not self.isleaf)
+ tree.SetPyData(node, self)
class ConnectionNode(Node):
- def expand(self):
- self.expanded = 1
- connection = self.navigator.connections.getConnection(self.connection,
login=1)
+ def expand(self):
+ self.expanded = 1
+ connection = self.navigator.connections.getConnection(self.connection,
login=1)
- schema = connection.readSchema ()
+ schema = connection.readSchema ()
- if schema is None:
- return
+ if schema is None:
+ return
- for tables in schema.findChildrenOfType ('GSTables', False, True):
- SchemaTypeNode (self.navigator, self.tree, self.node, tables = tables)
+ for tables in schema.findChildrenOfType ('GSTables', False, True):
+ SchemaTypeNode (self.navigator, self.tree, self.node, tables =
tables)
- def getLabel (self):
- return self.connection
+ def getLabel (self):
+ return self.connection
- def getColumn (self, i=0):
- data = self.navigator.connections.getConnectionParameters (self.connection)
- try:
- return data['comment'] + ' (' + data['provider'] + ')'
- except:
- return '(' + data['provider'] + ')'
+ def getColumn (self, i=0):
+ data = self.navigator.connections.getConnectionParameters
(self.connection)
+ try:
+ return data['comment'] + ' (' + data['provider'] + ')'
+ except:
+ return '(' + data['provider'] + ')'
class SchemaTypeNode (Node):
- def getLabel (self):
- return self.tables.name
- def getColumn (self, i=0):
- return ""
- def expand (self):
- self.expanded = 1
+ def getLabel (self):
+ return self.tables.name
+ def getColumn (self, i=0):
+ return ""
+ def expand (self):
+ self.expanded = 1
- for table in self.tables.findChildrenOfType ('GSTable', False, True):
- TableNode (self.navigator, self.tree, self.node, schema = table)
+ for table in self.tables.findChildrenOfType ('GSTable', False, True):
+ TableNode (self.navigator, self.tree, self.node, schema = table)
class TableNode(Node):
- def getLabel(self):
- return self.schema.name
- def getColumn(self, i=0):
- return ""
- def expand(self):
- self.expanded = 1
- for field in self.schema.findChildrenOfType ('GSField', False, True):
- FieldNode (self.navigator, self.tree, self.node, field = field)
+ def getLabel(self):
+ return self.schema.name
+ def getColumn(self, i=0):
+ return ""
+ def expand(self):
+ self.expanded = 1
+ for field in self.schema.findChildrenOfType ('GSField', False, True):
+ FieldNode (self.navigator, self.tree, self.node, field = field)
class FieldNode (Node):
- isleaf = 1
- def getLabel(self):
- return self.field.name
+ isleaf = 1
+ def getLabel(self):
+ return self.field.name
- def getColumn(self):
- rv = ""
- data = []
- rv += self.field.type.capitalize ()
- try:
- data.append (str (self.field.length))
- except:
- pass
- try:
- data.append (str (self.field.precision))
- except:
- pass
+ def getColumn(self):
+ rv = ""
+ data = []
+ rv += self.field.type.capitalize ()
+ try:
+ data.append (str (self.field.length))
+ except:
+ pass
+ try:
+ data.append (str (self.field.precision))
+ except:
+ pass
## if data:
## rv += '; Size: ' + string.join(data,',')
- if not self.field.nullable:
- rv += "; Not Null"
+ if not self.field.nullable:
+ rv += "; Not Null"
- return rv
+ return rv
- def expand(self):
- self.expanded = 1
+ def expand(self):
+ self.expanded = 1
@@ -328,6 +328,5 @@
class _SchemaToolbar(BaseToolBar):
## ICON_SIZE=(16,16)
- def init(self):
- self.addToolbarMapping(ToolbarMapping)
-
+ def init(self):
+ self.addToolbarMapping(ToolbarMapping)
Modified: trunk/gnue-designer/src/base/tools/SchemaViewer.py
===================================================================
--- trunk/gnue-designer/src/base/tools/SchemaViewer.py 2006-04-03 19:53:03 UTC
(rev 8343)
+++ trunk/gnue-designer/src/base/tools/SchemaViewer.py 2006-04-03 19:56:14 UTC
(rev 8344)
@@ -37,268 +37,268 @@
class SchemaViewer(ToolBase):
- runtime_section = "SchemaViewer"
+ runtime_section = "SchemaViewer"
- def init(self):
- self.connections = self.document.app.connections
+ def init(self):
+ self.connections = self.document.app.connections
- self.connectionName = None
- self.connectionNames = self.connections.getConnectionNames()
- self.connectionNames.sort()
- self.connectionCache = {}
+ self.connectionName = None
+ self.connectionNames = self.connections.getConnectionNames()
+ self.connectionNames.sort()
+ self.connectionCache = {}
## self.toolBar = ToolBar(self, parentWindow)
- self.splitter = wx.SplitterWindow(self, -1, style=wx.SP_3D,
point=wx.Point(0,32))
+ self.splitter = wx.SplitterWindow(self, -1, style=wx.SP_3D,
point=wx.Point(0,32))
- self.list = wx.ListCtrl(self.splitter, -1, pos=wx.Point(0,0),
- style=wx.LC_REPORT|
- wx.LC_HRULES|wx.LC_VRULES|wx.LC_SINGLE_SEL)
+ self.list = wx.ListCtrl(self.splitter, -1, pos=wx.Point(0,0),
+ style=wx.LC_REPORT|
+ wx.LC_HRULES|wx.LC_VRULES|wx.LC_SINGLE_SEL)
- self.list.InsertColumn(0,u_('Name'))
- self.list.InsertColumn(1,u_('Type'))
+ self.list.InsertColumn(0,u_('Name'))
+ self.list.InsertColumn(1,u_('Type'))
- self.schemaPanel = ChildSchemaViewer(self, self.splitter)
+ self.schemaPanel = ChildSchemaViewer(self, self.splitter)
- self.splitter.SplitHorizontally(self.list, self.schemaPanel,200)
+ self.splitter.SplitHorizontally(self.list, self.schemaPanel,200)
- wx.EVT_SIZE(self, self.OnSize)
+ wx.EVT_SIZE(self, self.OnSize)
- self.current = None
+ self.current = None
- # EventAware provided by ToolBase
- self.registerEventListeners({
- 'ObjectSelected' : self.onSetCurrentObject,
- 'ObjectCreated' : self.onCreateObject,
- 'ObjectModified' : self.onModifyObject,
- 'ObjectDeleted' : self.onDeleteObject,
- })
+ # EventAware provided by ToolBase
+ self.registerEventListeners({
+ 'ObjectSelected' : self.onSetCurrentObject,
+ 'ObjectCreated' : self.onCreateObject,
+ 'ObjectModified' : self.onModifyObject,
+ 'ObjectDeleted' : self.onDeleteObject,
+ })
- #
- # Set up the "selection" panel
- #
- self.combopanel = wx.Panel(self, -1, pos=wx.Point(0,0),
size=wx.Size(32,32),
- style=wx.RAISED_BORDER|wx.CLIP_CHILDREN)
+ #
+ # Set up the "selection" panel
+ #
+ self.combopanel = wx.Panel(self, -1, pos=wx.Point(0,0),
size=wx.Size(32,32),
+ style=wx.RAISED_BORDER|wx.CLIP_CHILDREN)
- self.connLabel = wx.StaticText(self.combopanel, -1, u_("Connection: "),
- pos=wx.Point(4,6))
- self.connCombo = wx.ComboBox(self.combopanel, -1,
- pos=wx.Point(self.connLabel.GetSize().width + 10,4),
-# size=self.connLabel.GetSize(),
- style=wx.CB_READONLY)
- self.typeLabel = wx.StaticText(self.combopanel, -1, u_("Show: "),
- pos=wx.Point(self.connCombo.GetPosition().x + \
- self.connCombo.GetSize().width + 20,6))
- self.typeCombo = wx.ComboBox(self.combopanel, -1,
- pos=wx.Point(self.typeLabel.GetPosition().x + \
- self.typeLabel.GetSize().width + 10,4),
- style=wx.CB_READONLY)
+ self.connLabel = wx.StaticText(self.combopanel, -1, u_("Connection: "),
+ pos=wx.Point(4,6))
+ self.connCombo = wx.ComboBox(self.combopanel, -1,
+ pos=wx.Point(self.connLabel.GetSize().width + 10,4),
+ # size=self.connLabel.GetSize(),
+ style=wx.CB_READONLY)
+ self.typeLabel = wx.StaticText(self.combopanel, -1, u_("Show: "),
+ pos=wx.Point(self.connCombo.GetPosition().x + \
+ self.connCombo.GetSize().width + 20,6))
+ self.typeCombo = wx.ComboBox(self.combopanel, -1,
+ pos=wx.Point(self.typeLabel.GetPosition().x + \
+ self.typeLabel.GetSize().width + 10,4),
+ style=wx.CB_READONLY)
- self.combopanel.SetSize(wx.Size(32, self.typeCombo.GetSize().height+12))
- self.splitter.SetPosition((0,self.combopanel.GetSize().height))
+ self.combopanel.SetSize(wx.Size(32,
self.typeCombo.GetSize().height+12))
+ self.splitter.SetPosition((0,self.combopanel.GetSize().height))
- self.connCombo.Append('')
+ self.connCombo.Append('')
- for name in self.connectionNames:
- self.connCombo.Append(name)
+ for name in self.connectionNames:
+ self.connCombo.Append(name)
- wx.EVT_COMBOBOX(self, self.connCombo.GetId(), self.OnConnectionSelected)
+ wx.EVT_COMBOBOX(self, self.connCombo.GetId(),
self.OnConnectionSelected)
- wx.EVT_LIST_BEGIN_DRAG(self, self.list.GetId(), self.OnBeginDrag)
- wx.EVT_LIST_ITEM_SELECTED(self, self.list.GetId(), self.OnTableSelected)
+ wx.EVT_LIST_BEGIN_DRAG(self, self.list.GetId(), self.OnBeginDrag)
+ wx.EVT_LIST_ITEM_SELECTED(self, self.list.GetId(),
self.OnTableSelected)
- self.finalized = 0
- self.splitter.SetSize(self.GetSize())
+ self.finalized = 0
+ self.splitter.SetSize(self.GetSize())
- def fillList(self):
+ def fillList(self):
- try:
- conn = self.connectionName
- if conn is None or conn == "":
- return
+ try:
+ conn = self.connectionName
+ if conn is None or conn == "":
+ return
- if not self.connections.isConnectionActive(conn):
- return
+ if not self.connections.isConnectionActive(conn):
+ return
- # TODO: Much error catching... any DB errors should be
- # TODO: trapped so the designing session can continue,
- # TODO: albeit without schema support.
+ # TODO: Much error catching... any DB errors should be
+ # TODO: trapped so the designing session can continue,
+ # TODO: albeit without schema support.
- # Create a cache by connection to conserve database calls
- try:
- types, tables = self.connectionCache[conn]
- except KeyError:
- c = self.connections.getConnection (conn, True)
+ # Create a cache by connection to conserve database calls
+ try:
+ types, tables = self.connectionCache[conn]
+ except KeyError:
+ c = self.connections.getConnection (conn, True)
- gstree = c.readSchema ()
- types = []
- tables = None
+ gstree = c.readSchema ()
+ types = []
+ tables = None
- if gstree is not None:
- for item in gstree.findChildrenOfType ('GSTables', False, True):
- types.append (item.name)
- tables = gstree.findChildrenOfType ('GSTable', False, True)
+ if gstree is not None:
+ for item in gstree.findChildrenOfType ('GSTables', False,
True):
+ types.append (item.name)
+ tables = gstree.findChildrenOfType ('GSTable', False, True)
- self.connectionCache[conn] = (types, tables)
+ self.connectionCache[conn] = (types, tables)
- index = 0
- self.list.DeleteAllItems()
+ index = 0
+ self.list.DeleteAllItems()
- for schema in tables:
+ for schema in tables:
- self.list.InsertStringItem(index, schema.name)
- self.list.SetStringItem(index, 1, schema.type)
- self.list.SetItemData(index, index)
- index += 1
+ self.list.InsertStringItem(index, schema.name)
+ self.list.SetStringItem(index, 1, schema.type)
+ self.list.SetItemData(index, index)
+ index += 1
- except:
+ except:
- buffer = StringIO.StringIO()
- traceback.print_exc(file=buffer)
+ buffer = StringIO.StringIO()
+ traceback.print_exc(file=buffer)
- assert gDebug(5,"Exception when retrieving schema (last 5 lines):")
- assert gDebug(5,"%s"%buffer.getvalue())
- buffer.close()
+ assert gDebug(5,"Exception when retrieving schema (last 5 lines):")
+ assert gDebug(5,"%s"%buffer.getvalue())
+ buffer.close()
- def onSetCurrentObject (self, event):
- object = event.object
- handler = event.originator
+ def onSetCurrentObject (self, event):
+ object = event.object
+ handler = event.originator
- def onCreateObject (self, event):
- object = event.object
- handler = event.originator
+ def onCreateObject (self, event):
+ object = event.object
+ handler = event.originator
- def onModifyObject (self, event):
- object = event.object
- handler = event.originator
+ def onModifyObject (self, event):
+ object = event.object
+ handler = event.originator
- def onDeleteObject (self, event):
- object = event.object
- handler = event.originator
+ def onDeleteObject (self, event):
+ object = event.object
+ handler = event.originator
- def OnSize(self, event):
- if not self.finalized:
- self.finalize()
- self.splitter.SetSize(self.GetSize())
+ def OnSize(self, event):
+ if not self.finalized:
+ self.finalize()
+ self.splitter.SetSize(self.GetSize())
- w,h = self.GetClientSizeTuple()
- self.combopanel.SetSize(wx.Size(w,self.combopanel.GetSize().height))
- self.splitter.SetSize(wx.Size(w,h-self.combopanel.GetSize().height))
+ w,h = self.GetClientSizeTuple()
+ self.combopanel.SetSize(wx.Size(w,self.combopanel.GetSize().height))
+ self.splitter.SetSize(wx.Size(w,h-self.combopanel.GetSize().height))
- # Runtime Setting Support
- def finalize(self):
+ # Runtime Setting Support
+ def finalize(self):
- self.finalized = 1
+ self.finalized = 1
- self.SetPosition((
- RuntimeSettings.getint(self.runtime_section, 'x', -1),
- RuntimeSettings.getint(self.runtime_section, 'y', -1)))
+ self.SetPosition((
+ RuntimeSettings.getint(self.runtime_section, 'x', -1),
+ RuntimeSettings.getint(self.runtime_section, 'y', -1)))
- self.splitter.SetSashPosition(
- RuntimeSettings.getint(
- self.runtime_section, 'sash', 100) or 100)
+ self.splitter.SetSashPosition(
+ RuntimeSettings.getint(
+ self.runtime_section, 'sash', 100) or 100)
- for i in range(2): # Should be the number of columns in the list
- self.list.SetColumnWidth(i,
- RuntimeSettings.getint(
- self.runtime_section, "col%s" % i, -2))
+ for i in range(2): # Should be the number of columns in the list
+ self.list.SetColumnWidth(i,
+ RuntimeSettings.getint(
+ self.runtime_section, "col%s" % i, -2))
- for i in range(SCH_COLUMNS):
- self.schemaPanel.list.SetColumnWidth(i,
- RuntimeSettings.getint(
- self.runtime_section, "fieldCol%s" % i, -2))
+ for i in range(SCH_COLUMNS):
+ self.schemaPanel.list.SetColumnWidth(i,
+ RuntimeSettings.getint(
+ self.runtime_section, "fieldCol%s" % i, -2))
- self.list.Refresh()
- self.Refresh()
+ self.list.Refresh()
+ self.Refresh()
- def saveRuntimeSettings(self):
- sash = self.GetPositionTuple()
+ def saveRuntimeSettings(self):
+ sash = self.GetPositionTuple()
- settings = {
- 'sash': self.splitter.GetSashPosition(),
- }
+ settings = {
+ 'sash': self.splitter.GetSashPosition(),
+ }
- # Save the top-level list column sizes
- for i in range(2): # Should be the number of columns in the list
- settings["col%s" % i] = self.list.GetColumnWidth(i)
+ # Save the top-level list column sizes
+ for i in range(2): # Should be the number of columns in the list
+ settings["col%s" % i] = self.list.GetColumnWidth(i)
- # Save the schema viewer column sizes
- for i in range(SCH_COLUMNS):
- settings["fieldCol%s" % i] = self.schemaPanel.list.GetColumnWidth(i)
+ # Save the schema viewer column sizes
+ for i in range(SCH_COLUMNS):
+ settings["fieldCol%s" % i] =
self.schemaPanel.list.GetColumnWidth(i)
- return ( self.runtime_section,
- settings )
+ return ( self.runtime_section,
+ settings )
- # A connection was selected in the dropdown
- def OnConnectionSelected(self, event):
+ # A connection was selected in the dropdown
+ def OnConnectionSelected(self, event):
- self.connectionName =
self.connCombo.GetString(self.connCombo.GetSelection())
- self.typeCombo.Clear()
- self.typeCombo.Append('All')
+ self.connectionName =
self.connCombo.GetString(self.connCombo.GetSelection())
+ self.typeCombo.Clear()
+ self.typeCombo.Append('All')
- self.schemaPanel.clear()
- self.fillList()
+ self.schemaPanel.clear()
+ self.fillList()
- try:
- for type in self.connectionCache[self.connectionName][0]:
- self.typeCombo.Append(type[1]+ 's')
- except KeyError:
- pass
+ try:
+ for type in self.connectionCache[self.connectionName][0]:
+ self.typeCombo.Append(type[1]+ 's')
+ except KeyError:
+ pass
- # A Datasource was selected in the menu
- def OnTableSelected(self, event):
- self.current =
self.connectionCache[self.connectionName][1][event.GetData()]
- self.schemaPanel.OnTableSelected(self.current)
+ # A Datasource was selected in the menu
+ def OnTableSelected(self, event):
+ self.current =
self.connectionCache[self.connectionName][1][event.GetData()]
+ self.schemaPanel.OnTableSelected(self.current)
- def OnBeginDrag(self, event):
+ def OnBeginDrag(self, event):
- object = self.connectionCache[self.connectionName][1]\
- [self.list.HitTest(event.GetPoint())[0]]
+ object = self.connectionCache[self.connectionName][1]\
+ [self.list.HitTest(event.GetPoint())[0]]
- do =
wx.CustomDataObject(wx.CustomDataFormat("application/x-gnue-designer"))
- do.SetData(cPickle.dumps(self.buildDataObject(object),1))
+ do =
wx.CustomDataObject(wx.CustomDataFormat("application/x-gnue-designer"))
+ do.SetData(cPickle.dumps(self.buildDataObject(object),1))
- dropSource = wx.DropSource(self)
- dropSource.SetData(do)
- result = dropSource.DoDragDrop(False)
+ dropSource = wx.DropSource(self)
+ dropSource.SetData(do)
+ result = dropSource.DoDragDrop(False)
- def buildDataObject(self, object):
+ def buildDataObject(self, object):
- basename = string.join(string.split(string.capwords( \
- string.replace(
- string.replace(object.name,'.',''),'_',' '))),'')
+ basename = string.join(string.split(string.capwords( \
+ string.replace(
+ string.replace(object.name,'.',''),'_',' '))),'')
- dname = self.document.getUniqueName("dts%s" % basename)
- bname = self.document.getUniqueName("blk%s" % basename)
+ dname = self.document.getUniqueName("dts%s" % basename)
+ bname = self.document.getUniqueName("blk%s" % basename)
- data = [ { "Type" : "datasource",
- "Attributes": {
- "name": dname,
- "table": object.name,
- "connection": self.connectionName } },
- { "Type" : "block",
- "Attributes": {
- "name": bname,
- "datasource": dname } } ]
+ data = [ { "Type" : "datasource",
+ "Attributes": {
+ "name": dname,
+ "table": object.name,
+ "connection": self.connectionName } },
+ { "Type" : "block",
+ "Attributes": {
+ "name": bname,
+ "datasource": dname } } ]
- return data
+ return data
@@ -316,164 +316,163 @@
class ChildSchemaViewer(wx.Panel):
- def __init__(self, editor, parentWindow):
- wx.Panel.__init__(self, parentWindow, -1)
- self.editor = editor
+ def __init__(self, editor, parentWindow):
+ wx.Panel.__init__(self, parentWindow, -1)
+ self.editor = editor
- self.list = wx.ListCtrl(self, -1, pos=wx.Point(0,0),
- style=wx.LC_REPORT|wx.LC_HRULES|wx.LC_VRULES)
+ self.list = wx.ListCtrl(self, -1, pos=wx.Point(0,0),
+ style=wx.LC_REPORT|wx.LC_HRULES|wx.LC_VRULES)
- self.list.InsertColumn(SCH_FIELD, u_('Field'))
- self.list.InsertColumn(SCH_TYPE, u_('Base Type'))
- self.list.InsertColumn(SCH_SIZE, u_('Size'), wx.LIST_FORMAT_RIGHT)
- self.list.InsertColumn(SCH_NATIVE,u_('Native Type'))
- self.list.InsertColumn(SCH_REQ, u_('Required'))
+ self.list.InsertColumn(SCH_FIELD, u_('Field'))
+ self.list.InsertColumn(SCH_TYPE, u_('Base Type'))
+ self.list.InsertColumn(SCH_SIZE, u_('Size'), wx.LIST_FORMAT_RIGHT)
+ self.list.InsertColumn(SCH_NATIVE,u_('Native Type'))
+ self.list.InsertColumn(SCH_REQ, u_('Required'))
- wx.EVT_SIZE(self, self.OnSize)
- wx.EVT_LIST_ITEM_SELECTED(self, self.list.GetId(), self.OnFieldSelected)
- wx.EVT_LIST_BEGIN_DRAG(self, self.list.GetId(), self.OnBeginDrag)
+ wx.EVT_SIZE(self, self.OnSize)
+ wx.EVT_LIST_ITEM_SELECTED(self, self.list.GetId(),
self.OnFieldSelected)
+ wx.EVT_LIST_BEGIN_DRAG(self, self.list.GetId(), self.OnBeginDrag)
- def clear(self):
- self.list.DeleteAllItems()
+ def clear(self):
+ self.list.DeleteAllItems()
- def fillList(self):
+ def fillList(self):
- try:
+ try:
- # TODO: Much error catching... any DB errors should be
- # TODO: trapped so the designing session can continue,
- # TODO: albeit without schema support.
+ # TODO: Much error catching... any DB errors should be
+ # TODO: trapped so the designing session can continue,
+ # TODO: albeit without schema support.
- index = 0
- self.list.DeleteAllItems()
+ index = 0
+ self.list.DeleteAllItems()
- # Cache the child schema definitions (fields)
- try:
- self.table.__childCache
- except AttributeError:
- self.table.__childCache = self.table.fields()
+ # Cache the child schema definitions (fields)
+ try:
+ self.table.__childCache
+ except AttributeError:
+ self.table.__childCache = self.table.fields()
- for field in self.table.__childCache:
+ for field in self.table.__childCache:
- self.list.InsertStringItem(index, field.name)
- self.list.SetStringItem(index, SCH_TYPE,
- string.upper(field.type[0]) + field.type[1:])
- self.list.SetStringItem(index, SCH_NATIVE,
- hasattr(field, 'nativetype') and field.nativetype or '(unknown)')
- self.list.SetStringItem(index, SCH_REQ,
- field.required and "Yes" or "No")
- if hasattr(field,'length'):
- if hasattr(field,'precision') and field.precision > 0:
- self.list.SetStringItem(index, SCH_SIZE, "%s;%s" % (
- field.length, field.precision))
- else:
- self.list.SetStringItem(index, SCH_SIZE, "%s" % field.length)
- else:
- self.list.SetStringItem(index, SCH_SIZE,'-')
- self.list.SetItemData(index, index)
- index += 1
+ self.list.InsertStringItem(index, field.name)
+ self.list.SetStringItem(index, SCH_TYPE,
+ string.upper(field.type[0]) + field.type[1:])
+ self.list.SetStringItem(index, SCH_NATIVE,
+ hasattr(field, 'nativetype') and field.nativetype or
'(unknown)')
+ self.list.SetStringItem(index, SCH_REQ,
+ field.required and "Yes" or "No")
+ if hasattr(field,'length'):
+ if hasattr(field,'precision') and field.precision > 0:
+ self.list.SetStringItem(index, SCH_SIZE, "%s;%s" % (
+ field.length, field.precision))
+ else:
+ self.list.SetStringItem(index, SCH_SIZE, "%s" %
field.length)
+ else:
+ self.list.SetStringItem(index, SCH_SIZE,'-')
+ self.list.SetItemData(index, index)
+ index += 1
- except:
+ except:
- buffer = StringIO.StringIO()
- traceback.print_exc(file=buffer)
+ buffer = StringIO.StringIO()
+ traceback.print_exc(file=buffer)
- assert gDebug(5,"Exception when retrieving schema (last 5 lines):")
- assert gDebug(5,"%s"%buffer.getvalue())
- buffer.close()
+ assert gDebug(5,"Exception when retrieving schema (last 5 lines):")
+ assert gDebug(5,"%s"%buffer.getvalue())
+ buffer.close()
- def OnTableSelected(self, object):
- self.table = object
- self.fillList()
+ def OnTableSelected(self, object):
+ self.table = object
+ self.fillList()
- # A field was selected in the dropdown
- def OnFieldSelected(self, event):
- self.current = self.table.__childCache[event.GetData()]
+ # A field was selected in the dropdown
+ def OnFieldSelected(self, event):
+ self.current = self.table.__childCache[event.GetData()]
- def OnSize(self, event):
- self.list.SetSize(self.GetSize())
+ def OnSize(self, event):
+ self.list.SetSize(self.GetSize())
- def OnBeginDrag(self, event):
+ def OnBeginDrag(self, event):
- #object = self.schemaMap[event.GetIndex()] # Bah! this always returns 0
- object = self.table.__childCache[self.list.HitTest(event.GetPoint())[0]]
+ #object = self.schemaMap[event.GetIndex()] # Bah! this always returns 0
+ object =
self.table.__childCache[self.list.HitTest(event.GetPoint())[0]]
- data = self.editor.buildDataObject(self.table)
+ data = self.editor.buildDataObject(self.table)
- item = -1
- # Cycle through each selected item
- while 1:
- item = self.list.GetNextItem(item,
- wx.LIST_NEXT_ALL,
- wx.LIST_STATE_SELECTED);
- if item == -1:
- break
+ item = -1
+ # Cycle through each selected item
+ while 1:
+ item = self.list.GetNextItem(item,
+ wx.LIST_NEXT_ALL,
+ wx.LIST_STATE_SELECTED);
+ if item == -1:
+ break
- object = self.table.__childCache[item]
+ object = self.table.__childCache[item]
- attributes = {
- "block": data[1]['Attributes']['name'],
- "name": self.editor.document.getUniqueName("fld%s" % (
- string.join(string.split(string.capwords( \
- string.replace(object.name,'_',' '))),''))),
- "field": object.name,
- "datatype": object.type,
- "required" : not object.nullable,
- }
+ attributes = {
+ "block": data[1]['Attributes']['name'],
+ "name": self.editor.document.getUniqueName("fld%s" % (
+ string.join(string.split(string.capwords( \
+ string.replace(object.name,'_',' '))),''))),
+ "field": object.name,
+ "datatype": object.type,
+ "required" : not object.nullable,
+ }
- if hasattr(object,'length') and object.length:
- attributes['max_length'] = object.length
- attributes['width'] = object.length < 30 and object.length or 30
+ if hasattr(object,'length') and object.length:
+ attributes['max_length'] = object.length
+ attributes['width'] = object.length < 30 and object.length or
30
- try:
- defaulttype = object.defaulttype
- defaultval = object.defaultval
- except AttributeError:
- defaulttype = None
- defaultval = None
+ try:
+ defaulttype = object.defaulttype
+ defaultval = object.defaultval
+ except AttributeError:
+ defaulttype = None
+ defaultval = None
- if defaulttype == 'constant':
- if defaultval[:1] in "\"'":
- defaultval = defaultval[1:-2]
- attributes['default'] = defaultval
- defaulttype = None
- defaultval = None
+ if defaulttype == 'constant':
+ if defaultval[:1] in "\"'":
+ defaultval = defaultval[1:-2]
+ attributes['default'] = defaultval
+ defaulttype = None
+ defaultval = None
- if hasattr(object, 'label') and len(object.label):
- label = object.label
- elif len(object.name) == 1:
- label = string.upper(object.name)
- else:
- label = string.join(string.split(string.capwords( \
- string.replace(object.name,'_',' '))),' ')
+ if hasattr(object, 'label') and len(object.label):
+ label = object.label
+ elif len(object.name) == 1:
+ label = string.upper(object.name)
+ else:
+ label = string.join(string.split(string.capwords( \
+ string.replace(object.name,'_',' '))),' ')
- data.append( { "Type" : "entry",
- "Attributes": attributes,
- "Label": label,
- "DefaultTrigger": defaulttype,
- "DefaultInfo": defaultval
- } )
+ data.append( { "Type" : "entry",
+ "Attributes": attributes,
+ "Label": label,
+ "DefaultTrigger": defaulttype,
+ "DefaultInfo": defaultval
+ } )
- do =
wx.CustomDataObject(wx.CustomDataFormat("application/x-gnue-designer"))
- do.SetData(cPickle.dumps(data,1))
+ do =
wx.CustomDataObject(wx.CustomDataFormat("application/x-gnue-designer"))
+ do.SetData(cPickle.dumps(data,1))
- dropSource = wx.DropSource(self)
- dropSource.SetData(do)
- result = dropSource.DoDragDrop(False)
+ dropSource = wx.DropSource(self)
+ dropSource.SetData(do)
+ result = dropSource.DoDragDrop(False)
# Get around a few wx 2.2.x shortcomings:
try:
- wx.LC_HRULES
- wx.LC_VRULES
+ wx.LC_HRULES
+ wx.LC_VRULES
except NameError:
- wx.LC_HRULES=0
- wx.LC_VRULES=0
-
+ wx.LC_HRULES=0
+ wx.LC_VRULES=0
Modified: trunk/gnue-designer/src/base/tools/TreeView.py
===================================================================
--- trunk/gnue-designer/src/base/tools/TreeView.py 2006-04-03 19:53:03 UTC
(rev 8343)
+++ trunk/gnue-designer/src/base/tools/TreeView.py 2006-04-03 19:56:14 UTC
(rev 8344)
@@ -44,141 +44,139 @@
class TreeView (ToolBase):
- default_dock = 'left-0'
+ default_dock = 'left-0'
- def init(self):
+ def init(self):
- # EventAware provided by ToolBase
- self.registerEventListeners({
- 'ObjectSelected' : self.onSetCurrentObject,
- 'ObjectCreated' : self.onCreateObject,
- 'ObjectModified' : self.onModifyObject,
- 'ObjectDeleted' : self.onDeleteObject,
- })
+ # EventAware provided by ToolBase
+ self.registerEventListeners({
+ 'ObjectSelected' : self.onSetCurrentObject,
+ 'ObjectCreated' : self.onCreateObject,
+ 'ObjectModified' : self.onModifyObject,
+ 'ObjectDeleted' : self.onDeleteObject,
+ })
- self.panel = wx.Panel(self,-1,style=wx.SIMPLE_BORDER, pos=wx.Point(6,6))
- wx.EVT_SIZE(self, self.onSize)
+ self.panel = wx.Panel(self,-1,style=wx.SIMPLE_BORDER,
pos=wx.Point(6,6))
+ wx.EVT_SIZE(self, self.onSize)
- self.tree = wx.TreeCtrl(self.panel, wx.NewId(),
- style=wx.TR_HAS_BUTTONS|#wx.TR_EDIT_LABELS|
- wx.TR_FULL_ROW_HIGHLIGHT)#|wx.TR_HIDE_ROOT)
- self._handler = None
+ self.tree = wx.TreeCtrl(self.panel, wx.NewId(),
+ style=wx.TR_HAS_BUTTONS|#wx.TR_EDIT_LABELS|
+ wx.TR_FULL_ROW_HIGHLIGHT)#|wx.TR_HIDE_ROOT)
+ self._handler = None
- self.tree.SetImageList(treeIconList)
+ self.tree.SetImageList(treeIconList)
- wx.EVT_TREE_BEGIN_LABEL_EDIT(self, self.tree.GetId(), self.OnTreeLabelEdit)
- wx.EVT_TREE_END_LABEL_EDIT(self, self.tree.GetId(),
self.OnTreeLabelEditEnd)
- wx.EVT_TREE_SEL_CHANGED(self, self.tree.GetId(), self.OnTreeItemSelected)
+ wx.EVT_TREE_BEGIN_LABEL_EDIT(self, self.tree.GetId(),
self.OnTreeLabelEdit)
+ wx.EVT_TREE_END_LABEL_EDIT(self, self.tree.GetId(),
self.OnTreeLabelEditEnd)
+ wx.EVT_TREE_SEL_CHANGED(self, self.tree.GetId(),
self.OnTreeItemSelected)
- root = self.rootObject._treeItem = self.tree.AddRoot(self.rootDescr)
- self.tree.SetPyData(self.rootObject._treeItem, self.rootObject)
+ root = self.rootObject._treeItem = self.tree.AddRoot(self.rootDescr)
+ self.tree.SetPyData(self.rootObject._treeItem, self.rootObject)
- wx.EVT_RIGHT_DOWN(self, self.OnRightDown)
- wx.EVT_LEFT_DCLICK(self, self.OnEditProperties)
+ wx.EVT_RIGHT_DOWN(self, self.OnRightDown)
+ wx.EVT_LEFT_DCLICK(self, self.OnEditProperties)
- self.inittree()
- self.rootObject.walk(self.inventoryObject)
- self.tree.Expand(root)
- self.Fit()
+ self.inittree()
+ self.rootObject.walk(self.inventoryObject)
+ self.tree.Expand(root)
+ self.Fit()
- # For use by subclasses
- def inittree(self):
- pass
+ # For use by subclasses
+ def inittree(self):
+ pass
- # For use by subclasses
- def inventoryObject(self):
- pass
+ # For use by subclasses
+ def inventoryObject(self):
+ pass
- def onSize(self, event):
- x,y = self.GetClientSizeTuple()
- self.panel.SetSize((x-12,y-12))
- self.tree.SetSize(self.panel.GetClientSizeTuple())
+ def onSize(self, event):
+ x,y = self.GetClientSizeTuple()
+ self.panel.SetSize((x-12,y-12))
+ self.tree.SetSize(self.panel.GetClientSizeTuple())
- def AppendItem(self, parent, description):
- rv = self.tree.AppendItem(parent, wxEncode(description))
- return rv
+ def AppendItem(self, parent, description):
+ rv = self.tree.AppendItem(parent, wxEncode(description))
+ return rv
- def onSetCurrentObject (self, event):
- object = event.object
- handler = event.originator
- if object == None:
- return
- if handler != __name__:
- self.tree.EnsureVisible(object._treeItem)
- self._handler = handler
- self.tree.SelectItem(object._treeItem)
- self._handler = None
+ def onSetCurrentObject (self, event):
+ object = event.object
+ handler = event.originator
+ if object == None:
+ return
+ if handler != __name__:
+ self.tree.EnsureVisible(object._treeItem)
+ self._handler = handler
+ self.tree.SelectItem(object._treeItem)
+ self._handler = None
- def onCreateObject (self, event):
- object = event.object
- handler = event.originator
- if object == None:
- return
- if handler != __name__:
- try:
- assert gDebug(4,"Adding %s (%s)" % (object.name, object._type))
- except:
- pass
- self.inventoryObject(object)
+ def onCreateObject (self, event):
+ object = event.object
+ handler = event.originator
+ if object == None:
+ return
+ if handler != __name__:
+ try:
+ assert gDebug(4,"Adding %s (%s)" % (object.name, object._type))
+ except:
+ pass
+ self.inventoryObject(object)
- def onModifyObject (self, event):
- object = event.object
- handler = event.originator
- if object == None:
- return
- if handler != __name__:
- for attribute in event.new.keys():
- value = event.new[attribute]
- if attribute == 'name' and object != self.rootObject:
- self.tree.SetItemText(object._treeItem, object.getDescription())
+ def onModifyObject (self, event):
+ object = event.object
+ handler = event.originator
+ if object == None:
+ return
+ if handler != __name__:
+ for attribute in event.new.keys():
+ value = event.new[attribute]
+ if attribute == 'name' and object != self.rootObject:
+ self.tree.SetItemText(object._treeItem,
object.getDescription())
- def onDeleteObject (self, event):
- object = event.object
- handler = event.originator
- if object == None:
- return
- if hasattr(object, '_treeItemTrigger'):
- self.tree.Delete(object._treeItemTrigger)
- if hasattr(object, '_treeItem'):
- if self.tree.GetSelection() == object._treeItem:
- self.tree.SelectItem(self.tree.GetItemParent(object._treeItem))
- self.tree.Delete(object._treeItem)
- self.Refresh()
+ def onDeleteObject (self, event):
+ object = event.object
+ handler = event.originator
+ if object == None:
+ return
+ if hasattr(object, '_treeItemTrigger'):
+ self.tree.Delete(object._treeItemTrigger)
+ if hasattr(object, '_treeItem'):
+ if self.tree.GetSelection() == object._treeItem:
+ self.tree.SelectItem(self.tree.GetItemParent(object._treeItem))
+ self.tree.Delete(object._treeItem)
+ self.Refresh()
- def OnTreeLabelEdit(self, event):
- event.Veto()
+ def OnTreeLabelEdit(self, event):
+ event.Veto()
- def OnTreeLabelEditEnd(self, event):
- pass
+ def OnTreeLabelEditEnd(self, event):
+ pass
- def OnTreeItemSelected(self, event):
- if self._handler == None:
- object = self.tree.GetPyData(event.GetItem())
- if object != None and not isinstance(object, ObjectMenu):
- self.dispatchEvent('ObjectSelected', object=object,
originator=__name__)
- else:
- self.dispatchEvent('ObjectSelected', object=None, originator=__name__)
+ def OnTreeItemSelected(self, event):
+ if self._handler == None:
+ object = self.tree.GetPyData(event.GetItem())
+ if object != None and not isinstance(object, ObjectMenu):
+ self.dispatchEvent('ObjectSelected', object=object,
originator=__name__)
+ else:
+ self.dispatchEvent('ObjectSelected', object=None,
originator=__name__)
- def OnRightDown(self, event):
- id, flags = self.tree.HitTest(event.GetPosition())
- object = self.tree.GetPyData(id)
- self.tree.EnsureVisible(id)
- self.tree.SelectItem(id)
- if isinstance(object, ObjectMenu):
- self.PopupMenu(object, event.GetPosition())
- elif object != None:
- self.PopupMenu(object._popupMenu, event.GetPosition())
+ def OnRightDown(self, event):
+ id, flags = self.tree.HitTest(event.GetPosition())
+ object = self.tree.GetPyData(id)
+ self.tree.EnsureVisible(id)
+ self.tree.SelectItem(id)
+ if isinstance(object, ObjectMenu):
+ self.PopupMenu(object, event.GetPosition())
+ elif object != None:
+ self.PopupMenu(object._popupMenu, event.GetPosition())
- def OnEditProperties(self, event):
+ def OnEditProperties(self, event):
- id, flags = self.HitTest(event.GetPosition())
- object = self.tree.GetPyData(id)
- self.tree.EnsureVisible(id)
- self.tree.SelectItem(id)
- if not isinstance(object, ObjectMenu):
- self.document.propertyEditorWindow.Show(1)
- self.document.propertyEditorWindow.Raise()
- self.document.propertyEditorWindow.SetFocus()
-
-
+ id, flags = self.HitTest(event.GetPosition())
+ object = self.tree.GetPyData(id)
+ self.tree.EnsureVisible(id)
+ self.tree.SelectItem(id)
+ if not isinstance(object, ObjectMenu):
+ self.document.propertyEditorWindow.Show(1)
+ self.document.propertyEditorWindow.Raise()
+ self.document.propertyEditorWindow.SetFocus()
Modified: trunk/gnue-designer/src/base/tools/TriggerEditor.py
===================================================================
--- trunk/gnue-designer/src/base/tools/TriggerEditor.py 2006-04-03 19:53:03 UTC
(rev 8343)
+++ trunk/gnue-designer/src/base/tools/TriggerEditor.py 2006-04-03 19:56:14 UTC
(rev 8344)
@@ -41,71 +41,71 @@
# ===========================================================================
class TriggerEditor (EditorBase):
- runtime_section = "TriggerEditor"
- icon = 'py'
+ runtime_section = "TriggerEditor"
+ icon = 'py'
- def init(self, object):
+ def init(self, object):
- editor = self.editor = PythonEditorControl(self,-1, pos=wx.Point(0,32))
- editor.InEditMode = True
+ editor = self.editor = PythonEditorControl(self,-1, pos=wx.Point(0,32))
+ editor.InEditMode = True
- self.document.app.ui.autoSizer(self, editor)
+ self.document.app.ui.autoSizer(self, editor)
- self.object = object
+ self.object = object
- self.triggerList = []
- self.triggerMap = {}
+ self.triggerList = []
+ self.triggerMap = {}
- self.editor.SetReadOnly(False)
- wx.EVT_KILL_FOCUS(self.editor, self.OnKillFocus)
- self.__ignoreevent = 0
+ self.editor.SetReadOnly(False)
+ wx.EVT_KILL_FOCUS(self.editor, self.OnKillFocus)
+ self.__ignoreevent = 0
- self.mode = NAMED_TRIGGER
+ self.mode = NAMED_TRIGGER
- self.__ignoreevent = 0
+ self.__ignoreevent = 0
- self.editor.SetReadOnly(0)
+ self.editor.SetReadOnly(0)
- if not len(object._children):
- GParserHelpers.GContent(object, "")
- elif len(object._children) > 1:
- content = object.getChildrenAsContent()
- object._children = []
- GParserHelpers.GContent(object, content)
+ if not len(object._children):
+ GParserHelpers.GContent(object, "")
+ elif len(object._children) > 1:
+ content = object.getChildrenAsContent()
+ object._children = []
+ GParserHelpers.GContent(object, content)
- self.editor.InEditMode = 0
- self.editor.SetText(object.getChildrenAsContent())
- self.editor.EmptyUndoBuffer()
- self.editor.Colourise(0, -1)
+ self.editor.InEditMode = 0
+ self.editor.SetText(object.getChildrenAsContent())
+ self.editor.EmptyUndoBuffer()
+ self.editor.Colourise(0, -1)
- self.setCaption(self._generateName(object))
+ self.setCaption(self._generateName(object))
- def _generateName(self, trigger):
- if trigger.type.upper() == 'NAMED':
- return trigger.name
- else:
- parent = trigger.getParent ()
- #name = '%s.%s' % (parent.name,
parent._validTriggers[trigger.type.upper()])
- name = '%s.%s' % (parent.name, trigger.type)
- try:
- name = parent.getParent ().name + '.' + name
- except:
- pass
- return '('+name+')'
+ def _generateName(self, trigger):
+ if trigger.type.upper() == 'NAMED':
+ return trigger.name
+ else:
+ parent = trigger.getParent ()
+ #name = '%s.%s' % (parent.name,
parent._validTriggers[trigger.type.upper()])
+ name = '%s.%s' % (parent.name, trigger.type)
+ try:
+ name = parent.getParent ().name + '.' + name
+ except:
+ pass
+ return '('+name+')'
- def OnKillFocus(self, event):
- # TODO: We might be able to ditch this now since it's done in onChange
- if self.object != None and not self.__ignoreevent:
- self.object._children[0]._content = self.editor.GetText()
+ def OnKillFocus(self, event):
+ # TODO: We might be able to ditch this now since it's done in onChange
+ if self.object != None and not self.__ignoreevent:
+ self.object._children[0]._content = self.editor.GetText()
# ===========================================================================
# Filter function
# ===========================================================================
def EditorFilter(gctrigger):
- assert gctrigger._type == 'GCTrigger'
- return not gctrigger.src
+ assert gctrigger._type == 'GCTrigger'
+ return not gctrigger.src
# ===========================================================================
@@ -114,22 +114,20 @@
# TODO: Add support for our JavaScript triggers
# TODO: Move to ui/wx?
class PythonEditorControl(PythonSTC):
- def __init__(self, parent, *args, **parms):
- PythonSTC.__init__(self, parent, *args, **parms)
- self.__makeDirty = parent.document.makeDirty
- self.__parent = parent
+ def __init__(self, parent, *args, **parms):
+ PythonSTC.__init__(self, parent, *args, **parms)
+ self.__makeDirty = parent.document.makeDirty
+ self.__parent = parent
- # TODO: FInd a better way...
- wx.stc.EVT_STC_MODIFIED(self, self.GetId(), self.__OnChange)
+ # TODO: FInd a better way...
+ wx.stc.EVT_STC_MODIFIED(self, self.GetId(), self.__OnChange)
- def __OnChange(self, evt):
- if self.InEditMode:
- self.__makeDirty()
- self.__parent.object.children[0]._content = self.GetText()
+ def __OnChange(self, evt):
+ if self.InEditMode:
+ self.__makeDirty()
+ self.__parent.object.children[0]._content = self.GetText()
- # The old code used SetEnabled, so we emulate that call here
- # TODO: See if this still matters
- def SetEnabled(self, bool):
- self.SetReadOnly(bool)
-
-
+ # The old code used SetEnabled, so we emulate that call here
+ # TODO: See if this still matters
+ def SetEnabled(self, bool):
+ self.SetReadOnly(bool)
Modified: trunk/gnue-designer/src/forms/BlockEditor.py
===================================================================
--- trunk/gnue-designer/src/forms/BlockEditor.py 2006-04-03 19:53:03 UTC
(rev 8343)
+++ trunk/gnue-designer/src/forms/BlockEditor.py 2006-04-03 19:56:14 UTC
(rev 8344)
@@ -39,20 +39,20 @@
class BlockEditor(ToolBase):
- runtime_section = "FormsBlockEditor"
- default_dock = 'frame' # 'right-20'
- uses_toolbar = 1
+ runtime_section = "FormsBlockEditor"
+ default_dock = 'frame' # 'right-20'
+ uses_toolbar = 1
## uses_feedback_bar = 1
- def init(self):
- self.grid = _BlockEditorGrid(self, self.document)
- wx.EVT_SIZE(self, self.__OnSize)
+ def init(self):
+ self.grid = _BlockEditorGrid(self, self.document)
+ wx.EVT_SIZE(self, self.__OnSize)
- def __OnSize(self, event):
- self.grid.SetSize(self.GetClientSize())
+ def __OnSize(self, event):
+ self.grid.SetSize(self.GetClientSize())
- def createToolbar(self, parent):
- return _BlockToolbar(parent, self.document)
+ def createToolbar(self, parent):
+ return _BlockToolbar(parent, self.document)
@@ -61,78 +61,78 @@
#
class _BlockEditorGrid(MultiObjectGridEditor):
- base_gobject = GFBlock
+ base_gobject = GFBlock
- def init(self):
- self.datasources = ObjectList(self.document, GDataSource,
- 'name', self.__datasourcesUpdated)
- self.document.registerEventListeners({'BlockEditor:Delete':
self.__OnDelete})
+ def init(self):
+ self.datasources = ObjectList(self.document, GDataSource,
+ 'name', self.__datasourcesUpdated)
+ self.document.registerEventListeners({'BlockEditor:Delete':
self.__OnDelete})
- def getColumnDefinitions(self):
- return (
- {'Name': 'Name', # Internal name
- 'Attribute': 'name', # Attribute (can be a method)
- 'Label': u_('Name'), # Column label
- },
- {'Name': 'Rows', # Internal name
- 'Attribute': 'rows', # Attribute (can be a method)
- 'Label': u_('# Rows'), # Column label
- },
- {'Name': 'DataSource', # Internal name
- 'Attribute': 'datasource', # Attribute (can be a method)
- 'Label': u_('Data Source'), # Column label
- 'ValidSet': self.__getDataSources,
- },
- {'Name': 'BaseTable', # Internal name
- 'Attribute': self.__getBaseTable, # Attribute (can be a method)
- 'ReadOnly': 1, # Can the user edit this field?
- 'Label': u_('Base Table'), # Column label
- },
- )
+ def getColumnDefinitions(self):
+ return (
+ {'Name': 'Name', # Internal name
+ 'Attribute': 'name', # Attribute (can be a method)
+ 'Label': u_('Name'), # Column label
+ },
+ {'Name': 'Rows', # Internal name
+ 'Attribute': 'rows', # Attribute (can be a method)
+ 'Label': u_('# Rows'), # Column label
+ },
+ {'Name': 'DataSource', # Internal name
+ 'Attribute': 'datasource', # Attribute (can be a method)
+ 'Label': u_('Data Source'), # Column label
+ 'ValidSet': self.__getDataSources,
+ },
+ {'Name': 'BaseTable', # Internal name
+ 'Attribute': self.__getBaseTable, # Attribute (can be a method)
+ 'ReadOnly': 1, # Can the user edit this field?
+ 'Label': u_('Base Table'), # Column label
+ },
+ )
- #
- # Given a datasource, find the base table
- #
- def __getBaseTable(self, object):
- try:
- if not object.datasource:
- return ""
- except AttributeError:
- return ""
+ #
+ # Given a datasource, find the base table
+ #
+ def __getBaseTable(self, object):
+ try:
+ if not object.datasource:
+ return ""
+ except AttributeError:
+ return ""
- try:
- datasource = self.datasources[object.datasource]
- except AttributeError:
- return ""
+ try:
+ datasource = self.datasources[object.datasource]
+ except AttributeError:
+ return ""
- if hasattr(datasource,'table') and datasource.table:
- return datasource.table
- elif datasource.type == 'static':
- return u_("(Custom List)")
- else:
- return ""
+ if hasattr(datasource,'table') and datasource.table:
+ return datasource.table
+ elif datasource.type == 'static':
+ return u_("(Custom List)")
+ else:
+ return ""
- #
- #
- #
- def __getDataSources(self):
- return self.datasources.getDict()
+ #
+ #
+ #
+ def __getDataSources(self):
+ return self.datasources.getDict()
- #
- # Called if any of the datasources have been updated
- #
- def __datasourcesUpdated(self):
- self.updateValidSet('DataSource')
+ #
+ # Called if any of the datasources have been updated
+ #
+ def __datasourcesUpdated(self):
+ self.updateValidSet('DataSource')
- #
- # User selected the delete icon
- #
- def __OnDelete(self, event):
- if self.current:
- self.document.incubator.deleteObject(self.document.rootObject,
- self.current, firstRun=0)
+ #
+ # User selected the delete icon
+ #
+ def __OnDelete(self, event):
+ if self.current:
+ self.document.incubator.deleteObject(self.document.rootObject,
+ self.current, firstRun=0)
######################################################################
@@ -143,5 +143,5 @@
class _BlockToolbar(BaseToolBar):
## ICON_SIZE=(16,16)
- def init(self):
- self.addToolbarMapping(ToolbarMapping)
+ def init(self):
+ self.addToolbarMapping(ToolbarMapping)
Modified: trunk/gnue-designer/src/forms/Debugger.py
===================================================================
--- trunk/gnue-designer/src/forms/Debugger.py 2006-04-03 19:53:03 UTC (rev
8343)
+++ trunk/gnue-designer/src/forms/Debugger.py 2006-04-03 19:56:14 UTC (rev
8344)
@@ -40,121 +40,121 @@
##
#####################################################
-class DebugSession:
- def __init__(self, caller):
- self.caller = caller
-
- #~ #Open output window to show debug messages there
- #~ #instead of the console
- #~ outputWindow = wx.Frame(caller, -1, u_("Console Output"),
- #~ size=wx.Size(300,50))
- #~ outputWindow.text = wx.TextCtrl(outputWindow, -1, style=wx.TE_MULTILINE)
- #~ outputWindow.Show(True)
- #~ caller.outputWindow = outputWindow
- #~ self.outputWindow = outputWindow
-
- #~ #Redirect stdout and stderr to output window
- #~ self.stdoutcatcher = _stdoutcatcher(outputWindow.text)
- #~ self.stderrcatcher = _stderrcatcher(outputWindow.text)
+class DebugSession:
+ def __init__(self, caller):
+ self.caller = caller
- try:
- self._saveexit = sys.exit
- sys.exit = self.debugClosing
- debugInstance = GFInstance.GFInstance(caller.app, \
- connections=caller.app.connections, \
- ui=DummyInterfaceModule, disableSplash=True, \
- moduleName='gnue.forms.uidrivers.wx.UIdriver')
- #debugInstance.addDialogs()
- debugInstance.addFormFromBuffer(caller.rootObject.dumpXML(treeDump=True))
-
-
#debugInstance.setForm(GFParser.loadFile(StringIO(caller.rootObject.dumpXML(treeDump=1)),
debugInstance))
-
- #strictly in this order,
- #or DebugUserInterfase.exitApplication won't be called
- debugInstance._uimodule._debuginstance = self
- debugInstance.activate()
- except:
- self.sanityCheck()
- raise
- #~ self.outputWindow.text.AppendText(u_('\n---- Form Closed Abruptly
----'))
+ #~ #Open output window to show debug messages there
+ #~ #instead of the console
+ #~ outputWindow = wx.Frame(caller, -1, u_("Console Output"),
+ #~ size=wx.Size(300,50))
+ #~ outputWindow.text = wx.TextCtrl(outputWindow, -1,
style=wx.TE_MULTILINE)
+ #~ outputWindow.Show(True)
+ #~ caller.outputWindow = outputWindow
+ #~ self.outputWindow = outputWindow
+ #~ #Redirect stdout and stderr to output window
+ #~ self.stdoutcatcher = _stdoutcatcher(outputWindow.text)
+ #~ self.stderrcatcher = _stderrcatcher(outputWindow.text)
- def debugClosing(self):
- self.sanityCheck()
- #~ self.outputWindow.text.AppendText(u_('\n---- Form Closed ----'))
- #self.outputWindow.Close()
-
+ try:
+ self._saveexit = sys.exit
+ sys.exit = self.debugClosing
+ debugInstance = GFInstance.GFInstance(caller.app, \
+ connections=caller.app.connections, \
+ ui=DummyInterfaceModule, disableSplash=True, \
+ moduleName='gnue.forms.uidrivers.wx.UIdriver')
+ #debugInstance.addDialogs()
+
debugInstance.addFormFromBuffer(caller.rootObject.dumpXML(treeDump=True))
- def sanityCheck(self):
- #~ self.stdoutcatcher.restore()
- #~ self.stderrcatcher.restore()
- sys.exit = self._saveexit
+
#debugInstance.setForm(GFParser.loadFile(StringIO(caller.rootObject.dumpXML(treeDump=1)),
debugInstance))
+ #strictly in this order,
+ #or DebugUserInterfase.exitApplication won't be called
+ debugInstance._uimodule._debuginstance = self
+ debugInstance.activate()
+ except:
+ self.sanityCheck()
+ raise
+ #~ self.outputWindow.text.AppendText(u_('\n---- Form Closed
Abruptly ----'))
-class DebugUserInterface(UIwxpython.GFUserInterface):
- def exitApplication(self, event):
- eo = event._form._instance
- eo._uimodule._debuginstance.debugClosing()
- UIwxpython.GFUserInterface.exitApplication(self, event)
-# Ack!!!
-class DummyInterfaceModule:
- GFUserInterface = DebugUserInterface
+ def debugClosing(self):
+ self.sanityCheck()
+ #~ self.outputWindow.text.AppendText(u_('\n---- Form Closed ----'))
+ #self.outputWindow.Close()
-#class DebugInstance(GFInstance.GFInstance):
+ def sanityCheck(self):
+ #~ self.stdoutcatcher.restore()
+ #~ self.stderrcatcher.restore()
+ sys.exit = self._saveexit
+
+
+class DebugUserInterface(UIwxpython.GFUserInterface):
+ def exitApplication(self, event):
+ eo = event._form._instance
+ eo._uimodule._debuginstance.debugClosing()
+ UIwxpython.GFUserInterface.exitApplication(self, event)
+
+# Ack!!!
+class DummyInterfaceModule:
+ GFUserInterface = DebugUserInterface
+
+
+#class DebugInstance(GFInstance.GFInstance):
# def __init__(self, manager, connections=None, ui=DummyInterfaceModule,
disableSplash=1,
# parameters={}):
# GFInstance.GFInstance.__init__(self,connections=manager.connections,
# ui=ui, disableSplash=disableSplash)
#
-# app, -1, app.connections,
+# app, -1, app.connections,
# DummyInterfaceModule,1)
-
-
+
+
class _stdoutcatcher:
- def __init__(self, textctrl):
- self.orig = sys.__stdout__
- self.textctl = textctrl
- sys.__stdout__ = self
-
- def write(self, str):
- self.orig.write(str)
- self.textctl.AppendText(str)
+ def __init__(self, textctrl):
+ self.orig = sys.__stdout__
+ self.textctl = textctrl
+ sys.__stdout__ = self
- def writelines(self, list):
- for line in list:
- self.write(str)
+ def write(self, str):
+ self.orig.write(str)
+ self.textctl.AppendText(str)
- def restore(self):
- self.__stdout__ = self.orig
-
- def flush(self):
- self.orig.flush()
+ def writelines(self, list):
+ for line in list:
+ self.write(str)
+ def restore(self):
+ self.__stdout__ = self.orig
+ def flush(self):
+ self.orig.flush()
+
+
class _stderrcatcher:
- def __init__(self, textctrl):
- self.orig = sys.__stderr__
- self.origfh = GDebug._fh
- self.textctl = textctrl
- #sys.__stderr__ = self
- #GDebug._fh = self
- GDebug.__catchStderr(self)
-
- def write(self, str):
- self.origfh.write(str)
- self.textctl.AppendText(str)
+ def __init__(self, textctrl):
+ self.orig = sys.__stderr__
+ self.origfh = GDebug._fh
+ self.textctl = textctrl
+ #sys.__stderr__ = self
+ #GDebug._fh = self
+ GDebug.__catchStderr(self)
- def writelines(self, list):
- for line in list:
- self.write(str)
+ def write(self, str):
+ self.origfh.write(str)
+ self.textctl.AppendText(str)
- def restore(self):
- #self.__stderr__ = self.orig
- #GDebug._fh = self.origfh
- GDebug.__catchStderr(self.origfh)
+ def writelines(self, list):
+ for line in list:
+ self.write(str)
- def flush(self):
- self.orig.flush()
+ def restore(self):
+ #self.__stderr__ = self.orig
+ #GDebug._fh = self.origfh
+ GDebug.__catchStderr(self.origfh)
+
+ def flush(self):
+ self.orig.flush()
Modified: trunk/gnue-designer/src/forms/Document.py
===================================================================
--- trunk/gnue-designer/src/forms/Document.py 2006-04-03 19:53:03 UTC (rev
8343)
+++ trunk/gnue-designer/src/forms/Document.py 2006-04-03 19:56:14 UTC (rev
8344)
@@ -71,343 +71,341 @@
# Document Instance class
#============================================================================
class Document(BaseDocument):
- """
- Designer's form editor document.
- """
+ """
+ Designer's form editor document.
+ """
- # =========================================================================
- # Public methods
- # =========================================================================
+ # =========================================================================
+ # Public methods
+ # =========================================================================
- def init(self):
- app = self.app
- self.incubator = Incubator(self) # Incubator
- self.properties = formProperties # List of the modules properties
- self.wizardRunner = WizardRunner #
- self.debugLevel = '1' # The debug level used when running a form
- # inside designer
+ def init(self):
+ app = self.app
+ self.incubator = Incubator(self) # Incubator
+ self.properties = formProperties # List of the modules properties
+ self.wizardRunner = WizardRunner #
+ self.debugLevel = '1' # The debug level used when running a
form
+ # inside designer
- # Create a GFInstance instance
- self.gfinstance = GFInstance.GFInstance(app,
- app.connections,
- None, disableSplash=1)
+ # Create a GFInstance instance
+ self.gfinstance = GFInstance.GFInstance(app,
+ app.connections,
+ None, disableSplash=1)
- # For GFInstance support, iirc
- ##self._pages = []
+ # For GFInstance support, iirc
+ ##self._pages = []
- # Build a list of positionable widgets
- self._positionableList = []
- elements = self.incubator.elements
- for tag in elements.keys():
- try:
- if elements['Positionable']:
- self._positionableList.append(tag)
- except KeyError:
- pass
+ # Build a list of positionable widgets
+ self._positionableList = []
+ elements = self.incubator.elements
+ for tag in elements.keys():
+ try:
+ if elements['Positionable']:
+ self._positionableList.append(tag)
+ except KeyError:
+ pass
- self.registerEventListeners({
- 'ObjectModified' : self.__onModifyObject,
- 'ObjectDeleted' : self.__onDeleteObject,
- 'Forms:RunForm': self.__onRunForm,
- 'Forms:RequestDebugLevel': self.__onSetDebugLevel
- })
+ self.registerEventListeners({
+ 'ObjectModified' : self.__onModifyObject,
+ 'ObjectDeleted' : self.__onDeleteObject,
+ 'Forms:RunForm': self.__onRunForm,
+ 'Forms:RequestDebugLevel': self.__onSetDebugLevel
+ })
- # Add our events/* stuff
- registerEvents(self)
+ # Add our events/* stuff
+ registerEvents(self)
- def finalize(self):
- # Convenience list to keep track of datasources and blocks
- # TODO: Anything that needs either of these two
- # TODO: should call getObjectList directly.
- # TODO: Left for historical reasons.
- self.datasources = self.getObjectList('datasource')
- self.blocks = self.getObjectList('block')
+ def finalize(self):
+ # Convenience list to keep track of datasources and blocks
+ # TODO: Anything that needs either of these two
+ # TODO: should call getObjectList directly.
+ # TODO: Left for historical reasons.
+ self.datasources = self.getObjectList('datasource')
+ self.blocks = self.getObjectList('block')
- # -------------------------------------------------------------------------
- # Load a form
- # -------------------------------------------------------------------------
- def loadBuffer(self, buffer):
- form = GFParser.loadFile (buffer, self.gfinstance, initialize=0)
- return form
+ # -------------------------------------------------------------------------
+ # Load a form
+ # -------------------------------------------------------------------------
+ def loadBuffer(self, buffer):
+ form = GFParser.loadFile (buffer, self.gfinstance, initialize=0)
+ return form
- def loadEmpty(self, style=None):
- form = GFForm.GFForm()
- options = GFObjects.GFOptions(form)
- form.title = u_("Untitled Form")
- form.height = 12
- GFObjects.GFLogic(form)
- layout = GFObjects.GFLayout(form)
- layout.Char__width = 40
- layout.Char__height = 12
- GFObjects.GFPage(layout)
- return form
+ def loadEmpty(self, style=None):
+ form = GFForm.GFForm()
+ options = GFObjects.GFOptions(form)
+ form.title = u_("Untitled Form")
+ form.height = 12
+ GFObjects.GFLogic(form)
+ layout = GFObjects.GFLayout(form)
+ layout.Char__width = 40
+ layout.Char__height = 12
+ GFObjects.GFPage(layout)
+ return form
- # -------------------------------------------------------------------------
- # Create the document tools/editors
- # -------------------------------------------------------------------------
- def createEditors(self):
- # Associate our LayoutEditor with GFPage objects
+ # -------------------------------------------------------------------------
+ # Create the document tools/editors
+ # -------------------------------------------------------------------------
+ def createEditors(self):
+ # Associate our LayoutEditor with GFPage objects
- self.registerEditor(LayoutEditor, 'GFPage')
- self.registerEditor(PagePainter, 'GFPage')
+ self.registerEditor(LayoutEditor, 'GFPage')
+ self.registerEditor(PagePainter, 'GFPage')
- def createTools(self):
- self.addTool('propertyEditor', u_('Property Inspector'), PropertyEditor,
- hotkey='F10', menuGroup=301)
- self.addTool('treeEditor', u_('Object Navigator'), TreeView,
- hotkey='F8', menuGroup=311)
+ def createTools(self):
+ self.addTool('propertyEditor', u_('Property Inspector'),
PropertyEditor,
+ hotkey='F10', menuGroup=301)
+ self.addTool('treeEditor', u_('Object Navigator'), TreeView,
+ hotkey='F8', menuGroup=311)
- self.addTool('schemaNavigator',u_('Schema Navigator'), SchemaNavigator,
- menuGroup=301)
- #self.addTool('datasourceEditor',u_('Data Source Editor'),
DataSourceEditor,
- # hotkey='F9', menuGroup=311)
- #self.addTool('blockEditor', u_('Block Editor'), BlockEditor,
- # hotkey='F5', menuGroup=311)
- #self.addTool('fieldEditor', u_('Field Editor'), FieldEditor,
- # hotkey='F6', menuGroup=201)
- self.addTool('eventEditor', u_('Trigger Mappings'), EventEditor,
- hotkey='F7', menuGroup=321)
+ self.addTool('schemaNavigator',u_('Schema Navigator'), SchemaNavigator,
+ menuGroup=301)
+ #self.addTool('datasourceEditor',u_('Data Source Editor'),
DataSourceEditor,
+ # hotkey='F9', menuGroup=311)
+ #self.addTool('blockEditor', u_('Block Editor'), BlockEditor,
+ # hotkey='F5', menuGroup=311)
+ #self.addTool('fieldEditor', u_('Field Editor'), FieldEditor,
+ # hotkey='F6', menuGroup=201)
+ self.addTool('eventEditor', u_('Trigger Mappings'), EventEditor,
+ hotkey='F7', menuGroup=321)
- def createWizards(self):
- self.loadWizards(wizards)
+ def createWizards(self):
+ self.loadWizards(wizards)
- # Instances can add to the primary toolbar
- def initToolBar(self):
- self.toolbar.addToolbarMapping(';Forms:RunForm,tb_exec;')
+ # Instances can add to the primary toolbar
+ def initToolBar(self):
+ self.toolbar.addToolbarMapping(';Forms:RunForm,tb_exec;')
- def initMenu(self):
- # Add the [sub]menus
- for location, text, grouping in (
- ('Modify|Arrange Items',u_('&Arrange Items'), 501),):
+ def initMenu(self):
+ # Add the [sub]menus
+ for location, text, grouping in (
+ ('Modify|Arrange Items',u_('&Arrange Items'), 501),):
- self.menubar.addMenu(location, text, grouping)
+ self.menubar.addMenu(location, text, grouping)
- for location, event, text, hotkey, help, grouping, canToggle in (
- ('View', 'LayoutEditor:ZoomIn', u_("Zoom In"), None, u_("Zoom in"),
11.1, 0),
- ('View', 'LayoutEditor:ZoomOut', u_("Zoom Out"), None, u_("Zoom out"),
11.2, 0),
- ('View', 'LayoutEditor:ShowFocus', u_("Show Focus Order"), None,
u_("Show the navigation order on the layout editor"), 21, 1),
+ for location, event, text, hotkey, help, grouping, canToggle in (
+ ('View', 'LayoutEditor:ZoomIn', u_("Zoom In"), None, u_("Zoom in"),
11.1, 0),
+ ('View', 'LayoutEditor:ZoomOut', u_("Zoom Out"), None, u_("Zoom
out"), 11.2, 0),
+ ('View', 'LayoutEditor:ShowFocus', u_("Show Focus Order"), None,
u_("Show the navigation order on the layout editor"), 21, 1),
- ('Tools','Forms:RunForm', u_("Run Form"), None, u_("Display and run the
current form"), 101.1, 0),
- ('Tools','Forms:RequestDebugLevel', u_("Change debugging level..."),
None, u_("Change the debugging output level for the Run Form option"), 101.2,
0),
+ ('Tools','Forms:RunForm', u_("Run Form"), None, u_("Display and run
the current form"), 101.1, 0),
+ ('Tools','Forms:RequestDebugLevel', u_("Change debugging
level..."), None, u_("Change the debugging output level for the Run Form
option"), 101.2, 0),
- ('Modify|Align Items','Forms:AlignLeft', u_("&Align Left Edges"), None,
u_("Horizontally align the currently selected items along their left
edges"),101.1, 0),
- ('Modify|Align Items','Forms:AlignRight', u_("&Align Right Edges"),
None, u_("Horizontally align the currently selected items along their right
edges"),101.2, 0),
- ('Modify|Align Items','Forms:AlignHCenter', u_("&Align Horizontal
Center"), None, u_("Horizontally align the currently selected items along their
centers"),101.2, 0),
- ('Modify|Align Items','Forms:AlignTop', u_("&Align Top Edges"), None,
u_("Vertically align the currently selected items along their top
edges"),111.1, 0),
- ('Modify|Align Items','Forms:AlignBottom', u_("&Align Bottom Edges"),
None, u_("Vertically align the currently selected items along their bottom
edges"),111.2, 0),
- ('Modify|Align Items','Forms:AlignVCenter', u_("&Align Vertical
Center"), None, u_("Vertically align the currently selected items along their
centers"),111.3, 0),
- ('Modify|Align Items','Forms:SmartAlign', u_("&Smart Align
Labels/Fields"), None, u_("Align Labels and fields into a block formation, with
all fields left aligned and all labels left aligned."),121.1, 0),
+ ('Modify|Align Items','Forms:AlignLeft', u_("&Align Left Edges"),
None, u_("Horizontally align the currently selected items along their left
edges"),101.1, 0),
+ ('Modify|Align Items','Forms:AlignRight', u_("&Align Right Edges"),
None, u_("Horizontally align the currently selected items along their right
edges"),101.2, 0),
+ ('Modify|Align Items','Forms:AlignHCenter', u_("&Align Horizontal
Center"), None, u_("Horizontally align the currently selected items along their
centers"),101.2, 0),
+ ('Modify|Align Items','Forms:AlignTop', u_("&Align Top Edges"),
None, u_("Vertically align the currently selected items along their top
edges"),111.1, 0),
+ ('Modify|Align Items','Forms:AlignBottom', u_("&Align Bottom
Edges"), None, u_("Vertically align the currently selected items along their
bottom edges"),111.2, 0),
+ ('Modify|Align Items','Forms:AlignVCenter', u_("&Align Vertical
Center"), None, u_("Vertically align the currently selected items along their
centers"),111.3, 0),
+ ('Modify|Align Items','Forms:SmartAlign', u_("&Smart Align
Labels/Fields"), None, u_("Align Labels and fields into a block formation, with
all fields left aligned and all labels left aligned."),121.1, 0),
- ('Modify','LayoutEditor:FocusOrder', u_("&Set Focus Order Manually"),
None, u_("Set the focus order by hand"),201.2, 0),
- ('Modify','LayoutEditor:AutoArrange', u_("&Reset Focus Order by
Position"), None, u_("Automatically set the focus order based on an items
position"),201.3, 0)):
- self.menubar.addAction(location, text, event,
- grouping, canDisable=1, canToggle=canToggle,
- icon=None, hotkey=hotkey, help=help)
+ ('Modify','LayoutEditor:FocusOrder', u_("&Set Focus Order
Manually"), None, u_("Set the focus order by hand"),201.2, 0),
+ ('Modify','LayoutEditor:AutoArrange', u_("&Reset Focus Order by
Position"), None, u_("Automatically set the focus order based on an items
position"),201.3, 0)):
+ self.menubar.addAction(location, text, event,
+ grouping, canDisable=1, canToggle=canToggle,
+ icon=None, hotkey=hotkey, help=help)
- # -------------------------------------------------------------------------
- # Called by the base instance just before a save occurs, for cleanup
- # -------------------------------------------------------------------------
- def preSave(self):
+ # -------------------------------------------------------------------------
+ # Called by the base instance just before a save occurs, for cleanup
+ # -------------------------------------------------------------------------
+ def preSave(self):
- # Get rid of form.name = '__main__'
- try:
- if self.rootObject.name == '__main__':
- del self.rootObject.name
- except AttributeError:
- pass
+ # Get rid of form.name = '__main__'
+ try:
+ if self.rootObject.name == '__main__':
+ del self.rootObject.name
+ except AttributeError:
+ pass
- # Do a little rearranging of objects
+ # Do a little rearranging of objects
- options = []
- imports = []
- databases = []
- datasources = []
- triggers = []
- logic = []
- layout = []
- other = []
+ options = []
+ imports = []
+ databases = []
+ datasources = []
+ triggers = []
+ logic = []
+ layout = []
+ other = []
- for child in self.rootObject._children:
- if isinstance(child, GFObjects.GFOptions):
- options.append(child)
- elif isinstance(child, GFLibrary.GFImport):
- imports.append(child)
- elif isinstance(child, GDataSource.GConnection):
- databases.append(child)
- elif isinstance(child, GFObjects.GFDataSource) or \
- (isinstance(child, GFLibrary.GFImportItem) and
- child._type == 'GFimport-datasource'):
- datasources.append(child)
- elif isinstance(child, GTrigger.GTrigger) or \
- (isinstance(child, GFLibrary.GFImportItem) and
- child._type == 'GFimport-trigger'):
- triggers.append(child)
- elif isinstance(child, GFObjects.GFLayout) or \
- (isinstance(child, GFLibrary.GFImportItem) and
- child._type == 'GFimport-layout'):
- layout.append(child)
- elif isinstance(child, GFObjects.GFLogic) or \
- (isinstance(child, GFLibrary.GFImportItem) and
- child._type == 'GFimport-logic'):
- logic.append(child)
- else:
- other.append(child)
+ for child in self.rootObject._children:
+ if isinstance(child, GFObjects.GFOptions):
+ options.append(child)
+ elif isinstance(child, GFLibrary.GFImport):
+ imports.append(child)
+ elif isinstance(child, GDataSource.GConnection):
+ databases.append(child)
+ elif isinstance(child, GFObjects.GFDataSource) or \
+ (isinstance(child, GFLibrary.GFImportItem) and
+ child._type == 'GFimport-datasource'):
+ datasources.append(child)
+ elif isinstance(child, GTrigger.GTrigger) or \
+ (isinstance(child, GFLibrary.GFImportItem) and
+ child._type == 'GFimport-trigger'):
+ triggers.append(child)
+ elif isinstance(child, GFObjects.GFLayout) or \
+ (isinstance(child, GFLibrary.GFImportItem) and
+ child._type == 'GFimport-layout'):
+ layout.append(child)
+ elif isinstance(child, GFObjects.GFLogic) or \
+ (isinstance(child, GFLibrary.GFImportItem) and
+ child._type == 'GFimport-logic'):
+ logic.append(child)
+ else:
+ other.append(child)
- # Do a little sanity check before saving...
- if len(logic[0]._children):
- valid = 1
- else:
- valid = 0 # No blocks! :(
+ # Do a little sanity check before saving...
+ if len(logic[0]._children):
+ valid = 1
+ else:
+ valid = 0 # No blocks! :(
- if not valid:
- if wx.MessageDialog(None,
- u_('The form definition you are about to save\n' + \
- 'does not appear to be a workable definition.' + \
- '\n\nIf you save an incomplete definition, you\n' + \
- 'may not be able to reopen it in Designer.\n\nSave anyway?'),
- u_("Incomplete Form Definition"), wx.YES_NO|wx.ICON_QUESTION
).ShowModal() == wx.ID_NO:
- return 1
+ if not valid:
+ if wx.MessageDialog(None,
+ u_('The form definition you are about to save\n' + \
+ 'does not appear to be a workable definition.' + \
+ '\n\nIf you save an incomplete definition, you\n' + \
+ 'may not be able to reopen it in Designer.\n\nSave anyway?'),
+ u_("Incomplete Form Definition"),
wx.YES_NO|wx.ICON_QUESTION ).ShowModal() == wx.ID_NO:
+ return 1
- # Reorder the children so items of same class are grouped
- self.rootObject._children = []
- for child in options:
- self.rootObject._children.append(child)
- for child in imports:
- self.rootObject._children.append(child)
- for child in databases:
- self.rootObject._children.append(child)
- for child in datasources:
- self.rootObject._children.append(child)
- for child in triggers:
- self.rootObject._children.append(child)
- for child in logic:
- self.rootObject._children.append(child)
- for child in layout:
- self.rootObject._children.append(child)
- for child in other:
- self.rootObject._children.append(child)
+ # Reorder the children so items of same class are grouped
+ self.rootObject._children = []
+ for child in options:
+ self.rootObject._children.append(child)
+ for child in imports:
+ self.rootObject._children.append(child)
+ for child in databases:
+ self.rootObject._children.append(child)
+ for child in datasources:
+ self.rootObject._children.append(child)
+ for child in triggers:
+ self.rootObject._children.append(child)
+ for child in logic:
+ self.rootObject._children.append(child)
+ for child in layout:
+ self.rootObject._children.append(child)
+ for child in other:
+ self.rootObject._children.append(child)
- # -------------------------------------------------------------------------
- # TemplateParser support
- # -------------------------------------------------------------------------
- # Used by TemplateParser to build a wizard.current dict
- def buildWizardCurrentDict(self):
- baseForm = self._currentObject.findParentOfType('GFForm')
- return {'form': baseForm,
- 'logic': baseForm._logic,
- 'layout': baseForm._layout,
- 'page': self.visualEditor.page,
- 'block': self.visualEditor.block,
- 'object': self._currentObject}
+ # -------------------------------------------------------------------------
+ # TemplateParser support
+ # -------------------------------------------------------------------------
+ # Used by TemplateParser to build a wizard.current dict
+ def buildWizardCurrentDict(self):
+ baseForm = self._currentObject.findParentOfType('GFForm')
+ return {'form': baseForm,
+ 'logic': baseForm._logic,
+ 'layout': baseForm._layout,
+ 'page': self.visualEditor.page,
+ 'block': self.visualEditor.block,
+ 'object': self._currentObject}
- # =========================================================================
- # Private methods
- # =========================================================================
+ # =========================================================================
+ # Private methods
+ # =========================================================================
- # -------------------------------------------------------------------------
- # Object tracking
- # -------------------------------------------------------------------------
- def inventoryObject(self, object):
- if object._type == 'GFForm':
- object._blockMap = {}
- elif object._type == 'GFLogic':
- object.getParent ()._logic = object
- elif object._type == 'GFLayout':
- object.getParent ()._layout = object
- # Yes, you guessed it! More layout mgmt hackery...
- object._xmlchildnamespaces = {'Char':'GNUe:Layout:Char'}
- elif object._type == 'GFBlock':
- if self.rootObject._blockMap.has_key(object.name):
- raise "Warning: Multiple blocks with name %s" % str(object.name)
- self.rootObject._blockMap[object.name] = object
- object._fieldMap = {}
- elif object._type == 'GFField':
- object.findParentOfType('GFBlock')._fieldMap[object.name] = object
- elif object._type == 'GFEntry':
- object._block = self.rootObject._blockMap[object.block]
- object._field = object._block._fieldMap[object.field]
- elif isinstance(object, GFObjects.GFPage) and \
- object.getParent () == self.rootObject:
- self._pages.append(object)
+ # -------------------------------------------------------------------------
+ # Object tracking
+ # -------------------------------------------------------------------------
+ def inventoryObject(self, object):
+ if object._type == 'GFForm':
+ object._blockMap = {}
+ elif object._type == 'GFLogic':
+ object.getParent ()._logic = object
+ elif object._type == 'GFLayout':
+ object.getParent ()._layout = object
+ # Yes, you guessed it! More layout mgmt hackery...
+ object._xmlchildnamespaces = {'Char':'GNUe:Layout:Char'}
+ elif object._type == 'GFBlock':
+ if self.rootObject._blockMap.has_key(object.name):
+ raise "Warning: Multiple blocks with name %s" %
str(object.name)
+ self.rootObject._blockMap[object.name] = object
+ object._fieldMap = {}
+ elif object._type == 'GFField':
+ object.findParentOfType('GFBlock')._fieldMap[object.name] = object
+ elif object._type == 'GFEntry':
+ object._block = self.rootObject._blockMap[object.block]
+ object._field = object._block._fieldMap[object.field]
+ elif isinstance(object, GFObjects.GFPage) and \
+ object.getParent () == self.rootObject:
+ self._pages.append(object)
- object._popupMenu = ObjectMenu(self, object)
+ object._popupMenu = ObjectMenu(self, object)
- def __onModifyObject(self, event):
+ def __onModifyObject(self, event):
- object = event.object
+ object = event.object
- #
- # Maintain all those fun dicts/lists created in inventoryObject()
- #
- old = event.old
- if object._type == 'GFBlock':
- try:
- del self.rootObject._blockMap[old['name']]
- except KeyError:
- pass
- self.rootObject._blockMap[object.name] = object
+ #
+ # Maintain all those fun dicts/lists created in inventoryObject()
+ #
+ old = event.old
+ if object._type == 'GFBlock':
+ try:
+ del self.rootObject._blockMap[old['name']]
+ except KeyError:
+ pass
+ self.rootObject._blockMap[object.name] = object
- elif object._type == 'GFField':
- block = object.findParentOfType('GFBlock')
- try:
- del block._fieldMap[old['name']]
- except KeyError:
- pass
- block._fieldMap[object.name] = object
+ elif object._type == 'GFField':
+ block = object.findParentOfType('GFBlock')
+ try:
+ del block._fieldMap[old['name']]
+ except KeyError:
+ pass
+ block._fieldMap[object.name] = object
- def __onDeleteObject(self, event):
- object = event.object
- if object._type == 'GFPage':
- self._pages.remove(object)
+ def __onDeleteObject(self, event):
+ object = event.object
+ if object._type == 'GFPage':
+ self._pages.remove(object)
- # Maintain all those fun dicts/lists created in inventoryObject()
- if object._type == 'GFBlock':
- del self.rootObject._blockMap[object.name]
- elif object._type == 'GFField':
- del object.findParentOfType('GFBlock')._fieldMap[object.name]
- elif isinstance(object, GFObjects.GFPage) and \
- object.getParent () == self.rootObject:
- del self._pages[object]
+ # Maintain all those fun dicts/lists created in inventoryObject()
+ if object._type == 'GFBlock':
+ del self.rootObject._blockMap[object.name]
+ elif object._type == 'GFField':
+ del object.findParentOfType('GFBlock')._fieldMap[object.name]
+ elif isinstance(object, GFObjects.GFPage) and \
+ object.getParent () == self.rootObject:
+ del self._pages[object]
- object._popupMenu = ObjectMenu(self, object)
+ object._popupMenu = ObjectMenu(self, object)
- # -------------------------------------------------------------------------
- # Form Debugging support
- # -------------------------------------------------------------------------
- def __onSetDebugLevel(self, event):
- """Opens a dialog to let the user set the debug level
- before running a form inside Designer."""
- tmpLevel = self.debugLevel
- tmpRez = ''
- tmpMessage = u_("Please enter debugging level - integer numbers [0..n]")
- tmpCaption = u_("Choose debug level")
- tmpRez = wx.GetTextFromUser(tmpMessage, tmpCaption, tmpLevel, None)
- if (tmpRez != ''):
- self.debugLevel = tmpRez
+ # -------------------------------------------------------------------------
+ # Form Debugging support
+ # -------------------------------------------------------------------------
+ def __onSetDebugLevel(self, event):
+ """Opens a dialog to let the user set the debug level
+ before running a form inside Designer."""
+ tmpLevel = self.debugLevel
+ tmpRez = ''
+ tmpMessage = u_("Please enter debugging level - integer numbers
[0..n]")
+ tmpCaption = u_("Choose debug level")
+ tmpRez = wx.GetTextFromUser(tmpMessage, tmpCaption, tmpLevel, None)
+ if (tmpRez != ''):
+ self.debugLevel = tmpRez
- def __onRunForm (self, event):
- #TODO: This does not work... But everyone tried this first...
- #TODO: No, not just you. I mean EVERYONE!!!
- GDebug.setDebug(str(self.debugLevel), "")
- DebugSession(self)
- #~ wx.MessageDialog(self,
- #~ u_('Running a form within GNUe Designer is\n' + \
- #~ 'not implemented yet.' + \
- #~ '\n\nPlease save the form and run it using\n' + \
- #~ 'the GNUe Forms tool (gnue-forms).'),
- #~ u_("NOT IMPLEMENTED"), wx.OK|wx.ICON_EXCLAMATION ).ShowModal()
-
-
+ def __onRunForm (self, event):
+ #TODO: This does not work... But everyone tried this first...
+ #TODO: No, not just you. I mean EVERYONE!!!
+ GDebug.setDebug(str(self.debugLevel), "")
+ DebugSession(self)
+ #~ wx.MessageDialog(self,
+ #~ u_('Running a form within GNUe Designer is\n' + \
+ #~ 'not implemented yet.' + \
+ #~ '\n\nPlease save the form and run it using\n' + \
+ #~ 'the GNUe Forms tool (gnue-forms).'),
+ #~ u_("NOT IMPLEMENTED"), wx.OK|wx.ICON_EXCLAMATION
).ShowModal()
Modified: trunk/gnue-designer/src/forms/EventEditor.py
===================================================================
--- trunk/gnue-designer/src/forms/EventEditor.py 2006-04-03 19:53:03 UTC
(rev 8343)
+++ trunk/gnue-designer/src/forms/EventEditor.py 2006-04-03 19:56:14 UTC
(rev 8344)
@@ -37,21 +37,21 @@
from gnue.designer.base.ToolBase import *
class EventEditor (BaseEventEditor):
- def reset(self):
- BaseEventEditor.reset(self)
+ def reset(self):
+ BaseEventEditor.reset(self)
- #
- # GFEntry? Show the corresponding GFField
- #
- if self.object._type == 'GFEntry':
- assert gDebug(4,'Adding a new entry property manager')
- self.addPage(FieldInspectorPanel(self, self.notebook), "Field")
- if self.object._block:
- self.addPage(EntryBlockInspectorPanel(self, self.notebook), "Block")
+ #
+ # GFEntry? Show the corresponding GFField
+ #
+ if self.object._type == 'GFEntry':
+ assert gDebug(4,'Adding a new entry property manager')
+ self.addPage(FieldInspectorPanel(self, self.notebook), "Field")
+ if self.object._block:
+ self.addPage(EntryBlockInspectorPanel(self, self.notebook),
"Block")
- # Block?
- if self.object.findParentOfType('GFBlock',includeSelf=0):
- self.addPage(BlockInspectorPanel(self, self.notebook), "Block")
+ # Block?
+ if self.object.findParentOfType('GFBlock',includeSelf=0):
+ self.addPage(BlockInspectorPanel(self, self.notebook), "Block")
@@ -60,18 +60,17 @@
#
class FieldInspectorPanel(BaseInspectorPanel):
- def setCurrent(self, object):
- self._setCurrent(object._field)
+ def setCurrent(self, object):
+ self._setCurrent(object._field)
#
# Block properties (when Entry/Field is selected)
#
class BlockInspectorPanel(BaseInspectorPanel):
- def setCurrent(self, object):
- self._setCurrent(object.findParentOfType('GFBlock'))
+ def setCurrent(self, object):
+ self._setCurrent(object.findParentOfType('GFBlock'))
class EntryBlockInspectorPanel(BaseInspectorPanel):
- def setCurrent(self, object):
- self._setCurrent(object._block)
-
+ def setCurrent(self, object):
+ self._setCurrent(object._block)
Modified: trunk/gnue-designer/src/forms/Incubator.py
===================================================================
--- trunk/gnue-designer/src/forms/Incubator.py 2006-04-03 19:53:03 UTC (rev
8343)
+++ trunk/gnue-designer/src/forms/Incubator.py 2006-04-03 19:56:14 UTC (rev
8344)
@@ -34,10 +34,9 @@
class Incubator(BaseIncubator):
- elements = GFParser.getXMLelements()
+ elements = GFParser.getXMLelements()
- def _handleUnknownAttribute(self, tag, object, attr, value):
- # Hackery for forms Layout Management (namespace) support
- if attr.find(':')+1:
- object.__dict__[attr.replace(':','__')] = value
-
+ def _handleUnknownAttribute(self, tag, object, attr, value):
+ # Hackery for forms Layout Management (namespace) support
+ if attr.find(':')+1:
+ object.__dict__[attr.replace(':','__')] = value
Modified: trunk/gnue-designer/src/forms/LayoutEditor/DisplayDropTarget.py
===================================================================
--- trunk/gnue-designer/src/forms/LayoutEditor/DisplayDropTarget.py
2006-04-03 19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/forms/LayoutEditor/DisplayDropTarget.py
2006-04-03 19:56:14 UTC (rev 8344)
@@ -36,270 +36,270 @@
# Drag and Drop support for our grid
#
class DisplayDropTarget(wx.PyDropTarget):
- TYPEMAP = {'date' : 'date',
- 'datetime': 'date',
- 'time' : 'date',
- 'number' : 'number'}
+ TYPEMAP = {'date' : 'date',
+ 'datetime': 'date',
+ 'time' : 'date',
+ 'number' : 'number'}
- def __init__(self, editor):
- wx.PyDropTarget.__init__(self)
- self.editor = editor
+ def __init__(self, editor):
+ wx.PyDropTarget.__init__(self)
+ self.editor = editor
- self.data =
wx.CustomDataObject(wx.CustomDataFormat("application/x-gnue-designer"))
- self.SetDataObject(self.data)
+ self.data =
wx.CustomDataObject(wx.CustomDataFormat("application/x-gnue-designer"))
+ self.SetDataObject(self.data)
- def OnEnter(self, x, y, d):
- return d
+ def OnEnter(self, x, y, d):
+ return d
- def OnLeave(self):
- pass
+ def OnLeave(self):
+ pass
- def OnDrop(self, x, y):
- pass
+ def OnDrop(self, x, y):
+ pass
- def OnDragOver(self, x, y, d):
- return d
+ def OnDragOver(self, x, y, d):
+ return d
- # Called when OnDrop returns True. We need to get the data and
- # do something with it.
- def OnData(self, bx, by, d):
+ # Called when OnDrop returns True. We need to get the data and
+ # do something with it.
+ def OnData(self, bx, by, d):
- instance = self.editor.document
+ instance = self.editor.document
- # copy the data from the drag source to our data object
- if self.GetData():
- # convert it back to our format
- data = self.data.GetData()
- unpickled = cPickle.loads(data)
+ # copy the data from the drag source to our data object
+ if self.GetData():
+ # convert it back to our format
+ data = self.data.GetData()
+ unpickled = cPickle.loads(data)
- nextY = int(by / self.editor.gridHeight)
- x = int(bx / self.editor.gridWidth)
- for params in unpickled:
- y = nextY
+ nextY = int(by / self.editor.gridHeight)
+ x = int(bx / self.editor.gridWidth)
+ for params in unpickled:
+ y = nextY
- if params['Type'] == 'SchemaDrop':
- self.schemaDrop(params, bx, by)
- continue
+ if params['Type'] == 'SchemaDrop':
+ self.schemaDrop(params, bx, by)
+ continue
- # TODO: Most of this crap can be purged out of here
- # TODO: schemaDrop replaced most of it
+ # TODO: Most of this crap can be purged out of here
+ # TODO: schemaDrop replaced most of it
- attributes = params['Attributes']
+ attributes = params['Attributes']
- # Entry types require a "block".. find or create one
- if params['Type'] in ('entry',):
- try:
- parent = params['Block']
- except KeyError:
- # Find the parent block
+ # Entry types require a "block".. find or create one
+ if params['Type'] in ('entry',):
+ try:
+ parent = params['Block']
+ except KeyError:
+ # Find the parent block
- parent = None
+ parent = None
- if not attributes.has_key('block') and \
- attributes.has_key('datasource'):
+ if not attributes.has_key('block') and \
+ attributes.has_key('datasource'):
- datasource = string.lower(attributes['datasource'])
+ datasource = string.lower(attributes['datasource'])
- for child in self.editor.page._children:
- if child._type == 'GFBlock' and \
- hasattr(child,'datasource') and \
- string.lower(child.datasource) == datasource:
- parent = child
- break
+ for child in self.editor.page._children:
+ if child._type == 'GFBlock' and \
+ hasattr(child,'datasource') and \
+ string.lower(child.datasource) == datasource:
+ parent = child
+ break
- if parent is None:
- dlg = wx.MessageDialog(None,
- "The current page does not have a block\n"
- "corresponding to Data Source %s.\n"
- "Create a new block on the current page?" % \
- attributes['datasource'],
- "No Target Block Found", style=wx.YES_NO|wx.ICON_WARNING)
- save = dlg.ShowModal()
- dlg.Destroy()
- if save == wx.ID_NO:
- return d # TODO: This should actually return a failure
+ if parent is None:
+ dlg = wx.MessageDialog(None,
+ "The current page does not have a block\n"
+ "corresponding to Data Source %s.\n"
+ "Create a new block on the current page?" % \
+ attributes['datasource'],
+ "No Target Block Found",
style=wx.YES_NO|wx.ICON_WARNING)
+ save = dlg.ShowModal()
+ dlg.Destroy()
+ if save == wx.ID_NO:
+ return d # TODO: This should actually
return a failure
- # Create a parent block
- parent = instance.incubator.createObject(
- instance.rootObject,
- 'block',
- self.editor.page,
- attributes={'datasource':datasource})
- else:
- for child in self.editor.page._children:
- if child._type == 'GFBlock' and \
- child.name == attributes['block']:
+ # Create a parent block
+ parent = instance.incubator.createObject(
+ instance.rootObject,
+ 'block',
+ self.editor.page,
+
attributes={'datasource':datasource})
+ else:
+ for child in self.editor.page._children:
+ if child._type == 'GFBlock' and \
+ child.name == attributes['block']:
- parent = child
- break
+ parent = child
+ break
- try:
- defaulttype = params['DefaultType']
- defaultval = params['DefaultVal']
- if defaulttype == 'constant':
- if defaultval[:1] in "\"'":
- defaultval = defaultval [1:-2]
- attributes['default'] = defaultval
- except KeyError:
- pass
+ try:
+ defaulttype = params['DefaultType']
+ defaultval = params['DefaultVal']
+ if defaulttype == 'constant':
+ if defaultval[:1] in "\"'":
+ defaultval = defaultval [1:-2]
+ attributes['default'] = defaultval
+ except KeyError:
+ pass
- createLabels = "left" # TODO:
string.lower(gConfig("CreateLabelsOnDrop"))
+ createLabels = "left" # TODO:
string.lower(gConfig("CreateLabelsOnDrop"))
- if createLabels != "no":
- label = params["Label"] + ":"
+ if createLabels != "no":
+ label = params["Label"] + ":"
- # Figure out the position of the label
- # If the entry is for a multirow block,
- # we assume that the label goes above.
- if createLabels == "left" and\
- not(hasattr(parent,'rows') and parent.rows > 1 or 0):
- lx = x - len(label) - 1
- if lx < 0:
- x = len(label) + 1
- lx = 0
- ly = y
- else: # "above"
- nextY += 1
- lx = x
- ly = y - 1
+ # Figure out the position of the label
+ # If the entry is for a multirow block,
+ # we assume that the label goes above.
+ if createLabels == "left" and\
+ not(hasattr(parent,'rows') and parent.rows > 1 or
0):
+ lx = x - len(label) - 1
+ if lx < 0:
+ x = len(label) + 1
+ lx = 0
+ ly = y
+ else: # "above"
+ nextY += 1
+ lx = x
+ ly = y - 1
- if ly < 0:
- ly = 0
- y += 1
+ if ly < 0:
+ ly = 0
+ y += 1
- # Create a label
- instance.incubator.createObject(
- instance.rootObject,
- 'label',
- self.editor.page,
- attributes={'x': lx,
- 'y': ly,
- 'width': len(label),
- 'text': label })
- nextY += 1
+ # Create a label
+ instance.incubator.createObject(
+ instance.rootObject,
+ 'label',
+ self.editor.page,
+ attributes={'x': lx,
+ 'y': ly,
+ 'width': len(label),
+ 'text': label })
+ nextY += 1
- elif params['Type'] in ('datasource',):
- parent = self.editor.rootObject
+ elif params['Type'] in ('datasource',):
+ parent = self.editor.rootObject
- elif params['Type'] in ('block',):
- parent = self.editor.page
- elif params['Type'] in ('selectedWidgets',):
- xshift = x - int(attributes['startingX'])
- yshift = y - int(attributes['startingY'])
- for widget in self.editor._currentSelection:
- widget._widgetHandler.relativeMove(xshift,yshift)
- else:
- parent = self.editor.page
- nextY += 1
+ elif params['Type'] in ('block',):
+ parent = self.editor.page
+ elif params['Type'] in ('selectedWidgets',):
+ xshift = x - int(attributes['startingX'])
+ yshift = y - int(attributes['startingY'])
+ for widget in self.editor._currentSelection:
+ widget._widgetHandler.relativeMove(xshift,yshift)
+ else:
+ parent = self.editor.page
+ nextY += 1
- attributes['x'] = x
- attributes['y'] = y
+ attributes['x'] = x
+ attributes['y'] = y
- #
- # Create our new object
- #
- if not params['Type'] in ('selectedWidgets',):
- object = instance.incubator.createObject(
- instance.rootObject,
- params['Type'],
- parent,
- attributes=attributes)
+ #
+ # Create our new object
+ #
+ if not params['Type'] in ('selectedWidgets',):
+ object = instance.incubator.createObject(
+ instance.rootObject,
+ params['Type'],
+ parent,
+ attributes=attributes)
- if params['Type'] in ('entry',):
- try:
- defaulttype = params['DefaultTrigger']
- defaultval = params['DefaultInfo']
- triggertext = ""
- if defaulttype == 'sequence':
- triggertext = "\n# Set default value\n" \
- + "if self.isEmpty():\n" \
- + " self.autofillBySequence('%s')\n" % defaultval
- if defaulttype == 'system' and defaultval == 'timestamp':
- triggertext = "\n# Set default value\n" \
- + "if self.isEmpty():\n" \
- + " self.value = %s.extensions.getTimeStamp()\n" \
- % parent.datasource
+ if params['Type'] in ('entry',):
+ try:
+ defaulttype = params['DefaultTrigger']
+ defaultval = params['DefaultInfo']
+ triggertext = ""
+ if defaulttype == 'sequence':
+ triggertext = "\n# Set default value\n" \
+ + "if self.isEmpty():\n" \
+ + "
self.autofillBySequence('%s')\n" % defaultval
+ if defaulttype == 'system' and defaultval ==
'timestamp':
+ triggertext = "\n# Set default value\n" \
+ + "if self.isEmpty():\n" \
+ + " self.value =
%s.extensions.getTimeStamp()\n" \
+ % parent.datasource
- if triggertext:
- instance.incubator.createObject(
- instance.rootObject,
- 'trigger',
- object,
- attributes = {
- '_content_': triggertext,
- 'type': 'PRE-INSERT',
- 'name': '%s_PreInsert' % object.name
- })
+ if triggertext:
+ instance.incubator.createObject(
+ instance.rootObject,
+ 'trigger',
+ object,
+ attributes = {
+ '_content_': triggertext,
+ 'type': 'PRE-INSERT',
+ 'name': '%s_PreInsert' % object.name
+ })
- except KeyError:
- pass
+ except KeyError:
+ pass
- return d # what is returned signals the source what to do
- # with the original data (move, copy, etc.) In this
- # case we just return the suggested value given to us.
+ return d # what is returned signals the source what to do
+ # with the original data (move, copy, etc.) In
this
+ # case we just return the suggested value given to
us.
- #
- # This handles dropping from the Schema Navigator
- #
- def schemaDrop(self, params, x, y):
+ #
+ # This handles dropping from the Schema Navigator
+ #
+ def schemaDrop(self, params, x, y):
- try:
- table, fields = params['Data'][0]
- except:
- return
+ try:
+ table, fields = params['Data'][0]
+ except:
+ return
- instance = self.editor.document
+ instance = self.editor.document
- # TODO: if params['ShowMenu'], give user options
+ # TODO: if params['ShowMenu'], give user options
- blocks = []
- for set in ((self.editor.block,),instance.blocks):
- for test in set:
- try:
- datasource = instance.datasources[test.datasource]
- if datasource.connection.lower() == table['connection'].lower() and \
- datasource.table.lower() == table['name'].lower():
- blocks.append(test)
- except (KeyError, AttributeError):
- pass
+ blocks = []
+ for set in ((self.editor.block,),instance.blocks):
+ for test in set:
+ try:
+ datasource = instance.datasources[test.datasource]
+ if datasource.connection.lower() ==
table['connection'].lower() and \
+ datasource.table.lower() == table['name'].lower():
+ blocks.append(test)
+ except (KeyError, AttributeError):
+ pass
- if not params['ShowMenu']:
- # User left-click-dragged, so do the default action
- if blocks:
- self.schemaDrop_Add(table, fields, blocks[0], x, y)
- else:
- self.schemaDrop_Create(table, fields, x, y)
- else:
- # Present a menu of options
- menu = wx.Menu()
- current = 0
- if blocks and blocks[0] == self.editor.block:
- wid = wx.NewId()
- menu.Append(wid, u_('Add Fields to Current Block'))
- current = 1
- wx.EVT_MENU(menu, wid,
- lambda event, s=self, t=table, f=fields, x=x, y=y,
- b=blocks[0]: s.schemaDrop_Add(t, f, b, x, y) )
- wid = wx.NewId()
- menu.Append(wid, u_('Add Fields to New Block'))
- wx.EVT_MENU(menu, wid, lambda event, s=self, t=table, x=x, y=y,
- f=fields: s.schemaDrop_Create(t, f, x, y) )
- if len(blocks) > 1 + current:
- smenu = wx.Menu()
- menu.AppendMenu(wx.NewId(), u_("Add Fields to Block"), smenu)
- for block in blocks[1:]:
- wid = wx.NewId()
- smenu.Append(wid, block.name)
- wx.EVT_MENU(smenu, wid,
- lambda event, s=self, t=table, f=fields, x=x, y=y,
- b=block: s.schemaDrop_Add(t, f, b, x, y) )
+ if not params['ShowMenu']:
+ # User left-click-dragged, so do the default action
+ if blocks:
+ self.schemaDrop_Add(table, fields, blocks[0], x, y)
+ else:
+ self.schemaDrop_Create(table, fields, x, y)
+ else:
+ # Present a menu of options
+ menu = wx.Menu()
+ current = 0
+ if blocks and blocks[0] == self.editor.block:
+ wid = wx.NewId()
+ menu.Append(wid, u_('Add Fields to Current Block'))
+ current = 1
+ wx.EVT_MENU(menu, wid,
+ lambda event, s=self, t=table, f=fields, x=x, y=y,
+ b=blocks[0]: s.schemaDrop_Add(t, f, b, x,
y) )
+ wid = wx.NewId()
+ menu.Append(wid, u_('Add Fields to New Block'))
+ wx.EVT_MENU(menu, wid, lambda event, s=self, t=table, x=x, y=y,
+ f=fields: s.schemaDrop_Create(t, f, x,
y) )
+ if len(blocks) > 1 + current:
+ smenu = wx.Menu()
+ menu.AppendMenu(wx.NewId(), u_("Add Fields to Block"), smenu)
+ for block in blocks[1:]:
+ wid = wx.NewId()
+ smenu.Append(wid, block.name)
+ wx.EVT_MENU(smenu, wid,
+ lambda event, s=self, t=table, f=fields, x=x, y=y,
+ b=block: s.schemaDrop_Add(t, f, b, x,
y) )
## TODO: Finish schemaDrop_Dropdown
## menu.AppendSeparator()
@@ -309,242 +309,237 @@
## lambda event, s=self, t=table, x=x, y=y,
## f=fields: s.schemaDrop_Dropdown(t, f, x, y) )
- menu.AppendSeparator()
- wid = wx.NewId()
- menu.Append(wid, u_("Create Block (no fields)"))
- wx.EVT_MENU(menu, wid, lambda event, s=self, t=table,
- f=fields: s.schemaDrop_Block(t, f, select=1) )
- wid = wx.NewId()
- menu.Append(wid, u_("Create Data Source (no bound block)"))
- wx.EVT_MENU(menu, wid, lambda event, s=self, t=table,
- f=fields: s.schemaDrop_Datasource(t, f,
select=1) )
+ menu.AppendSeparator()
+ wid = wx.NewId()
+ menu.Append(wid, u_("Create Block (no fields)"))
+ wx.EVT_MENU(menu, wid, lambda event, s=self, t=table,
+ f=fields: s.schemaDrop_Block(t, f,
select=1) )
+ wid = wx.NewId()
+ menu.Append(wid, u_("Create Data Source (no bound block)"))
+ wx.EVT_MENU(menu, wid, lambda event, s=self, t=table,
+ f=fields: s.schemaDrop_Datasource(t, f,
select=1) )
- # Show the popup menu
- self.editor.panel.PopupMenuXY(menu, x, y)
+ # Show the popup menu
+ self.editor.panel.PopupMenuXY(menu, x, y)
- #
- # User requested we add fields to current block
- #
- def schemaDrop_Add(self, table, fields, block, x, y):
- y = int(y / self.editor.gridHeight)
- x = int(x / self.editor.gridWidth)
- maxWidth = x
- page = self.editor.page
- instance = self.editor.document
- selection = []
- for f in fields:
- try:
- label=f['label'] + ':'
- except KeyError:
- label=f['name'].replace('_',' ').capitalize()+':'
+ #
+ # User requested we add fields to current block
+ #
+ def schemaDrop_Add(self, table, fields, block, x, y):
+ y = int(y / self.editor.gridHeight)
+ x = int(x / self.editor.gridWidth)
+ maxWidth = x
+ page = self.editor.page
+ instance = self.editor.document
+ selection = []
+ for f in fields:
+ try:
+ label=f['label'] + ':'
+ except KeyError:
+ label=f['name'].replace('_',' ').capitalize()+':'
- # Create the field
- try:
- width = min(f['length'],30)
- except KeyError:
- width = 10
+ # Create the field
+ try:
+ width = min(f['length'],30)
+ except KeyError:
+ width = 10
- fattr = {'name': instance.getUniqueName('fld' + f['name'].capitalize()),
- 'field':f['name'],
- 'typecast': self.TYPEMAP.get (f['type'], 'text')}
+ fattr = {'name': instance.getUniqueName('fld' +
f['name'].capitalize()),
+ 'field':f['name'],
+ 'typecast': self.TYPEMAP.get (f['type'], 'text')}
- try:
- fattr['required'] = f['required']
- except KeyError:
- pass
+ try:
+ fattr['required'] = f['required']
+ except KeyError:
+ pass
- try:
- defaulttype = f['defaulttype']
- defaultval = f['defaultval']
- except KeyError:
- defaulttype = None
+ try:
+ defaulttype = f['defaulttype']
+ defaultval = f['defaultval']
+ except KeyError:
+ defaulttype = None
- if defaulttype == 'constant':
- fattr['default'] = defaultval
+ if defaulttype == 'constant':
+ fattr['default'] = defaultval
- field = instance.incubator.createObject(
- instance.rootObject,
- 'field',
- block,
- attributes=fattr,
- select=0)
+ field = instance.incubator.createObject(
+ instance.rootObject,
+ 'field',
+ block,
+ attributes=fattr,
+ select=0)
- # Create any pre-insert triggers
- triggertext = ""
- if defaulttype == 'sequence':
- triggertext = "\n# Set default value\n" \
- + "if self.isEmpty():\n" \
- + " self.autofillBySequence('%s')\n" % defaultval
- elif defaulttype == 'system' and defaultval == 'timestamp':
- triggertext = "\n# Set default value\n" \
- + "if self.isEmpty():\n" \
- + " self.value = %s.extensions.getTimeStamp()\n" \
- % block.datasource
+ # Create any pre-insert triggers
+ triggertext = ""
+ if defaulttype == 'sequence':
+ triggertext = "\n# Set default value\n" \
+ + "if self.isEmpty():\n" \
+ + " self.autofillBySequence('%s')\n" % defaultval
+ elif defaulttype == 'system' and defaultval == 'timestamp':
+ triggertext = "\n# Set default value\n" \
+ + "if self.isEmpty():\n" \
+ + " self.value = %s.extensions.getTimeStamp()\n" \
+ % block.datasource
- if triggertext:
- instance.incubator.createObject(
- instance.rootObject,
- 'trigger',
- field,
- attributes = {
- '_content_': triggertext,
- 'type': 'PRE-INSERT',
- 'name': '%s_PreInsert' % field.name },
- select=0)
+ if triggertext:
+ instance.incubator.createObject(
+ instance.rootObject,
+ 'trigger',
+ field,
+ attributes = {
+ '_content_': triggertext,
+ 'type': 'PRE-INSERT',
+ 'name': '%s_PreInsert' % field.name },
+ select=0)
- # Create the labels
- selection.append(instance.incubator.createObject(
- instance.rootObject,
- 'label',
- page,
- attributes={'name': instance.getUniqueName('lbl%s' %
f['name'].capitalize()),
- 'text': label,
- 'Char:x': x,
- 'Char:y': y,
- 'Char:width': len(label)},
- select=0))
+ # Create the labels
+ selection.append(instance.incubator.createObject(
+ instance.rootObject,
+ 'label',
+ page,
+ attributes={'name': instance.getUniqueName('lbl%s' %
f['name'].capitalize()),
+ 'text': label,
+ 'Char:x': x,
+ 'Char:y': y,
+ 'Char:width': len(label)},
+ select=0))
- # Create the entry
- selection.append(instance.incubator.createObject(
- instance.rootObject,
- 'entry',
- page,
- attributes={'name': instance.getUniqueName('ntry%s' %
f['name'].capitalize()),
- 'field': field.name,
- 'block': block.name,
- 'Char:x': x + len(label) + 1,
- 'Char:y': y,
- 'Char:width': width},
- select=0))
+ # Create the entry
+ selection.append(instance.incubator.createObject(
+ instance.rootObject,
+ 'entry',
+ page,
+ attributes={'name': instance.getUniqueName('ntry%s' %
f['name'].capitalize()),
+ 'field': field.name,
+ 'block': block.name,
+ 'Char:x': x + len(label) + 1,
+ 'Char:y': y,
+ 'Char:width': width},
+ select=0))
- maxWidth = max(maxWidth, x + len(label) + width + 2)
- y += 1
+ maxWidth = max(maxWidth, x + len(label) + width + 2)
+ y += 1
- # Adjust form height if necessary
- if y > instance.rootObject._layout.Char__height or \
- maxWidth > instance.rootObject._layout.Char__width:
+ # Adjust form height if necessary
+ if y > instance.rootObject._layout.Char__height or \
+ maxWidth > instance.rootObject._layout.Char__width:
- old = {}
- new = {}
+ old = {}
+ new = {}
- if y > instance.rootObject._layout.Char__height:
- old['Char:height'] = instance.rootObject._layout.Char__height
- new['Char:height'] = y
- instance.rootObject._layout.Char__height = y
+ if y > instance.rootObject._layout.Char__height:
+ old['Char:height'] = instance.rootObject._layout.Char__height
+ new['Char:height'] = y
+ instance.rootObject._layout.Char__height = y
- if maxWidth > instance.rootObject._layout.Char__width:
- old['Char:width'] = instance.rootObject._layout.Char__width
- new['Char:width'] = maxWidth
- instance.rootObject._layout.Char__width = maxWidth
+ if maxWidth > instance.rootObject._layout.Char__width:
+ old['Char:width'] = instance.rootObject._layout.Char__width
+ new['Char:width'] = maxWidth
+ instance.rootObject._layout.Char__width = maxWidth
- if sys.platform != 'win32':
- # if you dispatch this event on win32, it will crash :(
- instance.dispatchEvent('ObjectModified',
- object=instance.rootObject._layout,
- old=old,
- new=new,
- originator=__name__)
+ if sys.platform != 'win32':
+ # if you dispatch this event on win32, it will crash :(
+ instance.dispatchEvent('ObjectModified',
+ object=instance.rootObject._layout,
+ old=old,
+ new=new,
+ originator=__name__)
- # Select the new block
- if selection:
- o = selection[0]
- else:
- o = block
+ # Select the new block
+ if selection:
+ o = selection[0]
+ else:
+ o = block
- instance.dispatchEvent('ObjectSelected', object=o,
- originator=__name__,
- selection=selection)
+ instance.dispatchEvent('ObjectSelected', object=o,
+ originator=__name__,
+ selection=selection)
- # Move the focus onto our grid panel
- self.editor.panel.SetFocus()
+ # Move the focus onto our grid panel
+ self.editor.panel.SetFocus()
- #
- # User requested we create a new block and add fields
- #
- def schemaDrop_Create(self, table, fields, x, y):
- block = self.schemaDrop_Block(table, fields)
- self.schemaDrop_Add(table, fields, block, x, y)
+ #
+ # User requested we create a new block and add fields
+ #
+ def schemaDrop_Create(self, table, fields, x, y):
+ block = self.schemaDrop_Block(table, fields)
+ self.schemaDrop_Add(table, fields, block, x, y)
- #
- # user requested we only create a new block
- #
- def schemaDrop_Block(self, table, fields, select=0):
- instance = self.editor.document
- datasource = self.schemaDrop_Datasource(table, fields)
- o = instance.incubator.createObject(
- instance.rootObject,
- 'block',
- instance.rootObject._logic,
- attributes={'name':
instance.getUniqueName('blk%s'%table['name'].capitalize()),
- 'datasource':datasource.name},
- select=0)
+ #
+ # user requested we only create a new block
+ #
+ def schemaDrop_Block(self, table, fields, select=0):
+ instance = self.editor.document
+ datasource = self.schemaDrop_Datasource(table, fields)
+ o = instance.incubator.createObject(
+ instance.rootObject,
+ 'block',
+ instance.rootObject._logic,
+ attributes={'name':
instance.getUniqueName('blk%s'%table['name'].capitalize()),
+ 'datasource':datasource.name},
+ select=0)
- # Select the new block
- if select:
- instance.dispatchEvent('ObjectSelected', object=o, originator=__name__)
+ # Select the new block
+ if select:
+ instance.dispatchEvent('ObjectSelected', object=o,
originator=__name__)
- return o
+ return o
- #
- # User requested we only create a new datasource
- #
- def schemaDrop_Datasource(self, table, fields, attrs={}, select=0):
- instance = self.editor.document
- attrs.update({'name':
instance.getUniqueName('dts%s'%table['name'].capitalize()),
- 'connection':table['connection'],
- 'table': table['name']})
+ #
+ # User requested we only create a new datasource
+ #
+ def schemaDrop_Datasource(self, table, fields, attrs={}, select=0):
+ instance = self.editor.document
+ attrs.update({'name':
instance.getUniqueName('dts%s'%table['name'].capitalize()),
+ 'connection':table['connection'],
+ 'table': table['name']})
- # Add the primary key(s) if applicable
- try:
- if table['primarykey']:
- attrs['primarykey'] = string.join(table['primarykey'],',')
- except KeyError:
- pass
+ # Add the primary key(s) if applicable
+ try:
+ if table['primarykey']:
+ attrs['primarykey'] = string.join(table['primarykey'],',')
+ except KeyError:
+ pass
- o = instance.incubator.createObject(
- instance.rootObject,
- 'datasource',
- instance.rootObject,
- attributes=attrs,
- select=0)
+ o = instance.incubator.createObject(
+ instance.rootObject,
+ 'datasource',
+ instance.rootObject,
+ attributes=attrs,
+ select=0)
- # Select the new datasource
- if select:
- instance.dispatchEvent('ObjectSelected', object=o, originator=__name__)
+ # Select the new datasource
+ if select:
+ instance.dispatchEvent('ObjectSelected', object=o,
originator=__name__)
- return o
+ return o
- #
- # User requested we create a dropdown
- #
- def schemaDrop_Dropdown(self, table, fields, x, y):
- if not self.editor.block:
- print "No blocks in form" # TODO: Better feedback
- return
+ #
+ # User requested we create a dropdown
+ #
+ def schemaDrop_Dropdown(self, table, fields, x, y):
+ if not self.editor.block:
+ print "No blocks in form" # TODO: Better feedback
+ return
- datasource = self.schemaDrop_Datasource(table, fields, {'prequery': 1})
- block = self.editor.block
+ datasource = self.schemaDrop_Datasource(table, fields, {'prequery': 1})
+ block = self.editor.block
- fkid = None
- fkdescr = None
- try:
- pk = table['primarykey'] or []
- except KeyError:
- pk = []
+ fkid = None
+ fkdescr = None
+ try:
+ pk = table['primarykey'] or []
+ except KeyError:
+ pk = []
- for field in fields:
- if field['name'] in pk:
- fkid = field
- break
+ for field in fields:
+ if field['name'] in pk:
+ fkid = field
+ break
- # TODO: Finish me!
-
-
-
-
-
+ # TODO: Finish me!
Modified: trunk/gnue-designer/src/forms/LayoutEditor/LayoutEditor.py
===================================================================
--- trunk/gnue-designer/src/forms/LayoutEditor/LayoutEditor.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/forms/LayoutEditor/LayoutEditor.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -57,791 +57,791 @@
class LayoutEditor (EditorBase):
- runtime_section = "FormsLayoutEditor"
+ runtime_section = "FormsLayoutEditor"
- # TODO: Probably won't need these anymore...
- uses_feedback_bar = 1
- uses_toolbar = 1
+ # TODO: Probably won't need these anymore...
+ uses_feedback_bar = 1
+ uses_toolbar = 1
- def init(self, object):
+ def init(self, object):
- # TODO: blah.... historical reasons
- self._instance = self.document
+ # TODO: blah.... historical reasons
+ self._instance = self.document
- self.app = self.document.app
+ self.app = self.document.app
- self.page = object
- self.block = None
- self.lastBlock = None
- self.blockMap = {}
- self.panel = None
+ self.page = object
+ self.block = None
+ self.lastBlock = None
+ self.blockMap = {}
+ self.panel = None
- self.positionMappings = {}
- self.widgetList = []
- self._currentSelection = []
+ self.positionMappings = {}
+ self.widgetList = []
+ self._currentSelection = []
- self.setCaption(hasattr(object,'name') and \
- object['name'] or object['id'])
+ self.setCaption(hasattr(object,'name') and \
+ object['name'] or object['id'])
- # Create our own WX GFUserInterface instance
- # TODO: This should be moved into GFInstance...
- # TODO: here for historical reasons.
- try:
- self.uidriver = uidriver = self.document.__uidriver
- except AttributeError:
- self.document.__uidriver = self.uidriver = uidriver =
UIwxpython.GFUserInterface(self.document, 0)
+ # Create our own WX GFUserInterface instance
+ # TODO: This should be moved into GFInstance...
+ # TODO: here for historical reasons.
+ try:
+ self.uidriver = uidriver = self.document.__uidriver
+ except AttributeError:
+ self.document.__uidriver = self.uidriver = uidriver =
UIwxpython.GFUserInterface(self.document, 0)
- # Create a list of all UI widgets
- self.widgets = {}
- self.widgets.update(uidriver._supportedWidgets)
+ # Create a list of all UI widgets
+ self.widgets = {}
+ self.widgets.update(uidriver._supportedWidgets)
- # But we don't want a page to act like normal objects...
- # we have special plans for it (bwahahaha)
- del self.widgets['GFPage']
+ # But we don't want a page to act like normal objects...
+ # we have special plans for it (bwahahaha)
+ del self.widgets['GFPage']
- self.backcolor = wx.WHITE
+ self.backcolor = wx.WHITE
- wx.EVT_RIGHT_DOWN(self, self.onRightDown)
- wx.EVT_SIZE(self, self.OnSize)
+ wx.EVT_RIGHT_DOWN(self, self.onRightDown)
+ wx.EVT_SIZE(self, self.OnSize)
- self._currentObject = None
- self.mode = 'move'
- self.reorderfocus = ReorderFocus(self.document)
+ self._currentObject = None
+ self.mode = 'move'
+ self.reorderfocus = ReorderFocus(self.document)
- # Internal mouse states... used by OnMotion, etc
- self.__drawing = 0
- self.__x = 0
- self.__y = 0
- self.__ox = 0
- self.__oy = 0
+ # Internal mouse states... used by OnMotion, etc
+ self.__drawing = 0
+ self.__x = 0
+ self.__y = 0
+ self.__ox = 0
+ self.__oy = 0
- # EventAware provided by ToolBase
- self.registerEventListeners({
- 'ObjectSelected' : self.onSetCurrentObject,
- 'ObjectCreated' : self.onCreateObject,
- 'ObjectModified' : self.onModifyObject,
- 'ObjectDeleted' : self.onDeleteObject,
- 'LayoutEditor:ZoomIn' : self.zoomIn,
- 'LayoutEditor:ZoomOut': self.zoomOut,
- 'LayoutEditor:AutoArrange' : self.onAutoArrange,
- 'LayoutEditor:FocusOrder': self.beginFocusOrder,
- 'Cancel:LayoutEditor:FocusOrder': self.endFocusOrder,
- 'LayoutEditor:Prepositioning':
self.beginPrePositioningTemplate,
- 'Cancel:LayoutEditor:Prepositioning':
self.cancelPrePositioningTemplate,
- 'LayoutEditor:Select': self.beginSelectMode,
- 'Cancel:LayoutEditor:Select': self.cancelSelectMode,
- 'EndWizard': self.endWizard,
- })
+ # EventAware provided by ToolBase
+ self.registerEventListeners({
+ 'ObjectSelected' : self.onSetCurrentObject,
+ 'ObjectCreated' : self.onCreateObject,
+ 'ObjectModified' : self.onModifyObject,
+ 'ObjectDeleted' : self.onDeleteObject,
+ 'LayoutEditor:ZoomIn' : self.zoomIn,
+ 'LayoutEditor:ZoomOut': self.zoomOut,
+ 'LayoutEditor:AutoArrange' : self.onAutoArrange,
+ 'LayoutEditor:FocusOrder': self.beginFocusOrder,
+ 'Cancel:LayoutEditor:FocusOrder':
self.endFocusOrder,
+ 'LayoutEditor:Prepositioning':
self.beginPrePositioningTemplate,
+ 'Cancel:LayoutEditor:Prepositioning':
self.cancelPrePositioningTemplate,
+ 'LayoutEditor:Select': self.beginSelectMode,
+ 'Cancel:LayoutEditor:Select': self.cancelSelectMode,
+ 'EndWizard': self.endWizard,
+ })
- self.document.rootObject.walk (self.inventoryObject)
+ self.document.rootObject.walk (self.inventoryObject)
- ## Stuff needed by UIwxpython
- self._pageList = [] # Needed by UIwxpython
+ ## Stuff needed by UIwxpython
+ self._pageList = [] # Needed by UIwxpython
- self.workspacescroll = wx.ScrolledWindow(self, -1,
- pos=wx.Point(0,0),
- style=wx.CLIP_CHILDREN|wx.HSCROLL|wx.VSCROLL|wx.SUNKEN_BORDER)
+ self.workspacescroll = wx.ScrolledWindow(self, -1,
+ pos=wx.Point(0,0),
+ style=wx.CLIP_CHILDREN|wx.HSCROLL|wx.VSCROLL|wx.SUNKEN_BORDER)
- self.workspace = wx.Panel(self.workspacescroll,-1)
- self.workspace.SetBackgroundColour(self.backcolor)
+ self.workspace = wx.Panel(self.workspacescroll,-1)
+ self.workspace.SetBackgroundColour(self.backcolor)
- # TODO: historical reasons
- object.__workspace = self.workspace
+ # TODO: historical reasons
+ object.__workspace = self.workspace
- self.drawPage(object)
+ self.drawPage(object)
- def createToolbar(self, parent):
- self.toolbar = LayoutEditorTools(parent, self.document)
- self.blockCombo = self.toolbar.blockCombo
- wx.EVT_COMBOBOX(self.toolbar, self.blockCombo.GetId(),
self.OnBlockSelected)
- self._rebuildBlockCombo()
- return self.toolbar
+ def createToolbar(self, parent):
+ self.toolbar = LayoutEditorTools(parent, self.document)
+ self.blockCombo = self.toolbar.blockCombo
+ wx.EVT_COMBOBOX(self.toolbar, self.blockCombo.GetId(),
self.OnBlockSelected)
+ self._rebuildBlockCombo()
+ return self.toolbar
- # Recalculate the scrollbar sizes
- def __OnGridSize(self, event):
- w, h = self.panel.GetSizeTuple()
- w2, h2 = self.workspacescroll.GetClientSizeTuple()
- w = int(max(w, w2)*1.1+30)
- h = int(max(h, h2)*1.1+30)
- self.workspace.SetSize((w,h))
- self.workspacescroll.SetScrollbars(w/30-1,h/30-1,30,30)
+ # Recalculate the scrollbar sizes
+ def __OnGridSize(self, event):
+ w, h = self.panel.GetSizeTuple()
+ w2, h2 = self.workspacescroll.GetClientSizeTuple()
+ w = int(max(w, w2)*1.1+30)
+ h = int(max(h, h2)*1.1+30)
+ self.workspace.SetSize((w,h))
+ self.workspacescroll.SetScrollbars(w/30-1,h/30-1,30,30)
- def inventoryObject(self, object):
- if object._type == 'GFBlock':
- self.blockMap[object.name.lower()] = object
- if not self.block:
- self._setCurrentBlock(object)
+ def inventoryObject(self, object):
+ if object._type == 'GFBlock':
+ self.blockMap[object.name.lower()] = object
+ if not self.block:
+ self._setCurrentBlock(object)
- def onSetCurrentObject (self, event):
- object = event.object
- handler = event.originator
+ def onSetCurrentObject (self, event):
+ object = event.object
+ handler = event.originator
- try:
- selection = event.selection
- except:
- selection = [object]
+ try:
+ selection = event.selection
+ except:
+ selection = [object]
- self._currentObject = object
+ self._currentObject = object
- self._setFeedback()
- self._setCurrentBlock(object)
- self._setSelection(object, selection)
+ self._setFeedback()
+ self._setCurrentBlock(object)
+ self._setSelection(object, selection)
- def _setCurrentBlock(self,object):
- if not object:
- return
- block = object.findParentOfType('GFBlock')
- if not block:
- if object._type == 'GFEntry':
- block = object._block
- if block:
- self.block = block
- if hasattr(self,'blockCombo'):
- self.blockCombo.SetValue(block.name)
+ def _setCurrentBlock(self,object):
+ if not object:
+ return
+ block = object.findParentOfType('GFBlock')
+ if not block:
+ if object._type == 'GFEntry':
+ block = object._block
+ if block:
+ self.block = block
+ if hasattr(self,'blockCombo'):
+ self.blockCombo.SetValue(block.name)
## self._setFeedback()
- def _rebuildBlockCombo(self):
- if hasattr(self,'blockCombo'):
- # TODO
- srt = self.blockMap.keys()
- srt.sort()
- self.blockComboList = []
- self.blockCombo.Clear()
+ def _rebuildBlockCombo(self):
+ if hasattr(self,'blockCombo'):
+ # TODO
+ srt = self.blockMap.keys()
+ srt.sort()
+ self.blockComboList = []
+ self.blockCombo.Clear()
- for key in srt:
- block = self.blockMap[key]
- self.blockCombo.Append(block.name)
- self.blockComboList.append(block)
- if self.block:
- self.blockCombo.SetValue(self.block.name)
+ for key in srt:
+ block = self.blockMap[key]
+ self.blockCombo.Append(block.name)
+ self.blockComboList.append(block)
+ if self.block:
+ self.blockCombo.SetValue(self.block.name)
- def OnBlockSelected(self, event):
- s= event.GetSelection()
- block = self.blockComboList[s]
- if block != self.block:
- self.dispatchEvent('ObjectSelected',
- object = block,
- originator = None)
+ def OnBlockSelected(self, event):
+ s= event.GetSelection()
+ block = self.blockComboList[s]
+ if block != self.block:
+ self.dispatchEvent('ObjectSelected',
+ object = block,
+ originator = None)
- def _setFeedback(self):
+ def _setFeedback(self):
- object = self._currentObject
+ object = self._currentObject
- ft = ""
+ ft = ""
- # This sets the feedback text at the top of the Layout Editor window
- if object:
- try: ft += 'Name: % (%s)' % (object.name, object._type[2:])
- except: pass
+ # This sets the feedback text at the top of the Layout Editor window
+ if object:
+ try: ft += 'Name: % (%s)' % (object.name, object._type[2:])
+ except: pass
- try: ft += ' Col: %s' % object.Char__x
- except: pass
+ try: ft += ' Col: %s' % object.Char__x
+ except: pass
- try: ft += ' Row: %s' % object.Char__y
- except: pass
+ try: ft += ' Row: %s' % object.Char__y
+ except: pass
- try: ft += ' Width: %s' % object.Char__width
- except: pass
+ try: ft += ' Width: %s' % object.Char__width
+ except: pass
- try:
- if object.Char__height > 1:
- ft += ' Height: %s' % object.Char__height
- except:
- pass
+ try:
+ if object.Char__height > 1:
+ ft += ' Height: %s' % object.Char__height
+ except:
+ pass
- if ft:
- self.setFeedback(ft)
+ if ft:
+ self.setFeedback(ft)
- def _setSelection(self, focus, objects):
+ def _setSelection(self, focus, objects):
- # Unhighlight any previously selected items
- # that are no longer selected.
- for key in self._currentSelection:
- if key not in objects:
- try:
- key._widgetHandler.setSelected(0)
- except AttributeError:
- pass
+ # Unhighlight any previously selected items
+ # that are no longer selected.
+ for key in self._currentSelection:
+ if key not in objects:
+ try:
+ key._widgetHandler.setSelected(0)
+ except AttributeError:
+ pass
- # and now highlight any new items
- for object in objects:
- if hasattr(object, '_widgetHandler') and object not in
self._currentSelection:
- self._currentSelection.append(object)
- object._widgetHandler.setSelected(1, object == focus)
+ # and now highlight any new items
+ for object in objects:
+ if hasattr(object, '_widgetHandler') and object not in
self._currentSelection:
+ self._currentSelection.append(object)
+ object._widgetHandler.setSelected(1, object == focus)
- self._currentSelection = objects[:]
+ self._currentSelection = objects[:]
- def onCreateObject (self, event):
- object = event.object
- handler = event.originator
+ def onCreateObject (self, event):
+ object = event.object
+ handler = event.originator
## self._currentSelection = []
- if object == None:
- return
+ if object == None:
+ return
- if handler != "Forms::LayoutEditor":
- origpage = self.page
+ if handler != "Forms::LayoutEditor":
+ origpage = self.page
- if object._type != 'GFPage':
- page = object.findParentOfType('GFPage')
- if page == self.page:
- self.__drawItem(object)
+ if object._type != 'GFPage':
+ page = object.findParentOfType('GFPage')
+ if page == self.page:
+ self.__drawItem(object)
- self.inventoryObject(object)
- if object._type == 'GFBlock':
- self.blockMap[object.name.lower()] = object
- self._rebuildBlockCombo()
+ self.inventoryObject(object)
+ if object._type == 'GFBlock':
+ self.blockMap[object.name.lower()] = object
+ self._rebuildBlockCombo()
- def onModifyObject (self, event):
- object = event.object
- handler = event.originator
+ def onModifyObject (self, event):
+ object = event.object
+ handler = event.originator
- # TODO: adjust label width to match new length...this shouldn't be here
- if object._type == 'GFLabel':
- mods = []
- for field in event.new.keys():
- value = event.new[field]
- if field=='text':
- if (not hasattr(object,'alignment')) or ( object.alignment ==
'left'):
- if not hasattr(object,'Char__width') or object.Char__width !=
len(value):
- object.Char__width=len(value)
- # TODO: This should probably trigger a new ObjectModified event
- event.new['Char:width'] = object.Char__width
+ # TODO: adjust label width to match new length...this shouldn't be here
+ if object._type == 'GFLabel':
+ mods = []
+ for field in event.new.keys():
+ value = event.new[field]
+ if field=='text':
+ if (not hasattr(object,'alignment')) or ( object.alignment
== 'left'):
+ if not hasattr(object,'Char__width') or
object.Char__width != len(value):
+ object.Char__width=len(value)
+ # TODO: This should probably trigger a new
ObjectModified event
+ event.new['Char:width'] = object.Char__width
## self.propBar.onModifyObject(object, event)
- if object in (self.rootObject, self.page, self.rootObject._layout):
- self.refreshPage(self.page)
- elif object in self.widgetList:
- self.__redrawItem(object)
+ if object in (self.rootObject, self.page, self.rootObject._layout):
+ self.refreshPage(self.page)
+ elif object in self.widgetList:
+ self.__redrawItem(object)
- if object._type == 'GFBlock' and event.old.has_key('name'):
- del self.blockMap[event.old['name'].lower()]
- self.blockMap[object.name.lower()] = object
- self._rebuildBlockCombo()
+ if object._type == 'GFBlock' and event.old.has_key('name'):
+ del self.blockMap[event.old['name'].lower()]
+ self.blockMap[object.name.lower()] = object
+ self._rebuildBlockCombo()
- self._setFeedback()
+ self._setFeedback()
- def onDeleteObject (self, event):
+ def onDeleteObject (self, event):
- object = event.object
- handler = event.originator
+ object = event.object
+ handler = event.originator
- self._currentObject = None
+ self._currentObject = None
- if hasattr(object, '_widgetHandler') and object._widgetHandler != None:
- if object in self._currentSelection:
- object._widgetHandler.setSelected(0)
- del self._currentSelection[self._currentSelection.index(object)]
+ if hasattr(object, '_widgetHandler') and object._widgetHandler != None:
+ if object in self._currentSelection:
+ object._widgetHandler.setSelected(0)
+ del
self._currentSelection[self._currentSelection.index(object)]
- self.widgetList.remove(object)
- ##for i in range(len(self.widgetList)):
- ## if self.widgetList[i] == object:
- ## self.widgetList.pop(i)
- ## break
+ self.widgetList.remove(object)
+ ##for i in range(len(self.widgetList)):
+ ## if self.widgetList[i] == object:
+ ## self.widgetList.pop(i)
+ ## break
## object._widget.cleanup(object)
- object._widget._object = None
- object._widget = None
- object._widgetHandler.Destroy()
- object._widgetHandler = None
+ object._widget._object = None
+ object._widget = None
+ object._widgetHandler.Destroy()
+ object._widgetHandler = None
- def refreshPage(self, page):
- try:
- page.__panel.Destroy()
- del page.__panel
- except AttributeError:
- pass
+ def refreshPage(self, page):
+ try:
+ page.__panel.Destroy()
+ del page.__panel
+ except AttributeError:
+ pass
- self.drawPage(page)
+ self.drawPage(page)
- def calcGridSpacing(self):
- UIwxpython.initFont(self.panel)
+ def calcGridSpacing(self):
+ UIwxpython.initFont(self.panel)
- maxWidth, maxHeight, maxDescent, maxLeading = [0,0,0,0]
+ maxWidth, maxHeight, maxDescent, maxLeading = [0,0,0,0]
- checkchars = string.letters+string.digits+"-\|" + string.punctuation
- for letter in checkchars:
- width,height,descent,leading = self.panel.GetFullTextExtent(letter)
- maxWidth = maxWidth > width and maxWidth or width
- maxHeight = maxHeight > height and maxHeight or height
- maxDescent = maxDescent > descent and maxDescent or descent
- maxLeading = maxLeading > leading and maxLeading or leading
+ checkchars = string.letters+string.digits+"-\|" + string.punctuation
+ for letter in checkchars:
+ width,height,descent,leading = self.panel.GetFullTextExtent(letter)
+ maxWidth = maxWidth > width and maxWidth or width
+ maxHeight = maxHeight > height and maxHeight or height
+ maxDescent = maxDescent > descent and maxDescent or descent
+ maxLeading = maxLeading > leading and maxLeading or leading
- self.charWidth = maxWidth+maxLeading
- self.charHeight = maxHeight+maxDescent
+ self.charWidth = maxWidth+maxLeading
+ self.charHeight = maxHeight+maxDescent
- self.borderPercentage = (float(gConfig('borderPercentage',
section='designer')) / 100)
- self.textPercentage = (float(gConfig('textPercentage',
section='designer')) / 100)
+ self.borderPercentage = (float(gConfig('borderPercentage',
section='designer')) / 100)
+ self.textPercentage = (float(gConfig('textPercentage',
section='designer')) / 100)
- self.widgetWidth = int(self.charWidth * self.borderPercentage)
- self.widgetHeight = int(self.charHeight * self.borderPercentage) + 3
- self.textWidth = self.charWidth * self.textPercentage
- self.textHeight = self.charHeight * self.textPercentage
+ self.widgetWidth = int(self.charWidth * self.borderPercentage)
+ self.widgetHeight = int(self.charHeight * self.borderPercentage) + 3
+ self.textWidth = self.charWidth * self.textPercentage
+ self.textHeight = self.charHeight * self.textPercentage
- self.gridWidth = self.widgetWidth
- self.gridHeight = self.widgetHeight
+ self.gridWidth = self.widgetWidth
+ self.gridHeight = self.widgetHeight
- self.menu_sb_space=0 # the extra spaces needed by the menu, toolbar and
statusbar
+ self.menu_sb_space=0 # the extra spaces needed by the menu, toolbar
and statusbar
- width = self.rootObject._layout.Char__width
- height = self.rootObject._layout.Char__height
- self.panel.SetClientSize(wx.Size(int(width)*self.widgetWidth,
- int(height)*self.widgetHeight))
- self.panel.Refresh()
+ width = self.rootObject._layout.Char__width
+ height = self.rootObject._layout.Char__height
+ self.panel.SetClientSize(wx.Size(int(width)*self.widgetWidth,
+ int(height)*self.widgetHeight))
+ self.panel.Refresh()
- def drawPage(self, page):
- self._currentSelection = []
- self.page = page
+ def drawPage(self, page):
+ self._currentSelection = []
+ self.page = page
- try:
- self.panel = self.page.__panel
- except AttributeError:
- self.panel = GridPane(self, self.workspace, wx.Point(10,12))
+ try:
+ self.panel = self.page.__panel
+ except AttributeError:
+ self.panel = GridPane(self, self.workspace, wx.Point(10,12))
- # Automatically resize workspace
- wx.EVT_SIZE(self.panel, self.__OnGridSize)
+ # Automatically resize workspace
+ wx.EVT_SIZE(self.panel, self.__OnGridSize)
- # We are a drop target for Drag-and-Drop
- self.panel.SetDropTarget(DisplayDropTarget(self))
+ # We are a drop target for Drag-and-Drop
+ self.panel.SetDropTarget(DisplayDropTarget(self))
# self.panel.SetDropTarget(SchemaDropTarget(self))
- self.page.__panel = self.panel
- self.panelColor = self.panel.GetBackgroundColour()
- self.panelGridColor = wx.Colour(order(255,self.panelColor.Red()+16)[0],
- order(255,self.panelColor.Green()+16)[0],
- order(255,self.panelColor.Blue()+16)[0])
+ self.page.__panel = self.panel
+ self.panelColor = self.panel.GetBackgroundColour()
+ self.panelGridColor =
wx.Colour(order(255,self.panelColor.Red()+16)[0],
+ order(255,self.panelColor.Green()+16)[0],
+ order(255,self.panelColor.Blue()+16)[0])
- page.__pointSize = UIwxpython.getPointSize()
- self.calcGridSpacing()
+ page.__pointSize = UIwxpython.getPointSize()
+ self.calcGridSpacing()
- page.walk(self.__drawItem)
+ page.walk(self.__drawItem)
### coverPanel = TransparentPanel(self, self.panel)
- wx.EVT_CHAR(self.panel, self.keyTrap)
- wx.EVT_LEFT_DOWN(self.panel, self.OnLeftDown)
- wx.EVT_MOTION(self.panel, self.OnMotion)
- wx.EVT_LEFT_UP(self.panel, self.OnLeftUp)
- wx.EVT_RIGHT_UP(self.panel, self.OnRightUp)
+ wx.EVT_CHAR(self.panel, self.keyTrap)
+ wx.EVT_LEFT_DOWN(self.panel, self.OnLeftDown)
+ wx.EVT_MOTION(self.panel, self.OnMotion)
+ wx.EVT_LEFT_UP(self.panel, self.OnLeftUp)
+ wx.EVT_RIGHT_UP(self.panel, self.OnRightUp)
- def __drawItem(self, object):
- if self.widgets.has_key(object._type) and \
- (not hasattr(object, 'hidden') or not object.hidden):
- if hasattr(object, 'name'):
- assert gDebug(7, 'Drawing item %s of type %s' % (object.name,
object._type))
- else:
- assert gDebug(7, 'Drawing item of type %s' % (object._type))
- object._widgetHandler = WidgetHandler(self, object)
+ def __drawItem(self, object):
+ if self.widgets.has_key(object._type) and \
+ (not hasattr(object, 'hidden') or not object.hidden):
+ if hasattr(object, 'name'):
+ assert gDebug(7, 'Drawing item %s of type %s' % (object.name,
object._type))
+ else:
+ assert gDebug(7, 'Drawing item of type %s' % (object._type))
+ object._widgetHandler = WidgetHandler(self, object)
- cevent = Event('CreateUIWidget',None,
- parent=None,
- object=object,
- container=self.panel,
- textWidth=self.textWidth,
- textHeight=self.textHeight,
- widgetWidth=self.widgetWidth,
- widgetHeight=self.widgetHeight,
- interface=self,
- eventHandler=None,
- ui=self,
- initialize=0)
+ cevent = Event('CreateUIWidget',None,
+ parent=None,
+ object=object,
+ container=self.panel,
+ textWidth=self.textWidth,
+ textHeight=self.textHeight,
+ widgetWidth=self.widgetWidth,
+ widgetHeight=self.widgetHeight,
+ interface=self,
+ eventHandler=None,
+ ui=self,
+ initialize=0)
- object._widget = widget =
self.widgets[object._type].configuration['baseClass'](cevent)
+ object._widget = widget =
self.widgets[object._type].configuration['baseClass'](cevent)
- # TODO: This segfaults us... yay!!!
- widget.phaseInit(widget._buildObject())
+ # TODO: This segfaults us... yay!!!
+ widget.phaseInit(widget._buildObject())
- object._widget._object = object
- object._widgetHandler.initialize(object._widget)
- self.widgetList.append(object)
+ object._widget._object = object
+ object._widgetHandler.initialize(object._widget)
+ self.widgetList.append(object)
- def __redrawItem(self, object):
- object._widgetHandler.Destroy()
- self.widgetList.remove(object)
- self.__drawItem(object)
- object._widgetHandler.setSelected(1)
+ def __redrawItem(self, object):
+ object._widgetHandler.Destroy()
+ self.widgetList.remove(object)
+ self.__drawItem(object)
+ object._widgetHandler.setSelected(1)
- def OnSize(self, event):
- self.workspacescroll.SetSize(wx.Size(self.GetClientSize().x-8,
self.GetClientSize().y - 8))
+ def OnSize(self, event):
+ self.workspacescroll.SetSize(wx.Size(self.GetClientSize().x-8,
self.GetClientSize().y - 8))
- def OnLeftDown(self, event):
- x, y = event.GetPositionTuple()
- self.handleLeftDown(x,y)
- event.Skip()
+ def OnLeftDown(self, event):
+ x, y = event.GetPositionTuple()
+ self.handleLeftDown(x,y)
+ event.Skip()
- def handleLeftDown(self, x, y):
- self.__drawing = 1
+ def handleLeftDown(self, x, y):
+ self.__drawing = 1
- # Save starting coordinates for cross-selection box
- self.__cx = cx = int(x / self.gridWidth)
- self.__cy = cy = int(y / self.gridHeight)
+ # Save starting coordinates for cross-selection box
+ self.__cx = cx = int(x / self.gridWidth)
+ self.__cy = cy = int(y / self.gridHeight)
- self.setFeedback ('Col: %s Row: %s' % (cx, cy))
+ self.setFeedback ('Col: %s Row: %s' % (cx, cy))
- self.__brush = wx.Brush(wx.WHITE, style=wx.TRANSPARENT)
+ self.__brush = wx.Brush(wx.WHITE, style=wx.TRANSPARENT)
- self.__x = x
- self.__y = y
- self.__ox = None
- self.__oy = None
+ self.__x = x
+ self.__y = y
+ self.__ox = None
+ self.__oy = None
- # Used by the dragging routines to draw a selection box
- def xorBox(self, x1, y1, x2, y2, x3=None, y3=None):
- dc = wx.ClientDC(self.panel)
- dc.SetBrush(self.__brush)
- dc.SetPen(wx.GREY_PEN)
- dc.SetLogicalFunction(wx.XOR)
+ # Used by the dragging routines to draw a selection box
+ def xorBox(self, x1, y1, x2, y2, x3=None, y3=None):
+ dc = wx.ClientDC(self.panel)
+ dc.SetBrush(self.__brush)
+ dc.SetPen(wx.GREY_PEN)
+ dc.SetLogicalFunction(wx.XOR)
- if x3 != None:
- dc.DrawRectangle(x1,y1,x3-x1,y3-y1)
+ if x3 != None:
+ dc.DrawRectangle(x1,y1,x3-x1,y3-y1)
- dc.DrawRectangle(x1,y1,x2-x1,y2-y1)
+ dc.DrawRectangle(x1,y1,x2-x1,y2-y1)
- def OnMotion(self, event):
- # draw cross-selection box
- if self.__drawing and event.LeftIsDown():
+ def OnMotion(self, event):
+ # draw cross-selection box
+ if self.__drawing and event.LeftIsDown():
- if self.__drawing == 1:
- self.panel.SetCursor(wx.CROSS_CURSOR)
- self.__drawing = 2
+ if self.__drawing == 1:
+ self.panel.SetCursor(wx.CROSS_CURSOR)
+ self.__drawing = 2
- x, y = event.GetPositionTuple()
- cx = int(x / self.gridWidth)
- cy = int(y / self.gridHeight)
+ x, y = event.GetPositionTuple()
+ cx = int(x / self.gridWidth)
+ cy = int(y / self.gridHeight)
- cx1, cx2 = order(self.__cx, cx)
- cy1, cy2 = order(self.__cy, cy)
+ cx1, cx2 = order(self.__cx, cx)
+ cy1, cy2 = order(self.__cy, cy)
- self.setFeedback('Col: %s Row: %s Width: %s Height: %s'% (cx1,
cy1, cx2 - cx1 + 1, cy2 - cy1 + 1))
+ self.setFeedback('Col: %s Row: %s Width: %s Height: %s'%
(cx1, cy1, cx2 - cx1 + 1, cy2 - cy1 + 1))
- self.xorBox(self.__x, self.__y, x, y, self.__ox, self.__oy)
+ self.xorBox(self.__x, self.__y, x, y, self.__ox, self.__oy)
- self.__ox = x
- self.__oy = y
+ self.__ox = x
+ self.__oy = y
- event.Skip()
+ event.Skip()
- def OnLeftUp(self, event):
- x, y = event.GetPositionTuple()
- self.handleLeftUp(x,y)
- event.Skip()
+ def OnLeftUp(self, event):
+ x, y = event.GetPositionTuple()
+ self.handleLeftUp(x,y)
+ event.Skip()
- def handleLeftUp(self, x, y):
- selection = []
+ def handleLeftUp(self, x, y):
+ selection = []
- self.setFeedback('')
+ self.setFeedback('')
- if self.__drawing and self.__ox is not None:
+ if self.__drawing and self.__ox is not None:
- self.xorBox(self.__x, self.__y, self.__ox, self.__oy)
- self.__ox = None
- self.__oy = None
+ self.xorBox(self.__x, self.__y, self.__ox, self.__oy)
+ self.__ox = None
+ self.__oy = None
- self.__drawing = 0
+ self.__drawing = 0
- # Set x1,y1 to be smaller coordinates, and x2,y2 to be larger
- x1, x2 = order(int(self.__x / self.gridWidth), int(x / self.gridWidth))
- y1, y2 = order(int(self.__y / self.gridHeight),int(y / self.gridHeight))
+ # Set x1,y1 to be smaller coordinates, and x2,y2 to be larger
+ x1, x2 = order(int(self.__x / self.gridWidth), int(x / self.gridWidth))
+ y1, y2 = order(int(self.__y / self.gridHeight),int(y /
self.gridHeight))
- self.panel.SetCursor(wx.STANDARD_CURSOR)
- wx.SetCursor(wx.STANDARD_CURSOR)
+ self.panel.SetCursor(wx.STANDARD_CURSOR)
+ wx.SetCursor(wx.STANDARD_CURSOR)
- areaSelected = (x1 <> x2 or y1 <> y2)
+ areaSelected = (x1 <> x2 or y1 <> y2)
- if self.mode == 'move':
- if areaSelected:
- # We are selecting an area
- self.page.walk(self.selectWidgetInArea, x1, y1, x2, y2, selection)
- try:
- object = selection[-1]
- except IndexError:
- object = self.page
- self.dispatchEvent('ObjectSelected',
- object = object,
- originator = "Forms::LayoutEditor",
- selection = selection)
- else:
- self.dispatchEvent('ObjectSelected',
- object = self.page,
- originator = "Forms::LayoutEditor")
+ if self.mode == 'move':
+ if areaSelected:
+ # We are selecting an area
+ self.page.walk(self.selectWidgetInArea, x1, y1, x2, y2,
selection)
+ try:
+ object = selection[-1]
+ except IndexError:
+ object = self.page
+ self.dispatchEvent('ObjectSelected',
+ object = object,
+ originator = "Forms::LayoutEditor",
+ selection = selection)
+ else:
+ self.dispatchEvent('ObjectSelected',
+ object = self.page,
+ originator = "Forms::LayoutEditor")
- elif self.mode == 'positioning':
+ elif self.mode == 'positioning':
- if areaSelected:
- width = x2 - x1 + 1
- height = y2 - y1 + 1
- else:
- width = None
- height = None
+ if areaSelected:
+ width = x2 - x1 + 1
+ height = y2 - y1 + 1
+ else:
+ width = None
+ height = None
- wx.FutureCall(100,self.endPrePositioningTemplate,x1,y1,width,height)
+
wx.FutureCall(100,self.endPrePositioningTemplate,x1,y1,width,height)
- def selectWidgetInArea(self, object, x1, y1, x2, y2, selection):
- try:
- if x1 <= object.Char__x <= x2 and \
- y1 <= object.Char__y <= y2:
- if object not in selection:
- selection.append(object)
- except AttributeError:
- # Not all child objects have coordinates (x,y)
- pass
+ def selectWidgetInArea(self, object, x1, y1, x2, y2, selection):
+ try:
+ if x1 <= object.Char__x <= x2 and \
+ y1 <= object.Char__y <= y2:
+ if object not in selection:
+ selection.append(object)
+ except AttributeError:
+ # Not all child objects have coordinates (x,y)
+ pass
- def OnRightUp(self, event):
+ def OnRightUp(self, event):
## self.toolbar.resetTool(self.mode)
- self.mode = 'move'
- self.dispatchEvent('LayoutEditor:Select')
+ self.mode = 'move'
+ self.dispatchEvent('LayoutEditor:Select')
- x, y = event.GetPositionTuple()
+ x, y = event.GetPositionTuple()
- x = int(x / self.gridWidth)
- y = int(y / self.gridHeight)
+ x = int(x / self.gridWidth)
+ y = int(y / self.gridHeight)
- menu = wx.Menu('Layout Editor')
- form = self._currentObject._type == 'GFForm' and self._currentObject or \
- self._currentObject.findParentOfType('GFForm')
- page = self._currentObject._type == 'GFPage' and self._currentObject or \
- self._currentObject.findParentOfType('GFPage')
- block = self._currentObject._type == 'GFBlock' and self._currentObject or \
- self._currentObject.findParentOfType('GFBlock')
+ menu = wx.Menu('Layout Editor')
+ form = self._currentObject._type == 'GFForm' and self._currentObject
or \
+ self._currentObject.findParentOfType('GFForm')
+ page = self._currentObject._type == 'GFPage' and self._currentObject
or \
+ self._currentObject.findParentOfType('GFPage')
+ block = self._currentObject._type == 'GFBlock' and self._currentObject
or \
+ self._currentObject.findParentOfType('GFBlock')
- menu.AppendMenu(wx.NewId(), 'Form', PageMenu(self.document, form, x, y))
- if page:
- menu.AppendMenu(wx.NewId(), page.name, PageMenu(self.document, page, x,
y))
- if block:
- menu.AppendMenu(wx.NewId(), block.name, PageMenu(self.document, block,
x, y))
+ menu.AppendMenu(wx.NewId(), 'Form', PageMenu(self.document, form, x,
y))
+ if page:
+ menu.AppendMenu(wx.NewId(), page.name, PageMenu(self.document,
page, x, y))
+ if block:
+ menu.AppendMenu(wx.NewId(), block.name, PageMenu(self.document,
block, x, y))
- self.panel.PopupMenu(menu, event.GetPosition())
+ self.panel.PopupMenu(menu, event.GetPosition())
- def keyTrap(self, event):
- if event.KeyCode() in (wx.WXK_LEFT,wx.WXK_RIGHT,wx.WXK_UP,wx.WXK_DOWN) and
\
- len(self._currentSelection):
- if event.AltDown() or event.ControlDown() or event.ShiftDown():
- # caution: event.MetaDown() is always True on some architectures
- resize = None
- if event.KeyCode() == wx.WXK_LEFT:
- resize = (-1,0)
- if event.KeyCode() == wx.WXK_RIGHT:
- resize = (1,0)
- if event.KeyCode() == wx.WXK_UP:
- resize = (0,-1)
- if event.KeyCode() == wx.WXK_DOWN:
- resize = (0,1)
- if resize:
- self.dispatchEvent('BeginUndoGroup')
- for widget in self._currentSelection:
- widget._widgetHandler.relativeResize(*resize)
- self.dispatchEvent('EndUndoGroup')
- else:
- pos = None
- if event.KeyCode() == wx.WXK_LEFT:
- pos = (-1,0)
- if event.KeyCode() == wx.WXK_RIGHT:
- pos = (1,0)
- if event.KeyCode() == wx.WXK_UP:
- pos = (0,-1)
- if event.KeyCode() == wx.WXK_DOWN:
- pos = (0,1)
+ def keyTrap(self, event):
+ if event.KeyCode() in (wx.WXK_LEFT,wx.WXK_RIGHT,wx.WXK_UP,wx.WXK_DOWN)
and \
+ len(self._currentSelection):
+ if event.AltDown() or event.ControlDown() or event.ShiftDown():
+ # caution: event.MetaDown() is always True on some
architectures
+ resize = None
+ if event.KeyCode() == wx.WXK_LEFT:
+ resize = (-1,0)
+ if event.KeyCode() == wx.WXK_RIGHT:
+ resize = (1,0)
+ if event.KeyCode() == wx.WXK_UP:
+ resize = (0,-1)
+ if event.KeyCode() == wx.WXK_DOWN:
+ resize = (0,1)
+ if resize:
+ self.dispatchEvent('BeginUndoGroup')
+ for widget in self._currentSelection:
+ widget._widgetHandler.relativeResize(*resize)
+ self.dispatchEvent('EndUndoGroup')
+ else:
+ pos = None
+ if event.KeyCode() == wx.WXK_LEFT:
+ pos = (-1,0)
+ if event.KeyCode() == wx.WXK_RIGHT:
+ pos = (1,0)
+ if event.KeyCode() == wx.WXK_UP:
+ pos = (0,-1)
+ if event.KeyCode() == wx.WXK_DOWN:
+ pos = (0,1)
- if pos:
- self.dispatchEvent('BeginUndoGroup')
- for widget in self._currentSelection:
- if widget._type != 'GFPage':
- widget._widgetHandler.relativeMove(*pos)
- self.dispatchEvent('EndUndoGroup')
+ if pos:
+ self.dispatchEvent('BeginUndoGroup')
+ for widget in self._currentSelection:
+ if widget._type != 'GFPage':
+ widget._widgetHandler.relativeMove(*pos)
+ self.dispatchEvent('EndUndoGroup')
- elif event.KeyCode() == wx.WXK_DELETE and \
- len(self._currentSelection):
- self.dispatchEvent('BeginUndoGroup')
- for object in self._currentSelection:
- if object._type != 'GFPage':
- self.dispatchEvent('ObjectDeleted', object=object,
- originator=self)
- self.dispatchEvent('EndUndoGroup')
- elif event.KeyCode() == wx.WXK_TAB:
- if event.ShiftDown():
- object = self._currentObject
- if hasattr(object,'_widgetHandler') and not object._type == 'GFPage':
- i = object.getParent ()._children.index(object)
- lst = object.getParent ()._children[i:] + object.getParent
()._children[:i]
- else:
- lst = self.page._children[:]
- lst.reverse()
- for newobj in lst:
- if hasattr(newobj,'_widgetHandler'):
- self.document.dispatchEvent('ObjectSelected',
- originator=None,
- object=newobj)
- break
- elif not event.ControlDown() and not event.AltDown():
- object = self._currentObject
- if hasattr(object,'_widgetHandler') and not object._type == 'GFPage':
- i = object.getParent ()._children.index(object)
- lst = object.getParent ()._children[i+1:] + object.getParent
()._children[:i+1]
- else:
- lst = self.page._children[:]
- for newobj in lst:
- if hasattr(newobj,'_widgetHandler'):
- self.document.dispatchEvent('ObjectSelected',
- originator=None,
- object=newobj)
- break
+ elif event.KeyCode() == wx.WXK_DELETE and \
+ len(self._currentSelection):
+ self.dispatchEvent('BeginUndoGroup')
+ for object in self._currentSelection:
+ if object._type != 'GFPage':
+ self.dispatchEvent('ObjectDeleted', object=object,
+ originator=self)
+ self.dispatchEvent('EndUndoGroup')
+ elif event.KeyCode() == wx.WXK_TAB:
+ if event.ShiftDown():
+ object = self._currentObject
+ if hasattr(object,'_widgetHandler') and not object._type ==
'GFPage':
+ i = object.getParent ()._children.index(object)
+ lst = object.getParent ()._children[i:] + object.getParent
()._children[:i]
+ else:
+ lst = self.page._children[:]
+ lst.reverse()
+ for newobj in lst:
+ if hasattr(newobj,'_widgetHandler'):
+ self.document.dispatchEvent('ObjectSelected',
+ originator=None,
+ object=newobj)
+ break
+ elif not event.ControlDown() and not event.AltDown():
+ object = self._currentObject
+ if hasattr(object,'_widgetHandler') and not object._type ==
'GFPage':
+ i = object.getParent ()._children.index(object)
+ lst = object.getParent ()._children[i+1:] +
object.getParent ()._children[:i+1]
+ else:
+ lst = self.page._children[:]
+ for newobj in lst:
+ if hasattr(newobj,'_widgetHandler'):
+ self.document.dispatchEvent('ObjectSelected',
+ originator=None,
+ object=newobj)
+ break
- def zoomIn(self, event):
- size = UIwxpython.getPointSize()
- if size < 72:
- size = size + 1 # int(size * 1.05 + .5)
- UIwxpython.setPointSize(size)
- self.calcGridSpacing()
- self.refreshPage(self.page)
- self.setFeedback(u_('Adjusting base point size to %spt') % size)
- else:
- self.setFeedback(u_('Cannot adjust point size to more than 72pt'))
+ def zoomIn(self, event):
+ size = UIwxpython.getPointSize()
+ if size < 72:
+ size = size + 1 # int(size * 1.05 + .5)
+ UIwxpython.setPointSize(size)
+ self.calcGridSpacing()
+ self.refreshPage(self.page)
+ self.setFeedback(u_('Adjusting base point size to %spt') % size)
+ else:
+ self.setFeedback(u_('Cannot adjust point size to more than 72pt'))
- def zoomOut(self, event):
- size = UIwxpython.getPointSize()
- if size > 6:
- size = size - 1 # int(size * -1.05)
- UIwxpython.setPointSize(size)
- self.calcGridSpacing()
- self.refreshPage(self.page)
- self.setFeedback(u_('Adjusting base point size to %spt') % size)
- else:
- self.setFeedback(u_('Cannot adjust point size to less than 6pt'))
+ def zoomOut(self, event):
+ size = UIwxpython.getPointSize()
+ if size > 6:
+ size = size - 1 # int(size * -1.05)
+ UIwxpython.setPointSize(size)
+ self.calcGridSpacing()
+ self.refreshPage(self.page)
+ self.setFeedback(u_('Adjusting base point size to %spt') % size)
+ else:
+ self.setFeedback(u_('Cannot adjust point size to less than 6pt'))
- def beginPrePositioningTemplate(self, event):
- mode = self.mode
- self.mode = 'positioning'
- if mode == 'move':
- self.dispatchEvent('Cancel:LayoutEditor:Select')
- elif mode == 'refocus':
- self.dispatchEvent('Cancel:LayoutEditor:FocusOrder')
+ def beginPrePositioningTemplate(self, event):
+ mode = self.mode
+ self.mode = 'positioning'
+ if mode == 'move':
+ self.dispatchEvent('Cancel:LayoutEditor:Select')
+ elif mode == 'refocus':
+ self.dispatchEvent('Cancel:LayoutEditor:FocusOrder')
- ##self.panel.SetCursor(wx.CROSS_CURSOR)
- wx.SetCursor(wx.CROSS_CURSOR)
- self.__wizardrunner = event.wizardrunner
+ ##self.panel.SetCursor(wx.CROSS_CURSOR)
+ wx.SetCursor(wx.CROSS_CURSOR)
+ self.__wizardrunner = event.wizardrunner
- def cancelPrePositioningTemplate(self, event=None):
- if self.mode == 'prepositioning':
- self.__wizardrunner.cancel()
- wx.SetCursor(wx.STANDARD_CURSOR)
+ def cancelPrePositioningTemplate(self, event=None):
+ if self.mode == 'prepositioning':
+ self.__wizardrunner.cancel()
+ wx.SetCursor(wx.STANDARD_CURSOR)
- def endPrePositioningTemplate(self, x, y, width=None, height=None):
- self.mode = 'move'
- self.dispatchEvent('Cancel:LayoutEditor:Prepositioning')
- self.dispatchEvent('LayoutEditor:Select')
- self.__wizardrunner.positioned_run(x=x, y=y, width=width, height=height)
+ def endPrePositioningTemplate(self, x, y, width=None, height=None):
+ self.mode = 'move'
+ self.dispatchEvent('Cancel:LayoutEditor:Prepositioning')
+ self.dispatchEvent('LayoutEditor:Select')
+ self.__wizardrunner.positioned_run(x=x, y=y, width=width,
height=height)
- def onAutoArrange(self, event):
- self.dispatchEvent('LayoutEditor:FocusOrder')
- self.reorderfocus.autoArrange()
+ def onAutoArrange(self, event):
+ self.dispatchEvent('LayoutEditor:FocusOrder')
+ self.reorderfocus.autoArrange()
- def beginFocusOrder(self, event):
- mode = self.mode
- self.mode = 'refocus'
- if mode == 'move':
- event.dispatchAfter('Cancel:LayoutEditor:Select')
- elif mode == 'positioning':
- self.__wizardrunner.cancel()
- # Yes, you are reading this right...
- # I'm triggering the exact event that
- # triggered this method. Blame it on
- # the Tuesday night atmospheric crack
- # levels.
- self.dispatchEvent('LayoutEditor:FocusOrder')
- return
+ def beginFocusOrder(self, event):
+ mode = self.mode
+ self.mode = 'refocus'
+ if mode == 'move':
+ event.dispatchAfter('Cancel:LayoutEditor:Select')
+ elif mode == 'positioning':
+ self.__wizardrunner.cancel()
+ # Yes, you are reading this right...
+ # I'm triggering the exact event that
+ # triggered this method. Blame it on
+ # the Tuesday night atmospheric crack
+ # levels.
+ self.dispatchEvent('LayoutEditor:FocusOrder')
+ return
- self.reorderfocus.start(self.page)
+ self.reorderfocus.start(self.page)
- def endFocusOrder(self, event):
- self.reorderfocus.end()
- if self.mode == 'refocus':
- self.mode = 'move'
- self.dispatchEvent('LayoutEditor:Select')
+ def endFocusOrder(self, event):
+ self.reorderfocus.end()
+ if self.mode == 'refocus':
+ self.mode = 'move'
+ self.dispatchEvent('LayoutEditor:Select')
- def beginSelectMode(self, event=None):
- mode = self.mode
- self.mode = 'move'
- if mode == 'refocus':
- self.dispatchEvent('Cancel:LayoutEditor:FocusOrder')
- elif mode == 'positioning':
- self.dispatchEvent('Cancel:LayoutEditor:Prepositioning')
+ def beginSelectMode(self, event=None):
+ mode = self.mode
+ self.mode = 'move'
+ if mode == 'refocus':
+ self.dispatchEvent('Cancel:LayoutEditor:FocusOrder')
+ elif mode == 'positioning':
+ self.dispatchEvent('Cancel:LayoutEditor:Prepositioning')
- def cancelSelectMode(self, event=None):
- if self.mode == 'move':
- event.dispatchAfter('LayoutEditor:Select')
+ def cancelSelectMode(self, event=None):
+ if self.mode == 'move':
+ event.dispatchAfter('LayoutEditor:Select')
- def endWizard(self, event=None):
- mode = self.mode
- self.mode = 'move'
- if mode == 'refocus':
- self.dispatchEvent('Cancel:LayoutEditor:FocusOrder')
- elif mode == 'positioning':
- self.dispatchEvent('Cancel:LayoutEditor:Prepositioning')
- self.dispatchEvent('LayoutEditor:Select')
+ def endWizard(self, event=None):
+ mode = self.mode
+ self.mode = 'move'
+ if mode == 'refocus':
+ self.dispatchEvent('Cancel:LayoutEditor:FocusOrder')
+ elif mode == 'positioning':
+ self.dispatchEvent('Cancel:LayoutEditor:Prepositioning')
+ self.dispatchEvent('LayoutEditor:Select')
- def onRightDown(self, event):
- """
- Show "Add page" popup menu
- """
- pt = event.GetPositionTuple()
- wx.PyTypeCast(event.GetEventObject(),'wx.Window') \
- .PopupMenu(self.page._popupMenu, pt)
- event.Skip()
+ def onRightDown(self, event):
+ """
+ Show "Add page" popup menu
+ """
+ pt = event.GetPositionTuple()
+ wx.PyTypeCast(event.GetEventObject(),'wx.Window') \
+ .PopupMenu(self.page._popupMenu, pt)
+ event.Skip()
class TransparentPanel:
- def __init__(self, layoutEditor, parent):
- self.parent = parent
- self.editor = layoutEditor
- self.bitmap = wx.EmptyBitmap(*self.parent.GetClientSizeTuple())
+ def __init__(self, layoutEditor, parent):
+ self.parent = parent
+ self.editor = layoutEditor
+ self.bitmap = wx.EmptyBitmap(*self.parent.GetClientSizeTuple())
class TransparentPanelXXXX(wx.Window):
- def __init__(self, layoutEditor, parent):
- wx.Window.__init__(self, parent, -1, pos=wx.Point(0,0),
size=parent.GetClientSize())
+ def __init__(self, layoutEditor, parent):
+ wx.Window.__init__(self, parent, -1, pos=wx.Point(0,0),
size=parent.GetClientSize())
# wx.EVT_PAINT(self, self.OnPaint)
- wx.EVT_ERASE_BACKGROUND(self, self.OnEraseBackground)
+ wx.EVT_ERASE_BACKGROUND(self, self.OnEraseBackground)
# parent.Refresh()
- def OnEraseBackground(self, event):
- print "Painting"
- pass
+ def OnEraseBackground(self, event):
+ print "Painting"
+ pass
- def OnPaint(self, event):
- object = wx.PyTypeCast(event.GetEventObject(),'wx.Window')
- dc = wx.PaintDC(object)
- dc.BeginDrawing()
- dc.SetBackgroundMode(wx.TRANSPARENT)
- dc.SetClippingRegion(5,5,10,50)
+ def OnPaint(self, event):
+ object = wx.PyTypeCast(event.GetEventObject(),'wx.Window')
+ dc = wx.PaintDC(object)
+ dc.BeginDrawing()
+ dc.SetBackgroundMode(wx.TRANSPARENT)
+ dc.SetClippingRegion(5,5,10,50)
##
dc.SetBackground(wx.Brush(self.parent.GetBackgroundColour(),wx.TRANSPARENT))
## dc.SetBackground(wx.Brush(wx.BLACK,wx.TRANSPARENT))
@@ -855,7 +855,4 @@
## if self.focused:
## dc.DrawRectangle(1,1,x1-2,y1-2)
- dc.EndDrawing()
-
-
-
+ dc.EndDrawing()
Modified: trunk/gnue-designer/src/forms/LayoutEditor/LayoutEditorTools.py
===================================================================
--- trunk/gnue-designer/src/forms/LayoutEditor/LayoutEditorTools.py
2006-04-03 19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/forms/LayoutEditor/LayoutEditorTools.py
2006-04-03 19:56:14 UTC (rev 8344)
@@ -49,62 +49,61 @@
class LayoutEditorTools(BaseToolBar):
- def init(self):
- self.registerEventListeners( {'BeginWizard' : self.onBeginWizard,
- 'EndWizard' : self.onEndWizard,
- 'LayoutEditor:Select': self.onSelect,
- 'LayoutEditor:FocusOrder':self.onFocusOrder,
- 'Cancel:LayoutEditor:Select':
self.onEndSelect,
-
'Cancel:LayoutEditor:FocusOrder':self.onEndFocusOrder })
+ def init(self):
+ self.registerEventListeners( {'BeginWizard' : self.onBeginWizard,
+ 'EndWizard' : self.onEndWizard,
+ 'LayoutEditor:Select': self.onSelect,
+
'LayoutEditor:FocusOrder':self.onFocusOrder,
+ 'Cancel:LayoutEditor:Select':
self.onEndSelect,
+
'Cancel:LayoutEditor:FocusOrder':self.onEndFocusOrder })
- self.addToolbarMapping(ToolbarMapping)
- self.AddSeparator()
- self.addToolbarMapping(ToolbarMapping2)
- self.AddSeparator()
- self.AddControl(wx.StaticText(self,-1,u_("Block: ")))
- self.blockCombo = wx.ComboBox(self, -1)
- w, h = self.blockCombo.GetSizeTuple()
- self.blockCombo.SetSize((int(w*1.4), h))
+ self.addToolbarMapping(ToolbarMapping)
+ self.AddSeparator()
+ self.addToolbarMapping(ToolbarMapping2)
+ self.AddSeparator()
+ self.AddControl(wx.StaticText(self,-1,u_("Block: ")))
+ self.blockCombo = wx.ComboBox(self, -1)
+ w, h = self.blockCombo.GetSizeTuple()
+ self.blockCombo.SetSize((int(w*1.4), h))
- self.AddControl(self.blockCombo)
+ self.AddControl(self.blockCombo)
- self.onSelect(None)
+ self.onSelect(None)
- def onBeginWizard(self, event):
- try:
- self.ToggleTool(self.mapping['Wizard:%s' % event.template['BaseID']],1)
- except KeyError:
- pass
+ def onBeginWizard(self, event):
+ try:
+ self.ToggleTool(self.mapping['Wizard:%s' %
event.template['BaseID']],1)
+ except KeyError:
+ pass
- def onEndWizard(self, event):
- try:
- self.ToggleTool(self.mapping['Wizard:%s' % event.template['BaseID']],0)
- except KeyError:
- pass
+ def onEndWizard(self, event):
+ try:
+ self.ToggleTool(self.mapping['Wizard:%s' %
event.template['BaseID']],0)
+ except KeyError:
+ pass
- def onSelect(self, event):
- try:
- self.ToggleTool(self.mapping['LayoutEditor:Select'],1)
- except KeyError:
- pass
+ def onSelect(self, event):
+ try:
+ self.ToggleTool(self.mapping['LayoutEditor:Select'],1)
+ except KeyError:
+ pass
- def onFocusOrder(self, event):
- try:
- self.ToggleTool(self.mapping['LayoutEditor:FocusOrder'],1)
- except KeyError:
- pass
+ def onFocusOrder(self, event):
+ try:
+ self.ToggleTool(self.mapping['LayoutEditor:FocusOrder'],1)
+ except KeyError:
+ pass
- def onEndSelect(self, event):
- try:
- self.ToggleTool(self.mapping['LayoutEditor:Select'],0)
- except KeyError:
- pass
+ def onEndSelect(self, event):
+ try:
+ self.ToggleTool(self.mapping['LayoutEditor:Select'],0)
+ except KeyError:
+ pass
- def onEndFocusOrder(self, event):
- try:
- self.ToggleTool(self.mapping['LayoutEditor:FocusOrder'],0)
- except KeyError:
- pass
-
+ def onEndFocusOrder(self, event):
+ try:
+ self.ToggleTool(self.mapping['LayoutEditor:FocusOrder'],0)
+ except KeyError:
+ pass
Modified: trunk/gnue-designer/src/forms/LayoutEditor/PopupEditor.py
===================================================================
--- trunk/gnue-designer/src/forms/LayoutEditor/PopupEditor.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/forms/LayoutEditor/PopupEditor.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -38,47 +38,46 @@
# (if success = 1)
#
class PopupEditor(wx.TextCtrl):
- def __init__(self, panel, complete, x, y, width, height, value):
- wx.TextCtrl.__init__(self, panel, -1, pos=wx.Point(x,y),
- size=wx.Size(width,height),
- style=wx.TE_PROCESS_TAB|wx.TE_PROCESS_ENTER|wx.SIMPLE_BORDER)
- self.SetBackgroundColour(wx.Colour(255,239,176))
- self.__complete = complete
- self.SetValue(value)
- wx.EVT_CHAR(self, self.OnChar)
- wx.EVT_KILL_FOCUS(self, self.OnFocusOut)
+ def __init__(self, panel, complete, x, y, width, height, value):
+ wx.TextCtrl.__init__(self, panel, -1, pos=wx.Point(x,y),
+ size=wx.Size(width,height),
+ style=wx.TE_PROCESS_TAB|wx.TE_PROCESS_ENTER|wx.SIMPLE_BORDER)
+ self.SetBackgroundColour(wx.Colour(255,239,176))
+ self.__complete = complete
+ self.SetValue(value)
+ wx.EVT_CHAR(self, self.OnChar)
+ wx.EVT_KILL_FOCUS(self, self.OnFocusOut)
- def done(self, success):
- if self.__complete:
+ def done(self, success):
+ if self.__complete:
- self.OnFocusOut = self._dummy
+ self.OnFocusOut = self._dummy
- if success:
- self.__complete(1, self.GetValue())
- else:
- self.__complete(0)
+ if success:
+ self.__complete(1, self.GetValue())
+ else:
+ self.__complete(0)
- def OnChar(self, event):
- if event.GetKeyCode() in (wx.WXK_RETURN,wx.WXK_TAB):
- self.done(1)
+ def OnChar(self, event):
+ if event.GetKeyCode() in (wx.WXK_RETURN,wx.WXK_TAB):
+ self.done(1)
- elif event.GetKeyCode() == wx.WXK_ESCAPE:
- self.done(0)
- else:
- event.Skip()
+ elif event.GetKeyCode() == wx.WXK_ESCAPE:
+ self.done(0)
+ else:
+ event.Skip()
- def OnFocusOut(self, event):
- self.done(1)
+ def OnFocusOut(self, event):
+ self.done(1)
- def _dummy(self, event):
- event.Skip()
+ def _dummy(self, event):
+ event.Skip()
- def Destroy(self, *args, **parms):
- self.__complete = None
- wx.TextCtrl.Destroy(self, *args, **parms)
-
+ def Destroy(self, *args, **parms):
+ self.__complete = None
+ wx.TextCtrl.Destroy(self, *args, **parms)
Modified: trunk/gnue-designer/src/forms/LayoutEditor/PropertyBar.py
===================================================================
--- trunk/gnue-designer/src/forms/LayoutEditor/PropertyBar.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/forms/LayoutEditor/PropertyBar.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -34,24 +34,24 @@
#
#
class PropertyBar (wx.Panel):
- def __init__(self, parent):
- wx.Panel.__init__(self, parent, -1, style=wx.CLIP_CHILDREN)
- self.parent = parent
- self.object = None
+ def __init__(self, parent):
+ wx.Panel.__init__(self, parent, -1, style=wx.CLIP_CHILDREN)
+ self.parent = parent
+ self.object = None
# self.nameLabel = wx.StaticText(self, -1, "Current Object:",
pos=wx.Point(6,4))
# self.nameEditor = wx.TextCtrl(self, -1,
# pos=calcRelPos(self.nameLabel, dx=6, absy=4))
# self.nameEditor.SetEditable(0)
- self.blockLabel = wx.StaticText(self, -1, "Current Block:",
- pos=wx.Point(6,4))
+ self.blockLabel = wx.StaticText(self, -1, "Current Block:",
+ pos=wx.Point(6,4))
# pos=calcRelPos(self.nameEditor, dx=6, absy=4))
- self.blockEditor = wx.ComboBox(self, -1,
- pos=calcRelPos(self.blockLabel, dx=6, absy=4))
+ self.blockEditor = wx.ComboBox(self, -1,
+ pos=calcRelPos(self.blockLabel, dx=6, absy=4))
- self.SetSize((100,8 + max(self.blockEditor.GetSizeTuple()[1],
-# self.nameEditor.GetSizeTuple()[1],
- self.blockLabel.GetSizeTuple()[1])))
+ self.SetSize((100,8 + max(self.blockEditor.GetSizeTuple()[1],
+ # self.nameEditor.GetSizeTuple()[1],
+ self.blockLabel.GetSizeTuple()[1])))
## self.typeLabel = wx.StaticText(self, -1, "Class:",
## pos=calcRelPos(self.nameEditor, absx=4, dy=8))
@@ -92,97 +92,96 @@
## wx.EVT_SPINCTRL(self, self.hEditor.GetId(), self.OnHeightUpdated)
- def OnNameUpdated(self, event):
- self.object.name = self.nameEditor.GetValue()
+ def OnNameUpdated(self, event):
+ self.object.name = self.nameEditor.GetValue()
# self.parent._instance.onModifyObject(self.object, "Forms::LayoutEditor",
- def OnXUpdated(self, event):
- if hasattr(self.object, 'x'):
- dx = self.xEditor.GetValue() - self.object.x
- if dx:
- self.object._widgetHandler.relativeMove(dx,0)
- else:
- self.xEditor.SetValue(0)
+ def OnXUpdated(self, event):
+ if hasattr(self.object, 'x'):
+ dx = self.xEditor.GetValue() - self.object.x
+ if dx:
+ self.object._widgetHandler.relativeMove(dx,0)
+ else:
+ self.xEditor.SetValue(0)
- def OnYUpdated(self, event):
- if hasattr(self.object, 'y'):
- dy = self.yEditor.GetValue() - self.object.y
- if dy:
- self.object._widgetHandler.relativeMove(0, dy)
- else:
- self.yEditor.SetValue(0)
+ def OnYUpdated(self, event):
+ if hasattr(self.object, 'y'):
+ dy = self.yEditor.GetValue() - self.object.y
+ if dy:
+ self.object._widgetHandler.relativeMove(0, dy)
+ else:
+ self.yEditor.SetValue(0)
- def OnWidthUpdated(self, event):
- if hasattr(self.object, 'width'):
- dw = self.wEditor.GetValue() - self.object.width
- if dw:
- self.object._widgetHandler.relativeResize(dw,0)
- else:
- self.wEditor.SetValue(0)
+ def OnWidthUpdated(self, event):
+ if hasattr(self.object, 'width'):
+ dw = self.wEditor.GetValue() - self.object.width
+ if dw:
+ self.object._widgetHandler.relativeResize(dw,0)
+ else:
+ self.wEditor.SetValue(0)
- def OnHeightUpdated(self, event):
- if hasattr(self.object, 'height'):
- dh = self.hEditor.GetValue() - self.object.height
- if dh:
- self.object._widgetHandler.relativeResize(0,dh)
- else:
- self.hEditor.SetValue(0)
+ def OnHeightUpdated(self, event):
+ if hasattr(self.object, 'height'):
+ dh = self.hEditor.GetValue() - self.object.height
+ if dh:
+ self.object._widgetHandler.relativeResize(0,dh)
+ else:
+ self.hEditor.SetValue(0)
- def setCurrentObject(self, object):
- self.object = object
+ def setCurrentObject(self, object):
+ self.object = object
- self.typeEditor.SetValue(object._type[2:])
+ self.typeEditor.SetValue(object._type[2:])
- if hasattr(object, 'x'):
- self.xEditor.SetValue(object.x)
+ if hasattr(object, 'x'):
+ self.xEditor.SetValue(object.x)
# self.xEditor.SetEditable(1)
- else:
- self.xEditor.SetValue(0)
+ else:
+ self.xEditor.SetValue(0)
# self.xEditor.SetEditable(0)
- if hasattr(object, 'y'):
- self.yEditor.SetValue(object.y)
+ if hasattr(object, 'y'):
+ self.yEditor.SetValue(object.y)
# self.yEditor.SetEditable(1)
- else:
- self.yEditor.SetValue(0)
+ else:
+ self.yEditor.SetValue(0)
# self.yEditor.SetEditable(0)
- if hasattr(object, 'width'):
- self.wEditor.SetValue(object.width)
+ if hasattr(object, 'width'):
+ self.wEditor.SetValue(object.width)
# self.wEditor.SetEditable(1)
- else:
- self.wEditor.SetValue(0)
+ else:
+ self.wEditor.SetValue(0)
# self.wEditor.SetEditable(0)
- if hasattr(object, 'height'):
- self.hEditor.SetValue(object.height)
+ if hasattr(object, 'height'):
+ self.hEditor.SetValue(object.height)
# self.hEditor.SetEditable(1)
- else:
- self.hEditor.SetValue(0)
+ else:
+ self.hEditor.SetValue(0)
# self.hEditor.SetEditable(0)
- if hasattr(object, 'name'):
- self.nameEditor.SetValue(object.name)
- self.nameEditor.SetEditable(0)
- else:
- self.nameEditor.SetValue(0)
- self.nameEditor.SetEditable(0)
+ if hasattr(object, 'name'):
+ self.nameEditor.SetValue(object.name)
+ self.nameEditor.SetEditable(0)
+ else:
+ self.nameEditor.SetValue(0)
+ self.nameEditor.SetEditable(0)
- def onModifyObject (self, event):
- raise "I have not been fixed yet!"
- if object == None:
- return
- if object == self.object:
- for modification in modifications:
- field, value = modification
- if field == 'x':
- self.xEditor.SetValue(value)
- elif field == 'y':
- self.yEditor.SetValue(value)
- elif field == 'width':
- self.wEditor.SetValue(value)
- elif field == 'height':
- self.hEditor.SetValue(value)
- elif field == 'name':
- self.nameEditor.SetValue(value)
-
+ def onModifyObject (self, event):
+ raise "I have not been fixed yet!"
+ if object == None:
+ return
+ if object == self.object:
+ for modification in modifications:
+ field, value = modification
+ if field == 'x':
+ self.xEditor.SetValue(value)
+ elif field == 'y':
+ self.yEditor.SetValue(value)
+ elif field == 'width':
+ self.wEditor.SetValue(value)
+ elif field == 'height':
+ self.hEditor.SetValue(value)
+ elif field == 'name':
+ self.nameEditor.SetValue(value)
Modified: trunk/gnue-designer/src/forms/LayoutEditor/ReorderFocus.py
===================================================================
--- trunk/gnue-designer/src/forms/LayoutEditor/ReorderFocus.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/forms/LayoutEditor/ReorderFocus.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -33,49 +33,49 @@
#
#
class ReorderFocus:
- def __init__(self, instance):
- self.document = instance
+ def __init__(self, instance):
+ self.document = instance
- def start(self, page):
- self.click = 1
- self.list = []
- self.page = page
- self.page.walk(self._buildList)
+ def start(self, page):
+ self.click = 1
+ self.list = []
+ self.page = page
+ self.page.walk(self._buildList)
- i = 1
- for tab in self.list:
- if hasattr(tab.widget, 'focusorder'):
- tab.setOrder(tab.widget.focusorder)
- else:
- tab.setOrder(i)
- i += 1
+ i = 1
+ for tab in self.list:
+ if hasattr(tab.widget, 'focusorder'):
+ tab.setOrder(tab.widget.focusorder)
+ else:
+ tab.setOrder(i)
+ i += 1
- def _buildList(self, object):
- # TODO: More intelligence
- # TODO: allow only cycling thru current block, selection, or page
- if object._type in ('GFEntry','GFButton') and
hasattr(object,'_widgetHandler'):
- self.list.append(WidgetFocusTab(self.document, object, self))
+ def _buildList(self, object):
+ # TODO: More intelligence
+ # TODO: allow only cycling thru current block, selection, or page
+ if object._type in ('GFEntry','GFButton') and
hasattr(object,'_widgetHandler'):
+ self.list.append(WidgetFocusTab(self.document, object, self))
- def end(self):
- while len(self.list):
- object = self.list.pop()
- object.close()
+ def end(self):
+ while len(self.list):
+ object = self.list.pop()
+ object.close()
- def autoArrange(self):
- self.list.sort(self.myCmp)
- i = 1
- for tab in self.list:
- tab.setOrder(i)
- i += 1
-
- def myCmp(self, a, b):
- if a.y < b.y:
- return -1
- elif a.y > b.y:
- return 1
- elif a.x < b.x:
- return -1
- elif a.x > b.x:
- return 1
- else:
- return 0
+ def autoArrange(self):
+ self.list.sort(self.myCmp)
+ i = 1
+ for tab in self.list:
+ tab.setOrder(i)
+ i += 1
+
+ def myCmp(self, a, b):
+ if a.y < b.y:
+ return -1
+ elif a.y > b.y:
+ return 1
+ elif a.x < b.x:
+ return -1
+ elif a.x > b.x:
+ return 1
+ else:
+ return 0
Modified: trunk/gnue-designer/src/forms/LayoutEditor/Utils.py
===================================================================
--- trunk/gnue-designer/src/forms/LayoutEditor/Utils.py 2006-04-03 19:53:03 UTC
(rev 8343)
+++ trunk/gnue-designer/src/forms/LayoutEditor/Utils.py 2006-04-03 19:56:14 UTC
(rev 8344)
@@ -34,31 +34,31 @@
# Convenience function for inplace sorting
#
def order(*p):
- rv = list(p) # Convert the tuple to a list
- rv.sort()
- return rv
+ rv = list(p) # Convert the tuple to a list
+ rv.sort()
+ return rv
def calcRelPos(xsource, ysource=None, absx=None, absy=None, dx=None, dy=None):
- if ysource == None:
- ysource = xsource
- x = xsource.GetPosition().x
- y = ysource.GetPosition().y
- w = xsource.GetSize().width
- h = ysource.GetSize().height
+ if ysource == None:
+ ysource = xsource
+ x = xsource.GetPosition().x
+ y = ysource.GetPosition().y
+ w = xsource.GetSize().width
+ h = ysource.GetSize().height
- if absx != None:
- x = absx
- else:
- x = x + w + dx
+ if absx != None:
+ x = absx
+ else:
+ x = x + w + dx
- if absy != None:
- y = absy
- else:
- y = y + h + dy
+ if absy != None:
+ y = absy
+ else:
+ y = y + h + dy
- return wx.Point (x,y)
+ return wx.Point (x,y)
@@ -67,10 +67,9 @@
#
class MoveDropSource(wx.DropSource):
- def __init__(self, handler, *args, **parms):
- self.__handler = handler
- wx.DropSource.__init__(self, *args, **parms)
+ def __init__(self, handler, *args, **parms):
+ self.__handler = handler
+ wx.DropSource.__init__(self, *args, **parms)
- def GiveFeedback(self, effect, scrolling=0):
- return 0
-
+ def GiveFeedback(self, effect, scrolling=0):
+ return 0
Modified: trunk/gnue-designer/src/forms/LayoutEditor/WidgetFocusTab.py
===================================================================
--- trunk/gnue-designer/src/forms/LayoutEditor/WidgetFocusTab.py
2006-04-03 19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/forms/LayoutEditor/WidgetFocusTab.py
2006-04-03 19:56:14 UTC (rev 8344)
@@ -38,42 +38,42 @@
#
#
class WidgetFocusTab:
- def __init__(self, instance, widget, container):
- self.document = instance
- panel = self.document.visualEditor.panel
- self.widget = widget
- self.container = container
- self.x, self.y = widget._widgetHandler.widget.GetPositionTuple()
+ def __init__(self, instance, widget, container):
+ self.document = instance
+ panel = self.document.visualEditor.panel
+ self.widget = widget
+ self.container = container
+ self.x, self.y = widget._widgetHandler.widget.GetPositionTuple()
# self.label = wx.StaticText(panel, -1, "0", pos=(self.x, self.y-10))
- self.label = wx.Button(panel, -1, "00", pos=(self.x-5, self.y-8),
style=wx.BU_EXACTFIT)
- self.label.SetBackgroundColour(inactiveColor)
- self.label.SetForegroundColour(textColor)
- wx.EVT_BUTTON(self.label, self.label.GetId(), self.buttonHandler)
+ self.label = wx.Button(panel, -1, "00", pos=(self.x-5, self.y-8),
style=wx.BU_EXACTFIT)
+ self.label.SetBackgroundColour(inactiveColor)
+ self.label.SetForegroundColour(textColor)
+ wx.EVT_BUTTON(self.label, self.label.GetId(), self.buttonHandler)
- def setOrder(self, position):
- self.position = position
- self.label.SetLabel("%s" % (position))
- self.widget.focusorder = position
+ def setOrder(self, position):
+ self.position = position
+ self.label.SetLabel("%s" % (position))
+ self.widget.focusorder = position
- def close(self):
- self.document = None
- self.widget = None
- self.label.Destroy()
+ def close(self):
+ self.document = None
+ self.widget = None
+ self.label.Destroy()
- def buttonHandler(self, event):
- if event.GetEventType() == wx.EVT_COMMAND_BUTTON_CLICKED:
- object = event.GetEventObject()
- clicked = int(object.GetLabel())
+ def buttonHandler(self, event):
+ if event.GetEventType() == wx.EVT_COMMAND_BUTTON_CLICKED:
+ object = event.GetEventObject()
+ clicked = int(object.GetLabel())
- if self.container.click <= len(self.container.list):
- if clicked > self.container.click:
- for focustab in self.container.list:
- lb = int(focustab.label.GetLabel())
- if lb < clicked and lb >= self.container.click:
- focustab.setOrder(lb+1)
+ if self.container.click <= len(self.container.list):
+ if clicked > self.container.click:
+ for focustab in self.container.list:
+ lb = int(focustab.label.GetLabel())
+ if lb < clicked and lb >= self.container.click:
+ focustab.setOrder(lb+1)
- self.setOrder(self.container.click)
- self.label.SetBackgroundColour(activeColor)
+ self.setOrder(self.container.click)
+ self.label.SetBackgroundColour(activeColor)
- self.container.click += 1
+ self.container.click += 1
Modified: trunk/gnue-designer/src/forms/LayoutEditor/WidgetHandler.py
===================================================================
--- trunk/gnue-designer/src/forms/LayoutEditor/WidgetHandler.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/forms/LayoutEditor/WidgetHandler.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -39,336 +39,336 @@
#
#
class WidgetHandler(wx.EvtHandler):
- def __init__(self, instance, object):
- wx.EvtHandler.__init__(self)
- self.editor = instance
- self.object = object
- self.hasFocus = 0
- self.highlightBox = WidgetHighlighter(self.editor.panel)
- self._iMoved = 0
- self._alreadySelected = 0
- self._popup_editor = None
+ def __init__(self, instance, object):
+ wx.EvtHandler.__init__(self)
+ self.editor = instance
+ self.object = object
+ self.hasFocus = 0
+ self.highlightBox = WidgetHighlighter(self.editor.panel)
+ self._iMoved = 0
+ self._alreadySelected = 0
+ self._popup_editor = None
- def initialize(self, widget):
- self.widget = widget.widgets[0]
- self.mainWidget = widget
- self.selected = 0
+ def initialize(self, widget):
+ self.widget = widget.widgets[0]
+ self.mainWidget = widget
+ self.selected = 0
- self.recalcBoundaries()
+ self.recalcBoundaries()
- for widget in self.mainWidget.widgets:
- widget.SetCursor (wx.STANDARD_CURSOR)
+ for widget in self.mainWidget.widgets:
+ widget.SetCursor (wx.STANDARD_CURSOR)
# try:
# widget.Enable(0)
# except:
# pass
- try:
- widget.SetEditable(0)
- except:
- pass
+ try:
+ widget.SetEditable(0)
+ except:
+ pass
- self.setAllChildren(wx.EVT_KEY_UP, widget, self.editor.keyTrap)
- self.setAllChildren(wx.EVT_SET_FOCUS, widget, self.focusGainedTrap)
- self.setAllChildren(wx.EVT_KILL_FOCUS, widget, self.focusLostTrap)
- self.setAllChildren(wx.EVT_LEFT_UP, widget, self.OnLeftUp)
- self.setAllChildren(wx.EVT_LEFT_DOWN, widget, self.OnLeftDown)
- self.setAllChildren(wx.EVT_RIGHT_DOWN, widget, self.OnRightDown)
- self.setAllChildren(wx.EVT_RIGHT_UP, widget, self.OnRightUp)
- self.setAllChildren(wx.EVT_MOTION, widget, self.OnMotion)
- self.setAllChildren(wx.EVT_LEFT_DCLICK, widget, self.onLeftDClick)
- self.setAllChildren(wx.EVT_KEY_UP, self.highlightBox, self.editor.keyTrap)
- self.setAllChildren(wx.EVT_SET_FOCUS, self.highlightBox,
self.focusGainedTrap)
- self.setAllChildren(wx.EVT_KILL_FOCUS, self.highlightBox,
self.focusLostTrap)
- self.setAllChildren(wx.EVT_LEFT_UP, self.highlightBox, self.OnLeftUp)
- self.setAllChildren(wx.EVT_LEFT_DOWN, self.highlightBox, self.OnLeftDown)
- self.setAllChildren(wx.EVT_RIGHT_UP, self.highlightBox, self.OnRightUp)
- self.setAllChildren(wx.EVT_MOTION, self.highlightBox, self.OnMotion)
+ self.setAllChildren(wx.EVT_KEY_UP, widget, self.editor.keyTrap)
+ self.setAllChildren(wx.EVT_SET_FOCUS, widget, self.focusGainedTrap)
+ self.setAllChildren(wx.EVT_KILL_FOCUS, widget, self.focusLostTrap)
+ self.setAllChildren(wx.EVT_LEFT_UP, widget, self.OnLeftUp)
+ self.setAllChildren(wx.EVT_LEFT_DOWN, widget, self.OnLeftDown)
+ self.setAllChildren(wx.EVT_RIGHT_DOWN, widget, self.OnRightDown)
+ self.setAllChildren(wx.EVT_RIGHT_UP, widget, self.OnRightUp)
+ self.setAllChildren(wx.EVT_MOTION, widget, self.OnMotion)
+ self.setAllChildren(wx.EVT_LEFT_DCLICK, widget, self.onLeftDClick)
+ self.setAllChildren(wx.EVT_KEY_UP, self.highlightBox,
self.editor.keyTrap)
+ self.setAllChildren(wx.EVT_SET_FOCUS, self.highlightBox,
self.focusGainedTrap)
+ self.setAllChildren(wx.EVT_KILL_FOCUS, self.highlightBox,
self.focusLostTrap)
+ self.setAllChildren(wx.EVT_LEFT_UP, self.highlightBox, self.OnLeftUp)
+ self.setAllChildren(wx.EVT_LEFT_DOWN, self.highlightBox,
self.OnLeftDown)
+ self.setAllChildren(wx.EVT_RIGHT_UP, self.highlightBox, self.OnRightUp)
+ self.setAllChildren(wx.EVT_MOTION, self.highlightBox, self.OnMotion)
- self.widget.Refresh()
+ self.widget.Refresh()
- def recalcBoundaries(self):
- x1,y1,x2,y2 = (9999999,9999999,0,0)
+ def recalcBoundaries(self):
+ x1,y1,x2,y2 = (9999999,9999999,0,0)
- for widget in self.mainWidget.widgets:
- tx, ty = widget.GetPositionTuple()
- tw, th = widget.GetSizeTuple()
- self.editor.positionMappings[widget] = [tx,ty,tx+tw-1,ty+tw-1,self]
- if tx < x1:
- x1 = tx
- if ty < y1:
- y1 = ty
- if tw + tx > x2:
- x2 = tw + tx
- if th + ty > y2:
- y2 = th + ty
+ for widget in self.mainWidget.widgets:
+ tx, ty = widget.GetPositionTuple()
+ tw, th = widget.GetSizeTuple()
+ self.editor.positionMappings[widget] = [tx,ty,tx+tw-1,ty+tw-1,self]
+ if tx < x1:
+ x1 = tx
+ if ty < y1:
+ y1 = ty
+ if tw + tx > x2:
+ x2 = tw + tx
+ if th + ty > y2:
+ y2 = th + ty
- self.highlightBox.setBoundary(x1-2,y1-2,x2+2,y2+2)
- for widget in self.mainWidget.widgets:
- widget.Refresh()
+ self.highlightBox.setBoundary(x1-2,y1-2,x2+2,y2+2)
+ for widget in self.mainWidget.widgets:
+ widget.Refresh()
- def setSelected(self, selected, focused=1):
- self.selected = selected
- self.focused = focused
- self.highlightBox.setSelected(selected, focused)
+ def setSelected(self, selected, focused=1):
+ self.selected = selected
+ self.focused = focused
+ self.highlightBox.setSelected(selected, focused)
- def setAllChildren(self, event, widget, trap):
- try:
- event(widget, trap)
- except:
- pass
- for child in widget.GetChildren():
- self.setAllChildren(event, child, trap)
+ def setAllChildren(self, event, widget, trap):
+ try:
+ event(widget, trap)
+ except:
+ pass
+ for child in widget.GetChildren():
+ self.setAllChildren(event, child, trap)
- def focusGainedTrap(self, event):
- self.editor.panel.SetFocus()
- pass
+ def focusGainedTrap(self, event):
+ self.editor.panel.SetFocus()
+ pass
# event.Skip()
- def focusLostTrap(self, event):
- event.Skip()
+ def focusLostTrap(self, event):
+ event.Skip()
- def beginDragDrop(self, event):
+ def beginDragDrop(self, event):
- # Drag and drop TODO: This needs changed to pull all selected widgets
+ # Drag and drop TODO: This needs changed to pull all selected widgets
- object = self.object
+ object = self.object
- x,y = event.GetPositionTuple()
+ x,y = event.GetPositionTuple()
- data = [ { "Type" : "selectedWidgets",
- "Attributes": {
- 'startingX': object.Char__x + int(x/self.editor.gridWidth),
- 'startingY': object.Char__y + int(y/self.editor.gridHeight),
- }
- }]
+ data = [ { "Type" : "selectedWidgets",
+ "Attributes": {
+ 'startingX': object.Char__x +
int(x/self.editor.gridWidth),
+ 'startingY': object.Char__y +
int(y/self.editor.gridHeight),
+ }
+ }]
# "name": dname,
# "table": object.name,
# "database": self.connectionName } }
#
#
- do =
wx.CustomDataObject(wx.CustomDataFormat("application/x-gnue-designer"))
- do.SetData(cPickle.dumps(data,1))
+ do =
wx.CustomDataObject(wx.CustomDataFormat("application/x-gnue-designer"))
+ do.SetData(cPickle.dumps(data,1))
## icon = FeedbackBitmap(10,10).icon()
- dropSource = MoveDropSource(self, self.editor)
- dropSource.SetData(do)
- result = dropSource.DoDragDrop(True)
- event.Skip()
+ dropSource = MoveDropSource(self, self.editor)
+ dropSource.SetData(do)
+ result = dropSource.DoDragDrop(True)
+ event.Skip()
- def OnLeftDown(self, event):
+ def OnLeftDown(self, event):
- if self.editor.mode == 'move':
+ if self.editor.mode == 'move':
- self.mouseStartX, self.mouseStartY = event.GetPositionTuple()
- self._iMoved = 0
+ self.mouseStartX, self.mouseStartY = event.GetPositionTuple()
+ self._iMoved = 0
- if event.ShiftDown():
- selections = self.editor._currentSelection[:]
- else:
- selections = []
+ if event.ShiftDown():
+ selections = self.editor._currentSelection[:]
+ else:
+ selections = []
- if self.object in selections:
- if event.ShiftDown():
- del selections[selections.index(self.object)]
- else:
- selections.append(self.object)
+ if self.object in selections:
+ if event.ShiftDown():
+ del selections[selections.index(self.object)]
+ else:
+ selections.append(self.object)
- self.editor._instance.dispatchEvent('ObjectSelected',object=self.object,
- originator="Forms::LayoutEditor",
- selection=selections)
- else:
- xo, yo = self.widget.GetPosition()
- x, y = event.GetPositionTuple()
- self.editor.handleLeftDown(x+xo,y+yo)
+
self.editor._instance.dispatchEvent('ObjectSelected',object=self.object,
+
originator="Forms::LayoutEditor",
+ selection=selections)
+ else:
+ xo, yo = self.widget.GetPosition()
+ x, y = event.GetPositionTuple()
+ self.editor.handleLeftDown(x+xo,y+yo)
- event.Skip()
+ event.Skip()
- def OnLeftUp(self, event):
- if self.editor.mode == 'move':
- if self._iMoved:
- self._iMoved = 0
- else:
- xo, yo = self.widget.GetPosition()
- x, y = event.GetPositionTuple()
- self.editor.handleLeftUp(x+xo,y+yo)
+ def OnLeftUp(self, event):
+ if self.editor.mode == 'move':
+ if self._iMoved:
+ self._iMoved = 0
+ else:
+ xo, yo = self.widget.GetPosition()
+ x, y = event.GetPositionTuple()
+ self.editor.handleLeftUp(x+xo,y+yo)
- event.Skip()
+ event.Skip()
- def OnMotion(self, event):
+ def OnMotion(self, event):
- if not self._iMoved and event.LeftIsDown():
- self._iMoved = 1
- self.beginDragDrop(event)
+ if not self._iMoved and event.LeftIsDown():
+ self._iMoved = 1
+ self.beginDragDrop(event)
- event.Skip()
+ event.Skip()
- def OnRightDown(self, event):
- event.Skip()
+ def OnRightDown(self, event):
+ event.Skip()
- def OnRightUp(self, event):
- if self.editor.mode == 'move':
- pt = event.GetPositionTuple()
- self.editor.dispatchEvent('ObjectSelected',object=self.object,
originator=None)
- wx.PyTypeCast(event.GetEventObject(),'wx.Window') \
- .PopupMenu(self.object._popupMenu, pt)
- event.Skip()
+ def OnRightUp(self, event):
+ if self.editor.mode == 'move':
+ pt = event.GetPositionTuple()
+ self.editor.dispatchEvent('ObjectSelected',object=self.object,
originator=None)
+ wx.PyTypeCast(event.GetEventObject(),'wx.Window') \
+ .PopupMenu(self.object._popupMenu, pt)
+ event.Skip()
- def _endPopupEditor(self, success, value=""):
- if success:
+ def _endPopupEditor(self, success, value=""):
+ if success:
- try:
- oldVals = {self.__popupAttr:self.object.__dict__[self.__popupAttr]}
- except KeyError:
- oldVals = {self.__popupAttr:None}
- newVals = {self.__popupAttr: value}
- self.object.__dict__.update(newVals)
- self.editor.dispatchEvent('ObjectModified', object=self.object,
- originator="Forms::LayoutEditor",
- old=oldVals,
- new=newVals)
+ try:
+ oldVals =
{self.__popupAttr:self.object.__dict__[self.__popupAttr]}
+ except KeyError:
+ oldVals = {self.__popupAttr:None}
+ newVals = {self.__popupAttr: value}
+ self.object.__dict__.update(newVals)
+ self.editor.dispatchEvent('ObjectModified', object=self.object,
+ originator="Forms::LayoutEditor",
+ old=oldVals,
+ new=newVals)
- self._popup_editor.Destroy()
- self._popup_editor = None
- self.widget.SetLabel(value or "<Unset>")
- if self.object._type == 'GFLabel':
- width = len(value) or 10
- self.widget.SetSize((width * self.editor.gridWidth,
- self.widget.GetSize().height))
- self.recalcBoundaries()
- self.setSelected(self.selected)
+ self._popup_editor.Destroy()
+ self._popup_editor = None
+ self.widget.SetLabel(value or "<Unset>")
+ if self.object._type == 'GFLabel':
+ width = len(value) or 10
+ self.widget.SetSize((width * self.editor.gridWidth,
+ self.widget.GetSize().height))
+ self.recalcBoundaries()
+ self.setSelected(self.selected)
- def onLeftDClick(self, event):
+ def onLeftDClick(self, event):
- if self.editor.mode == 'move':
- if self.object._type in ('GFBox','GFLabel'):
- # Create a popup text editor for the labels
- if self.object._type == 'GFBox':
- self.__popupAttr = 'label'
- x = self.widget.GetPosition().x + (self.editor.gridWidth/2)
- width = (self.object.Char__width - 2) * self.editor.gridWidth
- else:
- self.__popupAttr = 'text'
- x = self.widget.GetPosition().x
- width = self.widget.GetSize().width + self.editor.gridWidth
+ if self.editor.mode == 'move':
+ if self.object._type in ('GFBox','GFLabel'):
+ # Create a popup text editor for the labels
+ if self.object._type == 'GFBox':
+ self.__popupAttr = 'label'
+ x = self.widget.GetPosition().x + (self.editor.gridWidth/2)
+ width = (self.object.Char__width - 2) *
self.editor.gridWidth
+ else:
+ self.__popupAttr = 'text'
+ x = self.widget.GetPosition().x
+ width = self.widget.GetSize().width + self.editor.gridWidth
- self._popup_editor = PopupEditor(self.editor.workspace,
- self._endPopupEditor,
- x + self.editor.panel.GetPosition().x,
- self.widget.GetPosition().y + self.editor.panel.GetPosition().y,
- width,
- self.editor.gridHeight,
- self.object.__dict__[self.__popupAttr])
+ self._popup_editor = PopupEditor(self.editor.workspace,
+ self._endPopupEditor,
+ x + self.editor.panel.GetPosition().x,
+ self.widget.GetPosition().y +
self.editor.panel.GetPosition().y,
+ width,
+ self.editor.gridHeight,
+ self.object.__dict__[self.__popupAttr])
- self._popup_editor.SetFocus()
+ self._popup_editor.SetFocus()
- else:
- # Signal the Properties dialog
- self.editor._instance.dispatchEvent('Show:Tool:objectProperties')
+ else:
+ # Signal the Properties dialog
+
self.editor._instance.dispatchEvent('Show:Tool:objectProperties')
- #
- # Resize the current widget. dx and dy are incremental
- # resize units. (e.g, (-1,0) means make the widget one
- # unit smaller than it currently is.
- #
- def relativeResize(self, dx, dy):
- if not (dx or dy):
- return 0
+ #
+ # Resize the current widget. dx and dy are incremental
+ # resize units. (e.g, (-1,0) means make the widget one
+ # unit smaller than it currently is.
+ #
+ def relativeResize(self, dx, dy):
+ if not (dx or dy):
+ return 0
- nx = dx * self.editor.gridWidth
- ny = dy * self.editor.gridHeight
+ nx = dx * self.editor.gridWidth
+ ny = dy * self.editor.gridHeight
- try:
- self.object.Char__height
- except:
- self.object.Char__height = 1
+ try:
+ self.object.Char__height
+ except:
+ self.object.Char__height = 1
- if (self.object.Char__width + dx < 0 or self.object.Char__height + dy < 0):
- return 0
- else:
- for widget in self.mainWidget.widgets:
- x,y = widget.GetSizeTuple()
- widget.SetSize(wx.Size(x + nx,y + ny))
+ if (self.object.Char__width + dx < 0 or self.object.Char__height + dy
< 0):
+ return 0
+ else:
+ for widget in self.mainWidget.widgets:
+ x,y = widget.GetSizeTuple()
+ widget.SetSize(wx.Size(x + nx,y + ny))
- oldVals = {}
- newVals = {}
- if dx:
- oldVals['Char:width'] = self.object.Char__width
- self.object.Char__width = self.object.Char__width + dx
- newVals['Char:width'] = self.object.Char__width
- if dy:
- oldVals['Char:height'] = self.object.Char__height
- self.object.Char__height = self.object.Char__height + dy
- newVals['Char:height'] = self.object.Char__height
+ oldVals = {}
+ newVals = {}
+ if dx:
+ oldVals['Char:width'] = self.object.Char__width
+ self.object.Char__width = self.object.Char__width + dx
+ newVals['Char:width'] = self.object.Char__width
+ if dy:
+ oldVals['Char:height'] = self.object.Char__height
+ self.object.Char__height = self.object.Char__height + dy
+ newVals['Char:height'] = self.object.Char__height
- self.editor.dispatchEvent('ObjectModified', object=self.object,
- originator="Forms::LayoutEditor",
- old=oldVals,
- new=newVals)
+ self.editor.dispatchEvent('ObjectModified', object=self.object,
+ originator="Forms::LayoutEditor",
+ old=oldVals,
+ new=newVals)
- self.recalcBoundaries()
+ self.recalcBoundaries()
- #
- # Move the current widget. dx and dy are increments.
- # (e.g., (-1,-2) means move the object up one unit
- # and left two units.
- #
- def relativeMove(self, dx, dy):
- if not (dx or dy):
- return 0
+ #
+ # Move the current widget. dx and dy are increments.
+ # (e.g., (-1,-2) means move the object up one unit
+ # and left two units.
+ #
+ def relativeMove(self, dx, dy):
+ if not (dx or dy):
+ return 0
- nx = dx * self.editor.gridWidth
- ny = dy * self.editor.gridHeight
+ nx = dx * self.editor.gridWidth
+ ny = dy * self.editor.gridHeight
- if (self.object.Char__x + dx < 0 or self.object.Char__y + dy < 0):
- return 0
- else:
- for widget in self.mainWidget.widgets:
- x,y = widget.GetPositionTuple()
- widget.SetPosition(wx.Point(x + nx,y + ny))
- oldVals = {}
- newVals = {}
- if dx:
- oldVals['Char:x'] = self.object.Char__x
- self.object.Char__x += dx
- newVals['Char:x'] = self.object.Char__x
- if dy:
- oldVals['Char:y'] = self.object.Char__y
- self.object.Char__y += dy
- newVals['Char:y'] = self.object.Char__y
+ if (self.object.Char__x + dx < 0 or self.object.Char__y + dy < 0):
+ return 0
+ else:
+ for widget in self.mainWidget.widgets:
+ x,y = widget.GetPositionTuple()
+ widget.SetPosition(wx.Point(x + nx,y + ny))
+ oldVals = {}
+ newVals = {}
+ if dx:
+ oldVals['Char:x'] = self.object.Char__x
+ self.object.Char__x += dx
+ newVals['Char:x'] = self.object.Char__x
+ if dy:
+ oldVals['Char:y'] = self.object.Char__y
+ self.object.Char__y += dy
+ newVals['Char:y'] = self.object.Char__y
- self.editor.dispatchEvent('ObjectModified', object=self.object,
- originator="Forms::LayoutEditor",
- old=oldVals,
- new=newVals)
+ self.editor.dispatchEvent('ObjectModified', object=self.object,
+ originator="Forms::LayoutEditor",
+ old=oldVals,
+ new=newVals)
- self.recalcBoundaries()
+ self.recalcBoundaries()
- #
- # Recursively destroy this widget set
- #
- def Destroy(self):
+ #
+ # Recursively destroy this widget set
+ #
+ def Destroy(self):
- # TODO: Why the fsck can't I Destroy() this thing!?!??!?
- self.widget.Show(0)
+ # TODO: Why the fsck can't I Destroy() this thing!?!??!?
+ self.widget.Show(0)
- self.editor = None
- self.object = None
- self.highlightBox.Destroy()
- self.highlightBox = None
- self._popup_editor = None
- self.widget = None
- self.mainWidget = None
+ self.editor = None
+ self.object = None
+ self.highlightBox.Destroy()
+ self.highlightBox = None
+ self._popup_editor = None
+ self.widget = None
+ self.mainWidget = None
Modified: trunk/gnue-designer/src/forms/LayoutEditor/WidgetHighlighter.py
===================================================================
--- trunk/gnue-designer/src/forms/LayoutEditor/WidgetHighlighter.py
2006-04-03 19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/forms/LayoutEditor/WidgetHighlighter.py
2006-04-03 19:56:14 UTC (rev 8344)
@@ -38,188 +38,188 @@
#
class WidgetHighlighter:
- def __init__(self, parent):
- self.selected = 0
- self.focused = 0
- self.parent = parent
- self.x1 = 1
- self.y1 = 1
- self.x2 = 2
- self.y2 = 2
- self.west = None
- self.east = None
- self.north = None
- self.south = None
- self.westb = None
- self.eastb = None
- self.northb = None
- self.southb = None
+ def __init__(self, parent):
+ self.selected = 0
+ self.focused = 0
+ self.parent = parent
+ self.x1 = 1
+ self.y1 = 1
+ self.x2 = 2
+ self.y2 = 2
+ self.west = None
+ self.east = None
+ self.north = None
+ self.south = None
+ self.westb = None
+ self.eastb = None
+ self.northb = None
+ self.southb = None
- # Draw the lines comprising the highlights
- def createHighlights(self):
- if self.north:
- self.Destroy()
+ # Draw the lines comprising the highlights
+ def createHighlights(self):
+ if self.north:
+ self.Destroy()
- self.northb = wx.Window(self.parent, -1)
- self.southb = wx.Window(self.parent, -1)
- self.eastb = wx.Window(self.parent, -1)
- self.westb = wx.Window(self.parent, -1)
- for object in (self.northb,self.southb,self.eastb,self.westb):
- wx.EVT_PAINT(object, self.OnPaintBorder)
+ self.northb = wx.Window(self.parent, -1)
+ self.southb = wx.Window(self.parent, -1)
+ self.eastb = wx.Window(self.parent, -1)
+ self.westb = wx.Window(self.parent, -1)
+ for object in (self.northb,self.southb,self.eastb,self.westb):
+ wx.EVT_PAINT(object, self.OnPaintBorder)
- self.north = wx.Window(self.parent, -1)
- self.south = wx.Window(self.parent, -1)
- self.east = wx.Window(self.parent, -1)
- self.west = wx.Window(self.parent, -1)
- for object in (self.north,self.south,self.east,self.west):
- wx.EVT_PAINT(object, self.OnPaint)
+ self.north = wx.Window(self.parent, -1)
+ self.south = wx.Window(self.parent, -1)
+ self.east = wx.Window(self.parent, -1)
+ self.west = wx.Window(self.parent, -1)
+ for object in (self.north,self.south,self.east,self.west):
+ wx.EVT_PAINT(object, self.OnPaint)
- self.setBoundary(self.x1, self.y1, self.x2, self.y2)
+ self.setBoundary(self.x1, self.y1, self.x2, self.y2)
- # Delete the lines comprising the highlights
- def deleteHighlights(self):
- if self.west:
- self.west.Destroy()
- if self.east:
- self.east.Destroy()
- if self.north:
- self.north.Destroy()
- if self.south:
- self.south.Destroy()
- self.west = None
- self.east = None
- self.north = None
- self.south = None
+ # Delete the lines comprising the highlights
+ def deleteHighlights(self):
+ if self.west:
+ self.west.Destroy()
+ if self.east:
+ self.east.Destroy()
+ if self.north:
+ self.north.Destroy()
+ if self.south:
+ self.south.Destroy()
+ self.west = None
+ self.east = None
+ self.north = None
+ self.south = None
- if self.westb:
- self.westb.Destroy()
- if self.eastb:
- self.eastb.Destroy()
- if self.northb:
- self.northb.Destroy()
- if self.southb:
- self.southb.Destroy()
- self.westb = None
- self.eastb = None
- self.northb = None
- self.southb = None
+ if self.westb:
+ self.westb.Destroy()
+ if self.eastb:
+ self.eastb.Destroy()
+ if self.northb:
+ self.northb.Destroy()
+ if self.southb:
+ self.southb.Destroy()
+ self.westb = None
+ self.eastb = None
+ self.northb = None
+ self.southb = None
- def setBoundaryXXXXXX(self, x1, y1, x2, y2):
- self.x1 = x1
- self.y1 = y1
- self.x2 = x2
- self.y2 = y2
+ def setBoundaryXXXXXX(self, x1, y1, x2, y2):
+ self.x1 = x1
+ self.y1 = y1
+ self.x2 = x2
+ self.y2 = y2
- if self.west:
- self.west.SetPosition(wx.Point(x1,y1))
- self.west.SetSize(wx.Size(2,y2-y1+2))
- if self.east:
- self.east.SetPosition(wx.Point(x2,y1))
- self.east.SetSize(wx.Size(2,y2-y1+2))
- if self.south:
- self.south.SetPosition(wx.Point(x1,y2))
- self.south.SetSize(wx.Size(x2-x1+2,2))
- if self.north:
- self.north.SetPosition(wx.Point(x1,y1))
- self.north.SetSize(wx.Size(x2-x1+2,2))
+ if self.west:
+ self.west.SetPosition(wx.Point(x1,y1))
+ self.west.SetSize(wx.Size(2,y2-y1+2))
+ if self.east:
+ self.east.SetPosition(wx.Point(x2,y1))
+ self.east.SetSize(wx.Size(2,y2-y1+2))
+ if self.south:
+ self.south.SetPosition(wx.Point(x1,y2))
+ self.south.SetSize(wx.Size(x2-x1+2,2))
+ if self.north:
+ self.north.SetPosition(wx.Point(x1,y1))
+ self.north.SetSize(wx.Size(x2-x1+2,2))
- def setBoundary(self, x1, y1, x2, y2):
- self.x1 = x1
- self.y1 = y1
- self.x2 = x2
- self.y2 = y2
+ def setBoundary(self, x1, y1, x2, y2):
+ self.x1 = x1
+ self.y1 = y1
+ self.x2 = x2
+ self.y2 = y2
- mx = (x2 - x1)/2 + x1 - 1
- my = (y2 - y1)/2 + y1 - 1
+ mx = (x2 - x1)/2 + x1 - 1
+ my = (y2 - y1)/2 + y1 - 1
- if self.west:
- self.west.SetPosition(wx.Point(x1 - 3,my))
- self.west.SetSize(wx.Size(4,4))
- if self.east:
- self.east.SetPosition(wx.Point(x2,my))
- self.east.SetSize(wx.Size(4,4))
- if self.south:
- self.south.SetPosition(wx.Point(mx,y2))
- self.south.SetSize(wx.Size(4,4))
- if self.north:
- self.north.SetPosition(wx.Point(mx,y1 - 3))
- self.north.SetSize(wx.Size(4,4))
+ if self.west:
+ self.west.SetPosition(wx.Point(x1 - 3,my))
+ self.west.SetSize(wx.Size(4,4))
+ if self.east:
+ self.east.SetPosition(wx.Point(x2,my))
+ self.east.SetSize(wx.Size(4,4))
+ if self.south:
+ self.south.SetPosition(wx.Point(mx,y2))
+ self.south.SetSize(wx.Size(4,4))
+ if self.north:
+ self.north.SetPosition(wx.Point(mx,y1 - 3))
+ self.north.SetSize(wx.Size(4,4))
- if self.west:
- self.westb.SetPosition(wx.Point(x1,y1))
- self.westb.SetSize(wx.Size(1,y2-y1+1))
- if self.east:
- self.eastb.SetPosition(wx.Point(x2,y1))
- self.eastb.SetSize(wx.Size(1,y2-y1+1))
- if self.south:
- self.southb.SetPosition(wx.Point(x1,y2))
- self.southb.SetSize(wx.Size(x2-x1+1,1))
- if self.north:
- self.northb.SetPosition(wx.Point(x1,y1))
- self.northb.SetSize(wx.Size(x2-x1+1,1))
+ if self.west:
+ self.westb.SetPosition(wx.Point(x1,y1))
+ self.westb.SetSize(wx.Size(1,y2-y1+1))
+ if self.east:
+ self.eastb.SetPosition(wx.Point(x2,y1))
+ self.eastb.SetSize(wx.Size(1,y2-y1+1))
+ if self.south:
+ self.southb.SetPosition(wx.Point(x1,y2))
+ self.southb.SetSize(wx.Size(x2-x1+1,1))
+ if self.north:
+ self.northb.SetPosition(wx.Point(x1,y1))
+ self.northb.SetSize(wx.Size(x2-x1+1,1))
- def GetChildren(self):
- if self.west:
- return (self.north, self.south, self.east, self.west)
- else:
- return ()
+ def GetChildren(self):
+ if self.west:
+ return (self.north, self.south, self.east, self.west)
+ else:
+ return ()
- def Refresh(self):
- for object in (self.north,self.south,self.east,self.west):
- object.Refresh()
+ def Refresh(self):
+ for object in (self.north,self.south,self.east,self.west):
+ object.Refresh()
- def Destroy(self):
- self.deleteHighlights()
+ def Destroy(self):
+ self.deleteHighlights()
- def setSelected (self, selected, focused):
- if selected:
- self.selected = selected
- self.focused = focused
- self.createHighlights()
- self.Refresh()
- else:
- self.deleteHighlights()
+ def setSelected (self, selected, focused):
+ if selected:
+ self.selected = selected
+ self.focused = focused
+ self.createHighlights()
+ self.Refresh()
+ else:
+ self.deleteHighlights()
- def reconfigure(self, event):
- self.Refresh()
+ def reconfigure(self, event):
+ self.Refresh()
- def OnPaintXXXX(self, event):
- object = wx.PyTypeCast(event.GetEventObject(),'wx.Window')
- dc = wx.PaintDC(object)
- dc.BeginDrawing()
-
dc.SetBackground(wx.Brush(self.parent.GetBackgroundColour(),wx.TRANSPARENT))
- dc.Clear()
- if self.focused:
- dc.SetPen(wx.Pen(activeBorderColor))
- else:
- dc.SetPen(wx.Pen(inactiveBorderColor))
- x1,y1 = object.GetSizeTuple()
+ def OnPaintXXXX(self, event):
+ object = wx.PyTypeCast(event.GetEventObject(),'wx.Window')
+ dc = wx.PaintDC(object)
+ dc.BeginDrawing()
+
dc.SetBackground(wx.Brush(self.parent.GetBackgroundColour(),wx.TRANSPARENT))
+ dc.Clear()
+ if self.focused:
+ dc.SetPen(wx.Pen(activeBorderColor))
+ else:
+ dc.SetPen(wx.Pen(inactiveBorderColor))
+ x1,y1 = object.GetSizeTuple()
## dc.DrawRectangle(0,0,x1,y1)
## if self.focused:
## dc.DrawRectangle(1,1,x1-2,y1-2)
- dc.EndDrawing()
+ dc.EndDrawing()
- def OnPaint(self, event):
- if not self.focused: return
- object = wx.PyTypeCast(event.GetEventObject(),'wx.Window')
- dc = wx.PaintDC(object)
- dc.BeginDrawing()
+ def OnPaint(self, event):
+ if not self.focused: return
+ object = wx.PyTypeCast(event.GetEventObject(),'wx.Window')
+ dc = wx.PaintDC(object)
+ dc.BeginDrawing()
##
dc.SetBackground(wx.Brush(self.parent.GetBackgroundColour(),wx.TRANSPARENT))
- if self.focused:
- dc.SetBackground(wx.Brush(activeBorderColor,wx.TRANSPARENT))
- else:
- dc.SetBackground(wx.Brush(inactiveBorderColor,wx.TRANSPARENT))
+ if self.focused:
+ dc.SetBackground(wx.Brush(activeBorderColor,wx.TRANSPARENT))
+ else:
+ dc.SetBackground(wx.Brush(inactiveBorderColor,wx.TRANSPARENT))
- dc.Clear()
+ dc.Clear()
## if self.focused:
## dc.SetPen(wx.Pen(activeBorderColor))
## else:
@@ -229,16 +229,16 @@
## if self.focused:
## dc.DrawRectangle(1,1,x1-2,y1-2)
- dc.EndDrawing()
+ dc.EndDrawing()
- def OnPaintBorder(self, event):
- object = wx.PyTypeCast(event.GetEventObject(),'wx.Window')
- dc = wx.PaintDC(object)
- dc.BeginDrawing()
+ def OnPaintBorder(self, event):
+ object = wx.PyTypeCast(event.GetEventObject(),'wx.Window')
+ dc = wx.PaintDC(object)
+ dc.BeginDrawing()
##
dc.SetBackground(wx.Brush(self.parent.GetBackgroundColour(),wx.TRANSPARENT))
- dc.SetBackground(wx.Brush(wx.BLACK,wx.TRANSPARENT))
- dc.Clear()
+ dc.SetBackground(wx.Brush(wx.BLACK,wx.TRANSPARENT))
+ dc.Clear()
## if self.focused:
## dc.SetPen(wx.Pen(activeBorderColor))
## else:
@@ -248,8 +248,7 @@
## if self.focused:
## dc.DrawRectangle(1,1,x1-2,y1-2)
- dc.EndDrawing()
+ dc.EndDrawing()
- def OnEraseBackground(self, event):
- pass
-
+ def OnEraseBackground(self, event):
+ pass
Modified: trunk/gnue-designer/src/forms/LayoutEditor/Workspace.py
===================================================================
--- trunk/gnue-designer/src/forms/LayoutEditor/Workspace.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/forms/LayoutEditor/Workspace.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -52,63 +52,63 @@
class Workspace(wx.Panel):
- def __init__(self, parent, layouteditor, page):
+ def __init__(self, parent, layouteditor, page):
- self.scroller = scroller = wx.ScrolledWindow(parent, -1,
- pos=wx.Point(0,0),
- style=wx.CLIP_CHILDREN|wx.HSCROLL|wx.VSCROLL|wx.SUNKEN_BORDER)
+ self.scroller = scroller = wx.ScrolledWindow(parent, -1,
+ pos=wx.Point(0,0),
+ style=wx.CLIP_CHILDREN|wx.HSCROLL|wx.VSCROLL|wx.SUNKEN_BORDER)
- wx.Panel.__init__(self, scroller, -1)
+ wx.Panel.__init__(self, scroller, -1)
- wx.EVT_SIZE(self.scroller, self.__OnGridSize)
- self.SetBackgroundColour(panelColor)
+ wx.EVT_SIZE(self.scroller, self.__OnGridSize)
+ self.SetBackgroundColour(panelColor)
- self.layouteditor = layouteditor
- self.page = page
+ self.layouteditor = layouteditor
+ self.page = page
- # TODO: blah.... historical reasons
- self._instance = self.document = layouteditor.document
+ # TODO: blah.... historical reasons
+ self._instance = self.document = layouteditor.document
- self.app = self.document.app
+ self.app = self.document.app
- self.block = None
- self.lastBlock = None
- self.blockMap = {}
- self.panel = None
- self._notebookMap = {}
- self.positionMappings = {}
- self.widgetList = []
- self._currentSelection = []
+ self.block = None
+ self.lastBlock = None
+ self.blockMap = {}
+ self.panel = None
+ self._notebookMap = {}
+ self.positionMappings = {}
+ self.widgetList = []
+ self._currentSelection = []
- # Create our own WX GFUserInterface instance
- self.uidriver = uidriver = UIwxpython.GFUserInterface(self.document, 0)
+ # Create our own WX GFUserInterface instance
+ self.uidriver = uidriver = UIwxpython.GFUserInterface(self.document, 0)
- # Create a list of all UI widgets
- self.widgets = {}
- self.widgets.update(uidriver._supportedWidgets)
+ # Create a list of all UI widgets
+ self.widgets = {}
+ self.widgets.update(uidriver._supportedWidgets)
- # But we don't want a page to act like normal objects...
- # we have special plans for it (bwahahaha)
- del self.widgets['GFPage']
+ # But we don't want a page to act like normal objects...
+ # we have special plans for it (bwahahaha)
+ del self.widgets['GFPage']
- self.notebook = wx.Notebook(self, -1, pos=wx.Point(4, 4),
size=wx.Size(32,32))
- self.backcolor = wx.WHITE
+ self.notebook = wx.Notebook(self, -1, pos=wx.Point(4, 4),
size=wx.Size(32,32))
+ self.backcolor = wx.WHITE
- self._currentObject = None
- self.layouteditor.mode = 'move'
- self.reorderfocus = ReorderFocus(self.document)
+ self._currentObject = None
+ self.layouteditor.mode = 'move'
+ self.reorderfocus = ReorderFocus(self.document)
- # Internal mouse states... used by OnMotion, etc
- self.__drawing = 0
- self.__x = 0
- self.__y = 0
- self.__ox = 0
- self.__oy = 0
+ # Internal mouse states... used by OnMotion, etc
+ self.__drawing = 0
+ self.__x = 0
+ self.__y = 0
+ self.__ox = 0
+ self.__oy = 0
- # EventAware provided by ToolBase
+ # EventAware provided by ToolBase
## self.registerEventListeners({
## 'ObjectSelected' : self.onSetCurrentObject,
## 'ObjectCreated' : self.onCreateObject,
@@ -126,605 +126,604 @@
## })
- ## Stuff needed by UIwxpython
- self._pageList = [] # Needed by UIwxpython
+ ## Stuff needed by UIwxpython
+ self._pageList = [] # Needed by UIwxpython
- # Create our grid
- self.panel = GridPane(self.layouteditor, self, wx.Point(10,12))
+ # Create our grid
+ self.panel = GridPane(self.layouteditor, self, wx.Point(10,12))
- # Automatically resize workspace
- wx.EVT_SIZE(self.panel, self.__OnGridSize)
+ # Automatically resize workspace
+ wx.EVT_SIZE(self.panel, self.__OnGridSize)
- wx.EVT_CHAR(self.panel, self.keyTrap)
- wx.EVT_LEFT_DOWN(self.panel, self.OnLeftDown)
- wx.EVT_MOTION(self.panel, self.OnMotion)
- wx.EVT_LEFT_UP(self.panel, self.OnLeftUp)
- wx.EVT_RIGHT_UP(self.panel, self.OnRightUp)
+ wx.EVT_CHAR(self.panel, self.keyTrap)
+ wx.EVT_LEFT_DOWN(self.panel, self.OnLeftDown)
+ wx.EVT_MOTION(self.panel, self.OnMotion)
+ wx.EVT_LEFT_UP(self.panel, self.OnLeftUp)
+ wx.EVT_RIGHT_UP(self.panel, self.OnRightUp)
- # We are a drop target for Drag-and-Drop
- self.panel.SetDropTarget(DisplayDropTarget(self))
+ # We are a drop target for Drag-and-Drop
+ self.panel.SetDropTarget(DisplayDropTarget(self))
# self.panel.SetDropTarget(SchemaDropTarget(self))
- self.panelColor = self.panel.GetBackgroundColour()
- self.panelGridColor = wx.Colour(min(255,self.panelColor.Red()+16),
- min(255,self.panelColor.Green()+16),
- min(255,self.panelColor.Blue()+16))
+ self.panelColor = self.panel.GetBackgroundColour()
+ self.panelGridColor = wx.Colour(min(255,self.panelColor.Red()+16),
+ min(255,self.panelColor.Green()+16),
+ min(255,self.panelColor.Blue()+16))
- page.__pointSize = UIwxpython.getPointSize()
- self.calcGridSpacing()
+ page.__pointSize = UIwxpython.getPointSize()
+ self.calcGridSpacing()
- # Draw the page
- self.drawPage()
+ # Draw the page
+ self.drawPage()
- # Recalculate the scrollbar sizes
- def __OnGridSize(self, event):
- w, h = self.panel.GetSizeTuple()
- w2, h2 = self.scroller.GetClientSizeTuple()
- w = int(max(w, w2)*1.1+30)
- h = int(max(h, h2)*1.1+30)
- self.SetSize((w,h))
- self.scroller.SetScrollbars(w/30-1,h/30-1,30,30)
+ # Recalculate the scrollbar sizes
+ def __OnGridSize(self, event):
+ w, h = self.panel.GetSizeTuple()
+ w2, h2 = self.scroller.GetClientSizeTuple()
+ w = int(max(w, w2)*1.1+30)
+ h = int(max(h, h2)*1.1+30)
+ self.SetSize((w,h))
+ self.scroller.SetScrollbars(w/30-1,h/30-1,30,30)
- def _setFeedback(self):
+ def _setFeedback(self):
- object = self._currentObject
+ object = self._currentObject
- ft = ""
+ ft = ""
- # This sets the feedback text at the top of the Layout Editor window
- if object:
- try: ft += 'Name: % (%s)' % (object.name, object._type[2:])
- except: pass
+ # This sets the feedback text at the top of the Layout Editor window
+ if object:
+ try: ft += 'Name: % (%s)' % (object.name, object._type[2:])
+ except: pass
- try: ft += ' Col: %s' % object.Char__x
- except: pass
+ try: ft += ' Col: %s' % object.Char__x
+ except: pass
- try: ft += ' Row: %s' % object.Char__y
- except: pass
+ try: ft += ' Row: %s' % object.Char__y
+ except: pass
- try: ft += ' Width: %s' % object.Char__width
- except: pass
+ try: ft += ' Width: %s' % object.Char__width
+ except: pass
- try:
- if object.Char__height > 1:
- ft += ' Height: %s' % object.Char__height
- except:
- pass
+ try:
+ if object.Char__height > 1:
+ ft += ' Height: %s' % object.Char__height
+ except:
+ pass
- if ft:
- self.layouteditor.setFeedback(ft)
+ if ft:
+ self.layouteditor.setFeedback(ft)
- def _setCurrentPage(self, object):
- if not object:
- return
- page = isinstance(object, GFObjects.GFPage) and object or \
- object.findParentOfType('GFPage')
+ def _setCurrentPage(self, object):
+ if not object:
+ return
+ page = isinstance(object, GFObjects.GFPage) and object or \
+ object.findParentOfType('GFPage')
- if page != None and page != self.page:
- self.page = page
+ if page != None and page != self.page:
+ self.page = page
- self.notebook.SetSelection(self._notebookMap[page])
- try:
- self.workspace = page.__workspace
- self.panel = self.page.__panel
- UIwxpython.setPointSize(self.page.__pointSize)
- self.calcGridSpacing()
- except AttributeError:
- # This simply means we are setting up
- # our notebook for the first time.
- pass
+ self.notebook.SetSelection(self._notebookMap[page])
+ try:
+ self.workspace = page.__workspace
+ self.panel = self.page.__panel
+ UIwxpython.setPointSize(self.page.__pointSize)
+ self.calcGridSpacing()
+ except AttributeError:
+ # This simply means we are setting up
+ # our notebook for the first time.
+ pass
- def _setSelection(self, focus, objects):
+ def _setSelection(self, focus, objects):
- # Unhighlight any previously selected items
- # that are no longer selected.
- for key in self._currentSelection:
- if key not in objects:
- try:
- key._widgetHandler.setSelected(0)
- except AttributeError:
- pass
+ # Unhighlight any previously selected items
+ # that are no longer selected.
+ for key in self._currentSelection:
+ if key not in objects:
+ try:
+ key._widgetHandler.setSelected(0)
+ except AttributeError:
+ pass
- # and now highlight any new items
- for object in objects:
- if hasattr(object, '_widgetHandler') and object not in
self._currentSelection:
- self._currentSelection.append(object)
- object._widgetHandler.setSelected(1, object == focus)
+ # and now highlight any new items
+ for object in objects:
+ if hasattr(object, '_widgetHandler') and object not in
self._currentSelection:
+ self._currentSelection.append(object)
+ object._widgetHandler.setSelected(1, object == focus)
- self._currentSelection = objects[:]
+ self._currentSelection = objects[:]
- def onCreateObject (self, event):
- object = event.object
- handler = event.originator
+ def onCreateObject (self, event):
+ object = event.object
+ handler = event.originator
## self._currentSelection = []
- if object == None:
- return
+ if object == None:
+ return
- if handler != "Forms::LayoutEditor":
- origpage = self.page
+ if handler != "Forms::LayoutEditor":
+ origpage = self.page
- if object._type != 'GFPage':
- page = object.findParentOfType('GFPage')
- if page:
- self._setCurrentPage(page)
- item = self.layouteditor.renderer.addWidget(object)
+ if object._type != 'GFPage':
+ page = object.findParentOfType('GFPage')
+ if page:
+ self._setCurrentPage(page)
+ item = self.layouteditor.renderer.addWidget(object)
- self.inventoryObject(object)
- self._setCurrentPage(origpage)
- if object._type == 'GFBlock':
- self.blockMap[object.name.lower()] = object
- self._rebuildBlockCombo()
+ self.inventoryObject(object)
+ self._setCurrentPage(origpage)
+ if object._type == 'GFBlock':
+ self.blockMap[object.name.lower()] = object
+ self._rebuildBlockCombo()
- def onModifyObject (self, event):
- object = event.object
- handler = event.originator
+ def onModifyObject (self, event):
+ object = event.object
+ handler = event.originator
- # TODO: adjust label width to match new length...this shouldn't be here
- if object._type == 'GFLabel':
- mods = []
- for field in event.new.keys():
- value = event.new[field]
- if field=='text':
- if (not hasattr(object,'alignment')) or ( object.alignment ==
'left'):
- if not hasattr(object,'Char__width') or object.Char__width !=
len(value):
- object.Char__width=len(value)
- # TODO: This should probably trigger a new ObjectModified event
- event.new['Char:width'] = object.Char__width
+ # TODO: adjust label width to match new length...this shouldn't be here
+ if object._type == 'GFLabel':
+ mods = []
+ for field in event.new.keys():
+ value = event.new[field]
+ if field=='text':
+ if (not hasattr(object,'alignment')) or ( object.alignment
== 'left'):
+ if not hasattr(object,'Char__width') or
object.Char__width != len(value):
+ object.Char__width=len(value)
+ # TODO: This should probably trigger a new
ObjectModified event
+ event.new['Char:width'] = object.Char__width
## self.propBar.onModifyObject(object, event)
- if handler != "Forms::LayoutEditor":
- if object._type == 'GFPage':
- self.notebook.SetPageText(self._notebookMap[object],object.name)
- self.notebook.SetSelection(self.notebook.GetSelection())
- else:
- page = object.findParentOfType('GFPage')
- if page:
- self._setCurrentPage(page)
+ if handler != "Forms::LayoutEditor":
+ if object._type == 'GFPage':
+
self.notebook.SetPageText(self._notebookMap[object],object.name)
+ self.notebook.SetSelection(self.notebook.GetSelection())
+ else:
+ page = object.findParentOfType('GFPage')
+ if page:
+ self._setCurrentPage(page)
- if object in (self.layouteditor.rootObject, self.page,
self.layouteditor.rootObject._layout) or object in self.widgetList:
- self.refreshPage(self.page)
+ if object in (self.layouteditor.rootObject, self.page,
self.layouteditor.rootObject._layout) or object in self.widgetList:
+ self.refreshPage(self.page)
- if object._type == 'GFBlock' and event.old.has_key('name'):
- del self.blockMap[event.old['name'].lower()]
- self.blockMap[object.name.lower()] = object
- self._rebuildBlockCombo()
+ if object._type == 'GFBlock' and event.old.has_key('name'):
+ del self.blockMap[event.old['name'].lower()]
+ self.blockMap[object.name.lower()] = object
+ self._rebuildBlockCombo()
- self._setFeedback()
+ self._setFeedback()
- def onDeleteObject (self, event):
+ def onDeleteObject (self, event):
- object = event.object
- handler = event.originator
+ object = event.object
+ handler = event.originator
- self._currentObject = None
+ self._currentObject = None
- if 1: ## handler != "Forms::LayoutEditor":
- if object._type == 'GFPage':
- index = self._notebookMap[object]
- for i in range(index+1, len(self._notebookMap.keys())/2):
- self._notebookMap[i-1] = self._notebookMap[i]
- del self._notebookMap[int(len(self._notebookMap.keys())/2)-1]
- del self._notebookMap[object]
- self.notebook.DeletePage(index)
+ if 1: ## handler != "Forms::LayoutEditor":
+ if object._type == 'GFPage':
+ index = self._notebookMap[object]
+ for i in range(index+1, len(self._notebookMap.keys())/2):
+ self._notebookMap[i-1] = self._notebookMap[i]
+ del self._notebookMap[int(len(self._notebookMap.keys())/2)-1]
+ del self._notebookMap[object]
+ self.notebook.DeletePage(index)
- if hasattr(object, '_widgetHandler') and object._widgetHandler != None:
- if object in self._currentSelection:
- object._widgetHandler.setSelected(0)
- del self._currentSelection[self._currentSelection.index(object)]
+ if hasattr(object, '_widgetHandler') and object._widgetHandler != None:
+ if object in self._currentSelection:
+ object._widgetHandler.setSelected(0)
+ del
self._currentSelection[self._currentSelection.index(object)]
- self.widgetList.remove(object)
- ##for i in range(len(self.widgetList)):
- ## if self.widgetList[i] == object:
- ## self.widgetList.pop(i)
- ## break
+ self.widgetList.remove(object)
+ ##for i in range(len(self.widgetList)):
+ ## if self.widgetList[i] == object:
+ ## self.widgetList.pop(i)
+ ## break
## object._widget.cleanup(object)
- object._widget._object = None
- object._widget = None
- object._widgetHandler.Destroy()
- object._widgetHandler = None
+ object._widget._object = None
+ object._widget = None
+ object._widgetHandler.Destroy()
+ object._widgetHandler = None
- def refreshPage(self, page):
- try:
- page.__panel.Destroy()
- del page.__panel
- except AttributeError:
- pass
+ def refreshPage(self, page):
+ try:
+ page.__panel.Destroy()
+ del page.__panel
+ except AttributeError:
+ pass
- self.drawPage()
+ self.drawPage()
- def drawPage(self):
- self._currentSelection = []
- page = self.page
+ def drawPage(self):
+ self._currentSelection = []
+ page = self.page
- def calcGridSpacing(self):
- UIwxpython.initFont(self.panel)
+ def calcGridSpacing(self):
+ UIwxpython.initFont(self.panel)
- maxWidth, maxHeight, maxDescent, maxLeading = [0,0,0,0]
+ maxWidth, maxHeight, maxDescent, maxLeading = [0,0,0,0]
- checkchars = string.letters+string.digits+"-\|" + string.punctuation
- for letter in checkchars:
- width,height,descent,leading = self.panel.GetFullTextExtent(letter)
- maxWidth = maxWidth > width and maxWidth or width
- maxHeight = maxHeight > height and maxHeight or height
- maxDescent = maxDescent > descent and maxDescent or descent
- maxLeading = maxLeading > leading and maxLeading or leading
+ checkchars = string.letters+string.digits+"-\|" + string.punctuation
+ for letter in checkchars:
+ width,height,descent,leading = self.panel.GetFullTextExtent(letter)
+ maxWidth = maxWidth > width and maxWidth or width
+ maxHeight = maxHeight > height and maxHeight or height
+ maxDescent = maxDescent > descent and maxDescent or descent
+ maxLeading = maxLeading > leading and maxLeading or leading
- self.charWidth = maxWidth+maxLeading
- self.charHeight = maxHeight+maxDescent
+ self.charWidth = maxWidth+maxLeading
+ self.charHeight = maxHeight+maxDescent
- self.borderPercentage = (float(gConfig('borderPercentage',
section='designer')) / 100)
- self.textPercentage = (float(gConfig('textPercentage',
section='designer')) / 100)
+ self.borderPercentage = (float(gConfig('borderPercentage',
section='designer')) / 100)
+ self.textPercentage = (float(gConfig('textPercentage',
section='designer')) / 100)
- self.widgetWidth = int(self.charWidth * self.borderPercentage)
- self.widgetHeight = int(self.charHeight * self.borderPercentage) + 3
- self.textWidth = self.charWidth * self.textPercentage
- self.textHeight = self.charHeight * self.textPercentage
+ self.widgetWidth = int(self.charWidth * self.borderPercentage)
+ self.widgetHeight = int(self.charHeight * self.borderPercentage) + 3
+ self.textWidth = self.charWidth * self.textPercentage
+ self.textHeight = self.charHeight * self.textPercentage
- self.gridWidth = self.widgetWidth
- self.gridHeight = self.widgetHeight
+ self.gridWidth = self.widgetWidth
+ self.gridHeight = self.widgetHeight
- self.menu_sb_space=0 # the extra spaces needed by the menu, toolbar and
statusbar
+ self.menu_sb_space=0 # the extra spaces needed by the menu, toolbar
and statusbar
- width = self.layouteditor.rootObject._layout.Char__width
- height = self.layouteditor.rootObject._layout.Char__height
- self.panel.SetClientSize(wx.Size(int(width)*self.widgetWidth,
- int(height)*self.widgetHeight))
- self.panel.Refresh()
+ width = self.layouteditor.rootObject._layout.Char__width
+ height = self.layouteditor.rootObject._layout.Char__height
+ self.panel.SetClientSize(wx.Size(int(width)*self.widgetWidth,
+ int(height)*self.widgetHeight))
+ self.panel.Refresh()
- def OnLeftDown(self, event):
- x, y = event.GetPositionTuple()
- self.handleLeftDown(x,y)
- event.Skip()
+ def OnLeftDown(self, event):
+ x, y = event.GetPositionTuple()
+ self.handleLeftDown(x,y)
+ event.Skip()
- def handleLeftDown(self, x, y):
- self.__drawing = 1
+ def handleLeftDown(self, x, y):
+ self.__drawing = 1
- # Save starting coordinates for cross-selection box
- self.__cx = cx = int(x / self.gridWidth)
- self.__cy = cy = int(y / self.gridHeight)
+ # Save starting coordinates for cross-selection box
+ self.__cx = cx = int(x / self.gridWidth)
+ self.__cy = cy = int(y / self.gridHeight)
- self.layouteditor.setFeedback ('Col: %s Row: %s' % (cx, cy))
+ self.layouteditor.setFeedback ('Col: %s Row: %s' % (cx, cy))
- self.__brush = wx.Brush(wx.WHITE, style=wx.TRANSPARENT)
+ self.__brush = wx.Brush(wx.WHITE, style=wx.TRANSPARENT)
- self.__x = x
- self.__y = y
- self.__ox = None
- self.__oy = None
+ self.__x = x
+ self.__y = y
+ self.__ox = None
+ self.__oy = None
- # Used by the dragging routines to draw a selection box
- def xorBox(self, x1, y1, x2, y2, x3=None, y3=None):
- dc = wx.ClientDC(self.panel)
- dc.SetBrush(self.__brush)
- dc.SetPen(wx.GREY_PEN)
- dc.SetLogicalFunction(wx.XOR)
+ # Used by the dragging routines to draw a selection box
+ def xorBox(self, x1, y1, x2, y2, x3=None, y3=None):
+ dc = wx.ClientDC(self.panel)
+ dc.SetBrush(self.__brush)
+ dc.SetPen(wx.GREY_PEN)
+ dc.SetLogicalFunction(wx.XOR)
- if x3 != None:
- dc.DrawRectangle(x1,y1,x3-x1,y3-y1)
+ if x3 != None:
+ dc.DrawRectangle(x1,y1,x3-x1,y3-y1)
- dc.DrawRectangle(x1,y1,x2-x1,y2-y1)
+ dc.DrawRectangle(x1,y1,x2-x1,y2-y1)
- def OnMotion(self, event):
- # draw cross-selection box
- if self.__drawing and event.LeftIsDown():
+ def OnMotion(self, event):
+ # draw cross-selection box
+ if self.__drawing and event.LeftIsDown():
- if self.__drawing == 1:
- self.panel.SetCursor(wx.CROSS_CURSOR)
- self.__drawing = 2
+ if self.__drawing == 1:
+ self.panel.SetCursor(wx.CROSS_CURSOR)
+ self.__drawing = 2
- x, y = event.GetPositionTuple()
- cx = int(x / self.gridWidth)
- cy = int(y / self.gridHeight)
+ x, y = event.GetPositionTuple()
+ cx = int(x / self.gridWidth)
+ cy = int(y / self.gridHeight)
- cx1, cx2 = order(self.__cx, cx)
- cy1, cy2 = order(self.__cy, cy)
+ cx1, cx2 = order(self.__cx, cx)
+ cy1, cy2 = order(self.__cy, cy)
- self.layouteditor.setFeedback('Col: %s Row: %s Width: %s Height:
%s'% (cx1, cy1, cx2 - cx1 + 1, cy2 - cy1 + 1))
+ self.layouteditor.setFeedback('Col: %s Row: %s Width: %s
Height: %s'% (cx1, cy1, cx2 - cx1 + 1, cy2 - cy1 + 1))
- self.xorBox(self.__x, self.__y, x, y, self.__ox, self.__oy)
+ self.xorBox(self.__x, self.__y, x, y, self.__ox, self.__oy)
- self.__ox = x
- self.__oy = y
+ self.__ox = x
+ self.__oy = y
- event.Skip()
+ event.Skip()
- def OnLeftUp(self, event):
- x, y = event.GetPositionTuple()
- self.handleLeftUp(x,y)
- event.Skip()
+ def OnLeftUp(self, event):
+ x, y = event.GetPositionTuple()
+ self.handleLeftUp(x,y)
+ event.Skip()
- def handleLeftUp(self, x, y):
- selection = []
+ def handleLeftUp(self, x, y):
+ selection = []
- self.layouteditor.setFeedback('')
+ self.layouteditor.setFeedback('')
- if self.__drawing and self.__ox is not None:
+ if self.__drawing and self.__ox is not None:
- self.xorBox(self.__x, self.__y, self.__ox, self.__oy)
- self.__ox = None
- self.__oy = None
+ self.xorBox(self.__x, self.__y, self.__ox, self.__oy)
+ self.__ox = None
+ self.__oy = None
- self.__drawing = 0
+ self.__drawing = 0
- # Set x1,y1 to be smaller coordinates, and x2,y2 to be larger
- x1, x2 = order(int(self.__x / self.gridWidth), int(x / self.gridWidth))
- y1, y2 = order(int(self.__y / self.gridHeight),int(y / self.gridHeight))
+ # Set x1,y1 to be smaller coordinates, and x2,y2 to be larger
+ x1, x2 = order(int(self.__x / self.gridWidth), int(x / self.gridWidth))
+ y1, y2 = order(int(self.__y / self.gridHeight),int(y /
self.gridHeight))
- self.panel.SetCursor(wx.STANDARD_CURSOR)
- wx.SetCursor(wx.STANDARD_CURSOR)
+ self.panel.SetCursor(wx.STANDARD_CURSOR)
+ wx.SetCursor(wx.STANDARD_CURSOR)
- areaSelected = (x1 <> x2 or y1 <> y2)
+ areaSelected = (x1 <> x2 or y1 <> y2)
- if self.layouteditor.mode == 'move':
- if areaSelected:
- # We are selecting an area
- self.page.walk(self.selectWidgetInArea, x1, y1, x2, y2, selection)
- try:
- object = selection[-1]
- except IndexError:
- object = self.page
- self.layouteditor.dispatchEvent('ObjectSelected',
- object = object,
- originator = "Forms::LayoutEditor",
- selection = selection)
- else:
- self.layouteditor.dispatchEvent('ObjectSelected',
- object = self.page,
- originator = "Forms::LayoutEditor")
+ if self.layouteditor.mode == 'move':
+ if areaSelected:
+ # We are selecting an area
+ self.page.walk(self.selectWidgetInArea, x1, y1, x2, y2,
selection)
+ try:
+ object = selection[-1]
+ except IndexError:
+ object = self.page
+ self.layouteditor.dispatchEvent('ObjectSelected',
+ object = object,
+ originator = "Forms::LayoutEditor",
+ selection = selection)
+ else:
+ self.layouteditor.dispatchEvent('ObjectSelected',
+ object = self.page,
+ originator = "Forms::LayoutEditor")
- elif self.layouteditor.mode == 'positioning':
+ elif self.layouteditor.mode == 'positioning':
- if areaSelected:
- width = x2 - x1 + 1
- height = y2 - y1 + 1
- else:
- width = None
- height = None
+ if areaSelected:
+ width = x2 - x1 + 1
+ height = y2 - y1 + 1
+ else:
+ width = None
+ height = None
-
PrepositioningTimer(self.endPrePositioningTemplate,x1,y1,width,height).Start(100,1)
+
PrepositioningTimer(self.endPrePositioningTemplate,x1,y1,width,height).Start(100,1)
- def selectWidgetInArea(self, object, x1, y1, x2, y2, selection):
- try:
- if x1 <= object.Char__x <= x2 and \
- y1 <= object.Char__y <= y2:
- if object not in selection:
- selection.append(object)
- except AttributeError:
- # Not all child objects have coordinates (x,y)
- pass
+ def selectWidgetInArea(self, object, x1, y1, x2, y2, selection):
+ try:
+ if x1 <= object.Char__x <= x2 and \
+ y1 <= object.Char__y <= y2:
+ if object not in selection:
+ selection.append(object)
+ except AttributeError:
+ # Not all child objects have coordinates (x,y)
+ pass
- def OnRightUp(self, event):
+ def OnRightUp(self, event):
## self.toolbar.resetTool(self.layouteditor.mode)
- self.layouteditor.mode = 'move'
- self.layouteditor.dispatchEvent('LayoutEditor:Select')
+ self.layouteditor.mode = 'move'
+ self.layouteditor.dispatchEvent('LayoutEditor:Select')
- x, y = event.GetPositionTuple()
+ x, y = event.GetPositionTuple()
- x = int(x / self.gridWidth)
- y = int(y / self.gridHeight)
+ x = int(x / self.gridWidth)
+ y = int(y / self.gridHeight)
- menu = wx.Menu('Layout Editor')
- form = self._currentObject._type == 'GFForm' and self._currentObject or \
- self._currentObject.findParentOfType('GFForm')
- page = self._currentObject._type == 'GFPage' and self._currentObject or \
- self._currentObject.findParentOfType('GFPage')
- block = self._currentObject._type == 'GFBlock' and self._currentObject or \
- self._currentObject.findParentOfType('GFBlock')
+ menu = wx.Menu('Layout Editor')
+ form = self._currentObject._type == 'GFForm' and self._currentObject
or \
+ self._currentObject.findParentOfType('GFForm')
+ page = self._currentObject._type == 'GFPage' and self._currentObject
or \
+ self._currentObject.findParentOfType('GFPage')
+ block = self._currentObject._type == 'GFBlock' and self._currentObject
or \
+ self._currentObject.findParentOfType('GFBlock')
- menu.AppendMenu(wx.NewId(), 'Form', PageMenu(self.document, form, x, y))
- if page:
- menu.AppendMenu(wx.NewId(), page.name, PageMenu(self.document, page, x,
y))
- if block:
- menu.AppendMenu(wx.NewId(), block.name, PageMenu(self.document, block,
x, y))
+ menu.AppendMenu(wx.NewId(), 'Form', PageMenu(self.document, form, x,
y))
+ if page:
+ menu.AppendMenu(wx.NewId(), page.name, PageMenu(self.document,
page, x, y))
+ if block:
+ menu.AppendMenu(wx.NewId(), block.name, PageMenu(self.document,
block, x, y))
- self.panel.PopupMenu(menu, event.GetPosition())
+ self.panel.PopupMenu(menu, event.GetPosition())
- def keyTrap(self, event):
- if event.KeyCode() in (wx.WXK_LEFT,wx.WXK_RIGHT,wx.WXK_UP,wx.WXK_DOWN) and
\
- len(self._currentSelection):
- if event.AltDown() or event.ControlDown() or event.ShiftDown():
- # caution: event.MetaDown() is always True on some architectures
- resize = None
- if event.KeyCode() == wx.WXK_LEFT:
- resize = (-1,0)
- if event.KeyCode() == wx.WXK_RIGHT:
- resize = (1,0)
- if event.KeyCode() == wx.WXK_UP:
- resize = (0,-1)
- if event.KeyCode() == wx.WXK_DOWN:
- resize = (0,1)
- if resize:
- self.layouteditor.dispatchEvent('BeginUndoGroup')
- for widget in self._currentSelection:
- widget._widgetHandler.relativeResize(*resize)
- self.layouteditor.dispatchEvent('EndUndoGroup')
- else:
- pos = None
- if event.KeyCode() == wx.WXK_LEFT:
- pos = (-1,0)
- if event.KeyCode() == wx.WXK_RIGHT:
- pos = (1,0)
- if event.KeyCode() == wx.WXK_UP:
- pos = (0,-1)
- if event.KeyCode() == wx.WXK_DOWN:
- pos = (0,1)
+ def keyTrap(self, event):
+ if event.KeyCode() in (wx.WXK_LEFT,wx.WXK_RIGHT,wx.WXK_UP,wx.WXK_DOWN)
and \
+ len(self._currentSelection):
+ if event.AltDown() or event.ControlDown() or event.ShiftDown():
+ # caution: event.MetaDown() is always True on some
architectures
+ resize = None
+ if event.KeyCode() == wx.WXK_LEFT:
+ resize = (-1,0)
+ if event.KeyCode() == wx.WXK_RIGHT:
+ resize = (1,0)
+ if event.KeyCode() == wx.WXK_UP:
+ resize = (0,-1)
+ if event.KeyCode() == wx.WXK_DOWN:
+ resize = (0,1)
+ if resize:
+ self.layouteditor.dispatchEvent('BeginUndoGroup')
+ for widget in self._currentSelection:
+ widget._widgetHandler.relativeResize(*resize)
+ self.layouteditor.dispatchEvent('EndUndoGroup')
+ else:
+ pos = None
+ if event.KeyCode() == wx.WXK_LEFT:
+ pos = (-1,0)
+ if event.KeyCode() == wx.WXK_RIGHT:
+ pos = (1,0)
+ if event.KeyCode() == wx.WXK_UP:
+ pos = (0,-1)
+ if event.KeyCode() == wx.WXK_DOWN:
+ pos = (0,1)
- if pos:
- self.layouteditor.dispatchEvent('BeginUndoGroup')
- for widget in self._currentSelection:
- if widget._type != 'GFPage':
- widget._widgetHandler.relativeMove(*pos)
- self.layouteditor.dispatchEvent('EndUndoGroup')
+ if pos:
+ self.layouteditor.dispatchEvent('BeginUndoGroup')
+ for widget in self._currentSelection:
+ if widget._type != 'GFPage':
+ widget._widgetHandler.relativeMove(*pos)
+ self.layouteditor.dispatchEvent('EndUndoGroup')
- elif event.KeyCode() == wx.WXK_DELETE and \
- len(self._currentSelection):
- self.layouteditor.dispatchEvent('BeginUndoGroup')
- for object in self._currentSelection:
- if object._type != 'GFPage':
- self.layouteditor.dispatchEvent('ObjectDeleted', object=object,
- originator=self)
- self.layouteditor.dispatchEvent('EndUndoGroup')
- elif event.KeyCode() == wx.WXK_TAB:
- if event.ShiftDown():
- object = self._currentObject
- if hasattr(object,'_widgetHandler') and not object._type == 'GFPage':
- i = object.getParent ()._children.index(object)
- lst = object.getParent ()._children[i:] + object.getParent
()._children[:i]
- else:
- lst = self.page._children[:]
- lst.reverse()
- for newobj in lst:
- if hasattr(newobj,'_widgetHandler'):
- self.document.dispatchEvent('ObjectSelected',
- originator=None,
- object=newobj)
- break
- elif not event.ControlDown() and not event.AltDown():
- object = self._currentObject
- if hasattr(object,'_widgetHandler') and not object._type == 'GFPage':
- i = object.getParent ()._children.index(object)
- lst = object.getParent ()._children[i+1:] + object.getParent
()._children[:i+1]
- else:
- lst = self.page._children[:]
- for newobj in lst:
- if hasattr(newobj,'_widgetHandler'):
- self.document.dispatchEvent('ObjectSelected',
- originator=None,
- object=newobj)
- break
+ elif event.KeyCode() == wx.WXK_DELETE and \
+ len(self._currentSelection):
+ self.layouteditor.dispatchEvent('BeginUndoGroup')
+ for object in self._currentSelection:
+ if object._type != 'GFPage':
+ self.layouteditor.dispatchEvent('ObjectDeleted',
object=object,
+ originator=self)
+ self.layouteditor.dispatchEvent('EndUndoGroup')
+ elif event.KeyCode() == wx.WXK_TAB:
+ if event.ShiftDown():
+ object = self._currentObject
+ if hasattr(object,'_widgetHandler') and not object._type ==
'GFPage':
+ i = object.getParent ()._children.index(object)
+ lst = object.getParent ()._children[i:] + object.getParent
()._children[:i]
+ else:
+ lst = self.page._children[:]
+ lst.reverse()
+ for newobj in lst:
+ if hasattr(newobj,'_widgetHandler'):
+ self.document.dispatchEvent('ObjectSelected',
+ originator=None,
+ object=newobj)
+ break
+ elif not event.ControlDown() and not event.AltDown():
+ object = self._currentObject
+ if hasattr(object,'_widgetHandler') and not object._type ==
'GFPage':
+ i = object.getParent ()._children.index(object)
+ lst = object.getParent ()._children[i+1:] +
object.getParent ()._children[:i+1]
+ else:
+ lst = self.page._children[:]
+ for newobj in lst:
+ if hasattr(newobj,'_widgetHandler'):
+ self.document.dispatchEvent('ObjectSelected',
+ originator=None,
+ object=newobj)
+ break
- def zoomIn(self, event):
- size = UIwxpython.getPointSize()
- if size < 72:
- size = size + 1 # int(size * 1.05 + .5)
- UIwxpython.setPointSize(size)
- self.calcGridSpacing()
- self.refreshPage(self.page)
- self.layouteditor.setFeedback(u_('Adjusting base point size to %spt') %
size)
- else:
- self.layouteditor.setFeedback(u_('Cannot adjust point size to more than
72pt'))
+ def zoomIn(self, event):
+ size = UIwxpython.getPointSize()
+ if size < 72:
+ size = size + 1 # int(size * 1.05 + .5)
+ UIwxpython.setPointSize(size)
+ self.calcGridSpacing()
+ self.refreshPage(self.page)
+ self.layouteditor.setFeedback(u_('Adjusting base point size to
%spt') % size)
+ else:
+ self.layouteditor.setFeedback(u_('Cannot adjust point size to more
than 72pt'))
- def zoomOut(self, event):
- size = UIwxpython.getPointSize()
- if size > 6:
- size = size - 1 # int(size * -1.05)
- UIwxpython.setPointSize(size)
- self.calcGridSpacing()
- self.refreshPage(self.page)
- self.layouteditor.setFeedback(u_('Adjusting base point size to %spt') %
size)
- else:
- self.layouteditor.setFeedback(u_('Cannot adjust point size to less than
6pt'))
+ def zoomOut(self, event):
+ size = UIwxpython.getPointSize()
+ if size > 6:
+ size = size - 1 # int(size * -1.05)
+ UIwxpython.setPointSize(size)
+ self.calcGridSpacing()
+ self.refreshPage(self.page)
+ self.layouteditor.setFeedback(u_('Adjusting base point size to
%spt') % size)
+ else:
+ self.layouteditor.setFeedback(u_('Cannot adjust point size to less
than 6pt'))
- def beginPrePositioningTemplate(self, event):
- mode = self.layouteditor.mode
- self.layouteditor.mode = 'positioning'
- if mode == 'move':
- self.layouteditor.dispatchEvent('Cancel:LayoutEditor:Select')
- elif mode == 'refocus':
- self.layouteditor.dispatchEvent('Cancel:LayoutEditor:FocusOrder')
+ def beginPrePositioningTemplate(self, event):
+ mode = self.layouteditor.mode
+ self.layouteditor.mode = 'positioning'
+ if mode == 'move':
+ self.layouteditor.dispatchEvent('Cancel:LayoutEditor:Select')
+ elif mode == 'refocus':
+ self.layouteditor.dispatchEvent('Cancel:LayoutEditor:FocusOrder')
- ##self.panel.SetCursor(wx.CROSS_CURSOR)
- wx.SetCursor(wx.CROSS_CURSOR)
- self.__wizardrunner = event.wizardrunner
+ ##self.panel.SetCursor(wx.CROSS_CURSOR)
+ wx.SetCursor(wx.CROSS_CURSOR)
+ self.__wizardrunner = event.wizardrunner
- def cancelPrePositioningTemplate(self, event=None):
- if self.layouteditor.mode == 'prepositioning':
- self.__wizardrunner.cancel()
- wx.SetCursor(wx.STANDARD_CURSOR)
+ def cancelPrePositioningTemplate(self, event=None):
+ if self.layouteditor.mode == 'prepositioning':
+ self.__wizardrunner.cancel()
+ wx.SetCursor(wx.STANDARD_CURSOR)
- def endPrePositioningTemplate(self, x, y, width=None, height=None):
- self.layouteditor.mode = 'move'
- self.layouteditor.dispatchEvent('Cancel:LayoutEditor:Prepositioning')
- self.layouteditor.dispatchEvent('LayoutEditor:Select')
- self.__wizardrunner.positioned_run(x=x, y=y, width=width, height=height)
+ def endPrePositioningTemplate(self, x, y, width=None, height=None):
+ self.layouteditor.mode = 'move'
+ self.layouteditor.dispatchEvent('Cancel:LayoutEditor:Prepositioning')
+ self.layouteditor.dispatchEvent('LayoutEditor:Select')
+ self.__wizardrunner.positioned_run(x=x, y=y, width=width,
height=height)
- def beginFocusOrder(self, event):
- mode = self.layouteditor.mode
- self.layouteditor.mode = 'refocus'
- if mode == 'move':
- event.dispatchAfter('Cancel:LayoutEditor:Select')
- elif mode == 'positioning':
- self.__wizardrunner.cancel()
- # Yes, you are reading this right...
- # I'm triggering the exact event that
- # triggered this method. Blame it on
- # the Tuesday night atmospheric crack
- # levels.
- self.layouteditor.dispatchEvent('LayoutEditor:FocusOrder')
- return
+ def beginFocusOrder(self, event):
+ mode = self.layouteditor.mode
+ self.layouteditor.mode = 'refocus'
+ if mode == 'move':
+ event.dispatchAfter('Cancel:LayoutEditor:Select')
+ elif mode == 'positioning':
+ self.__wizardrunner.cancel()
+ # Yes, you are reading this right...
+ # I'm triggering the exact event that
+ # triggered this method. Blame it on
+ # the Tuesday night atmospheric crack
+ # levels.
+ self.layouteditor.dispatchEvent('LayoutEditor:FocusOrder')
+ return
- self.reorderfocus.start(self.page)
+ self.reorderfocus.start(self.page)
- def endFocusOrder(self, event):
- self.reorderfocus.end()
- if self.layouteditor.mode == 'refocus':
- self.layouteditor.mode = 'move'
- self.layouteditor.dispatchEvent('LayoutEditor:Select')
+ def endFocusOrder(self, event):
+ self.reorderfocus.end()
+ if self.layouteditor.mode == 'refocus':
+ self.layouteditor.mode = 'move'
+ self.layouteditor.dispatchEvent('LayoutEditor:Select')
- def beginSelectMode(self, event=None):
- mode = self.layouteditor.mode
- self.layouteditor.mode = 'move'
- if mode == 'refocus':
- self.layouteditor.dispatchEvent('Cancel:LayoutEditor:FocusOrder')
- elif mode == 'positioning':
- self.layouteditor.dispatchEvent('Cancel:LayoutEditor:Prepositioning')
+ def beginSelectMode(self, event=None):
+ mode = self.layouteditor.mode
+ self.layouteditor.mode = 'move'
+ if mode == 'refocus':
+ self.layouteditor.dispatchEvent('Cancel:LayoutEditor:FocusOrder')
+ elif mode == 'positioning':
+
self.layouteditor.dispatchEvent('Cancel:LayoutEditor:Prepositioning')
- def cancelSelectMode(self, event=None):
- if self.layouteditor.mode == 'move':
- event.dispatchAfter('LayoutEditor:Select')
+ def cancelSelectMode(self, event=None):
+ if self.layouteditor.mode == 'move':
+ event.dispatchAfter('LayoutEditor:Select')
- def endWizard(self, event=None):
- mode = self.layouteditor.mode
- self.layouteditor.mode = 'move'
- if mode == 'refocus':
- self.layouteditor.dispatchEvent('Cancel:LayoutEditor:FocusOrder')
- elif mode == 'positioning':
- self.layouteditor.dispatchEvent('Cancel:LayoutEditor:Prepositioning')
- self.layouteditor.dispatchEvent('LayoutEditor:Select')
+ def endWizard(self, event=None):
+ mode = self.layouteditor.mode
+ self.layouteditor.mode = 'move'
+ if mode == 'refocus':
+ self.layouteditor.dispatchEvent('Cancel:LayoutEditor:FocusOrder')
+ elif mode == 'positioning':
+
self.layouteditor.dispatchEvent('Cancel:LayoutEditor:Prepositioning')
+ self.layouteditor.dispatchEvent('LayoutEditor:Select')
class PrepositioningTimer(wx.Timer):
- def __init__(self, method, *args, **params):
- self.__method = method
- self.__args = args
- self.__params = params
- wx.Timer.__init__(self)
+ def __init__(self, method, *args, **params):
+ self.__method = method
+ self.__args = args
+ self.__params = params
+ wx.Timer.__init__(self)
- def Notify(self):
- self.__method(*self.__args, **self.__params)
-
+ def Notify(self):
+ self.__method(*self.__args, **self.__params)
Modified: trunk/gnue-designer/src/forms/LayoutEditor/renderers/Base/Driver.py
===================================================================
--- trunk/gnue-designer/src/forms/LayoutEditor/renderers/Base/Driver.py
2006-04-03 19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/forms/LayoutEditor/renderers/Base/Driver.py
2006-04-03 19:56:14 UTC (rev 8344)
@@ -29,17 +29,16 @@
import wx
class BaseRenderer:
- def __init__(self, instance, workspace):
- self.document = instance
- self.workspace = workspace
+ def __init__(self, instance, workspace):
+ self.document = instance
+ self.workspace = workspace
- StartupStatus(u_('Loading Renderers'))
+ StartupStatus(u_('Loading Renderers'))
- self.init()
+ self.init()
- # For subclasses
- def init(self):
- pass
-
+ # For subclasses
+ def init(self):
+ pass
Modified: trunk/gnue-designer/src/forms/LayoutEditor/renderers/Base/GridPane.py
===================================================================
--- trunk/gnue-designer/src/forms/LayoutEditor/renderers/Base/GridPane.py
2006-04-03 19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/forms/LayoutEditor/renderers/Base/GridPane.py
2006-04-03 19:56:14 UTC (rev 8344)
@@ -35,56 +35,55 @@
#
#
class GridPane(wx.SashWindow):
- def __init__(self, instance, parent, pos):
- wx.SashWindow.__init__(self, parent, -1, pos=pos,
style=wx.WANTS_CHARS|wx.SIMPLE_BORDER)
- self.__showGrids = 1
- self.__instance = instance
- wx.EVT_PAINT(self, self.OnPaint)
+ def __init__(self, instance, parent, pos):
+ wx.SashWindow.__init__(self, parent, -1, pos=pos,
style=wx.WANTS_CHARS|wx.SIMPLE_BORDER)
+ self.__showGrids = 1
+ self.__instance = instance
+ wx.EVT_PAINT(self, self.OnPaint)
- # TODO: Have the sash events resize the form
- self.SetSashVisible(wx.SASH_RIGHT,1)
- self.SetSashVisible(wx.SASH_BOTTOM,1)
+ # TODO: Have the sash events resize the form
+ self.SetSashVisible(wx.SASH_RIGHT,1)
+ self.SetSashVisible(wx.SASH_BOTTOM,1)
- wx.EVT_SASH_DRAGGED(self, self.GetId(), self.SashChanged)
+ wx.EVT_SASH_DRAGGED(self, self.GetId(), self.SashChanged)
- def OnPaint(self, event):
- if self.__showGrids:
- dc = wx.PaintDC(self)
- dc.BeginDrawing()
- w, h = self.GetSizeTuple()
- dc.SetPen(wx.Pen(self.__instance.panelGridColor))
- for x in range(self.__instance.widgetWidth,w-3,
self.__instance.widgetWidth):
- dc.DrawLine(x,0,x,h-1)
+ def OnPaint(self, event):
+ if self.__showGrids:
+ dc = wx.PaintDC(self)
+ dc.BeginDrawing()
+ w, h = self.GetSizeTuple()
+ dc.SetPen(wx.Pen(self.__instance.panelGridColor))
+ for x in range(self.__instance.widgetWidth,w-3,
self.__instance.widgetWidth):
+ dc.DrawLine(x,0,x,h-1)
- for y in
range(self.__instance.widgetHeight,h-2,self.__instance.widgetHeight):
- dc.DrawLine(0,y,w-1,y)
- dc.EndDrawing()
- event.Skip()
+ for y in
range(self.__instance.widgetHeight,h-2,self.__instance.widgetHeight):
+ dc.DrawLine(0,y,w-1,y)
+ dc.EndDrawing()
+ event.Skip()
- def SashChanged(self, event):
- w = event.GetDragRect().width
- h = event.GetDragRect().height
+ def SashChanged(self, event):
+ w = event.GetDragRect().width
+ h = event.GetDragRect().height
- neww = int(w/float(self.__instance.widgetWidth)+.5)
- newh = int(h/float(self.__instance.widgetHeight)+.5)
+ neww = int(w/float(self.__instance.widgetWidth)+.5)
+ newh = int(h/float(self.__instance.widgetHeight)+.5)
- layout = self.__instance.document.rootObject._layout
+ layout = self.__instance.document.rootObject._layout
- oldvars = {}
- newvars = {}
+ oldvars = {}
+ newvars = {}
- if neww != layout.Char__width:
- oldvars['Char:width'] = layout.Char__width
- newvars['Char:width'] = neww
- layout.Char__width = neww
- if newh != layout.Char__height:
- oldvars['Char:height'] = layout.Char__height
- newvars['Char:height'] = newh
- layout.Char__height = newh
+ if neww != layout.Char__width:
+ oldvars['Char:width'] = layout.Char__width
+ newvars['Char:width'] = neww
+ layout.Char__width = neww
+ if newh != layout.Char__height:
+ oldvars['Char:height'] = layout.Char__height
+ newvars['Char:height'] = newh
+ layout.Char__height = newh
- if oldvars:
- self.__instance.document.dispatchEvent('ObjectModified', object=layout,
- originator="Forms::GridPane",
- old=oldvars,
- new=newvars)
-
+ if oldvars:
+ self.__instance.document.dispatchEvent('ObjectModified',
object=layout,
+ originator="Forms::GridPane",
+ old=oldvars,
+ new=newvars)
Modified: trunk/gnue-designer/src/forms/LayoutEditor/renderers/curses/Driver.py
===================================================================
--- trunk/gnue-designer/src/forms/LayoutEditor/renderers/curses/Driver.py
2006-04-03 19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/forms/LayoutEditor/renderers/curses/Driver.py
2006-04-03 19:56:14 UTC (rev 8344)
@@ -29,5 +29,5 @@
from gnue.designer.forms.LayoutEditor.renderers.Base import *
class Renderer(BaseRenderer):
- def init(self):
- pass
+ def init(self):
+ pass
Modified: trunk/gnue-designer/src/forms/LayoutEditor/renderers/native/Driver.py
===================================================================
--- trunk/gnue-designer/src/forms/LayoutEditor/renderers/native/Driver.py
2006-04-03 19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/forms/LayoutEditor/renderers/native/Driver.py
2006-04-03 19:56:14 UTC (rev 8344)
@@ -29,5 +29,5 @@
from gnue.designer.forms.LayoutEditor.renderers.Base import *
class Renderer(BaseRenderer):
- def init(self):
- pass
+ def init(self):
+ pass
Modified:
trunk/gnue-designer/src/forms/LayoutEditor/renderers/native/WidgetHandler.py
===================================================================
---
trunk/gnue-designer/src/forms/LayoutEditor/renderers/native/WidgetHandler.py
2006-04-03 19:53:03 UTC (rev 8343)
+++
trunk/gnue-designer/src/forms/LayoutEditor/renderers/native/WidgetHandler.py
2006-04-03 19:56:14 UTC (rev 8344)
@@ -39,336 +39,336 @@
#
#
class WidgetHandler(wx.EvtHandler):
- def __init__(self, instance, object):
- wx.EvtHandler.__init__(self)
- self.editor = instance
- self.object = object
- self.hasFocus = 0
- self.highlightBox = WidgetHighlighter(self.editor.panel)
- self._iMoved = 0
- self._alreadySelected = 0
- self._popup_editor = None
+ def __init__(self, instance, object):
+ wx.EvtHandler.__init__(self)
+ self.editor = instance
+ self.object = object
+ self.hasFocus = 0
+ self.highlightBox = WidgetHighlighter(self.editor.panel)
+ self._iMoved = 0
+ self._alreadySelected = 0
+ self._popup_editor = None
- def initialize(self, widget):
- self.widget = widget.widgets[0]
- self.mainWidget = widget
- self.selected = 0
+ def initialize(self, widget):
+ self.widget = widget.widgets[0]
+ self.mainWidget = widget
+ self.selected = 0
- self.recalcBoundaries()
+ self.recalcBoundaries()
- for widget in self.mainWidget.widgets:
- widget.SetCursor (wx.STANDARD_CURSOR)
+ for widget in self.mainWidget.widgets:
+ widget.SetCursor (wx.STANDARD_CURSOR)
# try:
# widget.Enable(0)
# except:
# pass
- try:
- widget.SetEditable(0)
- except:
- pass
+ try:
+ widget.SetEditable(0)
+ except:
+ pass
- self.setAllChildren(EVT_KEY_UP, widget, self.editor.keyTrap)
- self.setAllChildren(EVT_SET_FOCUS, widget, self.focusGainedTrap)
- self.setAllChildren(EVT_KILL_FOCUS, widget, self.focusLostTrap)
- self.setAllChildren(EVT_LEFT_UP, widget, self.OnLeftUp)
- self.setAllChildren(EVT_LEFT_DOWN, widget, self.OnLeftDown)
- self.setAllChildren(EVT_RIGHT_DOWN, widget, self.OnRightDown)
- self.setAllChildren(EVT_RIGHT_UP, widget, self.OnRightUp)
- self.setAllChildren(EVT_MOTION, widget, self.OnMotion)
- self.setAllChildren(EVT_LEFT_DCLICK, widget, self.onLeftDClick)
- self.setAllChildren(EVT_KEY_UP, self.highlightBox, self.editor.keyTrap)
- self.setAllChildren(EVT_SET_FOCUS, self.highlightBox, self.focusGainedTrap)
- self.setAllChildren(EVT_KILL_FOCUS, self.highlightBox, self.focusLostTrap)
- self.setAllChildren(EVT_LEFT_UP, self.highlightBox, self.OnLeftUp)
- self.setAllChildren(EVT_LEFT_DOWN, self.highlightBox, self.OnLeftDown)
- self.setAllChildren(EVT_RIGHT_UP, self.highlightBox, self.OnRightUp)
- self.setAllChildren(EVT_MOTION, self.highlightBox, self.OnMotion)
+ self.setAllChildren(EVT_KEY_UP, widget, self.editor.keyTrap)
+ self.setAllChildren(EVT_SET_FOCUS, widget, self.focusGainedTrap)
+ self.setAllChildren(EVT_KILL_FOCUS, widget, self.focusLostTrap)
+ self.setAllChildren(EVT_LEFT_UP, widget, self.OnLeftUp)
+ self.setAllChildren(EVT_LEFT_DOWN, widget, self.OnLeftDown)
+ self.setAllChildren(EVT_RIGHT_DOWN, widget, self.OnRightDown)
+ self.setAllChildren(EVT_RIGHT_UP, widget, self.OnRightUp)
+ self.setAllChildren(EVT_MOTION, widget, self.OnMotion)
+ self.setAllChildren(EVT_LEFT_DCLICK, widget, self.onLeftDClick)
+ self.setAllChildren(EVT_KEY_UP, self.highlightBox, self.editor.keyTrap)
+ self.setAllChildren(EVT_SET_FOCUS, self.highlightBox,
self.focusGainedTrap)
+ self.setAllChildren(EVT_KILL_FOCUS, self.highlightBox,
self.focusLostTrap)
+ self.setAllChildren(EVT_LEFT_UP, self.highlightBox, self.OnLeftUp)
+ self.setAllChildren(EVT_LEFT_DOWN, self.highlightBox, self.OnLeftDown)
+ self.setAllChildren(EVT_RIGHT_UP, self.highlightBox, self.OnRightUp)
+ self.setAllChildren(EVT_MOTION, self.highlightBox, self.OnMotion)
- self.widget.Refresh()
+ self.widget.Refresh()
- def recalcBoundaries(self):
- x1,y1,x2,y2 = (9999999,9999999,0,0)
+ def recalcBoundaries(self):
+ x1,y1,x2,y2 = (9999999,9999999,0,0)
- for widget in self.mainWidget.widgets:
- tx, ty = widget.GetPositionTuple()
- tw, th = widget.GetSizeTuple()
- self.editor.positionMappings[widget] = [tx,ty,tx+tw-1,ty+tw-1,self]
- if tx < x1:
- x1 = tx
- if ty < y1:
- y1 = ty
- if tw + tx > x2:
- x2 = tw + tx
- if th + ty > y2:
- y2 = th + ty
+ for widget in self.mainWidget.widgets:
+ tx, ty = widget.GetPositionTuple()
+ tw, th = widget.GetSizeTuple()
+ self.editor.positionMappings[widget] = [tx,ty,tx+tw-1,ty+tw-1,self]
+ if tx < x1:
+ x1 = tx
+ if ty < y1:
+ y1 = ty
+ if tw + tx > x2:
+ x2 = tw + tx
+ if th + ty > y2:
+ y2 = th + ty
- self.highlightBox.setBoundary(x1-2,y1-2,x2+2,y2+2)
- for widget in self.mainWidget.widgets:
- widget.Refresh()
+ self.highlightBox.setBoundary(x1-2,y1-2,x2+2,y2+2)
+ for widget in self.mainWidget.widgets:
+ widget.Refresh()
- def setSelected(self, selected, focused=1):
- self.selected = selected
- self.focused = focused
- self.highlightBox.setSelected(selected, focused)
+ def setSelected(self, selected, focused=1):
+ self.selected = selected
+ self.focused = focused
+ self.highlightBox.setSelected(selected, focused)
- def setAllChildren(self, event, widget, trap):
- try:
- event(widget, trap)
- except:
- pass
- for child in widget.GetChildren():
- self.setAllChildren(event, child, trap)
+ def setAllChildren(self, event, widget, trap):
+ try:
+ event(widget, trap)
+ except:
+ pass
+ for child in widget.GetChildren():
+ self.setAllChildren(event, child, trap)
- def focusGainedTrap(self, event):
- self.editor.panel.SetFocus()
- pass
+ def focusGainedTrap(self, event):
+ self.editor.panel.SetFocus()
+ pass
# event.Skip()
- def focusLostTrap(self, event):
- event.Skip()
+ def focusLostTrap(self, event):
+ event.Skip()
- def beginDragDrop(self, event):
+ def beginDragDrop(self, event):
- # Drag and drop TODO: This needs changed to pull all selected widgets
+ # Drag and drop TODO: This needs changed to pull all selected widgets
- object = self.object
+ object = self.object
- x,y = event.GetPositionTuple()
+ x,y = event.GetPositionTuple()
- data = [ { "Type" : "selectedWidgets",
- "Attributes": {
- 'startingX': object.Char__x + int(x/self.editor.gridWidth),
- 'startingY': object.Char__y + int(y/self.editor.gridHeight),
- }
- }]
+ data = [ { "Type" : "selectedWidgets",
+ "Attributes": {
+ 'startingX': object.Char__x +
int(x/self.editor.gridWidth),
+ 'startingY': object.Char__y +
int(y/self.editor.gridHeight),
+ }
+ }]
# "name": dname,
# "table": object.name,
# "database": self.connectionName } }
#
#
- do =
wx.CustomDataObject(wx.CustomDataFormat("application/x-gnue-designer"))
- do.SetData(cPickle.dumps(data,1))
+ do =
wx.CustomDataObject(wx.CustomDataFormat("application/x-gnue-designer"))
+ do.SetData(cPickle.dumps(data,1))
## icon = FeedbackBitmap(10,10).icon()
- dropSource = MoveDropSource(self, self.editor)
- dropSource.SetData(do)
- result = dropSource.DoDragDrop(True)
- event.Skip()
+ dropSource = MoveDropSource(self, self.editor)
+ dropSource.SetData(do)
+ result = dropSource.DoDragDrop(True)
+ event.Skip()
- def OnLeftDown(self, event):
+ def OnLeftDown(self, event):
- if self.editor.mode == 'move':
+ if self.editor.mode == 'move':
- self.mouseStartX, self.mouseStartY = event.GetPositionTuple()
- self._iMoved = 0
+ self.mouseStartX, self.mouseStartY = event.GetPositionTuple()
+ self._iMoved = 0
- if event.ShiftDown():
- selections = self.editor._currentSelection[:]
- else:
- selections = []
+ if event.ShiftDown():
+ selections = self.editor._currentSelection[:]
+ else:
+ selections = []
- if self.object in selections:
- if event.ShiftDown():
- del selections[selections.index(self.object)]
- else:
- selections.append(self.object)
+ if self.object in selections:
+ if event.ShiftDown():
+ del selections[selections.index(self.object)]
+ else:
+ selections.append(self.object)
- self.editor._instance.dispatchEvent('ObjectSelected',object=self.object,
- originator="Forms::LayoutEditor",
- selection=selections)
- else:
- xo, yo = self.widget.GetPosition()
- x, y = event.GetPositionTuple()
- self.editor.handleLeftDown(x+xo,y+yo)
+
self.editor._instance.dispatchEvent('ObjectSelected',object=self.object,
+
originator="Forms::LayoutEditor",
+ selection=selections)
+ else:
+ xo, yo = self.widget.GetPosition()
+ x, y = event.GetPositionTuple()
+ self.editor.handleLeftDown(x+xo,y+yo)
- event.Skip()
+ event.Skip()
- def OnLeftUp(self, event):
- if self.editor.mode == 'move':
- if self._iMoved:
- self._iMoved = 0
- else:
- xo, yo = self.widget.GetPosition()
- x, y = event.GetPositionTuple()
- self.editor.handleLeftUp(x+xo,y+yo)
+ def OnLeftUp(self, event):
+ if self.editor.mode == 'move':
+ if self._iMoved:
+ self._iMoved = 0
+ else:
+ xo, yo = self.widget.GetPosition()
+ x, y = event.GetPositionTuple()
+ self.editor.handleLeftUp(x+xo,y+yo)
- event.Skip()
+ event.Skip()
- def OnMotion(self, event):
+ def OnMotion(self, event):
- if not self._iMoved and event.LeftIsDown():
- self._iMoved = 1
- self.beginDragDrop(event)
+ if not self._iMoved and event.LeftIsDown():
+ self._iMoved = 1
+ self.beginDragDrop(event)
- event.Skip()
+ event.Skip()
- def OnRightDown(self, event):
- event.Skip()
+ def OnRightDown(self, event):
+ event.Skip()
- def OnRightUp(self, event):
- if self.editor.mode == 'move':
- pt = event.GetPositionTuple()
- self.editor.dispatchEvent('ObjectSelected',object=self.object,
originator=None)
- wx.PyTypeCast(event.GetEventObject(),'wx.Window') \
- .PopupMenu(self.object._popupMenu, pt)
- event.Skip()
+ def OnRightUp(self, event):
+ if self.editor.mode == 'move':
+ pt = event.GetPositionTuple()
+ self.editor.dispatchEvent('ObjectSelected',object=self.object,
originator=None)
+ wx.PyTypeCast(event.GetEventObject(),'wx.Window') \
+ .PopupMenu(self.object._popupMenu, pt)
+ event.Skip()
- def _endPopupEditor(self, success, value=""):
- if success:
+ def _endPopupEditor(self, success, value=""):
+ if success:
- try:
- oldVals = {self.__popupAttr:self.object.__dict__[self.__popupAttr]}
- except KeyError:
- oldVals = {self.__popupAttr:None}
- newVals = {self.__popupAttr: value}
- self.object.__dict__.update(newVals)
- self.editor.dispatchEvent('ObjectModified', object=self.object,
- originator="Forms::LayoutEditor",
- old=oldVals,
- new=newVals)
+ try:
+ oldVals =
{self.__popupAttr:self.object.__dict__[self.__popupAttr]}
+ except KeyError:
+ oldVals = {self.__popupAttr:None}
+ newVals = {self.__popupAttr: value}
+ self.object.__dict__.update(newVals)
+ self.editor.dispatchEvent('ObjectModified', object=self.object,
+ originator="Forms::LayoutEditor",
+ old=oldVals,
+ new=newVals)
- self._popup_editor.Destroy()
- self._popup_editor = None
- self.widget.SetLabel(value or "<Unset>")
- if self.object._type == 'GFLabel':
- width = len(value) or 10
- self.widget.SetSize((width * self.editor.gridWidth,
- self.widget.GetSize().height))
- self.recalcBoundaries()
- self.setSelected(self.selected)
+ self._popup_editor.Destroy()
+ self._popup_editor = None
+ self.widget.SetLabel(value or "<Unset>")
+ if self.object._type == 'GFLabel':
+ width = len(value) or 10
+ self.widget.SetSize((width * self.editor.gridWidth,
+ self.widget.GetSize().height))
+ self.recalcBoundaries()
+ self.setSelected(self.selected)
- def onLeftDClick(self, event):
+ def onLeftDClick(self, event):
- if self.editor.mode == 'move':
- if self.object._type in ('GFBox','GFLabel'):
- # Create a popup text editor for the labels
- if self.object._type == 'GFBox':
- self.__popupAttr = 'label'
- x = self.widget.GetPosition().x + (self.editor.gridWidth/2)
- width = (self.object.Char__width - 2) * self.editor.gridWidth
- else:
- self.__popupAttr = 'text'
- x = self.widget.GetPosition().x
- width = self.widget.GetSize().width + self.editor.gridWidth
+ if self.editor.mode == 'move':
+ if self.object._type in ('GFBox','GFLabel'):
+ # Create a popup text editor for the labels
+ if self.object._type == 'GFBox':
+ self.__popupAttr = 'label'
+ x = self.widget.GetPosition().x + (self.editor.gridWidth/2)
+ width = (self.object.Char__width - 2) *
self.editor.gridWidth
+ else:
+ self.__popupAttr = 'text'
+ x = self.widget.GetPosition().x
+ width = self.widget.GetSize().width + self.editor.gridWidth
- self._popup_editor = PopupEditor(self.editor.workspace,
- self._endPopupEditor,
- x + self.editor.panel.GetPosition().x,
- self.widget.GetPosition().y + self.editor.panel.GetPosition().y,
- width,
- self.editor.gridHeight,
- self.object.__dict__[self.__popupAttr])
+ self._popup_editor = PopupEditor(self.editor.workspace,
+ self._endPopupEditor,
+ x + self.editor.panel.GetPosition().x,
+ self.widget.GetPosition().y +
self.editor.panel.GetPosition().y,
+ width,
+ self.editor.gridHeight,
+ self.object.__dict__[self.__popupAttr])
- self._popup_editor.SetFocus()
+ self._popup_editor.SetFocus()
- else:
- # Signal the Properties dialog
- self.editor._instance.dispatchEvent('Show:Tool:objectProperties')
+ else:
+ # Signal the Properties dialog
+
self.editor._instance.dispatchEvent('Show:Tool:objectProperties')
- #
- # Resize the current widget. dx and dy are incremental
- # resize units. (e.g, (-1,0) means make the widget one
- # unit smaller than it currently is.
- #
- def relativeResize(self, dx, dy):
- if not (dx or dy):
- return 0
+ #
+ # Resize the current widget. dx and dy are incremental
+ # resize units. (e.g, (-1,0) means make the widget one
+ # unit smaller than it currently is.
+ #
+ def relativeResize(self, dx, dy):
+ if not (dx or dy):
+ return 0
- nx = dx * self.editor.gridWidth
- ny = dy * self.editor.gridHeight
+ nx = dx * self.editor.gridWidth
+ ny = dy * self.editor.gridHeight
- try:
- self.object.Char__height
- except:
- self.object.Char__height = 1
+ try:
+ self.object.Char__height
+ except:
+ self.object.Char__height = 1
- if (self.object.Char__width + dx < 0 or self.object.Char__height + dy < 0):
- return 0
- else:
- for widget in self.mainWidget.widgets:
- x,y = widget.GetSizeTuple()
- widget.SetSize(wx.Size(x + nx,y + ny))
+ if (self.object.Char__width + dx < 0 or self.object.Char__height + dy
< 0):
+ return 0
+ else:
+ for widget in self.mainWidget.widgets:
+ x,y = widget.GetSizeTuple()
+ widget.SetSize(wx.Size(x + nx,y + ny))
- oldVals = {}
- newVals = {}
- if dx:
- oldVals['Char:width'] = self.object.Char__width
- self.object.Char__width = self.object.Char__width + dx
- newVals['Char:width'] = self.object.Char__width
- if dy:
- oldVals['Char:height'] = self.object.Char__height
- self.object.Char__height = self.object.Char__height + dy
- newVals['Char:height'] = self.object.Char__height
+ oldVals = {}
+ newVals = {}
+ if dx:
+ oldVals['Char:width'] = self.object.Char__width
+ self.object.Char__width = self.object.Char__width + dx
+ newVals['Char:width'] = self.object.Char__width
+ if dy:
+ oldVals['Char:height'] = self.object.Char__height
+ self.object.Char__height = self.object.Char__height + dy
+ newVals['Char:height'] = self.object.Char__height
- self.editor.dispatchEvent('ObjectModified', object=self.object,
- originator="Forms::LayoutEditor",
- old=oldVals,
- new=newVals)
+ self.editor.dispatchEvent('ObjectModified', object=self.object,
+ originator="Forms::LayoutEditor",
+ old=oldVals,
+ new=newVals)
- self.recalcBoundaries()
+ self.recalcBoundaries()
- #
- # Move the current widget. dx and dy are increments.
- # (e.g., (-1,-2) means move the object up one unit
- # and left two units.
- #
- def relativeMove(self, dx, dy):
- if not (dx or dy):
- return 0
+ #
+ # Move the current widget. dx and dy are increments.
+ # (e.g., (-1,-2) means move the object up one unit
+ # and left two units.
+ #
+ def relativeMove(self, dx, dy):
+ if not (dx or dy):
+ return 0
- nx = dx * self.editor.gridWidth
- ny = dy * self.editor.gridHeight
+ nx = dx * self.editor.gridWidth
+ ny = dy * self.editor.gridHeight
- if (self.object.Char__x + dx < 0 or self.object.Char__y + dy < 0):
- return 0
- else:
- for widget in self.mainWidget.widgets:
- x,y = widget.GetPositionTuple()
- widget.SetPosition(wx.Point(x + nx,y + ny))
- oldVals = {}
- newVals = {}
- if dx:
- oldVals['Char:x'] = self.object.Char__x
- self.object.Char__x += dx
- newVals['Char:x'] = self.object.Char__x
- if dy:
- oldVals['Char:y'] = self.object.Char__y
- self.object.Char__y += dy
- newVals['Char:y'] = self.object.Char__y
+ if (self.object.Char__x + dx < 0 or self.object.Char__y + dy < 0):
+ return 0
+ else:
+ for widget in self.mainWidget.widgets:
+ x,y = widget.GetPositionTuple()
+ widget.SetPosition(wx.Point(x + nx,y + ny))
+ oldVals = {}
+ newVals = {}
+ if dx:
+ oldVals['Char:x'] = self.object.Char__x
+ self.object.Char__x += dx
+ newVals['Char:x'] = self.object.Char__x
+ if dy:
+ oldVals['Char:y'] = self.object.Char__y
+ self.object.Char__y += dy
+ newVals['Char:y'] = self.object.Char__y
- self.editor.dispatchEvent('ObjectModified', object=self.object,
- originator="Forms::LayoutEditor",
- old=oldVals,
- new=newVals)
+ self.editor.dispatchEvent('ObjectModified', object=self.object,
+ originator="Forms::LayoutEditor",
+ old=oldVals,
+ new=newVals)
- self.recalcBoundaries()
+ self.recalcBoundaries()
- #
- # Recursively destroy this widget set
- #
- def Destroy(self):
+ #
+ # Recursively destroy this widget set
+ #
+ def Destroy(self):
- # TODO: Why the fsck can't I Destroy() this thing!?!??!?
- self.widget.Show(0)
+ # TODO: Why the fsck can't I Destroy() this thing!?!??!?
+ self.widget.Show(0)
- self.editor = None
- self.object = None
- self.highlightBox.Destroy()
- self.highlightBox = None
- self._popup_editor = None
- self.widget = None
- self.mainWidget = None
+ self.editor = None
+ self.object = None
+ self.highlightBox.Destroy()
+ self.highlightBox = None
+ self._popup_editor = None
+ self.widget = None
+ self.mainWidget = None
Modified: trunk/gnue-designer/src/forms/PagePainter/PagePainter.py
===================================================================
--- trunk/gnue-designer/src/forms/PagePainter/PagePainter.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/forms/PagePainter/PagePainter.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -56,7 +56,7 @@
# Determine text extents
dc = wx.PaintDC(self)
dc.SetFont(wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT))
-
+
if not common.char_x_scale:
for char in string.digits + string.letters:
w, h = dc.GetTextExtent(char)
@@ -148,6 +148,3 @@
self.document_origin_x = common.char_x_scale * 2
self.document_origin_y = common.char_y_scale * 2
-
-
-
Modified: trunk/gnue-designer/src/forms/PagePainter/skins/common.py
===================================================================
--- trunk/gnue-designer/src/forms/PagePainter/skins/common.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/forms/PagePainter/skins/common.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -69,11 +69,11 @@
documentY = canvas.document_origin_y
# Right now, only Char positioning is supported.
- try:
- x = object['Char:x']
- y = object['Char:y']
- except:
- x = y = 0
+ try:
+ x = object['Char:x']
+ y = object['Char:y']
+ except:
+ x = y = 0
try:
w = object['Char:width']
@@ -118,11 +118,8 @@
pass
-class ContainerWidget(FormWidget):
+class ContainerWidget(FormWidget):
"""
A widget that can be a container
"""
container = True
-
-
-
\ No newline at end of file
Modified: trunk/gnue-designer/src/forms/PagePainter/skins/default.py
===================================================================
--- trunk/gnue-designer/src/forms/PagePainter/skins/default.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/forms/PagePainter/skins/default.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -25,7 +25,7 @@
Implement the default, simple GUI skin
"""
-import wx
+import wx
from gnue.designer.ui.wx.uihelpers.doccanvas.colors import color_map
from common import FormWidget, ContainerWidget
@@ -43,9 +43,9 @@
if object._type == 'GFLabel':
cls = LabelWidget
elif object._type == 'GFEntry':
- cls = EntryWidget
+ cls = EntryWidget
elif object._type == 'GFPage':
- cls = PageWidget
+ cls = PageWidget
elif object._type == 'GFBox':
cls = BoxWidget
elif object._type == 'GFButton':
@@ -57,7 +57,7 @@
# --------------------------------------------------------------------------
-# Page
+# Page
# --------------------------------------------------------------------------
class PageWidget(ContainerWidget):
def calc_metrics(self):
@@ -66,7 +66,7 @@
object = self.gobject.findParentOfType('GFLayout')
- # This gives us an offset onto the current drawing canvas,
+ # This gives us an offset onto the current drawing canvas,
# accounting for any workspace margins.
x_offset = canvas.document_origin_x
y_offset = canvas.document_origin_y
@@ -101,7 +101,7 @@
self.hit_test_exclusions = [
wx.Rect(x + x_offset + common.char_x_scale,
y + y_offset + common.char_y_scale,
- width - common.char_x_scale * 2,
+ width - common.char_x_scale * 2,
height - common.char_y_scale * 2) ]
# Save the area, relative to being drawn in a context at (0,0)
@@ -133,23 +133,23 @@
# Center each character in its cell
for char in object['text']:
text_width, text_height = dc.GetTextExtent(char)
- dc.DrawText(char,
- x + (common.char_x_scale - text_width) // 2,
+ dc.DrawText(char,
+ x + (common.char_x_scale - text_width) // 2,
y + 1)
x += common.char_x_scale
- def enter_edit_mode(self):
+ def enter_edit_mode(self):
"""
Called when the user double-clicks to edit
"""
object = self.gobject
x, y, width, height = self.hit_test_area.Get()
- self.text_edit(x, y,
- width,
- common.char_y_scale,
+ self.text_edit(x, y,
+ width,
+ common.char_y_scale,
self.gobject['text'])
-
- def end_text_edit(self, text):
+
+ def end_text_edit(self, text):
"""
Called when the text edit request is finished
"""
@@ -181,23 +181,23 @@
dc.SetFont(wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT))
text = self.gobject['label']
text_width, text_height = dc.GetTextExtent(text)
-
- dc.DrawText(text,
- x + width // 2 - text_width // 2,
+
+ dc.DrawText(text,
+ x + width // 2 - text_width // 2,
y + height // 2 - text_height // 2 - 2)
-
- def enter_edit_mode(self):
+
+ def enter_edit_mode(self):
"""
Called when the user double-clicks to edit
"""
object = self.gobject
x, y, width, height = self.hit_test_area.Get()
- self.text_edit(x, y,
- width,
- common.char_y_scale,
+ self.text_edit(x, y,
+ width,
+ common.char_y_scale,
self.gobject['label'])
-
- def end_text_edit(self, text):
+
+ def end_text_edit(self, text):
"""
Called when the text edit request is finished
"""
@@ -219,7 +219,7 @@
y1 = y + common.char_y_scale // 2 + 1
x2 = x + width - common.char_x_scale // 2
y2 = y + height - common.char_y_scale // 2
-
+
# Draw the lines
dc.SetFont(wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT))
@@ -229,32 +229,32 @@
dc.SetPen(wx.Pen(color_map['widgetdark']))
dc.DrawLine(x1 + 1, y2, x2, y2) # Bottom
dc.DrawLine(x2, y1 + 1, x2, y2) # Right
-
+
dc.SetPen(wx.Pen(color_map['widgetlight']))
- dc.DrawLine(x1, y1 + 1, x1, y2) # Left
+ dc.DrawLine(x1, y1 + 1, x1, y2) # Left
dc.DrawLine(x1 + 1, # Top
y1, x + int(common.char_x_scale * 1.5) - 4, y1)
- dc.DrawLine(x + int(common.char_x_scale * 1.5) + 3 + text_width,
+ dc.DrawLine(x + int(common.char_x_scale * 1.5) + 3 + text_width,
y1, x2, y1)
# and draw the text
dc.SetPen(wx.Pen(color_map['text']))
- dc.DrawText(text,
- x + int(common.char_x_scale * 1.5),
+ dc.DrawText(text,
+ x + int(common.char_x_scale * 1.5),
y + common.char_y_scale // 2 - text_height // 2)
-
- def enter_edit_mode(self):
+
+ def enter_edit_mode(self):
"""
Called when the user double-clicks to edit
"""
object = self.gobject
x, y, width, height = self.hit_test_area.Get()
- self.text_edit(x, y,
- width - common.char_x_scale * 3,
- common.char_y_scale,
+ self.text_edit(x, y,
+ width - common.char_x_scale * 3,
+ common.char_y_scale,
self.gobject['label'])
-
- def end_text_edit(self, text):
+
+ def end_text_edit(self, text):
"""
Called when the text edit request is finished
"""
@@ -273,5 +273,3 @@
x, y, width, height = self.draw_area.Get()
dc.SetFont(wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT))
dc.DrawRoundedRectangle(x, y, width, height - 1, 4)
-
-
Modified: trunk/gnue-designer/src/forms/PagePainter/skins/term.py
===================================================================
--- trunk/gnue-designer/src/forms/PagePainter/skins/term.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/forms/PagePainter/skins/term.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -23,8 +23,8 @@
"""
Implement a character-based (console or terminal) skin
-(i.e., simulate what the screen would look like on an
-ncurses screen.
+(i.e., simulate what the screen would look like on an
+ncurses screen.
"""
from common import FormWidget
@@ -32,4 +32,4 @@
from gnue.designer.ui.wx.uihelpers.doccanvas.colors import colorIndex
-# TODO
\ No newline at end of file
+# TODO
Modified: trunk/gnue-designer/src/forms/PropertyEditor.py
===================================================================
--- trunk/gnue-designer/src/forms/PropertyEditor.py 2006-04-03 19:53:03 UTC
(rev 8343)
+++ trunk/gnue-designer/src/forms/PropertyEditor.py 2006-04-03 19:56:14 UTC
(rev 8344)
@@ -37,47 +37,47 @@
from gnue.designer.base.ToolBase import *
class PropertyEditor (BasePropertyEditor):
- def reset(self):
- BasePropertyEditor.reset(self)
+ def reset(self):
+ BasePropertyEditor.reset(self)
- #
- # Is this a Positionable widget? If so, show x,y,w,h editor
- #
- try:
- layout = self.document.incubator.elements[
- (self.object._type[2:]).lower()]['Positionable']
- except KeyError:
- if self.object._type == 'GFLabel':
- raise
- layout = False
+ #
+ # Is this a Positionable widget? If so, show x,y,w,h editor
+ #
+ try:
+ layout = self.document.incubator.elements[
+ (self.object._type[2:]).lower()]['Positionable']
+ except KeyError:
+ if self.object._type == 'GFLabel':
+ raise
+ layout = False
- #
- # GFEntry? Show the corresponding GFField
- #
- if self.object._type == 'GFEntry':
- assert gDebug(4,'Adding a new entry property manager')
- self.addPage(FieldInspectorPanel(self, self.notebook), "Field")
- if self.object._block:
- self.addPage(EntryBlockInspectorPanel(self, self.notebook), "Block")
+ #
+ # GFEntry? Show the corresponding GFField
+ #
+ if self.object._type == 'GFEntry':
+ assert gDebug(4,'Adding a new entry property manager')
+ self.addPage(FieldInspectorPanel(self, self.notebook), "Field")
+ if self.object._block:
+ self.addPage(EntryBlockInspectorPanel(self, self.notebook),
"Block")
- # Child of Block?
- if self.object.findParentOfType('GFBlock',includeSelf=False):
- self.addPage(BlockInspectorPanel(self, self.notebook), "Block")
+ # Child of Block?
+ if self.object.findParentOfType('GFBlock',includeSelf=False):
+ self.addPage(BlockInspectorPanel(self, self.notebook), "Block")
- # Block?
- if self.object._type == 'GFBlock' and hasattr(self.object,'datasource') \
- and self.object.datasource and hasattr(self.document,'datasources'):
- self.addPage(DatasourceInspectorPanel(self, self.notebook), "Data
Source")
+ # Block?
+ if self.object._type == 'GFBlock' and
hasattr(self.object,'datasource') \
+ and self.object.datasource and
hasattr(self.document,'datasources'):
+ self.addPage(DatasourceInspectorPanel(self, self.notebook), "Data
Source")
- # Add layout
- if self.object._type == 'GFLayout':
- assert gDebug(4,'Adding a new layout property manager')
- self.addPage(CharSizeInspectorPanel(self, self.notebook), 'Layout')
+ # Add layout
+ if self.object._type == 'GFLayout':
+ assert gDebug(4,'Adding a new layout property manager')
+ self.addPage(CharSizeInspectorPanel(self, self.notebook), 'Layout')
- # Add layout
- elif layout:
- assert gDebug(4,'Adding a new layout property manager')
- self.addPage(CharPosInspectorPanel(self, self.notebook), 'Layout')
+ # Add layout
+ elif layout:
+ assert gDebug(4,'Adding a new layout property manager')
+ self.addPage(CharPosInspectorPanel(self, self.notebook), 'Layout')
#
@@ -85,60 +85,60 @@
#
class FieldInspectorPanel(BaseInspectorPanel):
- def setCurrent(self, object):
- self._setCurrent(object._field)
+ def setCurrent(self, object):
+ self._setCurrent(object._field)
#
# Block properties (when Entry/Field is selected)
#
class BlockInspectorPanel(BaseInspectorPanel):
- def setCurrent(self, object):
- self._setCurrent(object.findParentOfType('GFBlock'))
+ def setCurrent(self, object):
+ self._setCurrent(object.findParentOfType('GFBlock'))
class EntryBlockInspectorPanel(BaseInspectorPanel):
- def setCurrent(self, object):
- self._setCurrent(object._block)
+ def setCurrent(self, object):
+ self._setCurrent(object._block)
#
# Datasource properties (when Block is selected)
#
class DatasourceInspectorPanel(BaseInspectorPanel):
- def setCurrent(self, object):
- try:
- if hasattr(object,'datasource') and object.datasource:
- self._setCurrent(self.editor.document.datasources[object.datasource])
- except AttributeError:
- pass # Happens on startup
+ def setCurrent(self, object):
+ try:
+ if hasattr(object,'datasource') and object.datasource:
+
self._setCurrent(self.editor.document.datasources[object.datasource])
+ except AttributeError:
+ pass # Happens on startup
#
# Character-cell layout (x,y) properties
#
class CharPosInspectorPanel(BaseInspectorPanel):
- NAMESPACE = "Char"
+ NAMESPACE = "Char"
- def getAttributes(self, object):
- return {
- 'Char:x': { 'Typecast': GTypecast.whole },
- 'Char:y': { 'Typecast': GTypecast.whole },
- 'Char:width': { 'Typecast': GTypecast.whole },
- 'Char:height': { 'Typecast': GTypecast.whole } }
+ def getAttributes(self, object):
+ return {
+ 'Char:x': { 'Typecast': GTypecast.whole },
+ 'Char:y': { 'Typecast': GTypecast.whole },
+ 'Char:width': { 'Typecast': GTypecast.whole },
+ 'Char:height': { 'Typecast': GTypecast.whole } }
- def getPageText(self):
- return "Display"
+ def getPageText(self):
+ return "Display"
#
# Character-cell layout (x,y) properties
#
class CharSizeInspectorPanel(BaseInspectorPanel):
- NAMESPACE = "Char"
+ NAMESPACE = "Char"
- def getAttributes(self, object):
- return {
- 'Char:width': { 'Typecast': GTypecast.whole },
- 'Char:height': { 'Typecast': GTypecast.whole } }
+ def getAttributes(self, object):
+ return {
+ 'Char:width': { 'Typecast': GTypecast.whole },
+ 'Char:height': { 'Typecast': GTypecast.whole } }
- def getPageText(self):
- return "Display"
+ def getPageText(self):
+ return "Display"
Modified: trunk/gnue-designer/src/forms/TemplateSupport.py
===================================================================
--- trunk/gnue-designer/src/forms/TemplateSupport.py 2006-04-03 19:53:03 UTC
(rev 8343)
+++ trunk/gnue-designer/src/forms/TemplateSupport.py 2006-04-03 19:56:14 UTC
(rev 8344)
@@ -32,7 +32,7 @@
def createRootObject(instance):
- return GFForm(app=instance)
+ return GFForm(app=instance)
###########################################################
@@ -42,9 +42,9 @@
###########################################################
class FormTemplate(TemplateBase):
- # Initialize user code
- def Start(self, root, current):
- pass
+ # Initialize user code
+ def Start(self, root, current):
+ pass
@@ -60,17 +60,16 @@
###########################################################
class FormPrePositioningTemplate(FormTemplate):
- # Initialize user code
- def Start(self, root, current, **params):
- return self.StartWithPositioning(root, current,
- **params)
+ # Initialize user code
+ def Start(self, root, current, **params):
+ return self.StartWithPositioning(root, current,
+ **params)
- def StartWithPositioning(self, root, current, x=0, y=0,
- width=None, height=None):
- pass
+ def StartWithPositioning(self, root, current, x=0, y=0,
+ width=None, height=None):
+ pass
- def __init__(self, *args, **params):
- FormTemplate.__init__(self, *args, **params)
-
+ def __init__(self, *args, **params):
+ FormTemplate.__init__(self, *args, **params)
Modified: trunk/gnue-designer/src/forms/TreeView.py
===================================================================
--- trunk/gnue-designer/src/forms/TreeView.py 2006-04-03 19:53:03 UTC (rev
8343)
+++ trunk/gnue-designer/src/forms/TreeView.py 2006-04-03 19:56:14 UTC (rev
8344)
@@ -42,93 +42,91 @@
class TreeView (BaseTreeView):
- rootDescr = 'Form'
+ rootDescr = 'Form'
- def inittree(self):
+ def inittree(self):
- logic = None
- layout = None
- for child in self.rootObject._children:
- if child._type == 'GFLogic':
- logic = child
- elif child._type == 'GFLayout':
- layout = child
+ logic = None
+ layout = None
+ for child in self.rootObject._children:
+ if child._type == 'GFLogic':
+ logic = child
+ elif child._type == 'GFLayout':
+ layout = child
- self.rootObject._treeItemFormProperties = \
- self.AppendItem(self.rootObject._treeItem, u_("Properties"))
- self.tree.SetItemImage(self.rootObject._treeItemFormProperties,
treeIconMap['properties'])
- self.rootObject._treeItemImportedLibraries = \
- self.AppendItem(self.rootObject._treeItem, u_("Imported Libraries"))
- self.tree.SetItemImage(self.rootObject._treeItemImportedLibraries,
treeIconMap['import'])
- self.rootObject._treeItemDataSources = \
- self.AppendItem(self.rootObject._treeItem, u_("Data Sources"))
- self.tree.SetItemImage(self.rootObject._treeItemDataSources,
treeIconMap['datasource'])
- self.rootObject._treeItemNamedTriggers = \
- self.AppendItem(self.rootObject._treeItem, u_("Shared Triggers"))
- self.tree.SetItemImage(self.rootObject._treeItemNamedTriggers,
treeIconMap['trigger'])
- self.rootObject._treeItemLogic = logic._treeItem = \
- self.AppendItem(self.rootObject._treeItem, u_("Field Logic"))
- self.tree.SetItemImage(self.rootObject._treeItemLogic,
treeIconMap['block'])
- self.rootObject._treeItemPageLayout = layout._treeItem = \
- self.AppendItem(self.rootObject._treeItem, u_("Page Layout"))
- self.tree.SetItemImage(self.rootObject._treeItemPageLayout,
treeIconMap['page'])
+ self.rootObject._treeItemFormProperties = \
+ self.AppendItem(self.rootObject._treeItem, u_("Properties"))
+ self.tree.SetItemImage(self.rootObject._treeItemFormProperties,
treeIconMap['properties'])
+ self.rootObject._treeItemImportedLibraries = \
+ self.AppendItem(self.rootObject._treeItem, u_("Imported
Libraries"))
+ self.tree.SetItemImage(self.rootObject._treeItemImportedLibraries,
treeIconMap['import'])
+ self.rootObject._treeItemDataSources = \
+ self.AppendItem(self.rootObject._treeItem, u_("Data Sources"))
+ self.tree.SetItemImage(self.rootObject._treeItemDataSources,
treeIconMap['datasource'])
+ self.rootObject._treeItemNamedTriggers = \
+ self.AppendItem(self.rootObject._treeItem, u_("Shared Triggers"))
+ self.tree.SetItemImage(self.rootObject._treeItemNamedTriggers,
treeIconMap['trigger'])
+ self.rootObject._treeItemLogic = logic._treeItem = \
+ self.AppendItem(self.rootObject._treeItem, u_("Field Logic"))
+ self.tree.SetItemImage(self.rootObject._treeItemLogic,
treeIconMap['block'])
+ self.rootObject._treeItemPageLayout = layout._treeItem = \
+ self.AppendItem(self.rootObject._treeItem, u_("Page Layout"))
+ self.tree.SetItemImage(self.rootObject._treeItemPageLayout,
treeIconMap['page'])
- self.tree.SetPyData(self.rootObject._treeItemFormProperties,
ObjectMenu(self.document,None))
- self.tree.SetPyData(self.rootObject._treeItemDataSources,
ObjectMenu(self.document,None))
- self.tree.SetPyData(self.rootObject._treeItemNamedTriggers,
ObjectMenu(self.document,None))
- self.tree.SetPyData(self.rootObject._treeItemLogic, logic)
- self.tree.SetPyData(self.rootObject._treeItemPageLayout, layout)
+ self.tree.SetPyData(self.rootObject._treeItemFormProperties,
ObjectMenu(self.document,None))
+ self.tree.SetPyData(self.rootObject._treeItemDataSources,
ObjectMenu(self.document,None))
+ self.tree.SetPyData(self.rootObject._treeItemNamedTriggers,
ObjectMenu(self.document,None))
+ self.tree.SetPyData(self.rootObject._treeItemLogic, logic)
+ self.tree.SetPyData(self.rootObject._treeItemPageLayout, layout)
- def inventoryObject (self, object):
- if object != self.rootObject:
- icon = 'properties'
- if isinstance(object, GFObjects.GFOptions) and \
- object.getParent () == self.rootObject:
- object._treeItem = self.rootObject._treeItemFormProperties
- icon = 'properties'
- elif object._type in ('GFLogic','GFLayout') and \
- object.getParent () == self.rootObject:
- pass
- else:
- parentTreeItem = object.getParent ()._treeItem
- if isinstance(object, GTrigger.GTrigger) and \
- object.type == 'NAMED':
- parentTreeItem = self.rootObject._treeItemNamedTriggers
- icon = 'trigger'
- elif isinstance(object, GTrigger.GTrigger):
+ def inventoryObject (self, object):
+ if object != self.rootObject:
+ icon = 'properties'
+ if isinstance(object, GFObjects.GFOptions) and \
+ object.getParent () == self.rootObject:
+ object._treeItem = self.rootObject._treeItemFormProperties
+ icon = 'properties'
+ elif object._type in ('GFLogic','GFLayout') and \
+ object.getParent () == self.rootObject:
+ pass
+ else:
+ parentTreeItem = object.getParent ()._treeItem
+ if isinstance(object, GTrigger.GTrigger) and \
+ object.type == 'NAMED':
+ parentTreeItem = self.rootObject._treeItemNamedTriggers
+ icon = 'trigger'
+ elif isinstance(object, GTrigger.GTrigger):
- if not hasattr(object.getParent (),'_treeItemTrigger'):
- object.getParent ()._treeItemTrigger = \
- self.AppendItem(object.getParent ()._treeItem, u_("Events"))
- #self.tree.SetItemImage(object._parent._treeItemTrigger,
treeIconMap['trigger'])
+ if not hasattr(object.getParent (),'_treeItemTrigger'):
+ object.getParent ()._treeItemTrigger = \
+ self.AppendItem(object.getParent ()._treeItem,
u_("Events"))
+
#self.tree.SetItemImage(object._parent._treeItemTrigger, treeIconMap['trigger'])
- parentTreeItem = object.getParent ()._treeItemTrigger
- icon = 'trigger'
- elif isinstance(object, GFObjects.GFDataSource) or \
- isinstance(object, GDataSource.GConnection):
- parentTreeItem = self.rootObject._treeItemDataSources
- icon = 'datasource'
- elif isinstance(object, GFObjects.GFPage) and \
- object.getParent () == self.rootObject:
- icon = 'page'
- elif object._type in ('GFBlock',):
- icon = 'block'
- elif object._type in ('GFOption',):
- icon = 'properties'
- elif object._type in ('GFEntry',):
- icon = 'entry'
- elif len(object._type) >= 8 and \
- object._type[:8] == 'GFImport':
- icon = 'import'
- elif object.findParentOfType('GFPage') != None:
- icon = 'pagewidget'
+ parentTreeItem = object.getParent ()._treeItemTrigger
+ icon = 'trigger'
+ elif isinstance(object, GFObjects.GFDataSource) or \
+ isinstance(object, GDataSource.GConnection):
+ parentTreeItem = self.rootObject._treeItemDataSources
+ icon = 'datasource'
+ elif isinstance(object, GFObjects.GFPage) and \
+ object.getParent () == self.rootObject:
+ icon = 'page'
+ elif object._type in ('GFBlock',):
+ icon = 'block'
+ elif object._type in ('GFOption',):
+ icon = 'properties'
+ elif object._type in ('GFEntry',):
+ icon = 'entry'
+ elif len(object._type) >= 8 and \
+ object._type[:8] == 'GFImport':
+ icon = 'import'
+ elif object.findParentOfType('GFPage') != None:
+ icon = 'pagewidget'
- object._treeItem = self.AppendItem(parentTreeItem,
- "%s" % object.getDescription())
- self.tree.SetPyData(object._treeItem, object)
- #self.tree.SetItemImage(object._treeItem, treeIconMap[icon])
-
-
+ object._treeItem = self.AppendItem(parentTreeItem,
+ "%s" % object.getDescription())
+ self.tree.SetPyData(object._treeItem, object)
+ #self.tree.SetItemImage(object._treeItem, treeIconMap[icon])
Modified: trunk/gnue-designer/src/forms/WizardRunner.py
===================================================================
--- trunk/gnue-designer/src/forms/WizardRunner.py 2006-04-03 19:53:03 UTC
(rev 8343)
+++ trunk/gnue-designer/src/forms/WizardRunner.py 2006-04-03 19:56:14 UTC
(rev 8344)
@@ -37,26 +37,26 @@
# before the wizard begins.)
class WizardRunner(BaseWizardRunner):
- def run(self, event):
- # Handle FormPrePositioningTemplate specially;
- # i.e., intercept the run method.
- if issubclass( self.template['BaseClass'],
- TemplateSupport.FormPrePositioningTemplate ):
- self.document.dispatchEvent('BeginWizard',
- template=self.template)
- self.prepositioning = 1
- event.dispatchAfter('LayoutEditor:Prepositioning', wizardrunner=self)
- else:
- self.prepositioning = 0
- BaseWizardRunner.run(self, event)
+ def run(self, event):
+ # Handle FormPrePositioningTemplate specially;
+ # i.e., intercept the run method.
+ if issubclass( self.template['BaseClass'],
+ TemplateSupport.FormPrePositioningTemplate ):
+ self.document.dispatchEvent('BeginWizard',
+ template=self.template)
+ self.prepositioning = 1
+ event.dispatchAfter('LayoutEditor:Prepositioning',
wizardrunner=self)
+ else:
+ self.prepositioning = 0
+ BaseWizardRunner.run(self, event)
- def positioned_run(self, *args, **parms):
- self.prepositioning = 0
- BaseWizardRunner.run(self, None, *args, **parms)
+ def positioned_run(self, *args, **parms):
+ self.prepositioning = 0
+ BaseWizardRunner.run(self, None, *args, **parms)
- def cancel(self, event=None):
- if hasattr(self,'prepositioning') and self.prepositioning:
- self.document.dispatchEvent('Cancel:LayoutEditor:Prepositioning')
- self.document.dispatchEvent('EndWizard', template=self.template)
- else:
- BaseWizardRunner.cancel(self)
+ def cancel(self, event=None):
+ if hasattr(self,'prepositioning') and self.prepositioning:
+ self.document.dispatchEvent('Cancel:LayoutEditor:Prepositioning')
+ self.document.dispatchEvent('EndWizard', template=self.template)
+ else:
+ BaseWizardRunner.cancel(self)
Modified: trunk/gnue-designer/src/forms/__init__.py
===================================================================
--- trunk/gnue-designer/src/forms/__init__.py 2006-04-03 19:53:03 UTC (rev
8343)
+++ trunk/gnue-designer/src/forms/__init__.py 2006-04-03 19:56:14 UTC (rev
8344)
@@ -34,16 +34,15 @@
class FormModuleProperties: #(_BaseInstance.ModuleProperties):
- module = 'forms'
- application = 'GNUe Forms'
- nickname = 'Form'
- description = 'GNUe Form Definition'
- xmlOpeningTag = 'form'
+ module = 'forms'
+ application = 'GNUe Forms'
+ nickname = 'Form'
+ description = 'GNUe Form Definition'
+ xmlOpeningTag = 'form'
- fileExtensions = { 'gfd': 'GNUe Form Definition',
- 'gfl': 'GNUe Form Library' }
+ fileExtensions = { 'gfd': 'GNUe Form Definition',
+ 'gfl': 'GNUe Form Library' }
- defaultFileExtension = 'gfd'
+ defaultFileExtension = 'gfd'
properties = FormModuleProperties()
-
Modified: trunk/gnue-designer/src/forms/events/Arrange.py
===================================================================
--- trunk/gnue-designer/src/forms/events/Arrange.py 2006-04-03 19:53:03 UTC
(rev 8343)
+++ trunk/gnue-designer/src/forms/events/Arrange.py 2006-04-03 19:56:14 UTC
(rev 8344)
@@ -28,188 +28,184 @@
#
class Arrange:
- def __init__(self, instance):
- self.document = instance
- self.enabled = 1
- instance.registerEventListeners( {
- 'Forms:AlignLeft': self.leftEdge,
- 'Forms:AlignRight': self.rightEdge,
- 'Forms:AlignHCenter': self.hCenter,
- 'Forms:AlignTop': self.topEdge,
- 'Forms:AlignBottom': self.bottomEdge,
- 'Forms:AlignVCenter': self.vCenter,
- 'Forms:SmartAlign': self.smartAlign,
- 'ObjectSelected': self.objectSelected } )
- self.selection = None
+ def __init__(self, instance):
+ self.document = instance
+ self.enabled = 1
+ instance.registerEventListeners( {
+ 'Forms:AlignLeft': self.leftEdge,
+ 'Forms:AlignRight': self.rightEdge,
+ 'Forms:AlignHCenter': self.hCenter,
+ 'Forms:AlignTop': self.topEdge,
+ 'Forms:AlignBottom': self.bottomEdge,
+ 'Forms:AlignVCenter': self.vCenter,
+ 'Forms:SmartAlign': self.smartAlign,
+ 'ObjectSelected': self.objectSelected } )
+ self.selection = None
- def _getDimensions(self):
- objects = []
- x=99999
- y=99999
- mx = -1
- my = 1
- for object in self.selection:
- try:
- x = min(x, object['Char:x'])
- y = min(y, object['Char:y'])
- except KeyError:
- continue
- try:
- mx = max(mx, object['Char:x'] + object['Char:width'] - 1)
- except KeyError:
- mx = max(mx, object['Char:x'] + 9)
- try:
- my = max(my, object['Char:y'] + object['Char:width'] - 1)
- except KeyError:
- pass
- objects.append(object)
+ def _getDimensions(self):
+ objects = []
+ x=99999
+ y=99999
+ mx = -1
+ my = 1
+ for object in self.selection:
+ try:
+ x = min(x, object['Char:x'])
+ y = min(y, object['Char:y'])
+ except KeyError:
+ continue
+ try:
+ mx = max(mx, object['Char:x'] + object['Char:width'] - 1)
+ except KeyError:
+ mx = max(mx, object['Char:x'] + 9)
+ try:
+ my = max(my, object['Char:y'] + object['Char:width'] - 1)
+ except KeyError:
+ pass
+ objects.append(object)
## print x,y,mx, mx
- return (objects, x, y, mx, my)
+ return (objects, x, y, mx, my)
- def leftEdge(self, event):
- event.dispatchAfter('BeginUndoGroup')
- objects, x, y, mx, my = self._getDimensions()
- for object in objects:
- oldx = object['Char:x']
- if oldx != x:
- object.Char__x = x
- event.dispatchAfter('ObjectModified', originator=__name__,
- object=object,
- old={'Char:x': oldx},
- new={'Char:x': x})
- event.dispatchAfter('EndUndoGroup')
+ def leftEdge(self, event):
+ event.dispatchAfter('BeginUndoGroup')
+ objects, x, y, mx, my = self._getDimensions()
+ for object in objects:
+ oldx = object['Char:x']
+ if oldx != x:
+ object.Char__x = x
+ event.dispatchAfter('ObjectModified', originator=__name__,
+ object=object,
+ old={'Char:x': oldx},
+ new={'Char:x': x})
+ event.dispatchAfter('EndUndoGroup')
- def rightEdge(self, event):
- event.dispatchAfter('BeginUndoGroup')
- objects, x, y, mx, my = self._getDimensions()
- for object in objects:
- oldx = object['Char:x']
- try:
- newx = mx - object['Char:width'] + 1
- except KeyError:
- newx = mx - 9
- if oldx != newx:
- object.Char__x = newx
- event.dispatchAfter('ObjectModified', originator=__name__,
- object=object,
- old={'Char:x': oldx},
- new={'Char:x': newx})
- event.dispatchAfter('EndUndoGroup')
+ def rightEdge(self, event):
+ event.dispatchAfter('BeginUndoGroup')
+ objects, x, y, mx, my = self._getDimensions()
+ for object in objects:
+ oldx = object['Char:x']
+ try:
+ newx = mx - object['Char:width'] + 1
+ except KeyError:
+ newx = mx - 9
+ if oldx != newx:
+ object.Char__x = newx
+ event.dispatchAfter('ObjectModified', originator=__name__,
+ object=object,
+ old={'Char:x': oldx},
+ new={'Char:x': newx})
+ event.dispatchAfter('EndUndoGroup')
- def hCenter(self, event):
- event.dispatchAfter('BeginUndoGroup')
- objects, x, y, mx, my = self._getDimensions()
- bx = (mx - x + 1)/2
- for object in objects:
- oldx = object['Char:x']
- try:
- newx = int(bx - (object['Char:width']/2) + 1)
- except KeyError:
- newx = mx - 6
- if oldx != newx:
- object.Char__x = newx
- event.dispatchAfter('ObjectModified', originator=__name__,
- object=object,
- old={'Char:x': oldx},
- new={'Char:x': newx})
- event.dispatchAfter('EndUndoGroup')
+ def hCenter(self, event):
+ event.dispatchAfter('BeginUndoGroup')
+ objects, x, y, mx, my = self._getDimensions()
+ bx = (mx - x + 1)/2
+ for object in objects:
+ oldx = object['Char:x']
+ try:
+ newx = int(bx - (object['Char:width']/2) + 1)
+ except KeyError:
+ newx = mx - 6
+ if oldx != newx:
+ object.Char__x = newx
+ event.dispatchAfter('ObjectModified', originator=__name__,
+ object=object,
+ old={'Char:x': oldx},
+ new={'Char:x': newx})
+ event.dispatchAfter('EndUndoGroup')
- def topEdge(self, event):
- event.dispatchAfter('BeginUndoGroup')
- objects, x, y, mx, my = self._getDimensions()
- for object in objects:
- oldy = object['Char:y']
- if oldy != y:
- object.Char__y = y
- event.dispatchAfter('ObjectModified', originator=__name__,
- object=object,
- old={'Char:y': oldy},
- new={'Char:y': y})
- event.dispatchAfter('EndUndoGroup')
+ def topEdge(self, event):
+ event.dispatchAfter('BeginUndoGroup')
+ objects, x, y, mx, my = self._getDimensions()
+ for object in objects:
+ oldy = object['Char:y']
+ if oldy != y:
+ object.Char__y = y
+ event.dispatchAfter('ObjectModified', originator=__name__,
+ object=object,
+ old={'Char:y': oldy},
+ new={'Char:y': y})
+ event.dispatchAfter('EndUndoGroup')
- def bottomEdge(self, event):
- event.dispatchAfter('BeginUndoGroup')
- objects, x, y, mx, my = self._getDimensions()
- for object in objects:
- oldy = object['Char:y']
- try:
- newy = my - object['Char:height'] + 1
- except KeyError:
- newy = my
- if oldy != newy:
- object.Char__y = newy
- event.dispatchAfter('ObjectModified', originator=__name__,
- object=object,
- old={'Char:y': oldy},
- new={'Char:y': newy})
- event.dispatchAfter('EndUndoGroup')
+ def bottomEdge(self, event):
+ event.dispatchAfter('BeginUndoGroup')
+ objects, x, y, mx, my = self._getDimensions()
+ for object in objects:
+ oldy = object['Char:y']
+ try:
+ newy = my - object['Char:height'] + 1
+ except KeyError:
+ newy = my
+ if oldy != newy:
+ object.Char__y = newy
+ event.dispatchAfter('ObjectModified', originator=__name__,
+ object=object,
+ old={'Char:y': oldy},
+ new={'Char:y': newy})
+ event.dispatchAfter('EndUndoGroup')
- def vCenter(self, event):
- event.dispatchAfter('BeginUndoGroup')
- objects, x, y, mx, my = self._getDimensions()
- by = (my - y + 1)/2
- for object in objects:
- oldy = object['Char:y']
- try:
- newy = int(by - (object['Char:height']/2) + 1)
- except KeyError:
- newy = by
- if oldy != newy:
- object.Char__y = newy
- event.dispatchAfter('ObjectModified', originator=__name__,
- object=object,
- old={'Char:y': oldy},
- new={'Char:y': newy})
- event.dispatchAfter('EndUndoGroup')
+ def vCenter(self, event):
+ event.dispatchAfter('BeginUndoGroup')
+ objects, x, y, mx, my = self._getDimensions()
+ by = (my - y + 1)/2
+ for object in objects:
+ oldy = object['Char:y']
+ try:
+ newy = int(by - (object['Char:height']/2) + 1)
+ except KeyError:
+ newy = by
+ if oldy != newy:
+ object.Char__y = newy
+ event.dispatchAfter('ObjectModified', originator=__name__,
+ object=object,
+ old={'Char:y': oldy},
+ new={'Char:y': newy})
+ event.dispatchAfter('EndUndoGroup')
- def smartAlign(self, event):
- objects, x, y, mx, my = self._getDimensions()
- entries = [[]] * (my - y + 1)
- nonentries = [[]] * (my - y + 1)
- for object in objects:
- if object._type in ('entry','button','image'):
- entries[object['Char:y'] - y].append( (object['Char:x'],object))
- else:
- nonentries[object['Char:y'] - y].append( (object['Char:x'],object))
+ def smartAlign(self, event):
+ objects, x, y, mx, my = self._getDimensions()
+ entries = [[]] * (my - y + 1)
+ nonentries = [[]] * (my - y + 1)
+ for object in objects:
+ if object._type in ('entry','button','image'):
+ entries[object['Char:y'] - y].append(
(object['Char:x'],object))
+ else:
+ nonentries[object['Char:y'] - y].append(
(object['Char:x'],object))
- # TODO
+ # TODO
- def objectSelected(self, event):
- try:
- self.selection = event.selection
- except:
- self.selection = [event.object]
+ def objectSelected(self, event):
+ try:
+ self.selection = event.selection
+ except:
+ self.selection = [event.object]
- #
- # Enable/disable our menu options
- # depending on if enough items are
- # selected or not.
- #
- evt = None
- if len(self.selection) > 2 and not self.enabled:
- evt = 'Enable'
- elif self.enabled:
- evt = 'Disable'
+ #
+ # Enable/disable our menu options
+ # depending on if enough items are
+ # selected or not.
+ #
+ evt = None
+ if len(self.selection) > 2 and not self.enabled:
+ evt = 'Enable'
+ elif self.enabled:
+ evt = 'Disable'
- if evt:
- for task in ('FormsAlignLeft',
- 'FormsAlignRight',
- 'FormsAlignHCenter',
- 'FormsAlignTop',
- 'FormsAlignBottom',
- 'FormsAlignVCenter',
- 'FormsSmartAlign'):
- self.document.dispatchEvent('%s:%s' % (evt, task))
-
-
-
-
+ if evt:
+ for task in ('FormsAlignLeft',
+ 'FormsAlignRight',
+ 'FormsAlignHCenter',
+ 'FormsAlignTop',
+ 'FormsAlignBottom',
+ 'FormsAlignVCenter',
+ 'FormsSmartAlign'):
+ self.document.dispatchEvent('%s:%s' % (evt, task))
Modified: trunk/gnue-designer/src/forms/events/Events.py
===================================================================
--- trunk/gnue-designer/src/forms/events/Events.py 2006-04-03 19:53:03 UTC
(rev 8343)
+++ trunk/gnue-designer/src/forms/events/Events.py 2006-04-03 19:56:14 UTC
(rev 8344)
@@ -31,5 +31,5 @@
from Resize import Resize
def registerEvents(instance):
- for object in (Arrange, Resize):
- object(instance)
+ for object in (Arrange, Resize):
+ object(instance)
Modified: trunk/gnue-designer/src/forms/events/Resize.py
===================================================================
--- trunk/gnue-designer/src/forms/events/Resize.py 2006-04-03 19:53:03 UTC
(rev 8343)
+++ trunk/gnue-designer/src/forms/events/Resize.py 2006-04-03 19:56:14 UTC
(rev 8344)
@@ -28,74 +28,74 @@
#
class Resize:
- def __init__(self, instance):
- self.document = instance
- self.enabled = 1
- instance.registerEventListeners( {
- 'Forms:AutoResizePage': self.resizeGrid } )
+ def __init__(self, instance):
+ self.document = instance
+ self.enabled = 1
+ instance.registerEventListeners( {
+ 'Forms:AutoResizePage': self.resizeGrid } )
- def _isStandalonePage(self, page):
- return hasattr(page, 'style') and page.style in ('popup',)
+ def _isStandalonePage(self, page):
+ return hasattr(page, 'style') and page.style in ('popup',)
- def resizeGrid(self, event):
- if self._isStandalonePage(self.document.visualEditor.page):
- target = self.document.layoutEditor.page
- stack = [target]
- else:
- target = self.document.rootObject._layout
- stack = []
- for object in target._children:
- if not self._isStandalonePage(object):
- stack.append(object)
+ def resizeGrid(self, event):
+ if self._isStandalonePage(self.document.visualEditor.page):
+ target = self.document.layoutEditor.page
+ stack = [target]
+ else:
+ target = self.document.rootObject._layout
+ stack = []
+ for object in target._children:
+ if not self._isStandalonePage(object):
+ stack.append(object)
- mx = 0
- my = 0
+ mx = 0
+ my = 0
- while stack:
- object = stack.pop()
- for child in object._children:
- stack.insert(0,child)
- try:
- x = object.Char__x
- except AttributeError:
- continue
+ while stack:
+ object = stack.pop()
+ for child in object._children:
+ stack.insert(0,child)
+ try:
+ x = object.Char__x
+ except AttributeError:
+ continue
- try:
- y = object.Char__y
- except AttributeError:
- y = 0
+ try:
+ y = object.Char__y
+ except AttributeError:
+ y = 0
- try:
- h = object.Char__height
- except AttributeError:
- h = 1
+ try:
+ h = object.Char__height
+ except AttributeError:
+ h = 1
- try:
- w = object.Char__width
- except AttributeError:
- try:
- w = len(object.text)
- except AttributeError:
- w = 10
+ try:
+ w = object.Char__width
+ except AttributeError:
+ try:
+ w = len(object.text)
+ except AttributeError:
+ w = 10
- mx = max(mx, x + w)
- my = max(my, y + h)
+ mx = max(mx, x + w)
+ my = max(my, y + h)
- if not (my or mx):
- return
+ if not (my or mx):
+ return
- if not my: my = 12
- if not mx: mx = 40
+ if not my: my = 12
+ if not mx: mx = 40
- new = {}
- old = {}
- if mx != target.Char__width:
- old['Char:width'] = target.Char__width
- new['Char:width'] = target.Char__width = mx
+ new = {}
+ old = {}
+ if mx != target.Char__width:
+ old['Char:width'] = target.Char__width
+ new['Char:width'] = target.Char__width = mx
- if my != target.Char__height:
- old['Char:height'] = target.Char__height
- new['Char:height'] = target.Char__height = my
+ if my != target.Char__height:
+ old['Char:height'] = target.Char__height
+ new['Char:height'] = target.Char__height = my
- self.document.dispatchEvent('ObjectModified', originator=self,
- old=old, new=new, object=target)
+ self.document.dispatchEvent('ObjectModified', originator=self,
+ old=old, new=new, object=target)
Modified: trunk/gnue-designer/src/forms/wizards/AddBlock.py
===================================================================
--- trunk/gnue-designer/src/forms/wizards/AddBlock.py 2006-04-03 19:53:03 UTC
(rev 8343)
+++ trunk/gnue-designer/src/forms/wizards/AddBlock.py 2006-04-03 19:56:14 UTC
(rev 8344)
@@ -34,178 +34,178 @@
class AddBlockWizard(FormTemplate):
- # The first step in our wizard.
- # The template parser will initially
- # call GetStep(FIRST_STEP).
- FIRST_STEP = '0'
+ # The first step in our wizard.
+ # The template parser will initially
+ # call GetStep(FIRST_STEP).
+ FIRST_STEP = '0'
- ###############
- #
- # Initialize any runtime variables
- #
- def Start(self, root, current):
- self.form = root
- self.current = current
- self.variables['rows'] = '1'
+ ###############
+ #
+ # Initialize any runtime variables
+ #
+ def Start(self, root, current):
+ self.form = root
+ self.current = current
+ self.variables['rows'] = '1'
- self.__getExistingDatasources()
+ self.__getExistingDatasources()
- ###############
- #
- # Return the markup for a specific page
- #
- def GetStep(self, stepCode):
-
- if stepCode == '1':
- if self.variables['datasource'] == 0:
- stepCode = '1:new'
- elif self.variables['datasource'] == 1:
- stepCode = '1:reuse'
- else:
- stepCode = '1:none'
-
+ ###############
#
- # Step #0 / Get Name
+ # Return the markup for a specific page
#
- if stepCode == '0':
+ def GetStep(self, stepCode):
- if self.__firstConnection:
- self.variables['connection'] = self.__firstConnection
+ if stepCode == '1':
+ if self.variables['datasource'] == 0:
+ stepCode = '1:new'
+ elif self.variables['datasource'] == 1:
+ stepCode = '1:reuse'
+ else:
+ stepCode = '1:none'
- if len (self.__datasourceMap):
- set=((0,u_('Create a new datasource')),
- (1,u_('Use an existing datasource')),
- (2,u_('Create an unbound block (no datasource)') )
- )
- else:
- set=((0,u_('Create a new datasource')),
- (2,u_('Create an unbound block (no datasource)') )
- )
+ #
+ # Step #0 / Get Name
+ #
+ if stepCode == '0':
- content = [WizardText(u_('This will insert a new block.')),
- WizardInput('name',label=u_('Object
Name:'),required=1,size=20),
- WizardText(u_('Where will this block pull its data?')),
- WizardInput('datasource', label=u_('Source:'), required=1,
- maxSelections=1,
- set=set),
- WizardText(u_('How many rows should this block display at
once?')),
- WizardInput('rows', label=u_('Rows Displayed:'), required=1,
- typecast=whole
- ) ]
+ if self.__firstConnection:
+ self.variables['connection'] = self.__firstConnection
- return { 'title': u_('Add Block'),
- 'content': content,
- 'prev': None,
- 'next': '1' }
+ if len (self.__datasourceMap):
+ set=((0,u_('Create a new datasource')),
+ (1,u_('Use an existing datasource')),
+ (2,u_('Create an unbound block (no datasource)') )
+ )
+ else:
+ set=((0,u_('Create a new datasource')),
+ (2,u_('Create an unbound block (no datasource)') )
+ )
- #
- # Step #2 [New Datasource] / Get Connection
- #
- elif stepCode == '1:new':
- return { 'title': u_('DataSource Connection'),
- 'content': (WizardText('What connection should this form use
to connect to the \ndatabase?'),
- WizardInput('connection',label='Connection:',
required=1,
- set=self.GetAvailableConnections()),
- WizardText('You may be asked to login to this
connection.')),
- 'prev': '0',
- 'next': '2:new' }
+ content = [WizardText(u_('This will insert a new block.')),
+ WizardInput('name',label=u_('Object
Name:'),required=1,size=20),
+ WizardText(u_('Where will this block pull its data?')),
+ WizardInput('datasource', label=u_('Source:'),
required=1,
+ maxSelections=1,
+ set=set),
+ WizardText(u_('How many rows should this block display
at once?')),
+ WizardInput('rows', label=u_('Rows Displayed:'),
required=1,
+ typecast=whole
+ ) ]
- #
- # Step #3 [New Datasource] / Get Table
- #
- elif stepCode == '2:new':
- return { 'title': 'Select Base Table/Source',
- 'content': (WizardText('Now, please select the table the
dropdown will\nuse to populate its data set.'),
- WizardInput('table', label='Table:', required=1,
lines=5,
-
set=self.GetAvailableSources(self.variables['connection'])), ),
- 'prev': '1:new',
- 'next': None }
+ return { 'title': u_('Add Block'),
+ 'content': content,
+ 'prev': None,
+ 'next': '1' }
+ #
+ # Step #2 [New Datasource] / Get Connection
+ #
+ elif stepCode == '1:new':
+ return { 'title': u_('DataSource Connection'),
+ 'content': (WizardText('What connection should this
form use to connect to the \ndatabase?'),
+
WizardInput('connection',label='Connection:', required=1,
+
set=self.GetAvailableConnections()),
+ WizardText('You may be asked to login to
this connection.')),
+ 'prev': '0',
+ 'next': '2:new' }
- #
- # Step #2 [reuse Datasource] / Get DataSource
- #
- elif stepCode == '1:reuse':
- return { 'title': 'Datasource Connection',
- 'content': (WizardText('Which existing datasource should be
used?'),
- WizardInput('source',label='Datasource:',
required=1,
- set=self.__getExistingDatasources())),
- 'prev': '0',
- 'next': None }
+ #
+ # Step #3 [New Datasource] / Get Table
+ #
+ elif stepCode == '2:new':
+ return { 'title': 'Select Base Table/Source',
+ 'content': (WizardText('Now, please select the table
the dropdown will\nuse to populate its data set.'),
+ WizardInput('table', label='Table:',
required=1, lines=5,
+
set=self.GetAvailableSources(self.variables['connection'])), ),
+ 'prev': '1:new',
+ 'next': None }
+
+ #
+ # Step #2 [reuse Datasource] / Get DataSource
+ #
+ elif stepCode == '1:reuse':
+ return { 'title': 'Datasource Connection',
+ 'content': (WizardText('Which existing datasource
should be used?'),
+ WizardInput('source',label='Datasource:',
required=1,
+
set=self.__getExistingDatasources())),
+ 'prev': '0',
+ 'next': None }
+
+ #
+ # Step #2 [no DAtasource]
+ #
+ elif stepCode == '1:none':
+ return { 'title': u_('Done'),
+ 'content': (WizardText('We now have enough information
to create your block.'),),
+ 'prev': '0',
+ 'next': None }
+
+ ###############
#
- # Step #2 [no DAtasource]
+ # We have all the data, so generate our widget.
#
- elif stepCode == '1:none':
- return { 'title': u_('Done'),
- 'content': (WizardText('We now have enough information to
create your block.'),),
- 'prev': '0',
- 'next': None }
+ def Finalize(self):
- ###############
- #
- # We have all the data, so generate our widget.
- #
- def Finalize(self):
+ attrs = {'name': self.GetUniqueName(self.variables['name'] or
'Block1'),
+ 'rows': int(self.variables['rows'])}
+ # Find form...
+ logic = self.current['logic']
- attrs = {'name': self.GetUniqueName(self.variables['name'] or 'Block1'),
- 'rows': int(self.variables['rows'])}
- # Find form...
- logic = self.current['logic']
+ #
+ # Set up or retrieve our datasource
+ #
- #
- # Set up or retrieve our datasource
- #
+ # Create new datasource
+ if self.variables['datasource'] == 0:
+ datasource = self.AddElement('datasource', self.form,
+ { 'name': self.GetUniqueName("dts_%s_%s" %
(self.variables['table'],
+ self.variables['name'])),
+ 'connection': self.variables['connection'],
+ 'prequery': 1,
+ 'table': self.variables['table'] } )
+ attrs['datasource'] = datasource.name
- # Create new datasource
- if self.variables['datasource'] == 0:
- datasource = self.AddElement('datasource', self.form,
- { 'name': self.GetUniqueName("dts_%s_%s" % (self.variables['table'],
- self.variables['name'])),
- 'connection': self.variables['connection'],
- 'prequery': 1,
- 'table': self.variables['table'] } )
- attrs['datasource'] = datasource.name
+ # Reuse existing datasource
+ elif self.variables['datasource'] == 1:
+ datasource = self.__datasourceMap[self.variables['source']]
+ attrs['source'] = datasource.name
- # Reuse existing datasource
- elif self.variables['datasource'] == 1:
- datasource = self.__datasourceMap[self.variables['source']]
- attrs['source'] = datasource.name
+ # Create a "static" datasource
+ else:
+ datasource = None
- # Create a "static" datasource
- else:
- datasource = None
+ block = self.AddElement('block', logic, attrs)
- block = self.AddElement('block', logic, attrs)
+ return 1
- return 1
+ ###############
+ #
+ # Internal stuff
+ # Get a list of all existing datasources
+ #
+ def __getExistingDatasources(self):
+ self.__firstConnection = None
+ self.__datasourceSet = []
+ self.__datasourceMap = {}
+ for child in self.form.findChildrenOfType('GFDataSource'):
+ if hasattr(child,'table'):
+ self.__datasourceSet.append((child.name,"%s (%s)" %
(child.name, child.table)))
+ self.__datasourceMap[child.name] = child
+ if not self.__firstConnection:
+ self.__firstConnection = child.connection
+ return self.__datasourceSet
- ###############
- #
- # Internal stuff
- # Get a list of all existing datasources
- #
- def __getExistingDatasources(self):
- self.__firstConnection = None
- self.__datasourceSet = []
- self.__datasourceMap = {}
- for child in self.form.findChildrenOfType('GFDataSource'):
- if hasattr(child,'table'):
- self.__datasourceSet.append((child.name,"%s (%s)" % (child.name,
child.table)))
- self.__datasourceMap[child.name] = child
- if not self.__firstConnection:
- self.__firstConnection = child.connection
- return self.__datasourceSet
-
############
#
# Basic information about this template
@@ -221,4 +221,3 @@
'Behavior': WIZARD,
'MenuLocation' : ('Insert',u_('Block'), 301.1)
}
-
Modified: trunk/gnue-designer/src/forms/wizards/AddBox.py
===================================================================
--- trunk/gnue-designer/src/forms/wizards/AddBox.py 2006-04-03 19:53:03 UTC
(rev 8343)
+++ trunk/gnue-designer/src/forms/wizards/AddBox.py 2006-04-03 19:56:14 UTC
(rev 8344)
@@ -36,39 +36,39 @@
- ###############
- #
- # Initialize any runtime variables
- #
- def StartWithPositioning(self, root, current,
- x=0, y=0, width=10, height=4):
- self.form = root
- self.current = current
- self.x = x
- self.y = y
- self.width = width
- self.height = height
+ ###############
+ #
+ # Initialize any runtime variables
+ #
+ def StartWithPositioning(self, root, current,
+ x=0, y=0, width=10, height=4):
+ self.form = root
+ self.current = current
+ self.x = x
+ self.y = y
+ self.width = width
+ self.height = height
- ###############
- #
- # We have all the data, so generate our widget.
- #
- def Finalize(self):
+ ###############
+ #
+ # We have all the data, so generate our widget.
+ #
+ def Finalize(self):
- # Create element
- self.AddElement( 'box',
- self.current['page'],
- { 'name': self.GetUniqueName('Box1'),
- 'label': 'I am a Box',
- 'Char:x': self.x,
- 'Char:y': self.y,
- 'Char:width': self.width > 2 and self.width or 10,
- 'Char:height': self.height > 2 and self.height or 4})
+ # Create element
+ self.AddElement( 'box',
+ self.current['page'],
+ { 'name': self.GetUniqueName('Box1'),
+ 'label': 'I am a Box',
+ 'Char:x': self.x,
+ 'Char:y': self.y,
+ 'Char:width': self.width > 2 and self.width or 10,
+ 'Char:height': self.height > 2 and self.height or
4})
- return 1
+ return 1
@@ -87,4 +87,3 @@
'Behavior': TEMPLATE,
'MenuLocation' : ('Insert',u_('Box'), 401.2)
}
-
Modified: trunk/gnue-designer/src/forms/wizards/AddButton.py
===================================================================
--- trunk/gnue-designer/src/forms/wizards/AddButton.py 2006-04-03 19:53:03 UTC
(rev 8343)
+++ trunk/gnue-designer/src/forms/wizards/AddButton.py 2006-04-03 19:56:14 UTC
(rev 8344)
@@ -41,123 +41,123 @@
class AddButtonWizard(FormPrePositioningTemplate):
- # The first step in our wizard.
- # The template parser will initially
- # call GetStep(FIRST_STEP).
- FIRST_STEP = '0'
+ # The first step in our wizard.
+ # The template parser will initially
+ # call GetStep(FIRST_STEP).
+ FIRST_STEP = '0'
- ###############
- #
- # Initialize any runtime variables
- #
- def StartWithPositioning(self, root, current,
- x=0, y=0, width=10, height=1):
- self.form = root
- self.current = current
- self.x = x
- self.y = y
- self.width = width
- self.height = height
+ ###############
+ #
+ # Initialize any runtime variables
+ #
+ def StartWithPositioning(self, root, current,
+ x=0, y=0, width=10, height=1):
+ self.form = root
+ self.current = current
+ self.x = x
+ self.y = y
+ self.width = width
+ self.height = height
- ###############
- #
- # Return the markup for a specific Button
- #
- def GetStep(self, step):
-
+ ###############
#
- # Step #0 / Get Name
+ # Return the markup for a specific Button
#
- if step == '0':
+ def GetStep(self, step):
- content = [WizardText('This will insert a new Button.'),
- WizardInput('name',label='Object Name:',required=1,size=20),
- WizardInput('label',label='Button Label:',required=1,size=20),
- WizardInput('action', label='Source:', required=1,
- maxSelections=1,
- set=(
- ('t:trigger','Execute a custom trigger'),
- ('b:nextRecord','Move to the Next Record'),
- ('b:prevRecord','Move to the Previous
Record'),
- ('b:firstRecord','Move to the First Record'),
- ('b:lastRecord','Move to the Last Record'),
- ('b:newRecord','Insert a New Record'),
- ('b:deleteRecord','Delete the Current
Record'),
- ('f2:runForm','Call another form'),
- ('f:enterQuery','Enter a Query'),
- ('f:executeQuery','Execute a Query'),
- ('f:commit','Perform a Commit'),
- ('f:rollback','Perform a Rollback'))
+ #
+ # Step #0 / Get Name
+ #
+ if step == '0':
-)
- ]
+ content = [WizardText('This will insert a new Button.'),
+ WizardInput('name',label='Object
Name:',required=1,size=20),
+ WizardInput('label',label='Button
Label:',required=1,size=20),
+ WizardInput('action', label='Source:', required=1,
+ maxSelections=1,
+ set=(
+ ('t:trigger','Execute a custom
trigger'),
+ ('b:nextRecord','Move to the Next
Record'),
+ ('b:prevRecord','Move to the Previous
Record'),
+ ('b:firstRecord','Move to the First
Record'),
+ ('b:lastRecord','Move to the Last
Record'),
+ ('b:newRecord','Insert a New Record'),
+ ('b:deleteRecord','Delete the Current
Record'),
+ ('f2:runForm','Call another form'),
+ ('f:enterQuery','Enter a Query'),
+ ('f:executeQuery','Execute a Query'),
+ ('f:commit','Perform a Commit'),
+ ('f:rollback','Perform a Rollback'))
+ )
+ ]
- return { 'title': 'Add Button',
- 'content': content,
- 'prev': None,
- 'next': None }
+ return { 'title': 'Add Button',
+ 'content': content,
+ 'prev': None,
+ 'next': None }
- ###############
- #
- # Verify contents of current step
- # Return None if no problems, otherwise
- # return a tuple of error message strings
- #
- def ValidateStep(self, stepCode):
- # The Simple wizard uses basic "required"
- # settings in the Button markup, so doesn't
- # need any special validation.
- return None
+ ###############
+ #
+ # Verify contents of current step
+ # Return None if no problems, otherwise
+ # return a tuple of error message strings
+ #
+ def ValidateStep(self, stepCode):
+ # The Simple wizard uses basic "required"
+ # settings in the Button markup, so doesn't
+ # need any special validation.
+ return None
- ###############
- #
- # We have all the data, so generate our form. This
- # is called after the user clicks the "Finish" button.
- # No more user input is allowed at this point.
- #
- def Finalize(self):
- name = self.GetUniqueName(self.variables['name'] or 'Button1')
- label = self.variables['label'] or name
+ ###############
+ #
+ # We have all the data, so generate our form. This
+ # is called after the user clicks the "Finish" button.
+ # No more user input is allowed at this point.
+ #
+ def Finalize(self):
- attrs = {'name': name,
- 'label': label,
- 'Char:x': self.x,
- 'Char:y': self.y,
- 'Char:width': max(self.width, len(label) + 2),
- 'Char:height': self.height or 1}
+ name = self.GetUniqueName(self.variables['name'] or 'Button1')
+ label = self.variables['label'] or name
- button = self.AddElement('button', self.current['page'], attrs)
+ attrs = {'name': name,
+ 'label': label,
+ 'Char:x': self.x,
+ 'Char:y': self.y,
+ 'Char:width': max(self.width, len(label) + 2),
+ 'Char:height': self.height or 1}
- action, info = string.split(self.variables['action'],':')
+ button = self.AddElement('button', self.current['page'], attrs)
- if action == 'b':
- block = self.current['block']
- blockName = block.name
+ action, info = string.split(self.variables['action'],':')
+ if action == 'b':
+ block = self.current['block']
+ blockName = block.name
- code = triggerTemplates[action] % locals()
- trigger = self.AddElement('trigger',
- button,
- attributes = {
- 'name': '%sTrigger' % name,
- 'type':'On-Action' },
- content = code)
+ code = triggerTemplates[action] % locals()
- return 1
+ trigger = self.AddElement('trigger',
+ button,
+ attributes = {
+ 'name': '%sTrigger' % name,
+ 'type':'On-Action' },
+ content = code)
+ return 1
+
triggerTemplates = {
't': """\
##
@@ -221,5 +221,3 @@
# Add to the menu
'MenuLocation' : ('Insert', u_('Button'), 401.5)
}
-
-
Modified: trunk/gnue-designer/src/forms/wizards/AddCheckbox.py
===================================================================
--- trunk/gnue-designer/src/forms/wizards/AddCheckbox.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/forms/wizards/AddCheckbox.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -36,49 +36,49 @@
- ###############
- #
- # Initialize any runtime variables
- #
- def StartWithPositioning(self, root, current,
- x=0, y=0, width=10, height=1):
- self.form = root
- self.current = current
- self.x = x
- self.y = y
- self.width = width
- self.height = height
+ ###############
+ #
+ # Initialize any runtime variables
+ #
+ def StartWithPositioning(self, root, current,
+ x=0, y=0, width=10, height=1):
+ self.form = root
+ self.current = current
+ self.x = x
+ self.y = y
+ self.width = width
+ self.height = height
- if not self.current['block']:
- raise InsufficientInformation, u_("There are no blocks in this form.")
+ if not self.current['block']:
+ raise InsufficientInformation, u_("There are no blocks in this
form.")
- ###############
- #
- # We have all the data, so generate our widget.
- #
- def Finalize(self):
+ ###############
+ #
+ # We have all the data, so generate our widget.
+ #
+ def Finalize(self):
- page = self.current['page']
- block = self.current['block']
+ page = self.current['page']
+ block = self.current['block']
- field = self.AddElement('field',block,
- {'name': self.GetUniqueName('UnboundField1',block)})
+ field = self.AddElement('field',block,
+ {'name':
self.GetUniqueName('UnboundField1',block)})
- attrs = {'name': self.GetUniqueName('Entry1',page),
- 'field': field.name,
- 'block': block.name,
- 'style': 'checkbox',
- 'Char:x': self.x,
- 'Char:y': self.y,
- 'Char:width': self.width or 1,
- 'Char:height': self.height or 1}
+ attrs = {'name': self.GetUniqueName('Entry1',page),
+ 'field': field.name,
+ 'block': block.name,
+ 'style': 'checkbox',
+ 'Char:x': self.x,
+ 'Char:y': self.y,
+ 'Char:width': self.width or 1,
+ 'Char:height': self.height or 1}
- # Create entry element
- entry = self.AddElement('entry', page, attrs)
+ # Create entry element
+ entry = self.AddElement('entry', page, attrs)
- return 1
+ return 1
@@ -97,4 +97,3 @@
'Behavior': TEMPLATE,
'MenuLocation' : ('Insert',u_('Checkbox Entry'),401.2)
}
-
Modified: trunk/gnue-designer/src/forms/wizards/AddDataSource.py
===================================================================
--- trunk/gnue-designer/src/forms/wizards/AddDataSource.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/forms/wizards/AddDataSource.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -41,124 +41,124 @@
class AddDataSourceWizard(FormTemplate):
- # The first step in our wizard.
- # The template parser will initially
- # call GetStep(FIRST_STEP).
- FIRST_STEP = '0'
+ # The first step in our wizard.
+ # The template parser will initially
+ # call GetStep(FIRST_STEP).
+ FIRST_STEP = '0'
- ###############
- #
- # Initialize any runtime variables
- #
- def Start(self, root, current):
- self.form = root
- self.current = current
- self.__getExistingDatasources()
+ ###############
+ #
+ # Initialize any runtime variables
+ #
+ def Start(self, root, current):
+ self.form = root
+ self.current = current
+ self.__getExistingDatasources()
- ###############
- #
- # Return the markup for a specific page
- #
- def GetStep(self, stepCode):
-
+ ###############
#
- # Step #1 / Get Title, et al
+ # Return the markup for a specific page
#
- if stepCode == '0':
+ def GetStep(self, stepCode):
- if self.__firstConnection:
- self.variables['connection'] = self.__firstConnection
+ #
+ # Step #1 / Get Title, et al
+ #
+ if stepCode == '0':
- return { 'title': 'Add DataSource',
- 'content': (WizardText('To create your DataSource, I need to
know some basic information.\n\n'
- 'What connection should this form use
to connect to the \ndatabase?'),
- WizardInput('connection',label='Connection:',
required=1,
- set=self.GetAvailableConnections()),
- WizardText('You may be asked to login to this
connection.')),
- 'prev': None,
- 'next': '1' }
+ if self.__firstConnection:
+ self.variables['connection'] = self.__firstConnection
- #
- # Step #2 [New Datasource] / Get Table
- #
- elif stepCode == '1':
- return { 'title': 'Select Validator Table/Source',
- 'content': (WizardText('Now, please select the table the
DataSource will\nuse to populate its data set.'),
- WizardInput('table', label='Table:', required=1,
lines=5,
-
set=self.GetAvailableSources(self.variables['connection'])), ),
- 'prev': '0',
- 'next': '2' }
+ return { 'title': 'Add DataSource',
+ 'content': (WizardText('To create your DataSource, I
need to know some basic information.\n\n'
+ 'What connection should this
form use to connect to the \ndatabase?'),
+
WizardInput('connection',label='Connection:', required=1,
+
set=self.GetAvailableConnections()),
+ WizardText('You may be asked to login to
this connection.')),
+ 'prev': None,
+ 'next': '1' }
+ #
+ # Step #2 [New Datasource] / Get Table
+ #
+ elif stepCode == '1':
+ return { 'title': 'Select Validator Table/Source',
+ 'content': (WizardText('Now, please select the table
the DataSource will\nuse to populate its data set.'),
+ WizardInput('table', label='Table:',
required=1, lines=5,
+
set=self.GetAvailableSources(self.variables['connection'])), ),
+ 'prev': '0',
+ 'next': '2' }
- #
- # Step #3 [New Datasouce] / Get key/description fields
- #
- elif stepCode == '2':
- if not hasattr (self.variables,'name'):
- self.variables['name'] = 'dts_%s' % self.variables['table']
+ #
+ # Step #3 [New Datasouce] / Get key/description fields
+ #
+ elif stepCode == '2':
- return { 'title': 'Select Key/Description fields',
- 'content': (WizardText('What shall I call this datasource?'),
- WizardInput('name', label='Name:', required=1)),
- 'prev': '1',
- 'next': None }
+ if not hasattr (self.variables,'name'):
+ self.variables['name'] = 'dts_%s' % self.variables['table']
+ return { 'title': 'Select Key/Description fields',
+ 'content': (WizardText('What shall I call this
datasource?'),
+ WizardInput('name', label='Name:',
required=1)),
+ 'prev': '1',
+ 'next': None }
- ###############
- #
- # Verify contents of current step
- # Return None if no problems, otherwise
- # return a tuple of error message strings
- #
- def ValidateStep(self, stepCode):
- # TODO: This should validate step 1:fixed to verify the dataset is valid
- return None
+ ###############
+ #
+ # Verify contents of current step
+ # Return None if no problems, otherwise
+ # return a tuple of error message strings
+ #
+ def ValidateStep(self, stepCode):
+ # TODO: This should validate step 1:fixed to verify the dataset is
valid
+ return None
- ###############
- #
- # We have all the data, so generate our form. This
- # is called after the user clicks the "Finish" button.
- # No more user input is allowed at this point.
- #
- def Finalize(self):
+ ###############
#
- # Set up or retrieve our datasource
+ # We have all the data, so generate our form. This
+ # is called after the user clicks the "Finish" button.
+ # No more user input is allowed at this point.
#
+ def Finalize(self):
- # Create new datasource
- datasource = self.AddElement('datasource', self.form,
- { 'name': self.GetUniqueName(self.variables['name']),
- 'connection': self.variables['connection'],
- 'table': self.variables['table'] } )
+ #
+ # Set up or retrieve our datasource
+ #
+ # Create new datasource
+ datasource = self.AddElement('datasource', self.form,
+ { 'name': self.GetUniqueName(self.variables['name']),
+ 'connection': self.variables['connection'],
+ 'table': self.variables['table'] } )
- return 1
+ return 1
- ###############
- #
- # Internal stuff
- # Get a list of all existing datasources
- #
- def __getExistingDatasources(self):
- self.__firstConnection = None
- for child in self.form.findChildrenOfType('GFDataSource'):
- if hasattr(child,'table'):
- if not self.__firstConnection:
- self.__firstConnection = child.connection
- break
+ ###############
+ #
+ # Internal stuff
+ # Get a list of all existing datasources
+ #
+ def __getExistingDatasources(self):
+ self.__firstConnection = None
+ for child in self.form.findChildrenOfType('GFDataSource'):
+ if hasattr(child,'table'):
+ if not self.__firstConnection:
+ self.__firstConnection = child.connection
+ break
+
############
#
# Basic information about this template
@@ -174,4 +174,3 @@
'Behavior': WIZARD,
'MenuLocation' : ('Insert',u_('Datasource'), 301.2)
}
-
Modified: trunk/gnue-designer/src/forms/wizards/AddDropDown.py
===================================================================
--- trunk/gnue-designer/src/forms/wizards/AddDropDown.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/forms/wizards/AddDropDown.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -42,289 +42,289 @@
class AddDropDownWizard(FormPrePositioningTemplate):
- # The first step in our wizard.
- # The template parser will initially
- # call GetStep(FIRST_STEP).
- FIRST_STEP = '0'
+ # The first step in our wizard.
+ # The template parser will initially
+ # call GetStep(FIRST_STEP).
+ FIRST_STEP = '0'
- ###############
- #
- # Initialize any runtime variables
- #
- def StartWithPositioning(self, root, current,
- x=0, y=0, width=10, height=1):
- self.form = root
- self.current = current
- self.x = x
- self.y = y
- self.width = width
- self.height = height
+ ###############
+ #
+ # Initialize any runtime variables
+ #
+ def StartWithPositioning(self, root, current,
+ x=0, y=0, width=10, height=1):
+ self.form = root
+ self.current = current
+ self.x = x
+ self.y = y
+ self.width = width
+ self.height = height
- if not self.current['block']:
- raise InsufficientInformation, u_("There are no blocks in this form.")
+ if not self.current['block']:
+ raise InsufficientInformation, u_("There are no blocks in this
form.")
- self.__getExistingDatasources()
+ self.__getExistingDatasources()
- ###############
- #
- # Return the markup for a specific page
- #
- def GetStep(self, stepCode):
-
- if stepCode == '1':
- if self.variables['datasource'] == 0:
- stepCode = '1:new'
- elif self.variables['datasource'] == 1:
- stepCode = '1:reuse'
- else:
- stepCode = '1:fixed'
-
+ ###############
#
- # Step #1 / Get Title, et al
+ # Return the markup for a specific page
#
- if stepCode == '0':
+ def GetStep(self, stepCode):
- if self.__firstConnection:
- self.variables['connection'] = self.__firstConnection
+ if stepCode == '1':
+ if self.variables['datasource'] == 0:
+ stepCode = '1:new'
+ elif self.variables['datasource'] == 1:
+ stepCode = '1:reuse'
+ else:
+ stepCode = '1:fixed'
- if len (self.__datasourceMap):
- set=((0,'Create a new datasource'),
- (1,'Use an existing datasource'),
- (2,'Specify a static list of valid choices' )
- )
- else:
- set=((0,'Create a new datasource'),
- (2,'Specify a static list of valid choices' )
- )
+ #
+ # Step #1 / Get Title, et al
+ #
+ if stepCode == '0':
+ if self.__firstConnection:
+ self.variables['connection'] = self.__firstConnection
- return { 'title': 'Add Dropdown Entry',
- 'content': (WizardText('To create your dropdown, I need to
know some basic information. '
- 'First, what field will store the
dropdown\'s value?'),
- WizardInput('name', label='Field name:',
required=1,
- size=40),
- WizardText('Where will this dropdown pull its
data?'),
- WizardInput('datasource', label='Source:',
required=1,
- maxSelections=1,
- set=set)
- ),
- 'prev': None,
- 'next': '1' }
+ if len (self.__datasourceMap):
+ set=((0,'Create a new datasource'),
+ (1,'Use an existing datasource'),
+ (2,'Specify a static list of valid choices' )
+ )
+ else:
+ set=((0,'Create a new datasource'),
+ (2,'Specify a static list of valid choices' )
+ )
- #
- # Step #2 [New Datasource] / Get Connection
- #
- elif stepCode == '1:new':
- return { 'title': 'Datasource Connection',
- 'content': (WizardText('What connection should this form use
to connect to the \ndatabase?'),
- WizardInput('connection',label='Connection:',
required=1,
- set=self.GetAvailableConnections()),
- WizardText('You may be asked to login to this
connection.')),
- 'prev': '0',
- 'next': '2:new' }
- #
- # Step #3 [New Datasource] / Get Table
- #
- elif stepCode == '2:new':
- return { 'title': 'Select Validator Table/Source',
- 'content': (WizardText('Now, please select the table the
dropdown will\nuse to populate its data set.'),
- WizardInput('table', label='Table:', required=1,
lines=5,
-
set=self.GetAvailableSources(self.variables['connection'])), ),
- 'prev': '1:new',
- 'next': '3:new' }
+ return { 'title': 'Add Dropdown Entry',
+ 'content': (WizardText('To create your dropdown, I need
to know some basic information. '
+ 'First, what field will store
the dropdown\'s value?'),
+ WizardInput('name', label='Field name:',
required=1,
+ size=40),
+ WizardText('Where will this dropdown pull
its data?'),
+ WizardInput('datasource', label='Source:',
required=1,
+ maxSelections=1,
+ set=set)
+ ),
+ 'prev': None,
+ 'next': '1' }
+ #
+ # Step #2 [New Datasource] / Get Connection
+ #
+ elif stepCode == '1:new':
+ return { 'title': 'Datasource Connection',
+ 'content': (WizardText('What connection should this
form use to connect to the \ndatabase?'),
+
WizardInput('connection',label='Connection:', required=1,
+
set=self.GetAvailableConnections()),
+ WizardText('You may be asked to login to
this connection.')),
+ 'prev': '0',
+ 'next': '2:new' }
- #
- # Step #4 [New Datasouce] / Get key/description fields
- #
- elif stepCode == '3:new':
+ #
+ # Step #3 [New Datasource] / Get Table
+ #
+ elif stepCode == '2:new':
+ return { 'title': 'Select Validator Table/Source',
+ 'content': (WizardText('Now, please select the table
the dropdown will\nuse to populate its data set.'),
+ WizardInput('table', label='Table:',
required=1, lines=5,
+
set=self.GetAvailableSources(self.variables['connection'])), ),
+ 'prev': '1:new',
+ 'next': '3:new' }
- return { 'title': 'Select Key/Description fields',
- 'content': (WizardText('Which field will be the "key"? (i.e.,
which\nfield contains the value that will\nbe stored in the database?)'),
- WizardInput('key', label='Key Field:', required=1,
- maxSelections=1,
- set=self.GetAvailableFields( \
- self.variables['connection'],
- self.variables['table'])),
- WizardText('Which field will be the "description"
value?'),
- WizardInput('descr', label='Description:',
required=1,
- maxSelections=1,
- set=self.GetAvailableFields( \
- self.variables['connection'],
- self.variables['table']))),
- 'prev': '2:new',
- 'next': None }
- #
- # Step #2 [reuse Datasource] / Get DataSource
- #
- elif stepCode == '1:reuse':
- return { 'title': 'Datasource Connection',
- 'content': (WizardText('Which existing datasource should be
used?'),
- WizardInput('source',label='Datasource:',
required=1,
- set=self.__getExistingDatasources())),
- 'prev': '0',
- 'next': '2:reuse' }
+ #
+ # Step #4 [New Datasouce] / Get key/description fields
+ #
+ elif stepCode == '3:new':
- #
- # Step #3 [Reuse Datasouce] / Get key/description fields
- #
- elif stepCode == '2:reuse':
+ return { 'title': 'Select Key/Description fields',
+ 'content': (WizardText('Which field will be the "key"?
(i.e., which\nfield contains the value that will\nbe stored in the database?)'),
+ WizardInput('key', label='Key Field:',
required=1,
+ maxSelections=1,
+ set=self.GetAvailableFields( \
+
self.variables['connection'],
+
self.variables['table'])),
+ WizardText('Which field will be the
"description" value?'),
+ WizardInput('descr', label='Description:',
required=1,
+ maxSelections=1,
+ set=self.GetAvailableFields( \
+
self.variables['connection'],
+
self.variables['table']))),
+ 'prev': '2:new',
+ 'next': None }
- datasource = self.__datasourceMap[self.variables['source']]
+ #
+ # Step #2 [reuse Datasource] / Get DataSource
+ #
+ elif stepCode == '1:reuse':
+ return { 'title': 'Datasource Connection',
+ 'content': (WizardText('Which existing datasource
should be used?'),
+ WizardInput('source',label='Datasource:',
required=1,
+
set=self.__getExistingDatasources())),
+ 'prev': '0',
+ 'next': '2:reuse' }
+ #
+ # Step #3 [Reuse Datasouce] / Get key/description fields
+ #
+ elif stepCode == '2:reuse':
- return { 'title': 'Select Key/Description fields',
- 'content': (WizardText('Which field will be the "key"? (i.e.,
which\nfield contains the value that will\nbe stored in the database?)'),
- WizardInput('key', label='Key Field:', required=1,
- maxSelections=1,
- set=self.GetAvailableFields( \
- datasource.connection,
- datasource.table)),
- WizardText('Which field will be the "description"
value?'),
- WizardInput('descr', label='Description:',
required=1,
- maxSelections=1,
- set=self.GetAvailableFields( \
- datasource.connection,
- datasource.table))),
- 'prev': '1:reuse',
- 'next': None }
+ datasource = self.__datasourceMap[self.variables['source']]
- #
- # Step #2 [Static set] / Get Data Set
- #
- elif stepCode == '1:fixed':
+ return { 'title': 'Select Key/Description fields',
+ 'content': (WizardText('Which field will be the "key"?
(i.e., which\nfield contains the value that will\nbe stored in the database?)'),
+ WizardInput('key', label='Key Field:',
required=1,
+ maxSelections=1,
+ set=self.GetAvailableFields( \
+ datasource.connection,
+ datasource.table)),
+ WizardText('Which field will be the
"description" value?'),
+ WizardInput('descr', label='Description:',
required=1,
+ maxSelections=1,
+ set=self.GetAvailableFields( \
+ datasource.connection,
+ datasource.table))),
+ 'prev': '1:reuse',
+ 'next': None }
- return { 'title': 'Enter data set',
- 'content': (WizardText('Please enter the values the dropdown
box\nshould use. Enter in the format: val1:Display1|val2:display2|...\n(For
example, Y:Yes|N:No|M:Maybe'),
- WizardInput('dataset', label='Data Set:',
required=1, lines=5,
- size=40) ),
- 'prev': '0',
- 'next': None }
+ #
+ # Step #2 [Static set] / Get Data Set
+ #
+ elif stepCode == '1:fixed':
+ return { 'title': 'Enter data set',
+ 'content': (WizardText('Please enter the values the
dropdown box\nshould use. Enter in the format:
val1:Display1|val2:display2|...\n(For example, Y:Yes|N:No|M:Maybe'),
+ WizardInput('dataset', label='Data Set:',
required=1, lines=5,
+ size=40) ),
+ 'prev': '0',
+ 'next': None }
- ###############
- #
- # Verify contents of current step
- # Return None if no problems, otherwise
- # return a tuple of error message strings
- #
- def ValidateStep(self, stepCode):
- # TODO: This should validate step 1:fixed to verify the dataset is valid
- return None
+ ###############
+ #
+ # Verify contents of current step
+ # Return None if no problems, otherwise
+ # return a tuple of error message strings
+ #
+ def ValidateStep(self, stepCode):
+ # TODO: This should validate step 1:fixed to verify the dataset is
valid
+ return None
- ###############
- #
- # We have all the data, so generate our form. This
- # is called after the user clicks the "Finish" button.
- # No more user input is allowed at this point.
- #
- def Finalize(self):
+
+ ###############
#
- # Set up or retrieve our datasource
+ # We have all the data, so generate our form. This
+ # is called after the user clicks the "Finish" button.
+ # No more user input is allowed at this point.
#
+ def Finalize(self):
- # Create new datasource
- if self.variables['datasource'] == 0:
- datasource = self.AddElement('datasource', self.form,
- { 'name': self.GetUniqueName("dtsDrp_%s_%s" % (self.variables['table'],
- self.variables['name'])),
- 'connection': self.variables['connection'],
- 'prequery': 1,
- 'table': self.variables['table'] } )
- keyfield = self.variables['key']
- descrfield = self.variables['descr']
+ #
+ # Set up or retrieve our datasource
+ #
- # Reuse existing datasource
- elif self.variables['datasource'] == 1:
- datasource = self.__datasourceMap[self.variables['source']]
- keyfield = self.variables['key']
- descrfield = self.variables['descr']
+ # Create new datasource
+ if self.variables['datasource'] == 0:
+ datasource = self.AddElement('datasource', self.form,
+ { 'name': self.GetUniqueName("dtsDrp_%s_%s" %
(self.variables['table'],
+ self.variables['name'])),
+ 'connection': self.variables['connection'],
+ 'prequery': 1,
+ 'table': self.variables['table'] } )
+ keyfield = self.variables['key']
+ descrfield = self.variables['descr']
- # Create a "static" datasource
- else:
- datasource = self.AddElement('datasource', self.form,
- { 'name': self.GetUniqueName("dtsDrpStatic%s" %
self.variables['name']),
- 'prequery': 1,
- 'type': "static" } )
- keyfield = 'key'
- descrfield = 'descr'
- # Add staticset
- ss = self.AddElement( 'staticset', datasource,
- { 'fields': 'key,descr' } )
- # And each row...
- for r in string.split(self.variables['dataset'],'|'):
- try:
- key, descr = string.split(r,':',1)
- except ValueError:
- pass
- ssr = self.AddElement('staticsetrow', ss)
- self.AddElement('staticsetfield',ssr,{'name': 'key', 'value': key})
- self.AddElement('staticsetfield',ssr,{'name': 'descr','value': descr})
+ # Reuse existing datasource
+ elif self.variables['datasource'] == 1:
+ datasource = self.__datasourceMap[self.variables['source']]
+ keyfield = self.variables['key']
+ descrfield = self.variables['descr']
+ # Create a "static" datasource
+ else:
+ datasource = self.AddElement('datasource', self.form,
+ { 'name': self.GetUniqueName("dtsDrpStatic%s" %
self.variables['name']),
+ 'prequery': 1,
+ 'type': "static" } )
+ keyfield = 'key'
+ descrfield = 'descr'
+ # Add staticset
+ ss = self.AddElement( 'staticset', datasource,
+ { 'fields': 'key,descr' } )
+ # And each row...
+ for r in string.split(self.variables['dataset'],'|'):
+ try:
+ key, descr = string.split(r,':',1)
+ except ValueError:
+ pass
+ ssr = self.AddElement('staticsetrow', ss)
+ self.AddElement('staticsetfield',ssr,{'name': 'key', 'value':
key})
+ self.AddElement('staticsetfield',ssr,{'name': 'descr','value':
descr})
- #
- # Create the dropdown
- #
- # Make sure we find a Block
- block = self.current['block']
- page = self.current['page']
+ #
+ # Create the dropdown
+ #
- field = self.AddElement('field', block,
- { 'name': self.GetUniqueName('fld%s' %
self.variables['name'], block),
- 'field': self.variables['name'],
- 'fk_source': datasource.name,
- 'fk_key': keyfield,
- 'fk_description': descrfield } )
+ # Make sure we find a Block
+ block = self.current['block']
+ page = self.current['page']
+ field = self.AddElement('field', block,
+ { 'name': self.GetUniqueName('fld%s' %
self.variables['name'], block),
+ 'field': self.variables['name'],
+ 'fk_source': datasource.name,
+ 'fk_key': keyfield,
+ 'fk_description': descrfield } )
- self.AddElement('entry', page,
- { 'name': self.GetUniqueName('ntry%s' %
self.variables['name'], page),
- 'field': field.name,
- 'block': block.name,
- 'style': 'dropdown',
- 'Char:x': self.x,
- 'Char:y': self.y,
- 'Char:width': self.width or 10,
- 'Char:height': 1 } )
+ self.AddElement('entry', page,
+ { 'name': self.GetUniqueName('ntry%s' %
self.variables['name'], page),
+ 'field': field.name,
+ 'block': block.name,
+ 'style': 'dropdown',
+ 'Char:x': self.x,
+ 'Char:y': self.y,
+ 'Char:width': self.width or 10,
+ 'Char:height': 1 } )
- return 1
+ return 1
- ###############
- #
- # Internal stuff
- # Get a list of all existing datasources
- #
- def __getExistingDatasources(self):
- self.__firstConnection = None
- self.__datasourceSet = []
- self.__datasourceMap = {}
- for child in self.form.findChildrenOfType('GFDataSource'):
- if hasattr(child,'table'):
- self.__datasourceSet.append((child.name,"%s (%s)" % (child.name,
child.table)))
- self.__datasourceMap[child.name] = child
- if not self.__firstConnection:
- self.__firstConnection = child.connection
- return self.__datasourceSet
+ ###############
+ #
+ # Internal stuff
+ # Get a list of all existing datasources
+ #
+ def __getExistingDatasources(self):
+ self.__firstConnection = None
+ self.__datasourceSet = []
+ self.__datasourceMap = {}
+ for child in self.form.findChildrenOfType('GFDataSource'):
+ if hasattr(child,'table'):
+ self.__datasourceSet.append((child.name,"%s (%s)" %
(child.name, child.table)))
+ self.__datasourceMap[child.name] = child
+ if not self.__firstConnection:
+ self.__firstConnection = child.connection
+ return self.__datasourceSet
+
############
#
# Basic information about this template
@@ -340,4 +340,3 @@
'Behavior': WIZARD,
'MenuLocation' : ('Insert',u_('Dropdown'), 501.2)
}
-
Modified: trunk/gnue-designer/src/forms/wizards/AddEntry.py
===================================================================
--- trunk/gnue-designer/src/forms/wizards/AddEntry.py 2006-04-03 19:53:03 UTC
(rev 8343)
+++ trunk/gnue-designer/src/forms/wizards/AddEntry.py 2006-04-03 19:56:14 UTC
(rev 8344)
@@ -36,48 +36,48 @@
- ###############
- #
- # Initialize any runtime variables
- #
- def StartWithPositioning(self, root, current,
- x=0, y=0, width=10, height=1):
- self.form = root
- self.current = current
- self.x = x
- self.y = y
- self.width = width
- self.height = height
+ ###############
+ #
+ # Initialize any runtime variables
+ #
+ def StartWithPositioning(self, root, current,
+ x=0, y=0, width=10, height=1):
+ self.form = root
+ self.current = current
+ self.x = x
+ self.y = y
+ self.width = width
+ self.height = height
- if not self.current['block']:
- raise InsufficientInformation, u_("There are no blocks in this form.")
+ if not self.current['block']:
+ raise InsufficientInformation, u_("There are no blocks in this
form.")
- ###############
- #
- # We have all the data, so generate our widget.
- #
- def Finalize(self):
+ ###############
+ #
+ # We have all the data, so generate our widget.
+ #
+ def Finalize(self):
- page = self.current['page']
- block = self.current['block']
+ page = self.current['page']
+ block = self.current['block']
- field = self.AddElement('field',block,
- {'name': self.GetUniqueName('UnboundField1',block)})
+ field = self.AddElement('field',block,
+ {'name':
self.GetUniqueName('UnboundField1',block)})
- attrs = {'name': self.GetUniqueName('Entry1',page),
- 'field': field.name,
- 'block': block.name,
- 'Char:x': self.x,
- 'Char:y': self.y,
- 'Char:width': self.width or 10,
- 'Char:height': self.height or 1}
+ attrs = {'name': self.GetUniqueName('Entry1',page),
+ 'field': field.name,
+ 'block': block.name,
+ 'Char:x': self.x,
+ 'Char:y': self.y,
+ 'Char:width': self.width or 10,
+ 'Char:height': self.height or 1}
- # Create entry element
- entry = self.AddElement('entry', page, attrs)
+ # Create entry element
+ entry = self.AddElement('entry', page, attrs)
- return 1
+ return 1
@@ -96,4 +96,3 @@
'Behavior': TEMPLATE,
'MenuLocation' : ('Insert',u_('Unbound Entry'), 501.1)
}
-
Modified: trunk/gnue-designer/src/forms/wizards/AddLabel.py
===================================================================
--- trunk/gnue-designer/src/forms/wizards/AddLabel.py 2006-04-03 19:53:03 UTC
(rev 8343)
+++ trunk/gnue-designer/src/forms/wizards/AddLabel.py 2006-04-03 19:56:14 UTC
(rev 8344)
@@ -36,40 +36,40 @@
- ###############
- #
- # Initialize any runtime variables
- #
- def StartWithPositioning(self, root, current,
- x=0, y=0, width=10, height=4):
- self.form = root
- self.current = current
- self.x = x
- self.y = y
- self.width = width
- self.height = height
+ ###############
+ #
+ # Initialize any runtime variables
+ #
+ def StartWithPositioning(self, root, current,
+ x=0, y=0, width=10, height=4):
+ self.form = root
+ self.current = current
+ self.x = x
+ self.y = y
+ self.width = width
+ self.height = height
- ###############
- #
- # We have all the data, so generate our widget.
- #
- def Finalize(self):
+ ###############
+ #
+ # We have all the data, so generate our widget.
+ #
+ def Finalize(self):
- page = self.current['page']
+ page = self.current['page']
- # Create element
- self.AddElement( 'label',
- page,
- { 'name': self.GetUniqueName('Label1',page),
- 'text': 'Label:',
- 'Char:x': self.x,
- 'Char:y': self.y,
- 'Char:width': self.width or 10,
- 'Char:height': self.height or 1})
+ # Create element
+ self.AddElement( 'label',
+ page,
+ { 'name': self.GetUniqueName('Label1',page),
+ 'text': 'Label:',
+ 'Char:x': self.x,
+ 'Char:y': self.y,
+ 'Char:width': self.width or 10,
+ 'Char:height': self.height or 1})
- return 1
+ return 1
@@ -88,4 +88,3 @@
'Behavior': TEMPLATE,
'MenuLocation' : ('Insert',u_('Label'), 401.1)
}
-
Modified: trunk/gnue-designer/src/forms/wizards/AddPage.py
===================================================================
--- trunk/gnue-designer/src/forms/wizards/AddPage.py 2006-04-03 19:53:03 UTC
(rev 8343)
+++ trunk/gnue-designer/src/forms/wizards/AddPage.py 2006-04-03 19:56:14 UTC
(rev 8344)
@@ -49,88 +49,88 @@
class AddPageWizard(FormTemplate):
- # The first step in our wizard.
- # The template parser will initially
- # call GetStep(FIRST_STEP).
- FIRST_STEP = '0'
+ # The first step in our wizard.
+ # The template parser will initially
+ # call GetStep(FIRST_STEP).
+ FIRST_STEP = '0'
- ###############
- #
- # Initialize any runtime variables
- #
- def Start(self, root, current):
- self.form = root
- self.current = current
+ ###############
+ #
+ # Initialize any runtime variables
+ #
+ def Start(self, root, current):
+ self.form = root
+ self.current = current
- ###############
- #
- # Return the markup for a specific page
- #
- def GetStep(self, step):
-
+ ###############
#
- # Step #0 / Get Name
+ # Return the markup for a specific page
#
- if step == '0':
+ def GetStep(self, step):
- content = [WizardText('This will insert a new page.'),
- WizardInput('name',label='Object Name:',required=1,size=20),
- WizardText('The page caption is optional. It is displayed in
"tabbed"-style forms as the tab caption.'),
- WizardInput('name',label='Caption:',size=20)]
+ #
+ # Step #0 / Get Name
+ #
+ if step == '0':
- if hasattr(self.form,'tabbed') and self.form.tabbed:
- content.append(WizardInput('caption', label='Tab Caption: ',
required=1,
- size=20))
+ content = [WizardText('This will insert a new page.'),
+ WizardInput('name',label='Object
Name:',required=1,size=20),
+ WizardText('The page caption is optional. It is
displayed in "tabbed"-style forms as the tab caption.'),
+ WizardInput('name',label='Caption:',size=20)]
- return { 'title': 'Add Page',
- 'content': content,
- 'prev': None,
- 'next': None }
+ if hasattr(self.form,'tabbed') and self.form.tabbed:
+ content.append(WizardInput('caption', label='Tab Caption: ',
required=1,
+ size=20))
+ return { 'title': 'Add Page',
+ 'content': content,
+ 'prev': None,
+ 'next': None }
- ###############
- #
- # Verify contents of current step
- # Return None if no problems, otherwise
- # return a tuple of error message strings
- #
- def ValidateStep(self, stepCode):
- # The Simple wizard uses basic "required"
- # settings in the page markup, so doesn't
- # need any special validation.
- return None
+ ###############
+ #
+ # Verify contents of current step
+ # Return None if no problems, otherwise
+ # return a tuple of error message strings
+ #
+ def ValidateStep(self, stepCode):
+ # The Simple wizard uses basic "required"
+ # settings in the page markup, so doesn't
+ # need any special validation.
+ return None
- ###############
- #
- # We have all the data, so generate our form. This
- # is called after the user clicks the "Finish" button.
- # No more user input is allowed at this point.
- #
- def Finalize(self):
+ ###############
+ #
+ # We have all the data, so generate our form. This
+ # is called after the user clicks the "Finish" button.
+ # No more user input is allowed at this point.
+ #
+ def Finalize(self):
- attrs = {'name': self.GetUniqueName(self.variables['name'] or 'Page1')}
- try:
- if attrs['caption']:
- attrs['caption'] = self.variables['caption']
- except KeyError:
- pass
+ attrs = {'name': self.GetUniqueName(self.variables['name'] or 'Page1')}
- page = self.AddElement('page', self.current['layout'], attrs)
+ try:
+ if attrs['caption']:
+ attrs['caption'] = self.variables['caption']
+ except KeyError:
+ pass
- return 1
+ page = self.AddElement('page', self.current['layout'], attrs)
+ return 1
+
############
#
# Basic information about this template
@@ -146,4 +146,3 @@
'Behavior': WIZARD,
'MenuLocation' : ('Insert',u_('Blank Page'), 201)
}
-
Modified: trunk/gnue-designer/src/forms/wizards/CreateSchema.py
===================================================================
--- trunk/gnue-designer/src/forms/wizards/CreateSchema.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/forms/wizards/CreateSchema.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -38,276 +38,276 @@
class CreateSchemaWizard(FormTemplate):
- # The first step in our wizard.
- # The template parser will initially
- # call GetStep(FIRST_STEP).
- FIRST_STEP = '0'
+ # The first step in our wizard.
+ # The template parser will initially
+ # call GetStep(FIRST_STEP).
+ FIRST_STEP = '0'
- ###############
- #
- # Initialize any runtime variables
- #
- def Start(self, root, current):
- self.form = root
- self.current = current
+ ###############
+ #
+ # Initialize any runtime variables
+ #
+ def Start(self, root, current):
+ self.form = root
+ self.current = current
- return 0
+ return 0
- ###############
- #
- # Return the markup for a specific page
- #
- def GetStep(self, step):
-
- # 0 - Get name / Source (existing datasource, new
- # bound datasource, fixed set of choices)
- # 1 - Select / Create Source
-
+ ###############
#
- # Step #0 / Get Name
+ # Return the markup for a specific page
#
- if step == '0':
+ def GetStep(self, step):
- content = [WizardText(u_('This will create a GNUe schema definition '+
- 'according to the needs of this form.')),
- WizardInput('file',label=u_('Write to
File:'),required=1,size=20)]
+ # 0 - Get name / Source (existing datasource, new
+ # bound datasource, fixed set of choices)
+ # 1 - Select / Create Source
- return { 'title': 'Create Schema Definition',
- 'content': content,
- 'prev': None,
- 'next': None }
+ #
+ # Step #0 / Get Name
+ #
+ if step == '0':
+ content = [WizardText(u_('This will create a GNUe schema
definition '+
+ 'according to the needs of this form.')),
+ WizardInput('file',label=u_('Write to
File:'),required=1,size=20)]
- ###############
- #
- # Verify contents of current step
- # Return None if no problems, otherwise
- # return a tuple of error message strings
- #
- def ValidateStep(self, stepCode):
+ return { 'title': 'Create Schema Definition',
+ 'content': content,
+ 'prev': None,
+ 'next': None }
- # The Simple wizard uses basic "required"
- # settings in the page markup, so doesn't
- # need any special validation.
- return None
+ ###############
+ #
+ # Verify contents of current step
+ # Return None if no problems, otherwise
+ # return a tuple of error message strings
+ #
+ def ValidateStep(self, stepCode):
+ # The Simple wizard uses basic "required"
+ # settings in the page markup, so doesn't
+ # need any special validation.
+ return None
- ###############
- #
- # We have all the data, so generate our form. This
- # is called after the user clicks the "Finish" button.
- # No more user input is allowed at this point.
- #
- def Finalize(self):
- self.tablelist = {}
- self.schema = GSchema.GSSchema()
- self.gstables = GSchema.GSTables(self.schema)
- # Create Tables out of <datasource> tags
- self.form.walk(self.CreateTables)
+ ###############
+ #
+ # We have all the data, so generate our form. This
+ # is called after the user clicks the "Finish" button.
+ # No more user input is allowed at this point.
+ #
+ def Finalize(self):
- # Populate tables with fields, primary and foreign keys
- self.form.walk(self.PopulateSchema)
+ self.tablelist = {}
+ self.schema = GSchema.GSSchema()
+ self.gstables = GSchema.GSTables(self.schema)
- dest = open(self.variables['file'],"w")
+ # Create Tables out of <datasource> tags
+ self.form.walk(self.CreateTables)
- dest.write("""<?xml version="1.0"?>
-<!-- Schema definition created by GNUe Designer's
- "Create Schema from Form" plugin -->
-""")
+ # Populate tables with fields, primary and foreign keys
+ self.form.walk(self.PopulateSchema)
- dest.write(self.schema.dumpXML().encode('utf-8'))
- dest.close()
+ dest = open(self.variables['file'],"w")
- return 1
+ dest.write("""<?xml version="1.0"?>
+ <!-- Schema definition created by GNUe Designer's
+ "Create Schema from Form" plugin -->
+ """)
- def CreateTables(self,obj):
- if obj._type=='GFDataSource':
+ dest.write(self.schema.dumpXML().encode('utf-8'))
+ dest.close()
- if hasattr(obj,'table'):
+ return 1
- #
- # add the table
- #
+ def CreateTables(self,obj):
+ if obj._type=='GFDataSource':
- newtable = GSchema.GSTable(self.gstables)
- newtable.name=obj.table
- GSchema.GSFields(newtable)
- GSchema.GSConstraints(newtable)
- self.tablelist[string.lower(obj.name)]=newtable
+ if hasattr(obj,'table'):
- else:
- print "WARNING: You defined a datasource without an 'table' "+\
- "attribute."
+ #
+ # add the table
+ #
+ newtable = GSchema.GSTable(self.gstables)
+ newtable.name=obj.table
+ GSchema.GSFields(newtable)
+ GSchema.GSConstraints(newtable)
+ self.tablelist[string.lower(obj.name)]=newtable
- def PopulateSchema(self,obj):
- # TODO: * care for multiple fields in fk_descriptions
- # * add error messages in case of missing/wrong datasources
- # for a fk_source, or a datasource field (in <block ...>)
- # * add a way to check for a datasource name with right case before
- # just don't care for the case
- # * add a function for guessing row types
+ else:
+ print "WARNING: You defined a datasource without an 'table' "+\
+ "attribute."
- if obj._type=='GFEntry':
- myblock=obj.findParentOfType('GFBlock')
+ def PopulateSchema(self,obj):
+ # TODO: * care for multiple fields in fk_descriptions
+ # * add error messages in case of missing/wrong datasources
+ # for a fk_source, or a datasource field (in <block ...>)
+ # * add a way to check for a datasource name with right case
before
+ # just don't care for the case
+ # * add a function for guessing row types
- #
- # add a simple field to the table
- #
- if hasattr(obj,'field') and hasattr(myblock,'datasource') and \
- self.tablelist.has_key(string.lower(myblock.datasource)):
+ if obj._type=='GFEntry':
- table=self.tablelist[string.lower(myblock.datasource)]
+ myblock=obj.findParentOfType('GFBlock')
- type = self.DEFAULT_TYPE # standart type
+ #
+ # add a simple field to the table
+ #
+ if hasattr(obj,'field') and hasattr(myblock,'datasource') and \
+ self.tablelist.has_key(string.lower(myblock.datasource)):
- if hasattr(obj,'style') and obj.style == 'checkbox':
- type = self.BOOLEAN_TYPE
+ table=self.tablelist[string.lower(myblock.datasource)]
- if hasattr(obj,'numeric') and obj.numeric==1:
- type = self.NUMERIC_TYPE
+ type = self.DEFAULT_TYPE # standart type
- if hasattr(obj,'height') and obj.height>1:
- type = self.TEXT_TYPE
+ if hasattr(obj,'style') and obj.style == 'checkbox':
+ type = self.BOOLEAN_TYPE
- if hasattr(obj,'typecast'):
- if obj.typecast=='number':
- type = self.NUMERIC_TYPE
+ if hasattr(obj,'numeric') and obj.numeric==1:
+ type = self.NUMERIC_TYPE
- if obj.typecast=='date':
- type = self.DATE_TYPE
+ if hasattr(obj,'height') and obj.height>1:
+ type = self.TEXT_TYPE
- if obj.typecast=='text' and hasattr(obj,'numeric') and \
- obj.numeric==1: # reset previous numeric fields
- type = self.STRING_TYPE
+ if hasattr(obj,'typecast'):
+ if obj.typecast=='number':
+ type = self.NUMERIC_TYPE
- # string type needs a definit size
- if type == self.STRING_TYPE:
+ if obj.typecast=='date':
+ type = self.DATE_TYPE
- size = self.DEFAULT_SIZE
+ if obj.typecast=='text' and hasattr(obj,'numeric') and \
+ obj.numeric==1: # reset previous numeric fields
+ type = self.STRING_TYPE
- if hasattr(obj,'max_length'):
- size = obj.max_length
+ # string type needs a definit size
+ if type == self.STRING_TYPE:
- elif hasattr(obj,'width'):
- size = obj.width
+ size = self.DEFAULT_SIZE
- self.AddField(table, obj.field, self.STRING_TYPE, size)
+ if hasattr(obj,'max_length'):
+ size = obj.max_length
- else:
+ elif hasattr(obj,'width'):
+ size = obj.width
- self.AddField(table, obj.field, type)
+ self.AddField(table, obj.field, self.STRING_TYPE, size)
- #
- # add fields to the table referenced in dropdowns
- #
- if hasattr(obj,'fk_key') and hasattr(obj,'fk_source') and\
- self.tablelist.has_key(string.lower(obj.fk_source)):
+ else:
- table=self.tablelist[string.lower(obj.fk_source)]
+ self.AddField(table, obj.field, type)
- # add 'fk_key' field
- if type == self.STRING_TYPE:
- self.AddField(table, obj.fk_key, type, size)
+ #
+ # add fields to the table referenced in dropdowns
+ #
+ if hasattr(obj,'fk_key') and hasattr(obj,'fk_source') and\
+ self.tablelist.has_key(string.lower(obj.fk_source)):
- else:
- self.AddField(table, obj.fk_key, type)
+ table=self.tablelist[string.lower(obj.fk_source)]
- if hasattr(obj,'fk_description'):
+ # add 'fk_key' field
+ if type == self.STRING_TYPE:
+ self.AddField(table, obj.fk_key, type, size)
- # add 'fk_description' field
- self.AddField(table, obj.fk_description, self.STRING_TYPE)
+ else:
+ self.AddField(table, obj.fk_key, type)
+ if hasattr(obj,'fk_description'):
- elif obj._type=='GFDataSource':
+ # add 'fk_description' field
+ self.AddField(table, obj.fk_description, self.STRING_TYPE)
- if hasattr(obj,'table'):
- #
- # check for master/detail relation ship
- #
+ elif obj._type=='GFDataSource':
- if hasattr(obj,'master') and hasattr(obj,'masterlink') and \
- hasattr(obj,'detaillink'):
+ if hasattr(obj,'table'):
- table=self.tablelist[string.lower(obj.name)]
+ #
+ # check for master/detail relation ship
+ #
- # create a foreign key on this table
- newconstraint=GSchema.GSConstraint ( \
- table.findChildOfType ('GSConstraints'))
- newconstraint.name="fk_%s_%s" % (obj.table,obj.detaillink)
- newconstraint.type="foreignkey"
+ if hasattr(obj,'master') and hasattr(obj,'masterlink') and \
+ hasattr(obj,'detaillink'):
- nfk_field=GSchema.GSConstraintField(newconstraint)
- nfk_field.name=obj.detaillink
- nfk_ref=GSchema.GSConstraintRef(newconstraint)
- nfk_ref.name=obj.masterlink
+ table=self.tablelist[string.lower(obj.name)]
- # create a field for that key, use string type for now
- # TODO: Check if detaillink or masterlink type is defined
- # if it one of the two is defined, then use the definition for both
- self.AddField(table, obj.detaillink, self.DEFAULT_TYPE)
+ # create a foreign key on this table
+ newconstraint=GSchema.GSConstraint ( \
+ table.findChildOfType ('GSConstraints'))
+ newconstraint.name="fk_%s_%s" % (obj.table,obj.detaillink)
+ newconstraint.type="foreignkey"
- if self.tablelist[string.lower(obj.master)]:
+ nfk_field=GSchema.GSConstraintField(newconstraint)
+ nfk_field.name=obj.detaillink
+ nfk_ref=GSchema.GSConstraintRef(newconstraint)
+ nfk_ref.name=obj.masterlink
- mtable=self.tablelist[string.lower(obj.master)]
- # set table name for foreign key
- nfk_ref.table=mtable.name
+ # create a field for that key, use string type for now
+ # TODO: Check if detaillink or masterlink type is defined
+ # if it one of the two is defined, then use the definition
for both
+ self.AddField(table, obj.detaillink, self.DEFAULT_TYPE)
- oldpkey=mtable.findChildOfType("GSPKField")
- if oldpkey==None:
- pkey=GSchema.GSPrimaryKey(mtable)
- pkey.name="pk_%s_%s" % (mtable.name,obj.masterlink)
- pkeyf=GSchema.GSPKField(pkey)
- pkeyf.name=obj.masterlink
+ if self.tablelist[string.lower(obj.master)]:
- # add field to master table, using default type
- self.AddField(mtable, obj.masterlink, self.DEFAULT_TYPE)
+ mtable=self.tablelist[string.lower(obj.master)]
+ # set table name for foreign key
+ nfk_ref.table=mtable.name
- elif oldpkey.name!=obj.masterlink:
- print "WARNING: different primary keys computed out of "+\
- "master detail relationship ('%s'!='%s')." % \
- (oldpkey.name!=obj.masterlink)
- else:
- print "WARNING: master datasource is not defined in this file."
+ oldpkey=mtable.findChildOfType("GSPKField")
+ if oldpkey==None:
+ pkey=GSchema.GSPrimaryKey(mtable)
+ pkey.name="pk_%s_%s" % (mtable.name,obj.masterlink)
+ pkeyf=GSchema.GSPKField(pkey)
+ pkeyf.name=obj.masterlink
+ # add field to master table, using default type
+ self.AddField(mtable, obj.masterlink,
self.DEFAULT_TYPE)
- else:
- pass
+ elif oldpkey.name!=obj.masterlink:
+ print "WARNING: different primary keys computed
out of "+\
+ "master detail relationship ('%s'!='%s')." %
\
+ (oldpkey.name!=obj.masterlink)
+ else:
+ print "WARNING: master datasource is not defined in
this file."
- def AddField(self,table,fieldname,type,length=None):
- fields = table.findChildOfType('GSFields')
+ else:
+ pass
- # check if field already exists
- for child in fields._children:
- if child._type == 'GSField' and child.name==fieldname:
- # field already exists, so returning
- # (possibly updating fieldtype here)
- if type!=self.DEFAULT_TYPE:
- child.type=type
+ def AddField(self,table,fieldname,type,length=None):
- if length!=None:
- child.size=int(length)
- return
+ fields = table.findChildOfType('GSFields')
- # create field
- newfield = GSchema.GSField(fields)
- newfield.name=fieldname
- newfield.type=type
- if length!=None:
- newfield.size=int(length)
- elif type==self.STRING_TYPE:
- newfield.size=self.DEFAULT_SIZE
+ # check if field already exists
+ for child in fields._children:
+ if child._type == 'GSField' and child.name==fieldname:
+ # field already exists, so returning
+ # (possibly updating fieldtype here)
+ if type!=self.DEFAULT_TYPE:
+ child.type=type
+ if length!=None:
+ child.size=int(length)
+ return
+ # create field
+ newfield = GSchema.GSField(fields)
+ newfield.name=fieldname
+ newfield.type=type
+ if length!=None:
+ newfield.size=int(length)
+ elif type==self.STRING_TYPE:
+ newfield.size=self.DEFAULT_SIZE
+
+
############
#
# Basic information about this template
@@ -325,4 +325,3 @@
'Behavior': WIZARD,
'MenuLocation' : ('Tools|Extras',u_('Create Schema from Form'))
}
-
Modified: trunk/gnue-designer/src/forms/wizards/CreateWebForm.py
===================================================================
--- trunk/gnue-designer/src/forms/wizards/CreateWebForm.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/forms/wizards/CreateWebForm.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -54,536 +54,536 @@
class CreateWebFormWizard(FormTemplate):
- # The first step in our wizard.
- # The template parser will initially
- # call GetStep(FIRST_STEP).
- FIRST_STEP = '0'
+ # The first step in our wizard.
+ # The template parser will initially
+ # call GetStep(FIRST_STEP).
+ FIRST_STEP = '0'
- ###############
- #
- # Define some settings, which could be configured
- #
+ ###############
+ #
+ # Define some settings, which could be configured
+ #
- # the default name of the webserver
- DEFAULT_SERVERNAME=""
+ # the default name of the webserver
+ DEFAULT_SERVERNAME=""
- ###############
- #
- # Initialize any runtime variables
- #
- def Start(self, root, current):
- self.form = root
- self.current = current
- self.Xsize=0
- self.Ysize=0
- self.Xraster=15
- self.Yraster=30
- self.yBase=10
- self.xBase=5
- self.baseline=6
- self.fontsize=18
- self.lineheight=35
- self.fontsize_entry=12
- self.statusBar=1
- self.buttonBar=1
+ ###############
+ #
+ # Initialize any runtime variables
+ #
+ def Start(self, root, current):
+ self.form = root
+ self.current = current
+ self.Xsize=0
+ self.Ysize=0
+ self.Xraster=15
+ self.Yraster=30
+ self.yBase=10
+ self.xBase=5
+ self.baseline=6
+ self.fontsize=18
+ self.lineheight=35
+ self.fontsize_entry=12
+ self.statusBar=1
+ self.buttonBar=1
- ###############
- #
- # Return the markup for a specific page
- #
- def GetStep(self, step):
-
- # 0 - Get filename
- # 1 - Confirm
-
+ ###############
#
- # Step #0 / Get Filename Name
+ # Return the markup for a specific page
#
- if step == '0':
+ def GetStep(self, step):
- self.variables['cellwidth']=str(self.Xraster)
- self.variables['cellheight']=str(self.Yraster)
+ # 0 - Get filename
+ # 1 - Confirm
- content = [WizardText('This will build a dynamic web form writen in '+
- 'HTML and Javascript. For more information '+
- 'confer to "jsclient/INSTALL.TXT".\n\n '),
- WizardInput('file',label='File Name:',required=1,size=20),
- WizardText('\n\nChoose default cell size (in Pixel):'),
- WizardInput('cellwidth',label='Cell Width :',
- required=1,size=10),
- WizardInput('cellheight',label='Cell Height :',
- required=1,size=10)]
+ #
+ # Step #0 / Get Filename Name
+ #
+ if step == '0':
- return { 'title': 'Create Web Forms File',
- 'content': content,
- 'prev': None,
- 'next': '1' }
+ self.variables['cellwidth']=str(self.Xraster)
+ self.variables['cellheight']=str(self.Yraster)
- if step == '1':
+ content = [WizardText('This will build a dynamic web form writen
in '+
+ 'HTML and Javascript. For more information '+
+ 'confer to "jsclient/INSTALL.TXT".\n\n '),
+ WizardInput('file',label='File
Name:',required=1,size=20),
+ WizardText('\n\nChoose default cell size (in Pixel):'),
+ WizardInput('cellwidth',label='Cell Width :',
+ required=1,size=10),
+ WizardInput('cellheight',label='Cell Height :',
+ required=1,size=10)]
- self.computePageSize(self.form.findChildOfType("GFLayout"))
+ return { 'title': 'Create Web Forms File',
+ 'content': content,
+ 'prev': None,
+ 'next': '1' }
- if self.variables['file'][-5:]!=".html":
- self.variables['file']+=".html"
+ if step == '1':
- self.Xraster=int(self.variables['cellwidth'])
- self.Yraster=int(self.variables['cellheight'])
- self.baseline=int(self.Yraster*6/35)
- self.fontsize=int(self.Yraster*18/35)
- self.lineheight=self.Yraster
- self.fontsize_entry=int(self.Yraster*16/35)
+ self.computePageSize(self.form.findChildOfType("GFLayout"))
- self.variables['encoding']=gConfig('textEncoding')
- choices=(('iso8859-1','Western'),
- ('utf-8','Unicode'),
- ('big5','Trad. Chinese' ),
- ('gb2312','Simpl. Chinese' ),
- ('jis','Japanese' ))
+ if self.variables['file'][-5:]!=".html":
+ self.variables['file']+=".html"
- content = [WizardText('The web form will be stored in the file '+
- ('%s.\n\n' % self.variables['file'])),
- WizardText('Form Size: %sx%s => ' % \
- (self.Xsize,self.Ysize)+\
- '%sx%s Pixel' % \
- (self.Xsize*self.Xraster,
- self.Ysize*self.Yraster)),
- WizardInput('encoding',label='Default Encoding :',
- required=1,size=10,set=choices)]
+ self.Xraster=int(self.variables['cellwidth'])
+ self.Yraster=int(self.variables['cellheight'])
+ self.baseline=int(self.Yraster*6/35)
+ self.fontsize=int(self.Yraster*18/35)
+ self.lineheight=self.Yraster
+ self.fontsize_entry=int(self.Yraster*16/35)
- return { 'title': 'Create Web Forms File',
- 'content': content,
- 'prev': '0',
- 'next': None }
+ self.variables['encoding']=gConfig('textEncoding')
+ choices=(('iso8859-1','Western'),
+ ('utf-8','Unicode'),
+ ('big5','Trad. Chinese' ),
+ ('gb2312','Simpl. Chinese' ),
+ ('jis','Japanese' ))
+ content = [WizardText('The web form will be stored in the file '+
+ ('%s.\n\n' % self.variables['file'])),
+ WizardText('Form Size: %sx%s => ' % \
+ (self.Xsize,self.Ysize)+\
+ '%sx%s Pixel' % \
+ (self.Xsize*self.Xraster,
+ self.Ysize*self.Yraster)),
+ WizardInput('encoding',label='Default Encoding :',
+ required=1,size=10,set=choices)]
- ###############
- #
- # Verify contents of current step
- # Return None if no problems, otherwise
- # return a tuple of error message strings
- #
- def ValidateStep(self, stepCode):
+ return { 'title': 'Create Web Forms File',
+ 'content': content,
+ 'prev': '0',
+ 'next': None }
- # The Simple wizard uses basic "required"
- # settings in the page markup, so doesn't
- # need any special validation.
- return None
+ ###############
+ #
+ # Verify contents of current step
+ # Return None if no problems, otherwise
+ # return a tuple of error message strings
+ #
+ def ValidateStep(self, stepCode):
+ # The Simple wizard uses basic "required"
+ # settings in the page markup, so doesn't
+ # need any special validation.
+ return None
- ###############
- #
- # We have all the data, so generate our form. This
- # is called after the user clicks the "Finish" button.
- # No more user input is allowed at this point.
- #
- def Finalize(self):
- title = "GNUe jsForms: Untitled Form"
- if hasattr(self.form,"title"):
- title = "GNUe jsForms: %s" % self.form.title
+ ###############
+ #
+ # We have all the data, so generate our form. This
+ # is called after the user clicks the "Finish" button.
+ # No more user input is allowed at this point.
+ #
+ def Finalize(self):
- dest = open(self.variables['file'],"w")
+ title = "GNUe jsForms: Untitled Form"
- dest.write("<HTML>\n <HEAD>\n <TITLE>%s</TITLE></HEAD>" % title)
+ if hasattr(self.form,"title"):
+ title = "GNUe jsForms: %s" % self.form.title
- charset=self.variables['encoding']
+ dest = open(self.variables['file'],"w")
- dest.write('<meta http-equiv="Content-Type" content="text/html;'+\
- ' charset=%s">\n </HEAD>\n' % charset)
+ dest.write("<HTML>\n <HEAD>\n <TITLE>%s</TITLE></HEAD>" % title)
- dest.write('<BODY onLoad="setup();form.run();" onUnload="form.close();">')
+ charset=self.variables['encoding']
- if hasattr(self,'showtitle'):
- dest.write('<H1>%s</H1>' % title)
+ dest.write('<meta http-equiv="Content-Type" content="text/html;'+\
+ ' charset=%s">\n </HEAD>\n' % charset)
- # write javascript include
- dest.write('<SCRIPT src="vcXMLRPC.js"></SCRIPT>\n' +\
- '<SCRIPT src="gnue-forms.js"></SCRIPT>\n')
- # write datasource data, trigger information etc.
- dest.write(self.buildCode(self.form))
+ dest.write('<BODY onLoad="setup();form.run();"
onUnload="form.close();">')
- if self.buttonBar:
- dest.write(self.addButtonBar())
+ if hasattr(self,'showtitle'):
+ dest.write('<H1>%s</H1>' % title)
+ # write javascript include
+ dest.write('<SCRIPT src="vcXMLRPC.js"></SCRIPT>\n' +\
+ '<SCRIPT src="gnue-forms.js"></SCRIPT>\n')
+ # write datasource data, trigger information etc.
+ dest.write(self.buildCode(self.form))
- # Create Formpages
- visible=1
- layout=self.form.findChildOfType("GFLayout")
+ if self.buttonBar:
+ dest.write(self.addButtonBar())
- if hasattr(layout,"tabbed") and len(layout.tabbed)>0:
- # Create Page tabs
- pos=0
- for child in layout._children:
- if child._type=="GFPage":
- dest.write(self.addPageTab(child.name,pos))
- pos+=200
- # TODO: support top,down,left,right instead of converting everything
to top
- self.yBase+=self.Yraster
+ # Create Formpages
+ visible=1
+ layout=self.form.findChildOfType("GFLayout")
- dest.write(self.addBackground())
+ if hasattr(layout,"tabbed") and len(layout.tabbed)>0:
+ # Create Page tabs
+ pos=0
+ for child in layout._children:
+ if child._type=="GFPage":
+ dest.write(self.addPageTab(child.name,pos))
+ pos+=200
+ # TODO: support top,down,left,right instead of converting
everything to top
+ self.yBase+=self.Yraster
- for child in layout._children:
- if child._type=="GFPage":
- ## dest.write("<h2>%s</H2>" % child.name)
- dest.write('<DIV id="%s_page">' % child.name)
- dest.write(self.drawElements(child,visible))
- dest.write("</DIV>")
- visible=0
+ dest.write(self.addBackground())
- if self.statusBar:
- dest.write(self.addStatusBar())
+ for child in layout._children:
+ if child._type=="GFPage":
+ ## dest.write("<h2>%s</H2>" % child.name)
+ dest.write('<DIV id="%s_page">' % child.name)
+ dest.write(self.drawElements(child,visible))
+ dest.write("</DIV>")
+ visible=0
- dest.write(self.addLoginDialog())
- dest.write("<BODY></HTML>")
- dest.close()
- return 1
+ if self.statusBar:
+ dest.write(self.addStatusBar())
- def buildCode(self,obj):
- # TODO: reuse GFParser for this stuff
- outp=""
+ dest.write(self.addLoginDialog())
+ dest.write("<BODY></HTML>")
+ dest.close()
- if obj._type=="GFForm":
- outp+='<script language="JavaScript"><!--\n' +\
- 'var form;\n' +\
- '// add aditional function, because only functions '+\
- 'have real global scope.\n' +\
- 'function getForm() {\n' +\
- ' return form;\n' +\
- '};\n' +\
- 'function setup() {\n' +\
- 'form = new GFForm(form);\n' +\
- "form.title='%s';\n\n" % obj.title
+ return 1
- if obj._type=='GFDataSource':
- outp+="dts = new GFDataSource(form);\n"
- outp+="dts._setParent(form);\n"
- outp+="dts.name='%s';\n" % obj.name
- outp+="dts.table='%s';\n" % obj.table
+ def buildCode(self,obj):
+ # TODO: reuse GFParser for this stuff
+ outp=""
- if hasattr(obj,"order_by"):
- outp+="dts.order_by='%s';\n" % obj.order_by
+ if obj._type=="GFForm":
+ outp+='<script language="JavaScript"><!--\n' +\
+ 'var form;\n' +\
+ '// add aditional function, because only functions '+\
+ 'have real global scope.\n' +\
+ 'function getForm() {\n' +\
+ ' return form;\n' +\
+ '};\n' +\
+ 'function setup() {\n' +\
+ 'form = new GFForm(form);\n' +\
+ "form.title='%s';\n\n" % obj.title
- if hasattr(obj,"prequery"):
- outp+="dts.prequery='%s';\n" % obj.prequery
+ if obj._type=='GFDataSource':
+ outp+="dts = new GFDataSource(form);\n"
+ outp+="dts._setParent(form);\n"
+ outp+="dts.name='%s';\n" % obj.name
+ outp+="dts.table='%s';\n" % obj.table
- if hasattr(obj,"detaillink"):
- outp+="dts.detaillink='%s';\n" % obj.detaillink
+ if hasattr(obj,"order_by"):
+ outp+="dts.order_by='%s';\n" % obj.order_by
- if hasattr(obj,"master"):
- outp+="dts.master='%s';\n" % obj.master
+ if hasattr(obj,"prequery"):
+ outp+="dts.prequery='%s';\n" % obj.prequery
- if hasattr(obj,"masterlink"):
- outp+="dts.masterlink='%s';\n" % obj.masterlink
+ if hasattr(obj,"detaillink"):
+ outp+="dts.detaillink='%s';\n" % obj.detaillink
- if hasattr(obj,"cache"):
- outp+="dts.cache=%s;\n" % obj.cache
+ if hasattr(obj,"master"):
+ outp+="dts.master='%s';\n" % obj.master
- outp+="dts.connection='%s';\n\n" % obj.connection
+ if hasattr(obj,"masterlink"):
+ outp+="dts.masterlink='%s';\n" % obj.masterlink
+ if hasattr(obj,"cache"):
+ outp+="dts.cache=%s;\n" % obj.cache
- if obj._type=="GFLogic":
- pass
+ outp+="dts.connection='%s';\n\n" % obj.connection
- if obj._type=='GFBlock':
- outp+="blk = new GFBlock(form);\n"
- outp+="blk._setParent(form);\n"
- outp+="blk.name='%s';\n" % obj.name
- outp+="blk.datasource='%s';\n\n" % obj.datasource
- if obj._type=='GFField':
- outp+="field = new GFField(blk);\n"
- outp+="field._setParent(blk);\n"
- outp+="field.name='%s';\n" % obj.name
- if hasattr(obj,"field"):
- outp+="field.field='%s';\n" % obj.field
- else:
- outp+="field.field='%s';\n" % obj.name
+ if obj._type=="GFLogic":
+ pass
- if hasattr(obj,'default'):
- # TODO: fix default values (default is a keyword in javascript)
- outp+="field._default='%s';\n" % obj.default
+ if obj._type=='GFBlock':
+ outp+="blk = new GFBlock(form);\n"
+ outp+="blk._setParent(form);\n"
+ outp+="blk.name='%s';\n" % obj.name
+ outp+="blk.datasource='%s';\n\n" % obj.datasource
- if hasattr(obj,'max_length'):
- outp+="field.max_length='%s';\n" % obj.max_length
- # TODO: add rest of attributs
- outp+="\n"
+ if obj._type=='GFField':
+ outp+="field = new GFField(blk);\n"
+ outp+="field._setParent(blk);\n"
+ outp+="field.name='%s';\n" % obj.name
+ if hasattr(obj,"field"):
+ outp+="field.field='%s';\n" % obj.field
+ else:
+ outp+="field.field='%s';\n" % obj.name
- if obj._type=='GFPage':
- outp+="page = new GFPage(form);\n" # do we need to add gflayout?
- outp+="page._setParent(form);\n"
- outp+="page.name='%s';\n" % obj.name
+ if hasattr(obj,'default'):
+ # TODO: fix default values (default is a keyword in javascript)
+ outp+="field._default='%s';\n" % obj.default
- if obj._type=='GFLabel':
- outp+="label = new GFLabel(page);\n" # do we need to add gflayout?
- outp+="label._setParent(page);\n"
- outp+="label.name='%s';\n\n" % obj.name
+ if hasattr(obj,'max_length'):
+ outp+="field.max_length='%s';\n" % obj.max_length
+ # TODO: add rest of attributs
+ outp+="\n"
- if obj._type=='GFBox':
- outp+="box = new GFBox(page);\n" # do we need to add gflayout?
- outp+="box._setParent(page);\n"
- outp+="box.name='%s';\n\n" % obj.name
+ if obj._type=='GFPage':
+ outp+="page = new GFPage(form);\n" # do we need to add gflayout?
+ outp+="page._setParent(form);\n"
+ outp+="page.name='%s';\n" % obj.name
- if obj._type=='GFButton':
- outp+="btn = new GFButton(page);\n" # do we need to add gflayout?
- outp+="btn._setParent(page);\n"
- outp+="btn.name='%s';\n\n" % obj.name
- # TODO: add simple trigger script
+ if obj._type=='GFLabel':
+ outp+="label = new GFLabel(page);\n" # do we need to add gflayout?
+ outp+="label._setParent(page);\n"
+ outp+="label.name='%s';\n\n" % obj.name
- if obj._type=='GFEntry':
- outp+="entry = new GFEntry(page);\n"
- outp+="entry._setParent(page);\n"
- outp+="entry.name='%s';\n" % obj.name
- outp+="entry.block='%s';\n" % obj.block
- if hasattr(obj,"field"):
- outp+="entry.field='%s';\n" % obj.field
- #else:
- # outp+="entry.field='%s';\n" % obj.name
+ if obj._type=='GFBox':
+ outp+="box = new GFBox(page);\n" # do we need to add gflayout?
+ outp+="box._setParent(page);\n"
+ outp+="box.name='%s';\n\n" % obj.name
- if hasattr(obj,'__Char_x'):
- outp+="entry.__char_x='%s';\n" % obj.__Char_x
+ if obj._type=='GFButton':
+ outp+="btn = new GFButton(page);\n" # do we need to add gflayout?
+ outp+="btn._setParent(page);\n"
+ outp+="btn.name='%s';\n\n" % obj.name
+ # TODO: add simple trigger script
- if hasattr(obj,'__Char_y'):
- outp+="entry.__char_y='%s';\n" % obj.__Char_y
+ if obj._type=='GFEntry':
+ outp+="entry = new GFEntry(page);\n"
+ outp+="entry._setParent(page);\n"
+ outp+="entry.name='%s';\n" % obj.name
+ outp+="entry.block='%s';\n" % obj.block
+ if hasattr(obj,"field"):
+ outp+="entry.field='%s';\n" % obj.field
+ #else:
+ # outp+="entry.field='%s';\n" % obj.name
- if hasattr(obj,'__Char_width'):
- outp+="entry.__char_width='%s';\n" % obj.__Char_width
+ if hasattr(obj,'__Char_x'):
+ outp+="entry.__char_x='%s';\n" % obj.__Char_x
- if hasattr(obj,'__Char_height'):
- outp+="entry.__char_height='%s';\n" % obj.__Char_heigth
+ if hasattr(obj,'__Char_y'):
+ outp+="entry.__char_y='%s';\n" % obj.__Char_y
- ## Foreign key (f. dropdown) support
- if hasattr(obj,'fk_source'):
- outp+="entry.fk_source='%s';\n" % obj.fk_source
+ if hasattr(obj,'__Char_width'):
+ outp+="entry.__char_width='%s';\n" % obj.__Char_width
- if hasattr(obj,'fk_key'):
- outp+="entry.fk_key='%s';\n" % obj.fk_key
+ if hasattr(obj,'__Char_height'):
+ outp+="entry.__char_height='%s';\n" % obj.__Char_heigth
- if hasattr(obj,'fk_description'):
- outp+="entry.fk_descripion=%s';\n" % obj.fk_description
- outp+='\n'
+ ## Foreign key (f. dropdown) support
+ if hasattr(obj,'fk_source'):
+ outp+="entry.fk_source='%s';\n" % obj.fk_source
+ if hasattr(obj,'fk_key'):
+ outp+="entry.fk_key='%s';\n" % obj.fk_key
+ if hasattr(obj,'fk_description'):
+ outp+="entry.fk_descripion=%s';\n" % obj.fk_description
+ outp+='\n'
- if obj._type=='GFOption':
- pass
- for child in obj._children:
- outp+=self.buildCode(child)
- if obj._type=="GFForm":
- outp+='}\n</script>\n'
+ if obj._type=='GFOption':
+ pass
- return outp
+ for child in obj._children:
+ outp+=self.buildCode(child)
- def addBackground(self):
- outp='<DIV STYLE="position:absolute; '+\
- 'top: %spx;' % self.yBase +\
- 'left: %spx;\n' % self.xBase +\
- 'width: %spx;' % (self.Xsize*self.Xraster) +\
- 'height: %spx;\n' % (self.Ysize*self.Yraster) +\
- 'border-width: 1px;'+\
- 'border-style: solid;\nbackground-color:#EEEEEE;" align="center">\n'
- outp+=' '
- outp+='</DIV>'
- return outp
+ if obj._type=="GFForm":
+ outp+='}\n</script>\n'
- def addPageTab(self,name,pos):
- # outp = '<center><br><img src="img/gnue.png"><br>�</center>'
- outp='<DIV STYLE="position:absolute; '+\
- 'top: %spx;' % self.yBase +\
- 'left: %spx;\n' % (self.xBase+pos) +\
- 'width: %spx;' % 180 +\
- 'height: %spx;' % self.Yraster +\
- 'border-width: 1px;'+\
- 'border-style: solid;background-color:#EEEEEE;"\n' +\
- 'align="center" onclick="getForm().gotoPage(' +\
- "'%s');" % name + '">\n'
- outp+='%s' % name
- outp+='</DIV>'
- return outp
+ return outp
- def showButton(self,img,name,alt,command,key):
- b='<img src="images/'+img+'-24x24.png" name="'+name+'" alt="'+alt+\
- '" onclick="'+ command+';">\n';
- return b
+ def addBackground(self):
+ outp='<DIV STYLE="position:absolute; '+\
+ 'top: %spx;' % self.yBase +\
+ 'left: %spx;\n' % self.xBase +\
+ 'width: %spx;' % (self.Xsize*self.Xraster) +\
+ 'height: %spx;\n' % (self.Ysize*self.Yraster) +\
+ 'border-width: 1px;'+\
+ 'border-style: solid;\nbackground-color:#EEEEEE;"
align="center">\n'
+ outp+=' '
+ outp+='</DIV>'
+ return outp
- def addButtonBar(self):
- # outp = '<center><br><img src="img/gnue.png"><br>�</center>'
- outp='<DIV STYLE="position:absolute; '+\
- 'top: %spx;' % self.yBase +\
- 'left: %spx;\n' %
(max([self.Xsize*self.Xraster,540])/2+self.xBase-270) +\
- 'width: %spx;' % 540 +\
- 'border-width: 1px;'+\
- 'border-style: solid;\nbackground-color:#EEEEEE;" align="center">\n'
+ def addPageTab(self,name,pos):
+ # outp = '<center><br><img src="img/gnue.png"><br>�</center>'
+ outp='<DIV STYLE="position:absolute; '+\
+ 'top: %spx;' % self.yBase +\
+ 'left: %spx;\n' % (self.xBase+pos) +\
+ 'width: %spx;' % 180 +\
+ 'height: %spx;' % self.Yraster +\
+ 'border-width: 1px;'+\
+ 'border-style: solid;background-color:#EEEEEE;"\n' +\
+ 'align="center" onclick="getForm().gotoPage(' +\
+ "'%s');" % name + '">\n'
+ outp+='%s' % name
+ outp+='</DIV>'
+ return outp
- self.yBase=self.yBase+50
+ def showButton(self,img,name,alt,command,key):
+ b='<img src="images/'+img+'-24x24.png" name="'+name+'" alt="'+alt+\
+ '" onclick="'+ command+';">\n';
+ return b
- outp+=self.showButton('commit',"commit","Commit","getForm().commit();",'n')
- outp+=self.showButton('newrecord',"newrec","New
Record","getForm().newrec();",'n')
- outp+=self.showButton('markfordelete',"trash","Mark for Removal",
- "getForm().del();",'n')
- outp+=' '
- outp+=self.showButton('prevrecord',"prev","Previous
Record","getForm().prev();",'')
- outp+=self.showButton('nextrecord',"next","Next
Record","getForm().next();",'')
- outp+=' '
- outp+=self.showButton('enterquery',"prepq","Prepare
Query","getForm().prepQ();",'')
- outp+=self.showButton('execquery',"query","Execute
Query","getForm().execQ();",'')
- outp+=' '
-
outp+=self.showButton('rollback',"rollback","Rollback","getForm().rollback();",'')
- outp+=' '
- outp+=self.showButton('about',"help","About","getForm().about();",'')
- outp+=' '
- outp+=self.showButton('exit',"close","","getForm().close();",'')
- outp+='</DIV>'
- return outp;
+ def addButtonBar(self):
+ # outp = '<center><br><img src="img/gnue.png"><br>�</center>'
+ outp='<DIV STYLE="position:absolute; '+\
+ 'top: %spx;' % self.yBase +\
+ 'left: %spx;\n' %
(max([self.Xsize*self.Xraster,540])/2+self.xBase-270) +\
+ 'width: %spx;' % 540 +\
+ 'border-width: 1px;'+\
+ 'border-style: solid;\nbackground-color:#EEEEEE;"
align="center">\n'
- def addStatusBar(self):
- return '''
-<DIV STYLE="position:absolute; top: %spx;left: %spx;width: %spx;border-width:
1px; border-style: solid;background-color:#EEEEEE;" align="right">
- <div id="status" style="display:inline"></div>�|�
- <div id="pos" style="display:inline"></div>�|�
- <div id="max" style="display:inline"></div>
-</DIV>
-''' % (((self.Ysize+2)*self.Yraster)+self.yBase+20,\
- (max([self.Xsize*self.Xraster,540])/2+self.xBase-270),540)
+ self.yBase=self.yBase+50
+
outp+=self.showButton('commit',"commit","Commit","getForm().commit();",'n')
+ outp+=self.showButton('newrecord',"newrec","New
Record","getForm().newrec();",'n')
+ outp+=self.showButton('markfordelete',"trash","Mark for Removal",
+ "getForm().del();",'n')
+ outp+=' '
+ outp+=self.showButton('prevrecord',"prev","Previous
Record","getForm().prev();",'')
+ outp+=self.showButton('nextrecord',"next","Next
Record","getForm().next();",'')
+ outp+=' '
+ outp+=self.showButton('enterquery',"prepq","Prepare
Query","getForm().prepQ();",'')
+ outp+=self.showButton('execquery',"query","Execute
Query","getForm().execQ();",'')
+ outp+=' '
+
outp+=self.showButton('rollback',"rollback","Rollback","getForm().rollback();",'')
+ outp+=' '
+ outp+=self.showButton('about',"help","About","getForm().about();",'')
+ outp+=' '
+ outp+=self.showButton('exit',"close","","getForm().close();",'')
+ outp+='</DIV>'
+ return outp;
- def computePageSize(self,obj):
- if ((obj._type=='GFEntry') or (obj._type=='GFLabel') or \
- (obj._type=='GFButton')) and not obj.hidden:
+ def addStatusBar(self):
+ return '''
+ <DIV STYLE="position:absolute; top: %spx;left: %spx;width:
%spx;border-width: 1px; border-style: solid;background-color:#EEEEEE;"
align="right">
+ <div id="status" style="display:inline"></div>�|�
+ <div id="pos" style="display:inline"></div>�|�
+ <div id="max" style="display:inline"></div>
+ </DIV>
+ ''' % (((self.Ysize+2)*self.Yraster)+self.yBase+20,\
+ (max([self.Xsize*self.Xraster,540])/2+self.xBase-270),540)
- if not hasattr(obj,'Char__width'):
- if (obj._type=='GFLabel'):
- obj.Char__width=len(obj.text)
- else:
- obj.Char__width=10 # TODO: use default from gConfig instead
- if not hasattr(obj,'Char__height'):
- obj.Char__height=1 # TODO: use default from gConfig instead
+ def computePageSize(self,obj):
+ if ((obj._type=='GFEntry') or (obj._type=='GFLabel') or \
+ (obj._type=='GFButton')) and not obj.hidden:
- # compute max/min
- if obj.Char__x+obj.Char__width>self.Xsize:
- self.Xsize=int(obj.Char__x+obj.Char__width+1)
+ if not hasattr(obj,'Char__width'):
+ if (obj._type=='GFLabel'):
+ obj.Char__width=len(obj.text)
+ else:
+ obj.Char__width=10 # TODO: use default from gConfig instead
- if obj.Char__y+obj.Char__height>self.Ysize:
- self.Ysize=int(obj.Char__y+obj.Char__height+1)
+ if not hasattr(obj,'Char__height'):
+ obj.Char__height=1 # TODO: use default from gConfig instead
- for child in obj._children:
- self.computePageSize(child)
+ # compute max/min
+ if obj.Char__x+obj.Char__width>self.Xsize:
+ self.Xsize=int(obj.Char__x+obj.Char__width+1)
+ if obj.Char__y+obj.Char__height>self.Ysize:
+ self.Ysize=int(obj.Char__y+obj.Char__height+1)
- # function build the html code for page
- def drawElements(self,obj,visible):
+ for child in obj._children:
+ self.computePageSize(child)
- outp=""
- if ((obj._type=='GFEntry') or (obj._type=='GFLabel') or \
- (obj._type=='GFButton') or (obj._type=='GFBox')) and not obj.hidden:
+ # function build the html code for page
+ def drawElements(self,obj,visible):
- pos_code='STYLE="position:absolute; '+\
- 'top: %spx;' % int(obj.Char__y*self.Yraster+self.yBase) +\
- 'left: %spx;' % int(obj.Char__x*self.Xraster+self.xBase) +\
- 'width: %spx;' % int(obj.Char__width*self.Xraster) +\
- 'height: %spx;\n ' %
int(obj.Char__height*self.Yraster-self.baseline)
+ outp=""
- if visible==0:
- pos_code+='visibility:hidden;'
+ if ((obj._type=='GFEntry') or (obj._type=='GFLabel') or \
+ (obj._type=='GFButton') or (obj._type=='GFBox')) and not
obj.hidden:
- if obj._type=='GFLabel':
- pos_code+='font-size: %spx;' % int(self.fontsize) +\
- 'line-height: %spx' % int(self.lineheight)
- else:
- pos_code+='font-size: %spx;' % int(self.fontsize_entry)
+ pos_code='STYLE="position:absolute; '+\
+ 'top: %spx;' % int(obj.Char__y*self.Yraster+self.yBase)
+\
+ 'left: %spx;' % int(obj.Char__x*self.Xraster+self.xBase)
+\
+ 'width: %spx;' % int(obj.Char__width*self.Xraster) +\
+ 'height: %spx;\n ' %
int(obj.Char__height*self.Yraster-self.baseline)
- if obj._type=='GFEntry':
- pos_code+='background: #F6F6F6;'
+ if visible==0:
+ pos_code+='visibility:hidden;'
- if obj._type=='GFBox':
- pos_code+='border-width: 1px; border-style: solid;"'
- else:
- pos_code+='"'
+ if obj._type=='GFLabel':
+ pos_code+='font-size: %spx;' % int(self.fontsize) +\
+ 'line-height: %spx' % int(self.lineheight)
+ else:
+ pos_code+='font-size: %spx;' % int(self.fontsize_entry)
- # TODO: add loop for row setting
- if obj._type=='GFEntry':
- # TODO: add dropdown, height
- outp+='\n\n <!-- Entry %s -->\n' % obj.name
- if obj.style=="password":
- outp+=' <input type="password"'
- elif obj.style=="dropdown":
- outp+=' <select'
- print "ATTENTION: creating dropdown widgets which are not supported
by the javascript client yet!"
- elif obj.Char__height>1:
- outp+=' <textarea'
- else:
- outp+=' <input type="text"'
+ if obj._type=='GFEntry':
+ pos_code+='background: #F6F6F6;'
- outp+=' name="%s"\n id="%s_%s_field" ' %
(obj.name,obj.block,obj.field)
+ if obj._type=='GFBox':
+ pos_code+='border-width: 1px; border-style: solid;"'
+ else:
+ pos_code+='"'
- outp+='\n onfocus="getForm().gotoBlock('+"'%s'" % obj.block +\
- ');"\n';
+ # TODO: add loop for row setting
+ if obj._type=='GFEntry':
+ # TODO: add dropdown, height
+ outp+='\n\n <!-- Entry %s -->\n' % obj.name
+ if obj.style=="password":
+ outp+=' <input type="password"'
+ elif obj.style=="dropdown":
+ outp+=' <select'
+ print "ATTENTION: creating dropdown widgets which are not
supported by the javascript client yet!"
+ elif obj.Char__height>1:
+ outp+=' <textarea'
+ else:
+ outp+=' <input type="text"'
- outp+=pos_code;
+ outp+=' name="%s"\n id="%s_%s_field" ' %
(obj.name,obj.block,obj.field)
- if not hasattr(obj,"default"):
- obj.default=""
+ outp+='\n onfocus="getForm().gotoBlock('+"'%s'" % obj.block +\
+ ');"\n';
- if obj.style=="dropdown":
- outp+='><options>%s</options></select>\n' % obj.default
- elif obj.Char__height>1:
- outp+='>%s</textarea>\n' % obj.default
- else:
- outp+='value="%s">\n' % obj.default
+ outp+=pos_code;
+ if not hasattr(obj,"default"):
+ obj.default=""
- elif obj._type=='GFLabel':
- outp+='\n <!-- Label %s -->\n' % obj.name
- outp+=' <DIV %s id="%s_label">%s</DIV>\n' %\
- (pos_code,obj.name,obj.text)
+ if obj.style=="dropdown":
+ outp+='><options>%s</options></select>\n' % obj.default
+ elif obj.Char__height>1:
+ outp+='>%s</textarea>\n' % obj.default
+ else:
+ outp+='value="%s">\n' % obj.default
- elif obj._type=='GFButton':
- outp+='\n <!-- Button %s -->\n' % obj.name
- outp+=' <button %s id="%s_button">%s</button>\n' % \
- (pos_code,obj.name,obj.label)
- elif obj._type=='GFBox':
- outp+='\n <!-- Box %s -->\n' % obj.name
- outp+=' <div %s id="%s_box">%s</div>\n' % \
- (pos_code,obj.name,obj.label)
+ elif obj._type=='GFLabel':
+ outp+='\n <!-- Label %s -->\n' % obj.name
+ outp+=' <DIV %s id="%s_label">%s</DIV>\n' %\
+ (pos_code,obj.name,obj.text)
+ elif obj._type=='GFButton':
+ outp+='\n <!-- Button %s -->\n' % obj.name
+ outp+=' <button %s id="%s_button">%s</button>\n' % \
+ (pos_code,obj.name,obj.label)
+ elif obj._type=='GFBox':
+ outp+='\n <!-- Box %s -->\n' % obj.name
+ outp+=' <div %s id="%s_box">%s</div>\n' % \
+ (pos_code,obj.name,obj.label)
- for child in obj._children:
- outp+=self.drawElements(child,visible)
- return outp
- def addLoginDialog(self):
- outp='<DIV STYLE="position:absolute; '+\
- 'top: %spx;' %
int(max([self.Ysize*self.Yraster,200])/2+self.yBase-100) +\
- 'left: %spx;' %
int(max([self.Xsize*self.Xraster,500])/2+self.xBase-175)+\
- 'width: %spx;\n' % int(350) +\
- 'height: %spx;' % int(200) +\
- 'border-width: 1px; border-style: solid;'+\
- 'background-color:#EEEEEE;visibility=visible"\n '+\
- 'id="loginForm" align="center">\n'
- outp+=' <BR>User: '+\
- '<INPUT type="text" id="username"><BR>\n'
- outp+='Password: <INPUT type="password" id="password"><BR><BR>\n'
- outp+='<BUTTON onClick="getForm().doLogin();">Login</BUTTON>\n</DIV>\n'
- return outp;
+ for child in obj._children:
+ outp+=self.drawElements(child,visible)
+ return outp
+ def addLoginDialog(self):
+ outp='<DIV STYLE="position:absolute; '+\
+ 'top: %spx;' %
int(max([self.Ysize*self.Yraster,200])/2+self.yBase-100) +\
+ 'left: %spx;' %
int(max([self.Xsize*self.Xraster,500])/2+self.xBase-175)+\
+ 'width: %spx;\n' % int(350) +\
+ 'height: %spx;' % int(200) +\
+ 'border-width: 1px; border-style: solid;'+\
+ 'background-color:#EEEEEE;visibility=visible"\n '+\
+ 'id="loginForm" align="center">\n'
+ outp+=' <BR>User: '+\
+ '<INPUT type="text" id="username"><BR>\n'
+ outp+='Password: <INPUT type="password" id="password"><BR><BR>\n'
+ outp+='<BUTTON onClick="getForm().doLogin();">Login</BUTTON>\n</DIV>\n'
+ return outp;
+
+
############
#
# Basic information about this template
@@ -601,5 +601,5 @@
}
if __name__ == "__main__":
- pass
- # TODO: add some code to use this wizard standalone
+ pass
+ # TODO: add some code to use this wizard standalone
Modified: trunk/gnue-designer/src/navigator/Document.py
===================================================================
--- trunk/gnue-designer/src/navigator/Document.py 2006-04-03 19:53:03 UTC
(rev 8343)
+++ trunk/gnue-designer/src/navigator/Document.py 2006-04-03 19:56:14 UTC
(rev 8344)
@@ -46,43 +46,40 @@
class Document(BaseDocument):
- def init(self):
- self.incubator = Incubator(self)
- self.properties = navProperties
+ def init(self):
+ self.incubator = Incubator(self)
+ self.properties = navProperties
- def loadBuffer(self, buffer):
- object = GNParser.loadProcesses (buffer, initialize=0)
+ def loadBuffer(self, buffer):
+ object = GNParser.loadProcesses (buffer, initialize=0)
## object.name = 'processes'
- return object
+ return object
- def loadEmpty(self, style=None):
- object = GNObjects.GNProcesses()
- object.title = "Untitled Process"
- return object
+ def loadEmpty(self, style=None):
+ object = GNObjects.GNProcesses()
+ object.title = "Untitled Process"
+ return object
- def inventoryObject(self, object):
- pass
+ def inventoryObject(self, object):
+ pass
- def createVisualEditor(self):
- return LayoutEditor(self, self.rootObject, self)
+ def createVisualEditor(self):
+ return LayoutEditor(self, self.rootObject, self)
- def createTools(self):
- pass
+ def createTools(self):
+ pass
## self.addTool('propertyEditor','Property Inspector', PropertyEditor)
## self.addToolol('treeEditor','Object Navigator', TreeView)
## self.addTool('triggerEditor','Event Editor', TriggerEditor)
## self.addTool('datasourceEditor','Data Source Editor', DataSourceEditor)
## self.addTool('schemaViewer','Schema Navigator', SchemaViewer)
- def createWizards(self):
- self.loadWizards(wizards)
+ def createWizards(self):
+ self.loadWizards(wizards)
- def preSave(self):
- pass
-
-
-
+ def preSave(self):
+ pass
Modified: trunk/gnue-designer/src/navigator/Incubator.py
===================================================================
--- trunk/gnue-designer/src/navigator/Incubator.py 2006-04-03 19:53:03 UTC
(rev 8343)
+++ trunk/gnue-designer/src/navigator/Incubator.py 2006-04-03 19:56:14 UTC
(rev 8344)
@@ -33,5 +33,4 @@
class Incubator(BaseIncubator):
- elements = GNParser.getXMLelements()
-
+ elements = GNParser.getXMLelements()
Modified: trunk/gnue-designer/src/navigator/LayoutEditor.py
===================================================================
--- trunk/gnue-designer/src/navigator/LayoutEditor.py 2006-04-03 19:53:03 UTC
(rev 8343)
+++ trunk/gnue-designer/src/navigator/LayoutEditor.py 2006-04-03 19:56:14 UTC
(rev 8344)
@@ -34,90 +34,90 @@
class LayoutEditor (ToolBase):
- runtime_section = 'ProcessVisualEditor'
+ runtime_section = 'ProcessVisualEditor'
- def init(self):
+ def init(self):
- self.splitter = wx.SplitterWindow(self, -1)
+ self.splitter = wx.SplitterWindow(self, -1)
- self.tree = MasterTreeView(self, self.splitter)
- self.list = ObjectEditor(self, self.splitter)
+ self.tree = MasterTreeView(self, self.splitter)
+ self.list = ObjectEditor(self, self.splitter)
- self.splitter.SplitHorizontally(self.tree, self.list,100)
+ self.splitter.SplitHorizontally(self.tree, self.list,100)
- self.finalize = 1
- wx.EVT_SIZE(self, self.OnSize)
+ self.finalize = 1
+ wx.EVT_SIZE(self, self.OnSize)
- rootObject.walk(self.inventoryObject)
- self.tree.postInit()
+ rootObject.walk(self.inventoryObject)
+ self.tree.postInit()
- # EventAware provided by ToolBase
- self.registerEventListeners({
- 'ObjectSelected' : self.onSetCurrentObject,
- 'ObjectCreated' : self.onCreateObject,
- 'ObjectModified' : self.onModifyObject,
- 'ObjectDeleted' : self.onDeleteObject,
- })
+ # EventAware provided by ToolBase
+ self.registerEventListeners({
+ 'ObjectSelected' : self.onSetCurrentObject,
+ 'ObjectCreated' : self.onCreateObject,
+ 'ObjectModified' : self.onModifyObject,
+ 'ObjectDeleted' : self.onDeleteObject,
+ })
- def inventoryObject(self, object):
- self.tree.inventoryObject(object)
+ def inventoryObject(self, object):
+ self.tree.inventoryObject(object)
- def onSetCurrentObject (self, event):
- object = event.object
- handler = event.originator
- if object == None:
- return
- if handler != __name__:
- pass
+ def onSetCurrentObject (self, event):
+ object = event.object
+ handler = event.originator
+ if object == None:
+ return
+ if handler != __name__:
+ pass
- def onCreateObject (self, event):
- object = event.object
- handler = event.originator
- if object == None:
- return
- if handler != __name__:
- pass
+ def onCreateObject (self, event):
+ object = event.object
+ handler = event.originator
+ if object == None:
+ return
+ if handler != __name__:
+ pass
- def onModifyObject (self, event):
- object = event.object
- handler = event.originator
- modifications = event.modifications
- if object == None:
- return
- if handler != __name__:
- pass
+ def onModifyObject (self, event):
+ object = event.object
+ handler = event.originator
+ modifications = event.modifications
+ if object == None:
+ return
+ if handler != __name__:
+ pass
- def onDeleteObject (self, event):
- object = event.object
- handler = event.originator
- if object == None:
- return
- if handler != __name__:
- pass
+ def onDeleteObject (self, event):
+ object = event.object
+ handler = event.originator
+ if object == None:
+ return
+ if handler != __name__:
+ pass
- #
- # Used by RuntimeSettings
- #
- def saveRuntimeSettings(self):
- x, y = self.GetPositionTuple()
- width, height = self.GetSizeTuple()
- return ( self.runtime_section,
- { 'sash': self.splitter.GetSashPosition() } )
+ #
+ # Used by RuntimeSettings
+ #
+ def saveRuntimeSettings(self):
+ x, y = self.GetPositionTuple()
+ width, height = self.GetSizeTuple()
+ return ( self.runtime_section,
+ { 'sash': self.splitter.GetSashPosition() } )
- def OnSize(self, event):
+ def OnSize(self, event):
- self.splitter.SetSize(self.GetSize())
+ self.splitter.SetSize(self.GetSize())
- if self.finalize:
- self.finalize = 0
- self.splitter.SetSashPosition(\
- RuntimeSettings.getint(self.runtime_section,'sash',100))
+ if self.finalize:
+ self.finalize = 0
+ self.splitter.SetSashPosition(\
+ RuntimeSettings.getint(self.runtime_section,'sash',100))
############################################################################
@@ -126,75 +126,75 @@
#
class MasterTreeView(wx.TreeCtrl):
- def __init__(self, editor, parentWindow):
- wx.TreeCtrl.__init__(self, parentWindow, -1,
- style=wx.TR_HAS_BUTTONS|wx.TR_EDIT_LABELS|wx.TR_HAS_VARIABLE_ROW_HEIGHT)
+ def __init__(self, editor, parentWindow):
+ wx.TreeCtrl.__init__(self, parentWindow, -1,
+
style=wx.TR_HAS_BUTTONS|wx.TR_EDIT_LABELS|wx.TR_HAS_VARIABLE_ROW_HEIGHT)
- self.editor = editor
+ self.editor = editor
- self.editor.rootObject._treeItem = self.AddRoot( \
- hasattr(self.editor.rootObject,'description') and \
- self.editor.rootObject.description or 'Processes')
+ self.editor.rootObject._treeItem = self.AddRoot( \
+ hasattr(self.editor.rootObject,'description') and \
+ self.editor.rootObject.description or 'Processes')
- self.SetPyData(self.editor.rootObject._treeItem, self.editor.rootObject)
+ self.SetPyData(self.editor.rootObject._treeItem,
self.editor.rootObject)
- wx.EVT_TREE_BEGIN_LABEL_EDIT(self, self.GetId(), self.OnBeginEdit)
- wx.EVT_TREE_END_LABEL_EDIT(self, self.GetId(), self.OnEndEdit)
+ wx.EVT_TREE_BEGIN_LABEL_EDIT(self, self.GetId(), self.OnBeginEdit)
+ wx.EVT_TREE_END_LABEL_EDIT(self, self.GetId(), self.OnEndEdit)
- def getName(self, object, includeDescr):
+ def getName(self, object, includeDescr):
- if hasattr(object,'description') and object.description != None:
- description = object.description
- if includeDescr:
- if object._type == 'GNProcess':
- description += ' [sub-process]'
- elif object._type == 'GNStep':
- description += ' [%s]' % object.type
- else:
- description = '(%s)'%object._type[2:]
+ if hasattr(object,'description') and object.description != None:
+ description = object.description
+ if includeDescr:
+ if object._type == 'GNProcess':
+ description += ' [sub-process]'
+ elif object._type == 'GNStep':
+ description += ' [%s]' % object.type
+ else:
+ description = '(%s)'%object._type[2:]
- return description
+ return description
- def inventoryObject(self, object):
- if object._type == 'GNParameter':
- return
- if object.getParent () != None:
+ def inventoryObject(self, object):
+ if object._type == 'GNParameter':
+ return
+ if object.getParent () != None:
- description = self.getName(object, 1)
+ description = self.getName(object, 1)
- object._treeItem = self.AppendItem(object.getParent ()._treeItem,
description)
- self.SetPyData(object._treeItem, object)
- if object._type == 'GNProcess':
- self.SetItemBold(object._treeItem,1)
+ object._treeItem = self.AppendItem(object.getParent ()._treeItem,
description)
+ self.SetPyData(object._treeItem, object)
+ if object._type == 'GNProcess':
+ self.SetItemBold(object._treeItem,1)
- def postInit(self):
- self.editor.rootObject.walk(self.__expand)
+ def postInit(self):
+ self.editor.rootObject.walk(self.__expand)
- def __expand(self, object):
- if hasattr(object,'_treeItem') and self.ItemHasChildren(object._treeItem):
- self.Expand(object._treeItem)
+ def __expand(self, object):
+ if hasattr(object,'_treeItem') and
self.ItemHasChildren(object._treeItem):
+ self.Expand(object._treeItem)
- def OnBeginEdit(self, event):
- object = self.GetPyData(event.GetItem())
- if object == self.editor.rootObject:
- event.Veto()
- return
- else:
- self.SetItemText(object._treeItem,self.getName(object,0))
+ def OnBeginEdit(self, event):
+ object = self.GetPyData(event.GetItem())
+ if object == self.editor.rootObject:
+ event.Veto()
+ return
+ else:
+ self.SetItemText(object._treeItem,self.getName(object,0))
- def OnEndEdit(self, event):
- object = self.GetPyData(event.GetItem())
- object.description = event.GetLabel()
- # TODO: Change to new struct
+ def OnEndEdit(self, event):
+ object = self.GetPyData(event.GetItem())
+ object.description = event.GetLabel()
+ # TODO: Change to new struct
## self.editor.instance.onModifyObject(self, object, __name__)
- self.SetItemText(object._treeItem, self.getName(object,1))
- event.Veto()
+ self.SetItemText(object._treeItem, self.getName(object,1))
+ event.Veto()
############################################################################
@@ -203,8 +203,6 @@
#
class ObjectEditor(wx.ListCtrl):
- def __init__(self, editor, parentWindow):
- wx.ListCtrl.__init__(self, parentWindow, -1)
- self.editor = editor
-
-
+ def __init__(self, editor, parentWindow):
+ wx.ListCtrl.__init__(self, parentWindow, -1)
+ self.editor = editor
Modified: trunk/gnue-designer/src/navigator/TemplateSupport.py
===================================================================
--- trunk/gnue-designer/src/navigator/TemplateSupport.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/navigator/TemplateSupport.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -31,7 +31,7 @@
# TODO
def createRootObject(instance):
- return None
+ return None
@@ -42,8 +42,6 @@
###########################################################
class NavigatorTemplate(TemplateBase):
- # Initialize user code
- def Start(self, report):
- pass
-
-
+ # Initialize user code
+ def Start(self, report):
+ pass
Modified: trunk/gnue-designer/src/navigator/__init__.py
===================================================================
--- trunk/gnue-designer/src/navigator/__init__.py 2006-04-03 19:53:03 UTC
(rev 8343)
+++ trunk/gnue-designer/src/navigator/__init__.py 2006-04-03 19:56:14 UTC
(rev 8344)
@@ -36,15 +36,15 @@
class NavigatorModuleProperties: #(_BaseInstance.ModuleProperties):
- module = 'navigator'
- application = 'GNUe Navigator'
- nickname = 'Navigation'
- description = 'GNUe Process Definition'
- xmlOpeningTag = 'processes'
+ module = 'navigator'
+ application = 'GNUe Navigator'
+ nickname = 'Navigation'
+ description = 'GNUe Process Definition'
+ xmlOpeningTag = 'processes'
- fileExtensions = { 'gpd': 'GNUe Menu/Process Definition' }
+ fileExtensions = { 'gpd': 'GNUe Menu/Process Definition' }
- defaultFileExtension = 'gpd'
+ defaultFileExtension = 'gpd'
properties = NavigatorModuleProperties()
Modified: trunk/gnue-designer/src/projects/Objects.py
===================================================================
--- trunk/gnue-designer/src/projects/Objects.py 2006-04-03 19:53:03 UTC (rev
8343)
+++ trunk/gnue-designer/src/projects/Objects.py 2006-04-03 19:56:14 UTC (rev
8344)
@@ -33,12 +33,10 @@
# Generic... all Project objects inherit this puppy
#
class ProjectObj (GObjects.GObj):
- pass
+ pass
# Root object
class GDProject (ProjectObj, GRootObj.GRootObj):
- def __init__(self):
- GRootObj.GRootObj.__init__(self, 'project', Parser.getXMLelements)
- ProjectObj.__init__(self, 'GDProject')
-
-
+ def __init__(self):
+ GRootObj.GRootObj.__init__(self, 'project', Parser.getXMLelements)
+ ProjectObj.__init__(self, 'GDProject')
Modified: trunk/gnue-designer/src/projects/Parser.py
===================================================================
--- trunk/gnue-designer/src/projects/Parser.py 2006-04-03 19:53:03 UTC (rev
8343)
+++ trunk/gnue-designer/src/projects/Parser.py 2006-04-03 19:56:14 UTC (rev
8344)
@@ -53,8 +53,8 @@
#######################################################
def loadProject(buffer, initialize=1):
- return GParser.loadXMLObject (buffer, xmlProcessHandler, 'GNProcesses',
'processes',
- initialize, attributes={})
+ return GParser.loadXMLObject (buffer, xmlProcessHandler, 'GNProcesses',
'processes',
+ initialize, attributes={})
xmlElements = None
@@ -62,77 +62,77 @@
def getXMLelements():
- global xmlElements
+ global xmlElements
- if xmlElements == None:
- import Objects
+ if xmlElements == None:
+ import Objects
- xmlElements = {
- 'project': {
- 'BaseClass': Objects.GPProject,
-# 'Required': 1,
- 'SingleInstance': 1,
- 'Attributes': {
- 'title': {
- 'Typecast': GTypecast.text,
- 'Default': 'Untitled Menu' } },
- 'ParentTags': None },
+ xmlElements = {
+ 'project': {
+ 'BaseClass': Objects.GPProject,
+ # 'Required': 1,
+ 'SingleInstance': 1,
+ 'Attributes': {
+ 'title': {
+ 'Typecast': GTypecast.text,
+ 'Default': 'Untitled Menu' } },
+ 'ParentTags': None },
- 'files': {
- 'BaseClass': Objects.GNProcess,
- 'Attributes': {
- 'id': {
-# 'Required': 1,
- 'Unique': 1,
- 'Typecast': GTypecast.name },
- 'title': {
- 'Typecast': GTypecast.text } },
- 'ParentTags': ('processes','process') },
+ 'files': {
+ 'BaseClass': Objects.GNProcess,
+ 'Attributes': {
+ 'id': {
+ # 'Required': 1,
+ 'Unique': 1,
+ 'Typecast': GTypecast.name },
+ 'title': {
+ 'Typecast': GTypecast.text } },
+ 'ParentTags': ('processes','process') },
- 'file': {
- 'BaseClass': Objects.GPFile,
- 'Attributes': {
- 'name': {
- 'Unique': 1,
- 'Typecast': GTypecast.name },
- 'type': {
- 'Required': 1,
- 'ValueSet': {
- 'app': {},
- 'form': {},
- 'report': {} },
- 'Typecast': GTypecast.name },
- 'location': {
- 'Typecast': GTypecast.text },
- 'title': {
- 'Typecast': GTypecast.text } },
- 'ParentTags': ('process',) },
+ 'file': {
+ 'BaseClass': Objects.GPFile,
+ 'Attributes': {
+ 'name': {
+ 'Unique': 1,
+ 'Typecast': GTypecast.name },
+ 'type': {
+ 'Required': 1,
+ 'ValueSet': {
+ 'app': {},
+ 'form': {},
+ 'report': {} },
+ 'Typecast': GTypecast.name },
+ 'location': {
+ 'Typecast': GTypecast.text },
+ 'title': {
+ 'Typecast': GTypecast.text } },
+ 'ParentTags': ('process',) },
- 'parameter': {
- 'BaseClass': Objects.GNParameter,
- 'Required': 1,
- 'Attributes': {
- 'name': {
- 'Required': 1,
- 'Typecast': GTypecast.name },
- 'value': {
- 'Unique': 1,
- 'Typecast': GTypecast.text } },
- 'ParentTags': ('parameter',) },
+ 'parameter': {
+ 'BaseClass': Objects.GNParameter,
+ 'Required': 1,
+ 'Attributes': {
+ 'name': {
+ 'Required': 1,
+ 'Typecast': GTypecast.name },
+ 'value': {
+ 'Unique': 1,
+ 'Typecast': GTypecast.text } },
+ 'ParentTags': ('parameter',) },
- 'description': {
- 'BaseClass': Objects.GNDescription,
- 'Attributes': {},
- 'MixedContent': 1,
- 'KeepWhitespace': 1,
- 'UsableBySiblings': 1,
- 'SingleInstance': 1,
- 'ParentTags': ('process') },
+ 'description': {
+ 'BaseClass': Objects.GNDescription,
+ 'Attributes': {},
+ 'MixedContent': 1,
+ 'KeepWhitespace': 1,
+ 'UsableBySiblings': 1,
+ 'SingleInstance': 1,
+ 'ParentTags': ('process') },
- }
+ }
- return xmlElements
+ return xmlElements
#######################################################
@@ -145,10 +145,8 @@
#######################################################
class xmlProcessHandler (GParser.xmlHandler):
- def __init__(self):
+ def __init__(self):
- GParser.xmlHandler.__init__(self)
+ GParser.xmlHandler.__init__(self)
- self.xmlElements = getXMLelements()
-
-
+ self.xmlElements = getXMLelements()
Modified: trunk/gnue-designer/src/projects/Project.py
===================================================================
--- trunk/gnue-designer/src/projects/Project.py 2006-04-03 19:53:03 UTC (rev
8343)
+++ trunk/gnue-designer/src/projects/Project.py 2006-04-03 19:56:14 UTC (rev
8344)
@@ -31,22 +31,22 @@
class Project:
- def __init__(self, location=None):
- if location:
- self.project = loadProject(self)
- else:
- self.project = Objects.GDProject()
- self.location = location
+ def __init__(self, location=None):
+ if location:
+ self.project = loadProject(self)
+ else:
+ self.project = Objects.GDProject()
+ self.location = location
- def saveProject(self):
- if not self.location:
- raise "Location not set in Project.saveProject"
+ def saveProject(self):
+ if not self.location:
+ raise "Location not set in Project.saveProject"
- # TODO: 1) check for file io errors
- # TODO: 2) make backup copy of a project file
- file = open(self.location,'w')
- file.write('<xml version="1.0">')
- file.write(self.project.dumpXML().encode('utf-8'))
- file.close()
+ # TODO: 1) check for file io errors
+ # TODO: 2) make backup copy of a project file
+ file = open(self.location,'w')
+ file.write('<xml version="1.0">')
+ file.write(self.project.dumpXML().encode('utf-8'))
+ file.close()
- ##def getProperty(self, property):
+ ##def getProperty(self, property):
Modified: trunk/gnue-designer/src/reports/Char/FilterSupport.py
===================================================================
--- trunk/gnue-designer/src/reports/Char/FilterSupport.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/reports/Char/FilterSupport.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -32,33 +32,30 @@
class FilterSupport(_BaseFilterSupport):
- NAMESPACE = 'GNUe:Reports:Char'
- INCUBATORCLASS = _Incubator
+ NAMESPACE = 'GNUe:Reports:Char'
+ INCUBATORCLASS = _Incubator
- def init(self):
- # EventAware provided by ToolBase
- self.document.registerEventListeners({
- 'ObjectCreated' : self.onCreateObject,
- 'ObjectModified' : self.onModifyObject,
- 'ObjectDeleted' : self.onDeleteObject,
- })
+ def init(self):
+ # EventAware provided by ToolBase
+ self.document.registerEventListeners({
+ 'ObjectCreated' : self.onCreateObject,
+ 'ObjectModified' : self.onModifyObject,
+ 'ObjectDeleted' : self.onDeleteObject,
+ })
- def addTools(self):
- self.document.addTool('visualEditor', u_('Layout Editor'), LayoutEditor,
- hotkey='F11', menuGroup=301)
+ def addTools(self):
+ self.document.addTool('visualEditor', u_('Layout Editor'),
LayoutEditor,
+ hotkey='F11', menuGroup=301)
- def onCreateObject(self, event):
- pass
+ def onCreateObject(self, event):
+ pass
- def onModifyObject(self, event):
- pass
+ def onModifyObject(self, event):
+ pass
- def onDeleteObject(self, event):
- pass
-
-
-
+ def onDeleteObject(self, event):
+ pass
Modified: trunk/gnue-designer/src/reports/Char/Incubator.py
===================================================================
--- trunk/gnue-designer/src/reports/Char/Incubator.py 2006-04-03 19:53:03 UTC
(rev 8343)
+++ trunk/gnue-designer/src/reports/Char/Incubator.py 2006-04-03 19:56:14 UTC
(rev 8344)
@@ -34,8 +34,6 @@
class Incubator(BaseReportIncubator):
- elements = GRParser.getXMLelements()
- layoutParser = dyn_import('gnue.reports.adapters.filters.Char.LayoutParser')
- elements.update(layoutParser.getXMLelements())
-
-
+ elements = GRParser.getXMLelements()
+ layoutParser =
dyn_import('gnue.reports.adapters.filters.Char.LayoutParser')
+ elements.update(layoutParser.getXMLelements())
Modified: trunk/gnue-designer/src/reports/Char/LayoutEditor.py
===================================================================
--- trunk/gnue-designer/src/reports/Char/LayoutEditor.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/reports/Char/LayoutEditor.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -34,52 +34,51 @@
class LayoutEditor (ToolBase):
- runtime_section = "ReportsLayoutEditor"
- default_dock = 'right-0'
- uses_feedback_bar = 1
- uses_toolbar = 0 #1
+ runtime_section = "ReportsLayoutEditor"
+ default_dock = 'right-0'
+ uses_feedback_bar = 1
+ uses_toolbar = 0 #1
- def init(self):
- self.backcolor = wx.WHITE
- self.panel = wx.Panel(self,-1,style=wx.SIMPLE_BORDER, pos=wx.Point(6,6))
- self.panelColor = self.GetBackgroundColour()
- self._instance = self.document
- self.rootObject = self.document.rootObject
- self.app = self.document.app
- self.rootObject.walk(self.inventoryObject)
+ def init(self):
+ self.backcolor = wx.WHITE
+ self.panel = wx.Panel(self,-1,style=wx.SIMPLE_BORDER,
pos=wx.Point(6,6))
+ self.panelColor = self.GetBackgroundColour()
+ self._instance = self.document
+ self.rootObject = self.document.rootObject
+ self.app = self.document.app
+ self.rootObject.walk(self.inventoryObject)
- # EventAware provided by ToolBase
- self.registerEventListeners({
- 'ObjectSelected' : self.onSetCurrentObject,
- 'ObjectCreated' : self.onCreateObject,
- 'ObjectModified' : self.onModifyObject,
- 'ObjectDeleted' : self.onDeleteObject,
- })
+ # EventAware provided by ToolBase
+ self.registerEventListeners({
+ 'ObjectSelected' : self.onSetCurrentObject,
+ 'ObjectCreated' : self.onCreateObject,
+ 'ObjectModified' : self.onModifyObject,
+ 'ObjectDeleted' : self.onDeleteObject,
+ })
- wx.EVT_SIZE(self, self.onSize)
+ wx.EVT_SIZE(self, self.onSize)
- def inventoryObject(self, object):
- pass
+ def inventoryObject(self, object):
+ pass
- def onSetCurrentObject (self, event):
- object = event.object
- handler = event.originator
+ def onSetCurrentObject (self, event):
+ object = event.object
+ handler = event.originator
- def onCreateObject (self, event):
- object = event.object
- handler = event.originator
+ def onCreateObject (self, event):
+ object = event.object
+ handler = event.originator
- def onModifyObject (self, event):
- object = event.object
- handler = event.originator
+ def onModifyObject (self, event):
+ object = event.object
+ handler = event.originator
# modifications = event.modifications
- def onDeleteObject (self, event):
- object = event.object
- handler = event.originator
+ def onDeleteObject (self, event):
+ object = event.object
+ handler = event.originator
- def onSize(self, event):
- x,y = self.GetClientSizeTuple()
- self.panel.SetSize((x-12,y-12))
-
+ def onSize(self, event):
+ x,y = self.GetClientSizeTuple()
+ self.panel.SetSize((x-12,y-12))
Modified: trunk/gnue-designer/src/reports/Default/FilterSupport.py
===================================================================
--- trunk/gnue-designer/src/reports/Default/FilterSupport.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/reports/Default/FilterSupport.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -29,6 +29,4 @@
from gnue.designer.reports.FilterSupport import FilterSupport as
_BaseFilterSupport
class FilterSupport(_BaseFilterSupport):
- pass
-
-
+ pass
Modified: trunk/gnue-designer/src/reports/Document.py
===================================================================
--- trunk/gnue-designer/src/reports/Document.py 2006-04-03 19:53:03 UTC (rev
8343)
+++ trunk/gnue-designer/src/reports/Document.py 2006-04-03 19:56:14 UTC (rev
8344)
@@ -47,129 +47,127 @@
class Document(BaseDocument):
- def init(self):
- self.properties = reportsProperties
+ def init(self):
+ self.properties = reportsProperties
- report = self.rootObject
- report._parameters = report.findChildOfType('GRParameters') or \
- self.incubator.createObject(report, 'parameters', report, select=0)
- report._sortoptions = report.findChildOfType('GRSortOptions') or \
- self.incubator.createObject(report, 'sortoptions', report, select=0)
- report._sources = report.findChildOfType('GRSources') or \
- self.incubator.createObject(report, 'sources', report, select=0)
- report._layout = report.findChildOfType('GRLayout') or \
- self.incubator.createObject(report, 'layout', report, select=0)
+ report = self.rootObject
+ report._parameters = report.findChildOfType('GRParameters') or \
+ self.incubator.createObject(report, 'parameters', report, select=0)
+ report._sortoptions = report.findChildOfType('GRSortOptions') or \
+ self.incubator.createObject(report, 'sortoptions', report,
select=0)
+ report._sources = report.findChildOfType('GRSources') or \
+ self.incubator.createObject(report, 'sources', report, select=0)
+ report._layout = report.findChildOfType('GRLayout') or \
+ self.incubator.createObject(report, 'layout', report, select=0)
- def loadBuffer(self, buffer):
- report = GRParser.loadFile (buffer, self, initialize=0)
- report.name = 'report'
+ def loadBuffer(self, buffer):
+ report = GRParser.loadFile (buffer, self, initialize=0)
+ report.name = 'report'
- # Find which filter is in use... yes, this is ugly
- namespace = report.findChildOfType('GRLayout')._findNamespace()
- filter = namespace.split(':')[-1]
+ # Find which filter is in use... yes, this is ugly
+ namespace = report.findChildOfType('GRLayout')._findNamespace()
+ filter = namespace.split(':')[-1]
- try:
- filtersupport = dyn_import('gnue.designer.reports.%s.FilterSupport' %
filter)
- usingDefault = 0
- except ImportError:
- assert gDebug(2,'No filter support for %s; using default')
- filtersupport = dyn_import('gnue.designer.reports.Default.FilterSupport')
- usingDefault = 1
+ try:
+ filtersupport =
dyn_import('gnue.designer.reports.%s.FilterSupport' % filter)
+ usingDefault = 0
+ except ImportError:
+ assert gDebug(2,'No filter support for %s; using default')
+ filtersupport =
dyn_import('gnue.designer.reports.Default.FilterSupport')
+ usingDefault = 1
- self.filter = filtersupport.FilterSupport(self, report)
+ self.filter = filtersupport.FilterSupport(self, report)
- if usingDefault:
- self.filter.setNamespace(namespace)
+ if usingDefault:
+ self.filter.setNamespace(namespace)
- self.incubator = self.filter.INCUBATORCLASS(self)
+ self.incubator = self.filter.INCUBATORCLASS(self)
- return report
+ return report
- def loadEmpty(self, style=None):
- report = GRReport.GRReport()
- report.title = "Untitled report"
- report.name = 'report'
- GRParameters.GRParameters(report)._buildObject()
- GRSortOptions.GRSortOptions(report)._buildObject()
- GRSources.GRSources(report)._buildObject()
- GRLayout.GRLayout(report)._buildObject()
+ def loadEmpty(self, style=None):
+ report = GRReport.GRReport()
+ report.title = "Untitled report"
+ report.name = 'report'
+ GRParameters.GRParameters(report)._buildObject()
+ GRSortOptions.GRSortOptions(report)._buildObject()
+ GRSources.GRSources(report)._buildObject()
+ GRLayout.GRLayout(report)._buildObject()
- # Find which filter is in use... yes, this is ugly
- namespace = style or "GNUe:Reports:Standard"
- filter = (namespace).split(':')[-1]
+ # Find which filter is in use... yes, this is ugly
+ namespace = style or "GNUe:Reports:Standard"
+ filter = (namespace).split(':')[-1]
- try:
- filtersupport = dyn_import('gnue.designer.reports.%s.FilterSupport' %
filter)
- usingDefault = 0
- except ImportError:
- assert gDebug(2,'No filter support for %s; using default')
- filtersupport = dyn_import('gnue.designer.reports.Default.FilterSupport')
- usingDefault = 1
+ try:
+ filtersupport =
dyn_import('gnue.designer.reports.%s.FilterSupport' % filter)
+ usingDefault = 0
+ except ImportError:
+ assert gDebug(2,'No filter support for %s; using default')
+ filtersupport =
dyn_import('gnue.designer.reports.Default.FilterSupport')
+ usingDefault = 1
- self.filter = filtersupport.FilterSupport(self, report)
+ self.filter = filtersupport.FilterSupport(self, report)
- if usingDefault:
- self.filter.setNamespace(namespace)
+ if usingDefault:
+ self.filter.setNamespace(namespace)
- self.incubator = self.filter.INCUBATORCLASS(self)
+ self.incubator = self.filter.INCUBATORCLASS(self)
- self.filter.initAsNew()
+ self.filter.initAsNew()
- report._buildObject()
- return report
+ report._buildObject()
+ return report
- def inventoryObject(self, object):
- pass
+ def inventoryObject(self, object):
+ pass
- def createTools(self):
- self.addTool('propertyEditor', u_('Property Inspector'), PropertyEditor,
- hotkey='F10', menuGroup=301)
- self.addTool('treeEditor', u_('Object Navigator'), TreeView,
- hotkey='F8', menuGroup=301)
- self.addTool('schemaViewer', u_('Schema Navigator'), SchemaViewer,
- menuGroup=301)
+ def createTools(self):
+ self.addTool('propertyEditor', u_('Property Inspector'),
PropertyEditor,
+ hotkey='F10', menuGroup=301)
+ self.addTool('treeEditor', u_('Object Navigator'), TreeView,
+ hotkey='F8', menuGroup=301)
+ self.addTool('schemaViewer', u_('Schema Navigator'), SchemaViewer,
+ menuGroup=301)
- self.addTool('datasourceEditor',u_('Data Source Editor'), DataSourceEditor,
- hotkey='F9', menuGroup=311)
- #self.addTool('groupEditor', u_('Group Editor'), GroupEditor,
- # hotkey='F5', menuGroup=311)
- #self.addTool('fieldEditor', u_('Field Editor'), FieldEditor,
- # hotkey='F6', menuGroup=311)
+ self.addTool('datasourceEditor',u_('Data Source Editor'),
DataSourceEditor,
+ hotkey='F9', menuGroup=311)
+ #self.addTool('groupEditor', u_('Group Editor'), GroupEditor,
+ # hotkey='F5', menuGroup=311)
+ #self.addTool('fieldEditor', u_('Field Editor'), FieldEditor,
+ # hotkey='F6', menuGroup=311)
- self.addTool('eventEditor', u_('Trigger Inspector'), EventEditor,
- hotkey='F7', menuGroup=321)
- self.addTool('triggerEditor', u_('Code Editor'), TriggerEditor,
- hotkey='F12', menuGroup=321)
+ self.addTool('eventEditor', u_('Trigger Inspector'), EventEditor,
+ hotkey='F7', menuGroup=321)
+ self.addTool('triggerEditor', u_('Code Editor'), TriggerEditor,
+ hotkey='F12', menuGroup=321)
- # Add filter-specific tools
- self.filter.addTools()
+ # Add filter-specific tools
+ self.filter.addTools()
- def createWizards(self):
- self.loadWizards(wizards)
+ def createWizards(self):
+ self.loadWizards(wizards)
- # Used by TemplateParser to build a wizard.current dict
- def buildWizardCurrentDict(self):
- report = self.rootObject
- return { 'report': report,
- 'sources': report._sources,
- 'parameters': report._parameters,
- 'layout': report._layout,
- 'sortoptions': report._sortoptions,
- 'object': self._currentObject }
+ # Used by TemplateParser to build a wizard.current dict
+ def buildWizardCurrentDict(self):
+ report = self.rootObject
+ return { 'report': report,
+ 'sources': report._sources,
+ 'parameters': report._parameters,
+ 'layout': report._layout,
+ 'sortoptions': report._sortoptions,
+ 'object': self._currentObject }
- def preSave(self):
+ def preSave(self):
- # Resort the main sections to a logical order
- report = self.rootObject
- for o in [report._parameters, report._sortoptions,
- report._sources, report._layout]:
- report._children.pop(report._children.index(o))
- if len(o._children):
- report._children.append(o)
-
-
+ # Resort the main sections to a logical order
+ report = self.rootObject
+ for o in [report._parameters, report._sortoptions,
+ report._sources, report._layout]:
+ report._children.pop(report._children.index(o))
+ if len(o._children):
+ report._children.append(o)
Modified: trunk/gnue-designer/src/reports/FilterSupport.py
===================================================================
--- trunk/gnue-designer/src/reports/FilterSupport.py 2006-04-03 19:53:03 UTC
(rev 8343)
+++ trunk/gnue-designer/src/reports/FilterSupport.py 2006-04-03 19:56:14 UTC
(rev 8344)
@@ -29,25 +29,23 @@
from Incubator import Incubator as _Incubator
class FilterSupport:
- NAMESPACE = ""
- INCUBATORCLASS = _Incubator
+ NAMESPACE = ""
+ INCUBATORCLASS = _Incubator
- def __init__(self, instance, report):
- self.document = instance
- self.report = report
- self.init()
+ def __init__(self, instance, report):
+ self.document = instance
+ self.report = report
+ self.init()
- def init(self):
- pass
+ def init(self):
+ pass
- def addTools(self):
- pass
+ def addTools(self):
+ pass
- def setNamespace(self, namespace):
- if namespace:
- self.report.findChildOfType('GRLayout')._xmlchildnamespace =
self.NAMESPACE
+ def setNamespace(self, namespace):
+ if namespace:
+ self.report.findChildOfType('GRLayout')._xmlchildnamespace =
self.NAMESPACE
- def initAsNew(self):
- self.setNamespace(self.NAMESPACE)
-
-
\ No newline at end of file
+ def initAsNew(self):
+ self.setNamespace(self.NAMESPACE)
Modified: trunk/gnue-designer/src/reports/Incubator.py
===================================================================
--- trunk/gnue-designer/src/reports/Incubator.py 2006-04-03 19:53:03 UTC
(rev 8343)
+++ trunk/gnue-designer/src/reports/Incubator.py 2006-04-03 19:56:14 UTC
(rev 8344)
@@ -35,54 +35,54 @@
class Incubator(BaseIncubator):
- elements = GRParser.getXMLelements()
+ elements = GRParser.getXMLelements()
- def createObject(self, rootObject, tag, parent, attributes={}, select=1):
- # Handle GRPassThru
- if tag.find(':')+1:
- o = self._handlePassThru(rootObject, tag, parent, attributes, select)
- if o:
- self.document.dispatchEvent('ObjectCreated',object=o,
originator=__name__)
- if select:
- self.document.dispatchEvent('ObjectSelected',object=object,
originator=__name__)
- return o
- else:
- return BaseIncubator.createObject(self, rootObject, tag, parent,
attributes, select)
+ def createObject(self, rootObject, tag, parent, attributes={}, select=1):
+ # Handle GRPassThru
+ if tag.find(':')+1:
+ o = self._handlePassThru(rootObject, tag, parent, attributes,
select)
+ if o:
+ self.document.dispatchEvent('ObjectCreated',object=o,
originator=__name__)
+ if select:
+
self.document.dispatchEvent('ObjectSelected',object=object, originator=__name__)
+ return o
+ else:
+ return BaseIncubator.createObject(self, rootObject, tag, parent,
attributes, select)
- def _handlePassThru(self, rootObject, tag, parent,
- attributes={}, select=1):
- # handle <out:region name="primary"> when
- # xmlns:out="GNUe:Reports:Labels"
- try:
- name = attributes['name']
- except KeyError:
- name = tag[tag.find(':')+1:]
+ def _handlePassThru(self, rootObject, tag, parent,
+ attributes={}, select=1):
+ # handle <out:region name="primary"> when
+ # xmlns:out="GNUe:Reports:Labels"
+ try:
+ name = attributes['name']
+ except KeyError:
+ name = tag[tag.find(':')+1:]
- xmltag = tag[tag.find(':')+1:]
- try:
- objclass = self.elements[xmltag]['BaseClass']
- if self.elements[xmltag].has_key('Attributes'):
- attrs = self.elements[xmltag]['Attributes']
- else:
- attrs = {}
- except KeyError:
- objclass = GRLayout.GRPassThru
+ xmltag = tag[tag.find(':')+1:]
+ try:
+ objclass = self.elements[xmltag]['BaseClass']
+ if self.elements[xmltag].has_key('Attributes'):
+ attrs = self.elements[xmltag]['Attributes']
+ else:
+ attrs = {}
+ except KeyError:
+ objclass = GRLayout.GRPassThru
- o = objclass(parent)
+ o = objclass(parent)
- # Add any GContent
- try:
- GParserHelpers.GContent(o, attributes['_content_'])
- except KeyError:
- pass
+ # Add any GContent
+ try:
+ GParserHelpers.GContent(o, attributes['_content_'])
+ except KeyError:
+ pass
- o.__dict__.update(attributes)
- o._xmltag = xmltag
- o._listedAttributes = attributes.keys()
- o._xmlnamespace = rootObject.findChildOfType('GRLayout')._xmlchildnamespace
+ o.__dict__.update(attributes)
+ o._xmltag = xmltag
+ o._listedAttributes = attributes.keys()
+ o._xmlnamespace =
rootObject.findChildOfType('GRLayout')._xmlchildnamespace
- o.name = name
- self.document.nameMappings[o.name] = o
- o._buildObject()
- return o
+ o.name = name
+ self.document.nameMappings[o.name] = o
+ o._buildObject()
+ return o
Modified: trunk/gnue-designer/src/reports/Labels/FilterSupport.py
===================================================================
--- trunk/gnue-designer/src/reports/Labels/FilterSupport.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/reports/Labels/FilterSupport.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -29,5 +29,4 @@
from gnue.designer.reports.FilterSupport import FilterSupport as
_BaseFilterSupport
class FilterSupport(_BaseFilterSupport):
- NAMESPACE = 'GNUe:Reports:Labels'
-
+ NAMESPACE = 'GNUe:Reports:Labels'
Modified: trunk/gnue-designer/src/reports/MailMerge/FilterSupport.py
===================================================================
--- trunk/gnue-designer/src/reports/MailMerge/FilterSupport.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/reports/MailMerge/FilterSupport.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -29,5 +29,4 @@
from gnue.designer.reports.FilterSupport import FilterSupport as
_BaseFilterSupport
class FilterSupport(_BaseFilterSupport):
- NAMESPACE = 'GNUe:Reports:MailMerge'
-
+ NAMESPACE = 'GNUe:Reports:MailMerge'
Modified: trunk/gnue-designer/src/reports/SimpleTabulation/FilterSupport.py
===================================================================
--- trunk/gnue-designer/src/reports/SimpleTabulation/FilterSupport.py
2006-04-03 19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/reports/SimpleTabulation/FilterSupport.py
2006-04-03 19:56:14 UTC (rev 8344)
@@ -29,5 +29,4 @@
from gnue.designer.reports.FilterSupport import FilterSupport as
_BaseFilterSupport
class FilterSupport(_BaseFilterSupport):
- NAMESPACE = 'GNUe:Reports:SimpleTabulation'
-
+ NAMESPACE = 'GNUe:Reports:SimpleTabulation'
Modified: trunk/gnue-designer/src/reports/Standard/FilterSupport.py
===================================================================
--- trunk/gnue-designer/src/reports/Standard/FilterSupport.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/reports/Standard/FilterSupport.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -33,39 +33,37 @@
class FilterSupport(_BaseFilterSupport):
- NAMESPACE = 'GNUe:Reports:Standard'
- INCUBATORCLASS = _Incubator
+ NAMESPACE = 'GNUe:Reports:Standard'
+ INCUBATORCLASS = _Incubator
- def init(self):
- # EventAware provided by ToolBase
- self.document.registerEventListeners({
- 'ObjectCreated' : self.onCreateObject,
- 'ObjectModified' : self.onModifyObject,
- 'ObjectDeleted' : self.onDeleteObject,
- })
+ def init(self):
+ # EventAware provided by ToolBase
+ self.document.registerEventListeners({
+ 'ObjectCreated' : self.onCreateObject,
+ 'ObjectModified' : self.onModifyObject,
+ 'ObjectDeleted' : self.onDeleteObject,
+ })
- def initAsNew(self):
- _BaseFilterSupport.initAsNew(self)
+ def initAsNew(self):
+ _BaseFilterSupport.initAsNew(self)
- def addTools(self):
- self.document.addToolSeparator()
- self.document.addTool('groupEditor', u_('Group Editor'), GroupEditor,
'F5')
- self.document.addTool('visualEditor', u_('Layout Editor'), LayoutEditor,
- hotkey='F11', menuGroup=301)
+ def addTools(self):
+ self.document.addToolSeparator()
+ self.document.addTool('groupEditor', u_('Group Editor'),
GroupEditor, 'F5')
+ self.document.addTool('visualEditor', u_('Layout Editor'),
LayoutEditor,
+ hotkey='F11', menuGroup=301)
- def onCreateObject(self, event):
- pass
+ def onCreateObject(self, event):
+ pass
- def onModifyObject(self, event):
- pass
+ def onModifyObject(self, event):
+ pass
- def onDeleteObject(self, event):
- pass
-
-
+ def onDeleteObject(self, event):
+ pass
Modified: trunk/gnue-designer/src/reports/Standard/GroupEditor.py
===================================================================
--- trunk/gnue-designer/src/reports/Standard/GroupEditor.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/reports/Standard/GroupEditor.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -49,230 +49,228 @@
class GroupEditor (ToolBase):
- runtime_section = 'ReportsStandardGroupEditor'
- uses_feedback_bar = 1
- default_dock = 'right-0'
+ runtime_section = 'ReportsStandardGroupEditor'
+ uses_feedback_bar = 1
+ default_dock = 'right-0'
- def init(self):
- self.panel = wx.Panel(self,-1,style=wx.SIMPLE_BORDER, pos=wx.Point(6,6))
+ def init(self):
+ self.panel = wx.Panel(self,-1,style=wx.SIMPLE_BORDER,
pos=wx.Point(6,6))
- self.object = None
- self.table = None
+ self.object = None
+ self.table = None
- self.objectList = []
- self.objectMap = {}
+ self.objectList = []
+ self.objectMap = {}
- # Set up our grid
- self.grid = Grid(self.panel, -1, pos=wx.Point(0,0))
- self.grid.CreateGrid(1,numcols)
+ # Set up our grid
+ self.grid = Grid(self.panel, -1, pos=wx.Point(0,0))
+ self.grid.CreateGrid(1,numcols)
- for i in range(numcols):
- self.grid.SetColLabelValue(i,Columns[i][1])
+ for i in range(numcols):
+ self.grid.SetColLabelValue(i,Columns[i][1])
## self.grid.SetColSize(i, self.
- self.grid.SetRowLabelSize(0)
+ self.grid.SetRowLabelSize(0)
- wx.EVT_GRID_CELL_CHANGE(self.grid, self.OnCellChange)
- wx.EVT_GRID_CELL_LEFT_DCLICK(self.grid, self.OnLeftDClick)
- wx.EVT_SIZE(self, self.onSize)
+ wx.EVT_GRID_CELL_CHANGE(self.grid, self.OnCellChange)
+ wx.EVT_GRID_CELL_LEFT_DCLICK(self.grid, self.OnLeftDClick)
+ wx.EVT_SIZE(self, self.onSize)
- # EventAware provided by ToolBase
- self.registerEventListeners({
- 'ObjectSelected' : self.onSetCurrentObject,
- 'ObjectCreated' : self.onCreateObject,
- 'ObjectModified' : self.onModifyObject,
- 'ObjectDeleted' : self.onDeleteObject,
- })
+ # EventAware provided by ToolBase
+ self.registerEventListeners({
+ 'ObjectSelected' : self.onSetCurrentObject,
+ 'ObjectCreated' : self.onCreateObject,
+ 'ObjectModified' : self.onModifyObject,
+ 'ObjectDeleted' : self.onDeleteObject,
+ })
- self.rootObject.walk(self.inventoryObject)
+ self.rootObject.walk(self.inventoryObject)
- self.saveRuntimeSettings()
+ self.saveRuntimeSettings()
- def onSetCurrentObject (self, event):
- object = event.object
- handler = event.originator
- table = object.findParentOfType('GSTable')
- if table and table != self.table:
- self._setCurrentTable(table)
+ def onSetCurrentObject (self, event):
+ object = event.object
+ handler = event.originator
+ table = object.findParentOfType('GSTable')
+ if table and table != self.table:
+ self._setCurrentTable(table)
- def _setCurrentTable(self, object):
- self.setFeedback("%s Table" % (object.name))
+ def _setCurrentTable(self, object):
+ self.setFeedback("%s Table" % (object.name))
- self.table = object
+ self.table = object
- try:
- self.triggerList = object._validTriggers
- except AttributeError:
- self.triggerList = {}
+ try:
+ self.triggerList = object._validTriggers
+ except AttributeError:
+ self.triggerList = {}
- # Speed up the process by not refreshing the grid yet
- self.grid.BeginBatch()
+ # Speed up the process by not refreshing the grid yet
+ self.grid.BeginBatch()
- # Delete any old rows from a previous object
- nr = self.grid.GetNumberRows()
- if nr:
- self.grid.DeleteRows(0,nr)
+ # Delete any old rows from a previous object
+ nr = self.grid.GetNumberRows()
+ if nr:
+ self.grid.DeleteRows(0,nr)
- # Create the number of rows we'll need
- self.grid.InsertRows(0,len(object._fieldList))
+ # Create the number of rows we'll need
+ self.grid.InsertRows(0,len(object._fieldList))
- i = 0
- for field in object._fieldList:
- for c in range(numcols):
- attr = Columns[c][0]
+ i = 0
+ for field in object._fieldList:
+ for c in range(numcols):
+ attr = Columns[c][0]
## self.grid.SetCellEditor(i, c,
EventCellEditor(self.grid,self.triggerTypes))
- try:
- self.grid.SetCellValue(i,c, "%s" % field.__dict__[attr])
- except KeyError:
- self.grid.SetCellValue(i,c, '')
- i += 1
+ try:
+ self.grid.SetCellValue(i,c, "%s" % field.__dict__[attr])
+ except KeyError:
+ self.grid.SetCellValue(i,c, '')
+ i += 1
- # Redraw the grid
- self.grid.EndBatch()
- try:
- self.grid.ForceRefresh() # Added in 2.3.1
- except AttributeError:
- pass
+ # Redraw the grid
+ self.grid.EndBatch()
+ try:
+ self.grid.ForceRefresh() # Added in 2.3.1
+ except AttributeError:
+ pass
- def onCreateObject (self, event):
- self.inventoryObject(event.object)
+ def onCreateObject (self, event):
+ self.inventoryObject(event.object)
- def onModifyObject (self, event):
- object = event.object
- handler = event.originator
- if object == None:
- return
- if isinstance(object,GTrigger) and \
- object.type.upper() == 'NAMED' and \
- event.new.has_key('name'):
- try:
- del self.namedMap[event.old['name']]
- except KeyError:
- pass
- self.namedMap[object.name] = object
- self._setCurrentTable(self.object)
+ def onModifyObject (self, event):
+ object = event.object
+ handler = event.originator
+ if object == None:
+ return
+ if isinstance(object,GTrigger) and \
+ object.type.upper() == 'NAMED' and \
+ event.new.has_key('name'):
+ try:
+ del self.namedMap[event.old['name']]
+ except KeyError:
+ pass
+ self.namedMap[object.name] = object
+ self._setCurrentTable(self.object)
## if handler != self and self.object == object:
## self._setCurrent(object)
- def onDeleteObject (self, event):
- object = event.object
- handler = event.originator
- if object == None:
- return
- if handler != __name__:
- pass
+ def onDeleteObject (self, event):
+ object = event.object
+ handler = event.originator
+ if object == None:
+ return
+ if handler != __name__:
+ pass
- def inventoryObject(self, object):
- if object._type == 'GSTable' and not self.table:
- self._setCurrentTable(object)
+ def inventoryObject(self, object):
+ if object._type == 'GSTable' and not self.table:
+ self._setCurrentTable(object)
- def onSize(self, event):
- x,y = self.GetClientSizeTuple()
- self.panel.SetSize((x-12,y-12))
- self.grid.SetSize(self.panel.GetClientSizeTuple())
- w,h = self.grid.GetClientSizeTuple()
+ def onSize(self, event):
+ x,y = self.GetClientSizeTuple()
+ self.panel.SetSize((x-12,y-12))
+ self.grid.SetSize(self.panel.GetClientSizeTuple())
+ w,h = self.grid.GetClientSizeTuple()
## self.grid.SetColSize(0, w - self.grid.GetRowLabelSize())
- try:
- self.grid.ForceRefresh() # Added in 2.3.1
- except AttributeError:
- pass
+ try:
+ self.grid.ForceRefresh() # Added in 2.3.1
+ except AttributeError:
+ pass
- # Force a grid cell into Edit mode when Double-Clicked
- def OnLeftDClick(self,evt):
- if self.grid.CanEnableCellControl():
- self.grid.EnableCellEditControl()
+ # Force a grid cell into Edit mode when Double-Clicked
+ def OnLeftDClick(self,evt):
+ if self.grid.CanEnableCellControl():
+ self.grid.EnableCellEditControl()
- def _generateName(self, object):
- parent = object.getParent ()
- name = '%s.%s (%s-Level Trigger)' % (parent.name,
parent._validTriggers[object.type.upper()], parent._type[2:].capitalize())
- return name
+ def _generateName(self, object):
+ parent = object.getParent ()
+ name = '%s.%s (%s-Level Trigger)' % (parent.name,
parent._validTriggers[object.type.upper()], parent._type[2:].capitalize())
+ return name
- def OnCellChange(self, evt):
- attr = self.rowList[evt.GetRow()]
- value = self.grid.GetCellValue(evt.GetRow(), evt.GetCol())
- try:
- oldvalue = self.mappedTriggers[attr]
- except:
- oldvalue = ""
+ def OnCellChange(self, evt):
+ attr = self.rowList[evt.GetRow()]
+ value = self.grid.GetCellValue(evt.GetRow(), evt.GetCol())
+ try:
+ oldvalue = self.mappedTriggers[attr]
+ except:
+ oldvalue = ""
- if oldvalue == value:
- return
+ if oldvalue == value:
+ return
- trigType = self.object._validTriggers[attr]
+ trigType = self.object._validTriggers[attr]
- try:
- trigger = self.triggerMap[attr]
- new = 0
- except KeyError:
- trigger = GTrigger(self.object, trigType)
- new = 1
+ try:
+ trigger = self.triggerMap[attr]
+ new = 0
+ except KeyError:
+ trigger = GTrigger(self.object, trigType)
+ new = 1
- oldStuff = {}
- newStuff = {}
+ oldStuff = {}
+ newStuff = {}
- # If custom trigger, save the text in case the user changes his mind
- if oldvalue == '(Custom Trigger)':
- try:
- self.object.__triggerHistory
- except:
- self.object.__triggerHistory = {}
- self.object.__triggerHistory[attr] = trigger.getChildrenAsContent()
- elif oldvalue:
- oldStuff[src] = oldvalue
- newStuff[src] = ""
+ # If custom trigger, save the text in case the user changes his mind
+ if oldvalue == '(Custom Trigger)':
+ try:
+ self.object.__triggerHistory
+ except:
+ self.object.__triggerHistory = {}
+ self.object.__triggerHistory[attr] = trigger.getChildrenAsContent()
+ elif oldvalue:
+ oldStuff[src] = oldvalue
+ newStuff[src] = ""
- # Clear any old content
- trigger._children = []
+ # Clear any old content
+ trigger._children = []
- if value:
- if value == '(Custom Trigger)':
- try:
- # Restore a previous life's custom trigger text...
- text = self.object.__triggerHistory[attr]
- except:
- # ... or not, and create a new blank trigger
- text = "##\n## %s\n##\n\nreturn\n\n" % (self._generateName(trigger))
- trigger.src = None
- GContent(trigger,text)
- elif value:
- # named trigger
- trigger.src = value
- if not oldStuff.has_key('src'):
- oldStuff['src'] = ''
- newStuff['src'] = value
+ if value:
+ if value == '(Custom Trigger)':
+ try:
+ # Restore a previous life's custom trigger text...
+ text = self.object.__triggerHistory[attr]
+ except:
+ # ... or not, and create a new blank trigger
+ text = "##\n## %s\n##\n\nreturn\n\n" %
(self._generateName(trigger))
+ trigger.src = None
+ GContent(trigger,text)
+ elif value:
+ # named trigger
+ trigger.src = value
+ if not oldStuff.has_key('src'):
+ oldStuff['src'] = ''
+ newStuff['src'] = value
- if new:
- self.dispatchEvent('ObjectCreated',object=trigger, originator=__name__)
- else:
- self.dispatchEvent('ObjectModified',object=trigger,
originator=__name__,
- old=oldStuff, new=newStuff)
+ if new:
+ self.dispatchEvent('ObjectCreated',object=trigger,
originator=__name__)
+ else:
+ self.dispatchEvent('ObjectModified',object=trigger,
originator=__name__,
+ old=oldStuff, new=newStuff)
- if trigger.src:
-
self.dispatchEvent('TriggerSelected',object=self.namedMap[trigger.src],
originator=__name__)
- else:
- self.dispatchEvent('TriggerSelected',object=trigger,
originator=__name__)
- else:
- # No trigger
- self.object._children.pop(self.object._children.index(trigger))
- self.dispatchEvent('ObjectDeleted',object=trigger, originator=__name__)
- self.dispatchEvent('TriggerSelected',object=None, originator=__name__)
+ if trigger.src:
+
self.dispatchEvent('TriggerSelected',object=self.namedMap[trigger.src],
originator=__name__)
+ else:
+ self.dispatchEvent('TriggerSelected',object=trigger,
originator=__name__)
+ else:
+ # No trigger
+ self.object._children.pop(self.object._children.index(trigger))
+ self.dispatchEvent('ObjectDeleted',object=trigger,
originator=__name__)
+ self.dispatchEvent('TriggerSelected',object=None,
originator=__name__)
- def saveRuntimeSettings(self):
- props = {}
- for i in range(numcols):
- props['GridCol%s' % i] = self.grid.GetColSize(i)
- return (self.runtime_section, props)
-
-
+ def saveRuntimeSettings(self):
+ props = {}
+ for i in range(numcols):
+ props['GridCol%s' % i] = self.grid.GetColSize(i)
+ return (self.runtime_section, props)
Modified: trunk/gnue-designer/src/reports/Standard/Incubator.py
===================================================================
--- trunk/gnue-designer/src/reports/Standard/Incubator.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/reports/Standard/Incubator.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -33,5 +33,4 @@
from gnue.designer.reports.Incubator import Incubator as BaseReportIncubator
class Incubator(BaseReportIncubator):
- pass
-
+ pass
Modified: trunk/gnue-designer/src/reports/Standard/LayoutEditor.py
===================================================================
--- trunk/gnue-designer/src/reports/Standard/LayoutEditor.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/reports/Standard/LayoutEditor.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -34,52 +34,51 @@
class LayoutEditor (ToolBase):
- runtime_section = "ReportsLayoutEditor"
- default_dock = 'right-0'
- uses_feedback_bar = 1
- uses_toolbar = 0 #1
+ runtime_section = "ReportsLayoutEditor"
+ default_dock = 'right-0'
+ uses_feedback_bar = 1
+ uses_toolbar = 0 #1
- def init(self):
- self.backcolor = wx.WHITE
- self.panel = wx.Panel(self,-1,style=wx.SIMPLE_BORDER, pos=wx.Point(6,6))
- self.panelColor = self.GetBackgroundColour()
- self._instance = self.document
- self.rootObject = self.document.rootObject
- self.app = self.document.app
- self.rootObject.walk(self.inventoryObject)
+ def init(self):
+ self.backcolor = wx.WHITE
+ self.panel = wx.Panel(self,-1,style=wx.SIMPLE_BORDER,
pos=wx.Point(6,6))
+ self.panelColor = self.GetBackgroundColour()
+ self._instance = self.document
+ self.rootObject = self.document.rootObject
+ self.app = self.document.app
+ self.rootObject.walk(self.inventoryObject)
- # EventAware provided by ToolBase
- self.registerEventListeners({
- 'ObjectSelected' : self.onSetCurrentObject,
- 'ObjectCreated' : self.onCreateObject,
- 'ObjectModified' : self.onModifyObject,
- 'ObjectDeleted' : self.onDeleteObject,
- })
+ # EventAware provided by ToolBase
+ self.registerEventListeners({
+ 'ObjectSelected' : self.onSetCurrentObject,
+ 'ObjectCreated' : self.onCreateObject,
+ 'ObjectModified' : self.onModifyObject,
+ 'ObjectDeleted' : self.onDeleteObject,
+ })
- wx.EVT_SIZE(self, self.onSize)
+ wx.EVT_SIZE(self, self.onSize)
- def inventoryObject(self, object):
- pass
+ def inventoryObject(self, object):
+ pass
- def onSetCurrentObject (self, event):
- object = event.object
- handler = event.originator
+ def onSetCurrentObject (self, event):
+ object = event.object
+ handler = event.originator
- def onCreateObject (self, event):
- object = event.object
- handler = event.originator
+ def onCreateObject (self, event):
+ object = event.object
+ handler = event.originator
- def onModifyObject (self, event):
- object = event.object
- handler = event.originator
- modifications = event.modifications
+ def onModifyObject (self, event):
+ object = event.object
+ handler = event.originator
+ modifications = event.modifications
- def onDeleteObject (self, event):
- object = event.object
- handler = event.originator
+ def onDeleteObject (self, event):
+ object = event.object
+ handler = event.originator
- def onSize(self, event):
- x,y = self.GetClientSizeTuple()
- self.panel.SetSize((x-12,y-12))
-
+ def onSize(self, event):
+ x,y = self.GetClientSizeTuple()
+ self.panel.SetSize((x-12,y-12))
Modified: trunk/gnue-designer/src/reports/TemplateSupport.py
===================================================================
--- trunk/gnue-designer/src/reports/TemplateSupport.py 2006-04-03 19:53:03 UTC
(rev 8343)
+++ trunk/gnue-designer/src/reports/TemplateSupport.py 2006-04-03 19:56:14 UTC
(rev 8344)
@@ -32,7 +32,7 @@
def createRootObject(instance):
- return GRReport.GRReport()
+ return GRReport.GRReport()
@@ -43,6 +43,6 @@
###########################################################
class ReportTemplate(TemplateBase):
- # Initialize user code
- def Start(self, root):
- pass
+ # Initialize user code
+ def Start(self, root):
+ pass
Modified: trunk/gnue-designer/src/reports/TreeView.py
===================================================================
--- trunk/gnue-designer/src/reports/TreeView.py 2006-04-03 19:53:03 UTC (rev
8343)
+++ trunk/gnue-designer/src/reports/TreeView.py 2006-04-03 19:56:14 UTC (rev
8344)
@@ -38,30 +38,28 @@
class TreeView (BaseTreeView):
- rootDescr = 'Report'
+ rootDescr = 'Report'
- def inventoryObject (self, object):
- if object != self.rootObject:
- icon = 'properties'
- parentTreeItem = object.getParent ()._treeItem
- if isinstance(object, GRParameters.GRParameters):
- icon = 'properties'
- elif isinstance(object, GRSortOptions.GRSortOptions):
- icon = 'properties'
- elif isinstance(object, GRSources.GRSources):
- icon = 'datasource'
- elif isinstance(object, GRLayout.GRLayout):
- icon = 'page'
- elif object._type == 'GRSsection':
- icon = 'block'
- elif object._type == 'GRSumm':
- icon = 'entry'
- elif object._type == 'GRFiled':
- icon = 'entry'
+ def inventoryObject (self, object):
+ if object != self.rootObject:
+ icon = 'properties'
+ parentTreeItem = object.getParent ()._treeItem
+ if isinstance(object, GRParameters.GRParameters):
+ icon = 'properties'
+ elif isinstance(object, GRSortOptions.GRSortOptions):
+ icon = 'properties'
+ elif isinstance(object, GRSources.GRSources):
+ icon = 'datasource'
+ elif isinstance(object, GRLayout.GRLayout):
+ icon = 'page'
+ elif object._type == 'GRSsection':
+ icon = 'block'
+ elif object._type == 'GRSumm':
+ icon = 'entry'
+ elif object._type == 'GRFiled':
+ icon = 'entry'
- object._treeItem = self.AppendItem(parentTreeItem,
- "%s" % object.getDescription())
- self.tree.SetPyData(object._treeItem, object)
- self.tree.SetItemImage(object._treeItem, treeIconMap[icon])
-
-
+ object._treeItem = self.AppendItem(parentTreeItem,
+ "%s" % object.getDescription())
+ self.tree.SetPyData(object._treeItem, object)
+ self.tree.SetItemImage(object._treeItem, treeIconMap[icon])
Modified: trunk/gnue-designer/src/reports/__init__.py
===================================================================
--- trunk/gnue-designer/src/reports/__init__.py 2006-04-03 19:53:03 UTC (rev
8343)
+++ trunk/gnue-designer/src/reports/__init__.py 2006-04-03 19:56:14 UTC (rev
8344)
@@ -31,16 +31,14 @@
class ReportsModuleProperties:
- module = 'reports'
- application = 'GNUe Reports'
- nickname = 'Reports'
- description = 'GNUe Report Definition'
- xmlOpeningTag = 'report'
+ module = 'reports'
+ application = 'GNUe Reports'
+ nickname = 'Reports'
+ description = 'GNUe Report Definition'
+ xmlOpeningTag = 'report'
- fileExtensions = { 'grd': 'GNUe Report Definition', }
+ fileExtensions = { 'grd': 'GNUe Report Definition', }
- defaultFileExtension = 'grd'
+ defaultFileExtension = 'grd'
properties = ReportsModuleProperties()
-
-
Modified: trunk/gnue-designer/src/schema/DiaEditor/VisualEditor.py
===================================================================
--- trunk/gnue-designer/src/schema/DiaEditor/VisualEditor.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/schema/DiaEditor/VisualEditor.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -33,282 +33,282 @@
class VisualEditor (ToolBase):
- runtime_section = 'SchemaDiaEditor'
+ runtime_section = 'SchemaDiaEditor'
- def init(self):
- # basic initialisation
- self.object = None
- self.app = self.document.app
+ def init(self):
+ # basic initialisation
+ self.object = None
+ self.app = self.document.app
- self.dragmode = False
- self.tables=[]
- self.hasNewObj = False
- self.rootObject.walk(self.inventoryObject)
+ self.dragmode = False
+ self.tables=[]
+ self.hasNewObj = False
+ self.rootObject.walk(self.inventoryObject)
- # Painting related stuff
- self.diagram=wx.ScrolledWindow(self, -1,
- style=wx.SUNKEN_BORDER)
- self.panelColor = self.GetBackgroundColour()
- self.panelheight=100
- self.panelwidth=200
- self.diagram.EnableScrolling(True, True)
- self.redrawBackground()
- #self.diagram.SetBackgroundColour(wx.WHITE)
- self.calculateTablePositions()
- Sizer = wx.BoxSizer(wx.HORIZONTAL)
- #Sizer.Add(self.toolPalette, 0)
- Sizer.Add(self.diagram, 1, wx.EXPAND)
+ # Painting related stuff
+ self.diagram=wx.ScrolledWindow(self, -1,
+ style=wx.SUNKEN_BORDER)
+ self.panelColor = self.GetBackgroundColour()
+ self.panelheight=100
+ self.panelwidth=200
+ self.diagram.EnableScrolling(True, True)
+ self.redrawBackground()
+ #self.diagram.SetBackgroundColour(wx.WHITE)
+ self.calculateTablePositions()
+ Sizer = wx.BoxSizer(wx.HORIZONTAL)
+ #Sizer.Add(self.toolPalette, 0)
+ Sizer.Add(self.diagram, 1, wx.EXPAND)
- self.SetAutoLayout(True)
- self.SetSizer(Sizer)
+ self.SetAutoLayout(True)
+ self.SetSizer(Sizer)
- # EventAware provided by ToolBase
- self.registerEventListeners({
- 'ObjectSelected' : self.onSetCurrentObject,
- 'ObjectCreated' : self.onCreateObject,
- 'ObjectModified' : self.onModifyObject,
- 'ObjectDeleted' : self.onDeleteObject,
- })
+ # EventAware provided by ToolBase
+ self.registerEventListeners({
+ 'ObjectSelected' : self.onSetCurrentObject,
+ 'ObjectCreated' : self.onCreateObject,
+ 'ObjectModified' : self.onModifyObject,
+ 'ObjectDeleted' : self.onDeleteObject,
+ })
- # WX WINDOWS Events
- wx.EVT_PAINT(self.diagram, self.onPaintEvent)
+ # WX WINDOWS Events
+ wx.EVT_PAINT(self.diagram, self.onPaintEvent)
# wx.EVT_LEFT_DOWN(self.diagram, self.onLeftClickEvent)
- wx.EVT_MOTION(self.diagram, self.onMouseEvent)
- wx.EVT_LEFT_UP(self.diagram, self.onMouseEvent)
- wx.EVT_LEFT_DOWN(self.diagram, self.onMouseEvent)
- wx.EVT_LEFT_DCLICK(self.diagram, self.onDoubleClickEvent)
- wx.EVT_RIGHT_DOWN(self.diagram, self.onRightClickEvent)
+ wx.EVT_MOTION(self.diagram, self.onMouseEvent)
+ wx.EVT_LEFT_UP(self.diagram, self.onMouseEvent)
+ wx.EVT_LEFT_DOWN(self.diagram, self.onMouseEvent)
+ wx.EVT_LEFT_DCLICK(self.diagram, self.onDoubleClickEvent)
+ wx.EVT_RIGHT_DOWN(self.diagram, self.onRightClickEvent)
- def calculateTablePositions(self):
- dc = wx.MemoryDC()
- self.diagram.PrepareDC(dc)
- dc.BeginDrawing()
- x=10
- y=10
- maxy=10
- maxx=10
- for vTbl in self.tables:
- (w,h)=vTbl.calculateDimensions(dc)
- vTbl.moveTo(x,y)
- x=x+10+w
- if y+h>maxy:
- maxy=y+h
- if x>maxx:
- maxx=x
- if x>600:
- x=10
- y=maxy+10
-
- dc.EndDrawing()
- self.resizeCanvas(maxx,maxy)
+ def calculateTablePositions(self):
+ dc = wx.MemoryDC()
+ self.diagram.PrepareDC(dc)
+ dc.BeginDrawing()
+ x=10
+ y=10
+ maxy=10
+ maxx=10
+ for vTbl in self.tables:
+ (w,h)=vTbl.calculateDimensions(dc)
+ vTbl.moveTo(x,y)
+ x=x+10+w
+ if y+h>maxy:
+ maxy=y+h
+ if x>maxx:
+ maxx=x
+ if x>600:
+ x=10
+ y=maxy+10
- # Rules for better positioning:
- # tables with most connections in the middle
- # ...
+ dc.EndDrawing()
+ self.resizeCanvas(maxx,maxy)
+ # Rules for better positioning:
+ # tables with most connections in the middle
+ # ...
- def inventoryObject(self, object):
- if object._type=="GSTable":
- self.tables.append(VisualTable(object))
-
- def onSetCurrentObject (self, event):
- object = event.object
- handler = event.originator
- if object == None:
- return
- if object != self.object:
- self.setCurrent(object)
+ def inventoryObject(self, object):
+ if object._type=="GSTable":
+ self.tables.append(VisualTable(object))
- def setCurrent(self, object):
- # mark actual object (in blue?)
- if self.object!=object:
- self.object=object
- dc = wx.ClientDC(self.diagram)
- self.diagram.PrepareDC(dc)
- self.drawWholeScreen(dc)
- def findFreePosition(self, x,y,w,h):
- conflict=True
- while conflict:
- conflict=False
- for i in self.tables:
- if i.isInRectangle(x,y,x+w,y+h):
- x=i.xpos+i.width+10
- if x>500:
- x=10
- y=i.ypos+i.height+10
- conflict=True
- self.resizeCanvas(x+w,y+h)
- return (x,y)
+ def onSetCurrentObject (self, event):
+ object = event.object
+ handler = event.originator
+ if object == None:
+ return
+ if object != self.object:
+ self.setCurrent(object)
+ def setCurrent(self, object):
+ # mark actual object (in blue?)
+ if self.object!=object:
+ self.object=object
+ dc = wx.ClientDC(self.diagram)
+ self.diagram.PrepareDC(dc)
+ self.drawWholeScreen(dc)
- def resizeCanvas(self,xmax,ymax):
- # resize canvas
- if xmax>self.panelwidth:
- self.panelwidth=xmax+10
- self.diagram.SetScrollbars(20, 20, self.panelwidth / 20,
- self.panelheight / 20)
- if ymax>self.panelheight:
- self.panelheight=ymax+10
- self.diagram.SetScrollbars(20, 20, self.panelwidth / 20,
- self.panelheight / 20)
+ def findFreePosition(self, x,y,w,h):
+ conflict=True
+ while conflict:
+ conflict=False
+ for i in self.tables:
+ if i.isInRectangle(x,y,x+w,y+h):
+ x=i.xpos+i.width+10
+ if x>500:
+ x=10
+ y=i.ypos+i.height+10
+ conflict=True
+ self.resizeCanvas(x+w,y+h)
+ return (x,y)
- def onCreateObject (self, event):
- object = event.object
- handler = event.originator
- if object == None:
- return
- if handler != __name__:
- try:
- assert gDebug(4,"Adding %s (%s)" % (object.name, object._type))
- except:
+ def resizeCanvas(self,xmax,ymax):
+ # resize canvas
+ if xmax>self.panelwidth:
+ self.panelwidth=xmax+10
+ self.diagram.SetScrollbars(20, 20, self.panelwidth / 20,
+ self.panelheight / 20)
+ if ymax>self.panelheight:
+ self.panelheight=ymax+10
+ self.diagram.SetScrollbars(20, 20, self.panelwidth / 20,
+ self.panelheight / 20)
+
+
+ def onCreateObject (self, event):
+ object = event.object
+ handler = event.originator
+ if object == None:
+ return
+ if handler != __name__:
+ try:
+ assert gDebug(4,"Adding %s (%s)" % (object.name, object._type))
+ except:
+ if object._type=="GSTable":
+ self.tables.append(VisualTable(object))
+ self.hasNewObj=True
+ self.refresh()
+ return
+ vTbl=VisualTable(object)
+ dc = wx.ClientDC(self.diagram)
+ self.diagram.PrepareDC(dc)
+ (w,h)=vTbl.calculateDimensions(dc)
+
+ # position new Table
+ (x,y)=self.findFreePosition(10,10,w,h)
+ vTbl.moveTo(x,y)
+
+ self.tables.append(vTbl)
+
+ if object._type=="GSField":
+ self.hasNewObj=True
+ self.onModifyObject(event)
+
+
+ def onModifyObject (self, event):
+ self.refresh()
+ return
+ tbl=object.findParentOfType('GSTable')
+ if tbl!=None:
+ for i in self.tables:
+ if i.document==tbl:
+ dc = wx.ClientDC(self.diagram)
+ self.diagram.PrepareDC(dc)
+ (w,h)=i.calculateDimensions(dc)
+ # check if still freepos
+ (x,y)=self.findFreePosition(i.xpos,i.ypos,w,h)
+ i.moveTo(x,y)
+ i.drawMe(dc,self.object)
+ return
+
+ def refresh(self):
+ self.diagram.Refresh(True)
+
+ def onDeleteObject (self, event):
+ object = event.object
+ handler = event.originator
if object._type=="GSTable":
- self.tables.append(VisualTable(object))
- self.hasNewObj=True
- self.refresh()
- return
- vTbl=VisualTable(object)
- dc = wx.ClientDC(self.diagram)
- self.diagram.PrepareDC(dc)
- (w,h)=vTbl.calculateDimensions(dc)
+ # search for GSTable and remove the VisualTable assigned to it
+ for vTbl in self.tables:
+ if vTbl.document==object:
+ self.tables.remove(vTbl)
+ self.refresh()
- # position new Table
- (x,y)=self.findFreePosition(10,10,w,h)
- vTbl.moveTo(x,y)
-
- self.tables.append(vTbl)
-
if object._type=="GSField":
- self.hasNewObj=True
- self.onModifyObject(event)
-
+ # search for GSTable and update corresponding vtable
+ tbl=object.findParentOfType("GSTable")
+ for vTbl in self.tables:
+ if vTbl.document==tbl:
+ dc = wx.MemoryDC()
+ vTbl.calculateDimensions(dc)
+ self.refresh()
- def onModifyObject (self, event):
- self.refresh()
- return
- tbl=object.findParentOfType('GSTable')
- if tbl!=None:
- for i in self.tables:
- if i.document==tbl:
- dc = wx.ClientDC(self.diagram)
- self.diagram.PrepareDC(dc)
- (w,h)=i.calculateDimensions(dc)
- # check if still freepos
- (x,y)=self.findFreePosition(i.xpos,i.ypos,w,h)
- i.moveTo(x,y)
- i.drawMe(dc,self.object)
- return
+ def onPaintEvent(self, event, clear=False):
+ if self.hasNewObj:
+ self.calculateTablePositions()
+ self.hasNewObj=False
+ dc = wx.PaintDC(self.diagram)
+ self.diagram.PrepareDC(dc)
+ if clear:
+ dc.SetBackground(self.panelColor)
+ dc.Clear()
+ self.drawWholeScreen(dc)
- def refresh(self):
- self.diagram.Refresh(True)
+ def drawWholeScreen(self,dc):
+ dc.BeginDrawing()
+ #dc.Blit(0,0,self.panelheight,self.panelwidth,self.imagedc,0,0)
+ #dc.EndDrawing()
+ #return
+ #dc.BeginDrawing()
+ for vTbl in self.tables:
+ vTbl.drawMe(dc,self.object)
+ dc.EndDrawing()
- def onDeleteObject (self, event):
- object = event.object
- handler = event.originator
- if object._type=="GSTable":
- # search for GSTable and remove the VisualTable assigned to it
- for vTbl in self.tables:
- if vTbl.document==object:
- self.tables.remove(vTbl)
- self.refresh()
+ def redrawBackground(self):
+ btm=wx.EmptyBitmap(self.panelheight,self.panelwidth,-1)
+ dc=wx.MemoryDC()
+ dc.SelectObject(btm);
+ for vTbl in self.tables:
+ vTbl.drawMe(dc,self.object)
+ self.imagedc=dc
- if object._type=="GSField":
- # search for GSTable and update corresponding vtable
- tbl=object.findParentOfType("GSTable")
- for vTbl in self.tables:
- if vTbl.document==tbl:
- dc = wx.MemoryDC()
- vTbl.calculateDimensions(dc)
- self.refresh()
-
- def onPaintEvent(self, event, clear=False):
- if self.hasNewObj:
- self.calculateTablePositions()
- self.hasNewObj=False
- dc = wx.PaintDC(self.diagram)
- self.diagram.PrepareDC(dc)
- if clear:
- dc.SetBackground(self.panelColor)
- dc.Clear()
- self.drawWholeScreen(dc)
-
- def drawWholeScreen(self,dc):
- dc.BeginDrawing()
- #dc.Blit(0,0,self.panelheight,self.panelwidth,self.imagedc,0,0)
- #dc.EndDrawing()
- #return
- #dc.BeginDrawing()
- for vTbl in self.tables:
- vTbl.drawMe(dc,self.object)
- dc.EndDrawing()
+ def calculateMousePos(self,event):
+ originX, originY = self.diagram.GetViewStart()
+ unitX, unitY = self.diagram.GetScrollPixelsPerUnit()
+ return (event.GetX() + (originX * unitX),
+ event.GetY() + (originY * unitY))
- def redrawBackground(self):
- btm=wx.EmptyBitmap(self.panelheight,self.panelwidth,-1)
- dc=wx.MemoryDC()
- dc.SelectObject(btm);
- for vTbl in self.tables:
- vTbl.drawMe(dc,self.object)
- self.imagedc=dc
- def calculateMousePos(self,event):
- originX, originY = self.diagram.GetViewStart()
- unitX, unitY = self.diagram.GetScrollPixelsPerUnit()
- return (event.GetX() + (originX * unitX),
- event.GetY() + (originY * unitY))
+ def getObjectAt(self,x,y):
+ self.tables.reverse()
+ for vTbl in self.tables:
+ object=vTbl.getObjectAt(x,y)
+ if object != None:
+ self.tables.reverse()
+ return object
+ self.tables.reverse()
+ # in case, that no object is selected, choose root object
+ return self.rootObject
+ def onMouseEvent(self,event):
+ if not (event.LeftDown() or event.Dragging() or event.LeftUp()):
+ return # Ignore mouse movement without click/drag.
+ if event.LeftDown():
+ (x,y) = self.calculateMousePos(event)
+ object=self.getObjectAt(x,y)
+ if object._type!='VisualTable':
+ self.dispatchEvent('ObjectSelected', object=object,\
+ originator=__name__)
+ return
+ else:
+ self.dragx=x-object.xpos
+ self.dragy=y-object.ypos
+ self.dragobj=object
+ dc = wx.ClientDC(self.diagram)
+ self.diagram.PrepareDC(dc)
+ self.spriteOn=False
+ self.dragmode=True
- def getObjectAt(self,x,y):
- self.tables.reverse()
- for vTbl in self.tables:
- object=vTbl.getObjectAt(x,y)
- if object != None:
- self.tables.reverse()
- return object
- self.tables.reverse()
- # in case, that no object is selected, choose root object
- return self.rootObject
+ elif event.LeftUp() and self.dragmode:
+ self.dragmode=False
+ self.refresh()
- def onMouseEvent(self,event):
- if not (event.LeftDown() or event.Dragging() or event.LeftUp()):
- return # Ignore mouse movement without click/drag.
- if event.LeftDown():
- (x,y) = self.calculateMousePos(event)
- object=self.getObjectAt(x,y)
- if object._type!='VisualTable':
- self.dispatchEvent('ObjectSelected', object=object,\
- originator=__name__)
- return
- else:
- self.dragx=x-object.xpos
- self.dragy=y-object.ypos
- self.dragobj=object
- dc = wx.ClientDC(self.diagram)
- self.diagram.PrepareDC(dc)
- self.spriteOn=False
- self.dragmode=True
+ elif event.Dragging() and self.dragmode:
+ (x,y) = self.calculateMousePos(event)
+ dc = wx.ClientDC(self.diagram)
+ self.diagram.PrepareDC(dc)
+ dc.BeginDrawing()
+ dc.SetLogicalFunction(wx.XOR)
+ if self.spriteOn:
+ self.dragobj.drawMe(dc,self.object,True)
- elif event.LeftUp() and self.dragmode:
- self.dragmode=False
- self.refresh()
-
- elif event.Dragging() and self.dragmode:
- (x,y) = self.calculateMousePos(event)
- dc = wx.ClientDC(self.diagram)
- self.diagram.PrepareDC(dc)
- dc.BeginDrawing()
- dc.SetLogicalFunction(wx.XOR)
- if self.spriteOn:
- self.dragobj.drawMe(dc,self.object,True)
-
- self.dragobj.moveTo(x-self.dragx,y-self.dragy)
- self.spriteOn=True
- self.dragobj.drawMe(dc,self.object,True)
+ self.dragobj.moveTo(x-self.dragx,y-self.dragy)
+ self.spriteOn=True
+ self.dragobj.drawMe(dc,self.object,True)
# TODO: implement a way to move tables as a whole and not
# only showing the border of the window.
@@ -318,178 +318,178 @@
# wx.MemoryDC, then you can move it on the real DC and you can
# restore the background by using Blit
- dc.EndDrawing()
+ dc.EndDrawing()
- # in case of a right mouse click show a context menu
- def onRightClickEvent(self,event):
- (x,y) = self.calculateMousePos(event)
- object=self.getObjectAt(x,y)
- menu = wx.Menu()
+ # in case of a right mouse click show a context menu
+ def onRightClickEvent(self,event):
+ (x,y) = self.calculateMousePos(event)
+ object=self.getObjectAt(x,y)
+ menu = wx.Menu()
- popup_NEWTABLE =1
- popup_NEWSTRFIELD =2
- popup_NEWNUMFIELD =3
- popup_NEWINDEX =4
- popup_NEWUINDEX =5
- popup_EDIT =6
- popup_RENAME =7
- popup_DUPPL =8
- popup_DEL =9
+ popup_NEWTABLE =1
+ popup_NEWSTRFIELD =2
+ popup_NEWNUMFIELD =3
+ popup_NEWINDEX =4
+ popup_NEWUINDEX =5
+ popup_EDIT =6
+ popup_RENAME =7
+ popup_DUPPL =8
+ popup_DEL =9
- # TODO: Use a generalized popup menu like in the forms designer
- # instead of this one. the popup menu in the treeview and
- # the visual editor should look the same
+ # TODO: Use a generalized popup menu like in the forms designer
+ # instead of this one. the popup menu in the treeview and
+ # the visual editor should look the same
- if object._type=='VisualTable':
- object=object.document
+ if object._type=='VisualTable':
+ object=object.document
- self.dispatchEvent('ObjectSelected', object=object, originator=__name__)
+ self.dispatchEvent('ObjectSelected', object=object,
originator=__name__)
- if object._type=='VisualTable' or object._type=="GSTable":
- menu.Append(popup_NEWSTRFIELD, "Add Field (String)")
- wx.EVT_MENU(self,popup_NEWSTRFIELD,self.onAddStringField)
- menu.Append(popup_NEWNUMFIELD, "Add Field (Number)")
- wx.EVT_MENU(self,popup_NEWNUMFIELD,self.onAddNumberField)
-
- elif object._type=="GSField":
- menu.Append(popup_NEWINDEX, "Add Index")
- wx.EVT_MENU(self,popup_NEWINDEX,self.onAddIndex)
+ if object._type=='VisualTable' or object._type=="GSTable":
+ menu.Append(popup_NEWSTRFIELD, "Add Field (String)")
+ wx.EVT_MENU(self,popup_NEWSTRFIELD,self.onAddStringField)
+ menu.Append(popup_NEWNUMFIELD, "Add Field (Number)")
+ wx.EVT_MENU(self,popup_NEWNUMFIELD,self.onAddNumberField)
- menu.Append(popup_NEWUINDEX, "Add Unique Index")
- wx.EVT_MENU(self,popup_NEWUINDEX,self.onAddUniqueIndex)
-
- else:
- menu.Append(popup_NEWTABLE, "New Table")
- wx.EVT_MENU(self,popup_NEWTABLE,self.onNewTable)
+ elif object._type=="GSField":
+ menu.Append(popup_NEWINDEX, "Add Index")
+ wx.EVT_MENU(self,popup_NEWINDEX,self.onAddIndex)
- if object._type!='GSSchema':
- menu.AppendSeparator()
+ menu.Append(popup_NEWUINDEX, "Add Unique Index")
+ wx.EVT_MENU(self,popup_NEWUINDEX,self.onAddUniqueIndex)
- menu.Append(popup_EDIT, "Edit")
- wx.EVT_MENU(self,popup_EDIT,self.onEdit)
+ else:
+ menu.Append(popup_NEWTABLE, "New Table")
+ wx.EVT_MENU(self,popup_NEWTABLE,self.onNewTable)
- menu.Append(popup_RENAME, "Rename")
- wx.EVT_MENU(self,popup_RENAME,self.onRename)
+ if object._type!='GSSchema':
+ menu.AppendSeparator()
- menu.Append(popup_DUPPL, "Duplicate")
- wx.EVT_MENU(self,popup_DUPPL,self.onDuplicate)
+ menu.Append(popup_EDIT, "Edit")
+ wx.EVT_MENU(self,popup_EDIT,self.onEdit)
- menu.Append(popup_DEL, "Delete")
- wx.EVT_MENU(self,popup_DEL,self.onDelete)
+ menu.Append(popup_RENAME, "Rename")
+ wx.EVT_MENU(self,popup_RENAME,self.onRename)
+ menu.Append(popup_DUPPL, "Duplicate")
+ wx.EVT_MENU(self,popup_DUPPL,self.onDuplicate)
- clickPt = wx.Point(x + self.diagram.GetPosition().x,
- y + self.diagram.GetPosition().y)
- self.diagram.PopupMenu(menu, clickPt)
- menu.Destroy()
+ menu.Append(popup_DEL, "Delete")
+ wx.EVT_MENU(self,popup_DEL,self.onDelete)
- def onNewTable(self,event):
- dialog = wx.TextEntryDialog(self.diagram,'Name of the new table:')
- if dialog.ShowModal() == wx.ID_OK:
- tables=self.rootObject.findChildOfType("GSTables")
- if tables==None:
- tables = self.document.incubator.createObject(
- self.rootObject, 'tables', self.rootObject)
- self.document.incubator.createObject(self.rootObject, 'table',
- tables, {"name":dialog.GetValue()})
+ clickPt = wx.Point(x + self.diagram.GetPosition().x,
+ y + self.diagram.GetPosition().y)
+ self.diagram.PopupMenu(menu, clickPt)
+ menu.Destroy()
- dialog.Destroy()
+ def onNewTable(self,event):
+ dialog = wx.TextEntryDialog(self.diagram,'Name of the new table:')
- def onAddNumberField(self,event):
- self.onAddField(event,'number')
+ if dialog.ShowModal() == wx.ID_OK:
+ tables=self.rootObject.findChildOfType("GSTables")
+ if tables==None:
+ tables = self.document.incubator.createObject(
+ self.rootObject, 'tables', self.rootObject)
+ self.document.incubator.createObject(self.rootObject, 'table',
+ tables, {"name":dialog.GetValue()})
- def onAddStringField(self,event):
- self.onAddField(event,'string')
-
- def onAddField(self,event,type='string'):
- dialog = wx.TextEntryDialog(self.diagram,'Name of the new field:')
+ dialog.Destroy()
- if dialog.ShowModal() == wx.ID_OK:
- fields=self.object.findChildOfType("GSFields")
- if fields==None:
- tbl=self.object.findChildOfType("GSTable")
- fields=self.document.incubator.createObject(
- self.rootObject,'fields', tbl)
+ def onAddNumberField(self,event):
+ self.onAddField(event,'number')
- params = {"name":dialog.GetValue()}
- if type=='string':
- params.update({"type":"string","size":20})
- else:
- params.update({"type":type,"size":4})
-
- self.document.incubator.createObject(self.rootObject, 'field',
- fields,params)
+ def onAddStringField(self,event):
+ self.onAddField(event,'string')
- dialog.Destroy()
-
- def onAddIndex(self,event):
- tbl=self.object.findParentOfType("GSTable")
- indexes=tbl.findChildOfType("GSIndexes")
- if indexes==None:
- indexes = self.document.incubator.createObject(
- self.rootObject, 'indexes', tbl)
- idx=self.document.incubator.createObject(
- self.rootObject, 'index', indexes,
- {"name":"%s_%s" % (tbl.name,self.object.name)})
- self.document.incubator.createObject(self.rootObject, 'index', idx,
- {"name":self.object.name})
- self.refresh()
+ def onAddField(self,event,type='string'):
+ dialog = wx.TextEntryDialog(self.diagram,'Name of the new field:')
- def onAddUniqueIndex(self,event):
- tbl=self.object.findParentOfType("GSTable")
- indexes=tbl.findChildOfType("GSIndexes")
- if indexes==None:
- indexes = self.document.incubator.createObject(
- self.rootObject, 'indexes',tbl)
- idx=self.document.incubator.createObject(
- self.rootObject, 'index', indexes,
- {"name":"%s_%s" % (tbl.name,self.object.name),
- "unique":"Y"})
- self.document.incubator.createObject(self.rootObject, 'index', idx,
- {"name":self.object.name})
- self.refresh()
+ if dialog.ShowModal() == wx.ID_OK:
+ fields=self.object.findChildOfType("GSFields")
+ if fields==None:
+ tbl=self.object.findChildOfType("GSTable")
+ fields=self.document.incubator.createObject(
+ self.rootObject,'fields', tbl)
+ params = {"name":dialog.GetValue()}
+ if type=='string':
+ params.update({"type":"string","size":20})
+ else:
+ params.update({"type":type,"size":4})
- def onAddConstraint(self,event):
- pass
+ self.document.incubator.createObject(self.rootObject, 'field',
+ fields,params)
- def onRename(self,event):
- dialog = wx.TextEntryDialog(self.diagram,'New Name')
- if hasattr(self.object,'name'):
- dialog.SetValue(self.object.name)
-
- if dialog.ShowModal() == wx.ID_OK:
- self.object.name=dialog.GetValue()
- self.document.onModifyObject(self.object,"schema",
- [('name',self.object.name)])
- self.refresh()
+ dialog.Destroy()
- dialog.Destroy()
-
- def onDuplicate(self,event):
- pass
+ def onAddIndex(self,event):
+ tbl=self.object.findParentOfType("GSTable")
+ indexes=tbl.findChildOfType("GSIndexes")
+ if indexes==None:
+ indexes = self.document.incubator.createObject(
+ self.rootObject, 'indexes', tbl)
+ idx=self.document.incubator.createObject(
+ self.rootObject, 'index', indexes,
+ {"name":"%s_%s" % (tbl.name,self.object.name)})
+ self.document.incubator.createObject(self.rootObject, 'index', idx,
+ {"name":self.object.name})
+ self.refresh()
- def onEdit(self,event):
- print "EDIT occured"
- pass
-
- def onDelete(self,event):
- self.document.incubator.deleteObject(self.rootObject, self.object,
firstRun=1)
+ def onAddUniqueIndex(self,event):
+ tbl=self.object.findParentOfType("GSTable")
+ indexes=tbl.findChildOfType("GSIndexes")
+ if indexes==None:
+ indexes = self.document.incubator.createObject(
+ self.rootObject, 'indexes',tbl)
+ idx=self.document.incubator.createObject(
+ self.rootObject, 'index', indexes,
+ {"name":"%s_%s" % (tbl.name,self.object.name),
+ "unique":"Y"})
+ self.document.incubator.createObject(self.rootObject, 'index', idx,
+ {"name":self.object.name})
+ self.refresh()
- def onLeftClickEvent(self,event):
- (x,y) = self.calculateMousePos(event)
- for vTbl in self.tables:
- object=vTbl.getObjectAt(x,y)
- if object != None:
- self.dispatchEvent('ObjectSelected', object=object,
originator=__name__)
+ def onAddConstraint(self,event):
+ pass
+ def onRename(self,event):
+ dialog = wx.TextEntryDialog(self.diagram,'New Name')
+ if hasattr(self.object,'name'):
+ dialog.SetValue(self.object.name)
- def onDoubleClickEvent(self,event):
- (x,y) = self.calculateMousePos(event)
- object=self.getObjectAt(x,y)
- if object != None and object._type!='VisualTable':
- # begin to edit this object
- self.dispatchEvent('ObjectSelected', object=object, originator=__name__)
- # TODO: add edit functions here
+ if dialog.ShowModal() == wx.ID_OK:
+ self.object.name=dialog.GetValue()
+ self.document.onModifyObject(self.object,"schema",
+ [('name',self.object.name)])
+ self.refresh()
+
+ dialog.Destroy()
+
+ def onDuplicate(self,event):
+ pass
+
+ def onEdit(self,event):
+ print "EDIT occured"
+ pass
+
+ def onDelete(self,event):
+ self.document.incubator.deleteObject(self.rootObject, self.object,
firstRun=1)
+
+
+ def onLeftClickEvent(self,event):
+ (x,y) = self.calculateMousePos(event)
+ for vTbl in self.tables:
+ object=vTbl.getObjectAt(x,y)
+ if object != None:
+ self.dispatchEvent('ObjectSelected', object=object,
originator=__name__)
+
+
+ def onDoubleClickEvent(self,event):
+ (x,y) = self.calculateMousePos(event)
+ object=self.getObjectAt(x,y)
+ if object != None and object._type!='VisualTable':
+ # begin to edit this object
+ self.dispatchEvent('ObjectSelected', object=object,
originator=__name__)
+ # TODO: add edit functions here
Modified: trunk/gnue-designer/src/schema/DiaEditor/VisualTable.py
===================================================================
--- trunk/gnue-designer/src/schema/DiaEditor/VisualTable.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/schema/DiaEditor/VisualTable.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -30,132 +30,131 @@
import wx
class VisualTable:
- def __init__(self, tableinstance):
- self.document=tableinstance
- self._type='VisualTable'
- #self.font = wx.Font(self.textSize, wx.DEFAULT,
wx.NORMAL,wx.NORMAL,0,fontname )
- self.pen = wx.BLACK_PEN # wx.Pen(...)
- self.pen_highlighted = wx.Pen(wx.BLUE, 1, wx.SOLID)
- self.brush = wx.WHITE_BRUSH # wx.TRANSPARENT_BRUSH # wx.BLACK_BRUSH
- self.pen_inv = wx.WHITE_PEN # wx.Pen(...)
- self.brush_inv = wx.BLACK_BRUSH # wx.TRANSPARENT_BRUSH # wx.BLACK_BRUSH
- self.xpos=-100
- self.ypos=-100
- self.width=10
- self.height=10
- self.textheight=10
-
-
- def calculateDimensions(self,dc):
- (w,h)=dc.GetTextExtent(self.document.name)
- self.width=w
- self.height=h
- self.textheight=h
- fields=self.document.findChildOfType('GSFields')
- if fields!=None:
- for c in fields._children:
- (w,h)=dc.GetTextExtent(c.name)
- if w>self.width:
- self.width=w
- self.height=self.height+5+h
+ def __init__(self, tableinstance):
+ self.document=tableinstance
+ self._type='VisualTable'
+ #self.font = wx.Font(self.textSize, wx.DEFAULT,
wx.NORMAL,wx.NORMAL,0,fontname )
+ self.pen = wx.BLACK_PEN # wx.Pen(...)
+ self.pen_highlighted = wx.Pen(wx.BLUE, 1, wx.SOLID)
+ self.brush = wx.WHITE_BRUSH # wx.TRANSPARENT_BRUSH # wx.BLACK_BRUSH
+ self.pen_inv = wx.WHITE_PEN # wx.Pen(...)
+ self.brush_inv = wx.BLACK_BRUSH # wx.TRANSPARENT_BRUSH # wx.BLACK_BRUSH
+ self.xpos=-100
+ self.ypos=-100
+ self.width=10
+ self.height=10
+ self.textheight=10
- # add some space for the borders
- self.height=self.height+40
- self.width=self.width+20
-
- return (self.width,self.height)
- def recalculateDimensions(self,dc):
- (w,h)=dc.GetTextExtent(self.document.name)
- self.width=w
- self.height=h
- self.textheight=h
- fields=self.document.findChildOfType('GSFields')
- if fields!=None:
- for c in fields._children:
- (w,h)=dc.GetTextExtent(c.name)
- if w>self.width:
- self.width=w
- self.height=self.height+5+h
+ def calculateDimensions(self,dc):
+ (w,h)=dc.GetTextExtent(self.document.name)
+ self.width=w
+ self.height=h
+ self.textheight=h
+ fields=self.document.findChildOfType('GSFields')
+ if fields!=None:
+ for c in fields._children:
+ (w,h)=dc.GetTextExtent(c.name)
+ if w>self.width:
+ self.width=w
+ self.height=self.height+5+h
- # add some space for the borders
- self.height=self.height+40
- self.width=self.width+20
-
- return (self.width,self.height)
+ # add some space for the borders
+ self.height=self.height+40
+ self.width=self.width+20
- def moveTo(self,x,y):
- self.xpos=x
- self.ypos=y
+ return (self.width,self.height)
- def drawMe(self,dc,current,inverse=False):
- if inverse:
- dc.SetPen(self.pen_inv)
- dc.SetBrush(self.brush_inv)
- else:
- dc.SetPen(self.pen)
- dc.SetBrush(self.brush)
+ def recalculateDimensions(self,dc):
+ (w,h)=dc.GetTextExtent(self.document.name)
+ self.width=w
+ self.height=h
+ self.textheight=h
+ fields=self.document.findChildOfType('GSFields')
+ if fields!=None:
+ for c in fields._children:
+ (w,h)=dc.GetTextExtent(c.name)
+ if w>self.width:
+ self.width=w
+ self.height=self.height+5+h
- dc.DrawRectangle(self.xpos,self.ypos,self.width,self.height)
- dc.DrawLine(self.xpos,self.ypos+self.textheight+20,
- self.xpos+self.width,self.ypos+self.textheight+20)
- dc.DrawLine(self.xpos,self.ypos+self.textheight+24,
- self.xpos+self.width,self.ypos+self.textheight+24)
+ # add some space for the borders
+ self.height=self.height+40
+ self.width=self.width+20
- # dc.SetFont(self.font)
- dc.DrawText(self.document.name,self.xpos+10,self.ypos+10)
- y=self.ypos+34
- fields=self.document.findChildOfType('GSFields')
- if fields!=None:
- for c in fields._children:
-
- # check if this field is the current selected object
- if c==current:
+ return (self.width,self.height)
+
+ def moveTo(self,x,y):
+ self.xpos=x
+ self.ypos=y
+
+ def drawMe(self,dc,current,inverse=False):
+ if inverse:
+ dc.SetPen(self.pen_inv)
+ dc.SetBrush(self.brush_inv)
+ else:
+ dc.SetPen(self.pen)
+ dc.SetBrush(self.brush)
+
+ dc.DrawRectangle(self.xpos,self.ypos,self.width,self.height)
+ dc.DrawLine(self.xpos,self.ypos+self.textheight+20,
+ self.xpos+self.width,self.ypos+self.textheight+20)
+ dc.DrawLine(self.xpos,self.ypos+self.textheight+24,
+ self.xpos+self.width,self.ypos+self.textheight+24)
+
+ # dc.SetFont(self.font)
+ dc.DrawText(self.document.name,self.xpos+10,self.ypos+10)
+ y=self.ypos+34
+ fields=self.document.findChildOfType('GSFields')
+ if fields!=None:
+ for c in fields._children:
+
+ # check if this field is the current selected object
+ if c==current:
+ dc.SetPen(self.pen_highlighted)
+ dc.SetBrush(wx.TRANSPARENT_BRUSH)
+
dc.DrawRectangle(self.xpos+3,y+8,self.width-6,self.textheight+4)
+
+ dc.DrawText(c.name,self.xpos+10,y+10)
+ y=y+self.textheight+5
+
+ # check if the table is selected
+ if self.document==current:
dc.SetPen(self.pen_highlighted)
dc.SetBrush(wx.TRANSPARENT_BRUSH)
- dc.DrawRectangle(self.xpos+3,y+8,self.width-6,self.textheight+4)
-
- dc.DrawText(c.name,self.xpos+10,y+10)
- y=y+self.textheight+5
+ dc.DrawRectangle(self.xpos+3,self.ypos+8,
+ self.width-6,self.textheight+4)
- # check if the table is selected
- if self.document==current:
- dc.SetPen(self.pen_highlighted)
- dc.SetBrush(wx.TRANSPARENT_BRUSH)
- dc.DrawRectangle(self.xpos+3,self.ypos+8,
- self.width-6,self.textheight+4)
+ # return pointer to field/table object depending on position
+ def getObjectAt(self,x,y):
+ if x>=self.xpos and x<=self.xpos+self.width and \
+ y>=self.ypos and y<=self.ypos+self.height:
- # return pointer to field/table object depending on position
- def getObjectAt(self,x,y):
- if x>=self.xpos and x<=self.xpos+self.width and \
- y>=self.ypos and y<=self.ypos+self.height:
-
- # cursor in upper part -> return table
- hy=self.ypos+34
- if y<hy:
- return self.document
-
- # cursor in the middle -> return fields
- fields=self.document.findChildOfType('GSFields')
- if fields!=None:
- for c in fields._children:
- hy=hy+self.textheight+5
- if y<hy:
- return c
-
- # cursor at the bottom part -> return table
- return self
- return self.document
-
- else:
- return None
+ # cursor in upper part -> return table
+ hy=self.ypos+34
+ if y<hy:
+ return self.document
- # return pointer to field/table object depending on position
- def isInRectangle(self,x,y,x2,y2):
- if (not (x>self.xpos+self.width or x2<self.xpos)) and \
- (not (y>self.ypos+self.width and y2<self.ypos)):
- return True
- else:
- return False
-
+ # cursor in the middle -> return fields
+ fields=self.document.findChildOfType('GSFields')
+ if fields!=None:
+ for c in fields._children:
+ hy=hy+self.textheight+5
+ if y<hy:
+ return c
+
+ # cursor at the bottom part -> return table
+ return self
+ return self.document
+
+ else:
+ return None
+
+ # return pointer to field/table object depending on position
+ def isInRectangle(self,x,y,x2,y2):
+ if (not (x>self.xpos+self.width or x2<self.xpos)) and \
+ (not (y>self.ypos+self.width and y2<self.ypos)):
+ return True
+ else:
+ return False
Modified: trunk/gnue-designer/src/schema/Document.py
===================================================================
--- trunk/gnue-designer/src/schema/Document.py 2006-04-03 19:53:03 UTC (rev
8343)
+++ trunk/gnue-designer/src/schema/Document.py 2006-04-03 19:56:14 UTC (rev
8344)
@@ -47,69 +47,65 @@
class Document(BaseInstance):
- def init(self):
- self.incubator = Incubator(self)
- self.properties = schemaPropertiess
- self._tableMappings = {}
+ def init(self):
+ self.incubator = Incubator(self)
+ self.properties = schemaPropertiess
+ self._tableMappings = {}
- def loadBuffer(self, buffer):
- schema = GSchema.loadFile (buffer, self, initialize=0)
- schema.name = 'schema'
- return schema
+ def loadBuffer(self, buffer):
+ schema = GSchema.loadFile (buffer, self, initialize=0)
+ schema.name = 'schema'
+ return schema
- def loadEmpty(self, style=None):
- schema = GSchema.GSSchema()
- schema.title = "Untitled schema"
- schema.name = 'schema'
- GSchema.GSTables(schema)
- return schema
+ def loadEmpty(self, style=None):
+ schema = GSchema.GSSchema()
+ schema.title = "Untitled schema"
+ schema.name = 'schema'
+ GSchema.GSTables(schema)
+ return schema
- def inventoryObject(self, object):
- if isinstance(object, GSchema.GSTables):
- self.tables = object
- elif object._type == 'GSTable':
- self._tableMappings[object.name] = object
- object._fieldList = []
- object._fieldMap = {}
- elif object._type == 'GSField':
- table = object.findParentOfType('GSTable')
- table._fieldList.append(object)
- table._fieldMap[object.name.lower()] = object
+ def inventoryObject(self, object):
+ if isinstance(object, GSchema.GSTables):
+ self.tables = object
+ elif object._type == 'GSTable':
+ self._tableMappings[object.name] = object
+ object._fieldList = []
+ object._fieldMap = {}
+ elif object._type == 'GSField':
+ table = object.findParentOfType('GSTable')
+ table._fieldList.append(object)
+ table._fieldMap[object.name.lower()] = object
- def createTools(self):
- self.addTool('tableEditor', u_('Table/Field Editor'), TableEditor,
- hotkey='F11', menuGroup=301)
- self.addTool('propertyEditor', u_('Property Inspector'), PropertyEditor,
- hotkey='F10', menuGroup=301)
- self.addTool('treeEditor', u_('Object Navigator'), TreeView,
- hotkey='F8', menuGroup=311)
+ def createTools(self):
+ self.addTool('tableEditor', u_('Table/Field Editor'), TableEditor,
+ hotkey='F11', menuGroup=301)
+ self.addTool('propertyEditor', u_('Property Inspector'),
PropertyEditor,
+ hotkey='F10', menuGroup=301)
+ self.addTool('treeEditor', u_('Object Navigator'), TreeView,
+ hotkey='F8', menuGroup=311)
- self.addTool('schemaNavigator',u_('Schema Navigator'), SchemaNavigator,
- menuGroup=301)
- self.addTool('visualEditor',u_('Visual Editor'), VisualEditor,
- hotkey='F9', menuGroup=311)
+ self.addTool('schemaNavigator',u_('Schema Navigator'), SchemaNavigator,
+ menuGroup=301)
+ self.addTool('visualEditor',u_('Visual Editor'), VisualEditor,
+ hotkey='F9', menuGroup=311)
- def createWizards(self):
- self.loadWizards(wizards)
+ def createWizards(self):
+ self.loadWizards(wizards)
- def preSave(self):
- pass
+ def preSave(self):
+ pass
- # Used by TemplateParser to build a wizard.current dict
- def buildWizardCurrentDict(self):
- return {'schema': self.rootObject,
- 'tables': self.tables,
- 'table': self.tableEditor.table,
-## 'field': self.visualEditor.page,
- 'object': self._currentObject}
+ # Used by TemplateParser to build a wizard.current dict
+ def buildWizardCurrentDict(self):
+ return {'schema': self.rootObject,
+ 'tables': self.tables,
+ 'table': self.tableEditor.table,
+ ## 'field': self.visualEditor.page,
+ 'object': self._currentObject}
## # Hack having to do with UIwxpython import
## def uiEventTrap(self, event):
## pass
-
-
-
-
Modified: trunk/gnue-designer/src/schema/Incubator.py
===================================================================
--- trunk/gnue-designer/src/schema/Incubator.py 2006-04-03 19:53:03 UTC (rev
8343)
+++ trunk/gnue-designer/src/schema/Incubator.py 2006-04-03 19:56:14 UTC (rev
8344)
@@ -33,6 +33,4 @@
class Incubator(BaseIncubator):
- elements = GSchema.getXMLelements()
-
-
+ elements = GSchema.getXMLelements()
Modified: trunk/gnue-designer/src/schema/LayoutEditor.py
===================================================================
--- trunk/gnue-designer/src/schema/LayoutEditor.py 2006-04-03 19:53:03 UTC
(rev 8343)
+++ trunk/gnue-designer/src/schema/LayoutEditor.py 2006-04-03 19:56:14 UTC
(rev 8344)
@@ -32,37 +32,36 @@
class LayoutEditor (ToolBase):
- runtime_section = 'SchemaLayoutEditor'
+ runtime_section = 'SchemaLayoutEditor'
- def init(self):
- self.panelColor = self.GetBackgroundColour()
- self.app = instance.app
- self.rootObject.walk(self.inventoryObject)
+ def init(self):
+ self.panelColor = self.GetBackgroundColour()
+ self.app = instance.app
+ self.rootObject.walk(self.inventoryObject)
- # EventAware provided by ToolBase
- self.registerEventListeners({
- 'ObjectSelected' : self.onSetCurrentObject,
- 'ObjectCreated' : self.onCreateObject,
- 'ObjectModified' : self.onModifyObject,
- 'ObjectDeleted' : self.onDeleteObject,
- })
+ # EventAware provided by ToolBase
+ self.registerEventListeners({
+ 'ObjectSelected' : self.onSetCurrentObject,
+ 'ObjectCreated' : self.onCreateObject,
+ 'ObjectModified' : self.onModifyObject,
+ 'ObjectDeleted' : self.onDeleteObject,
+ })
- def inventoryObject(self, object):
- pass
+ def inventoryObject(self, object):
+ pass
- def onSetCurrentObject (self, event):
- object = event.object
- handler = event.originator
+ def onSetCurrentObject (self, event):
+ object = event.object
+ handler = event.originator
- def onCreateObject (self, event):
- object = event.object
- handler = event.originator
+ def onCreateObject (self, event):
+ object = event.object
+ handler = event.originator
- def onModifyObject (self, event):
- object = event.object
- handler = event.originator
+ def onModifyObject (self, event):
+ object = event.object
+ handler = event.originator
- def onDeleteObject (self, event):
- object = event.object
- handler = event.originator
-
+ def onDeleteObject (self, event):
+ object = event.object
+ handler = event.originator
Modified: trunk/gnue-designer/src/schema/TableEditor.py
===================================================================
--- trunk/gnue-designer/src/schema/TableEditor.py 2006-04-03 19:53:03 UTC
(rev 8343)
+++ trunk/gnue-designer/src/schema/TableEditor.py 2006-04-03 19:56:14 UTC
(rev 8344)
@@ -48,165 +48,163 @@
class TableEditor (ToolBase):
- runtime_section = 'SchemaTableEditor'
- uses_feedback_bar = 1
- default_dock = 'right-0'
+ runtime_section = 'SchemaTableEditor'
+ uses_feedback_bar = 1
+ default_dock = 'right-0'
- def init(self):
- self.panel = wx.Panel(self,-1,style=wx.SIMPLE_BORDER, pos=wx.Point(6,6))
+ def init(self):
+ self.panel = wx.Panel(self,-1,style=wx.SIMPLE_BORDER,
pos=wx.Point(6,6))
- self.object = None
- self.table = None
+ self.object = None
+ self.table = None
- self.objectList = []
- self.objectMap = {}
+ self.objectList = []
+ self.objectMap = {}
- # Set up our grid
- self.grid = Grid(self.panel, -1, pos=wx.Point(0,0))
- self.grid.CreateGrid(1,numcols)
+ # Set up our grid
+ self.grid = Grid(self.panel, -1, pos=wx.Point(0,0))
+ self.grid.CreateGrid(1,numcols)
- for i in range(numcols):
- self.grid.SetColLabelValue(i,Columns[i][1])
+ for i in range(numcols):
+ self.grid.SetColLabelValue(i,Columns[i][1])
- self.grid.SetRowLabelSize(32)
+ self.grid.SetRowLabelSize(32)
- wx.EVT_GRID_CELL_CHANGE(self.grid, self.OnCellChange)
- wx.EVT_GRID_CELL_LEFT_DCLICK(self.grid, self.OnLeftDClick)
- wx.EVT_SIZE(self, self.onSize)
+ wx.EVT_GRID_CELL_CHANGE(self.grid, self.OnCellChange)
+ wx.EVT_GRID_CELL_LEFT_DCLICK(self.grid, self.OnLeftDClick)
+ wx.EVT_SIZE(self, self.onSize)
- # EventAware provided by ToolBase
- self.registerEventListeners({
- 'ObjectSelected' : self.onSetCurrentObject,
- 'ObjectCreated' : self.onCreateObject,
- 'ObjectModified' : self.onModifyObject,
- 'ObjectDeleted' : self.onDeleteObject,
- })
+ # EventAware provided by ToolBase
+ self.registerEventListeners({
+ 'ObjectSelected' : self.onSetCurrentObject,
+ 'ObjectCreated' : self.onCreateObject,
+ 'ObjectModified' : self.onModifyObject,
+ 'ObjectDeleted' : self.onDeleteObject,
+ })
- self.rootObject.walk(self.inventoryObject)
+ self.rootObject.walk(self.inventoryObject)
- self.saveRuntimeSettings()
+ self.saveRuntimeSettings()
- def onSetCurrentObject (self, event):
- object = event.object
- handler = event.originator
- table = object.findParentOfType('GSTable')
- if table and table != self.table:
- self._setCurrentTable(table)
+ def onSetCurrentObject (self, event):
+ object = event.object
+ handler = event.originator
+ table = object.findParentOfType('GSTable')
+ if table and table != self.table:
+ self._setCurrentTable(table)
- def _setCurrentTable(self, object):
- ##self.setFeedback("%s Table" % (object.name))
+ def _setCurrentTable(self, object):
+ ##self.setFeedback("%s Table" % (object.name))
- self.table = object
+ self.table = object
- try:
- self.triggerList = object._validTriggers
- except AttributeError:
- self.triggerList = {}
+ try:
+ self.triggerList = object._validTriggers
+ except AttributeError:
+ self.triggerList = {}
- # Speed up the process by not refreshing the grid yet
- self.grid.BeginBatch()
+ # Speed up the process by not refreshing the grid yet
+ self.grid.BeginBatch()
- # Delete any old rows from a previous object
- nr = self.grid.GetNumberRows()
- if nr:
- self.grid.DeleteRows(0,nr)
+ # Delete any old rows from a previous object
+ nr = self.grid.GetNumberRows()
+ if nr:
+ self.grid.DeleteRows(0,nr)
- # Create the number of rows we'll need
- self.grid.InsertRows(0,len(object._fieldList))
+ # Create the number of rows we'll need
+ self.grid.InsertRows(0,len(object._fieldList))
- i = 0
- for field in object._fieldList:
- for c in range(numcols):
- attr = Columns[c][0]
+ i = 0
+ for field in object._fieldList:
+ for c in range(numcols):
+ attr = Columns[c][0]
## self.grid.SetCellEditor(i, c,
EventCellEditor(self.grid,self.triggerTypes))
- try:
- self.grid.SetCellValue(i,c, "%s" % field.__dict__[attr])
- except KeyError:
- self.grid.SetCellValue(i,c, '')
- i += 1
+ try:
+ self.grid.SetCellValue(i,c, "%s" % field.__dict__[attr])
+ except KeyError:
+ self.grid.SetCellValue(i,c, '')
+ i += 1
- # Redraw the grid
- self.grid.EndBatch()
- try:
- self.grid.ForceRefresh() # Added in 2.3.1
- except AttributeError:
- pass
+ # Redraw the grid
+ self.grid.EndBatch()
+ try:
+ self.grid.ForceRefresh() # Added in 2.3.1
+ except AttributeError:
+ pass
- def onCreateObject (self, event):
- self.inventoryObject(event.object)
+ def onCreateObject (self, event):
+ self.inventoryObject(event.object)
- def onModifyObject (self, event):
- object = event.object
- handler = event.originator
- if object == None:
- return
- if isinstance(object,GTrigger) and \
- object.type.upper() == 'NAMED' and \
- event.new.has_key('name'):
- try:
- del self.namedMap[event.old['name']]
- except KeyError:
- pass
- self.namedMap[object.name] = object
- self._setCurrentTable(self.object)
+ def onModifyObject (self, event):
+ object = event.object
+ handler = event.originator
+ if object == None:
+ return
+ if isinstance(object,GTrigger) and \
+ object.type.upper() == 'NAMED' and \
+ event.new.has_key('name'):
+ try:
+ del self.namedMap[event.old['name']]
+ except KeyError:
+ pass
+ self.namedMap[object.name] = object
+ self._setCurrentTable(self.object)
## if handler != self and self.object == object:
## self._setCurrent(object)
- def onDeleteObject (self, event):
- object = event.object
- handler = event.originator
- if object == None:
- return
- if handler != __name__:
- pass
+ def onDeleteObject (self, event):
+ object = event.object
+ handler = event.originator
+ if object == None:
+ return
+ if handler != __name__:
+ pass
- def inventoryObject(self, object):
- if object._type == 'GSTable' and not self.table:
- self._setCurrentTable(object)
+ def inventoryObject(self, object):
+ if object._type == 'GSTable' and not self.table:
+ self._setCurrentTable(object)
- def onSize(self, event):
- x,y = self.GetClientSizeTuple()
- self.panel.SetSize((x-12,y-12))
- self.grid.SetSize(self.panel.GetClientSizeTuple())
- w,h = self.grid.GetClientSizeTuple()
+ def onSize(self, event):
+ x,y = self.GetClientSizeTuple()
+ self.panel.SetSize((x-12,y-12))
+ self.grid.SetSize(self.panel.GetClientSizeTuple())
+ w,h = self.grid.GetClientSizeTuple()
## self.grid.SetColSize(0, w - self.grid.GetRowLabelSize())
- try:
- self.grid.ForceRefresh() # Added in 2.3.1
- except AttributeError:
- pass
+ try:
+ self.grid.ForceRefresh() # Added in 2.3.1
+ except AttributeError:
+ pass
- # Force a grid cell into Edit mode when Double-Clicked
- def OnLeftDClick(self,evt):
- if self.grid.CanEnableCellControl():
- self.grid.EnableCellEditControl()
+ # Force a grid cell into Edit mode when Double-Clicked
+ def OnLeftDClick(self,evt):
+ if self.grid.CanEnableCellControl():
+ self.grid.EnableCellEditControl()
- def _generateName(self, object):
- parent = object.getParent ()
- name = '%s.%s (%s-Level Trigger)' % (parent.name,
parent._validTriggers[object.type.upper()], parent._type[2:].capitalize())
- return name
+ def _generateName(self, object):
+ parent = object.getParent ()
+ name = '%s.%s (%s-Level Trigger)' % (parent.name,
parent._validTriggers[object.type.upper()], parent._type[2:].capitalize())
+ return name
- def OnCellChange(self, evt):
- field = self.table._fieldList[evt.GetRow()]
- value = self.grid.GetCellValue(evt.GetRow(), evt.GetCol())
+ def OnCellChange(self, evt):
+ field = self.table._fieldList[evt.GetRow()]
+ value = self.grid.GetCellValue(evt.GetRow(), evt.GetCol())
- print field, value
+ print field, value
- def saveRuntimeSettings(self):
- props = {}
- for i in range(numcols):
- props['GridCol%s' % i] = self.grid.GetColSize(i)
- return (self.runtime_section, props)
-
-
+ def saveRuntimeSettings(self):
+ props = {}
+ for i in range(numcols):
+ props['GridCol%s' % i] = self.grid.GetColSize(i)
+ return (self.runtime_section, props)
Modified: trunk/gnue-designer/src/schema/TemplateSupport.py
===================================================================
--- trunk/gnue-designer/src/schema/TemplateSupport.py 2006-04-03 19:53:03 UTC
(rev 8343)
+++ trunk/gnue-designer/src/schema/TemplateSupport.py 2006-04-03 19:56:14 UTC
(rev 8344)
@@ -32,7 +32,7 @@
# TODO
def createRootObject(instance):
- return GSchema.GSSchema ()
+ return GSchema.GSSchema ()
@@ -43,7 +43,6 @@
###########################################################
class SchemaTemplate(TemplateBase):
- # Initialize user code
- def Start(self, root):
- pass
-
+ # Initialize user code
+ def Start(self, root):
+ pass
Modified: trunk/gnue-designer/src/schema/TreeView.py
===================================================================
--- trunk/gnue-designer/src/schema/TreeView.py 2006-04-03 19:53:03 UTC (rev
8343)
+++ trunk/gnue-designer/src/schema/TreeView.py 2006-04-03 19:56:14 UTC (rev
8344)
@@ -35,32 +35,30 @@
class TreeView (BaseTreeView):
- rootDescr = 'Schema'
+ rootDescr = 'Schema'
- def inventoryObject (self, object):
- if object != self.rootObject:
- icon = 'properties'
- try:
- parentTreeItem = object.getParent ()._treeItem
- except AttributeError:
- parentTreeItem = None
- # TODO:
- print "The parent object of this object has not been registered to "+\
- "the TreeView inventory. It is not possible to add this "+\
- "object to the inventory at the moment. This needs to be "+\
- "fixed. (Obj: ",object,")."
+ def inventoryObject (self, object):
+ if object != self.rootObject:
+ icon = 'properties'
+ try:
+ parentTreeItem = object.getParent ()._treeItem
+ except AttributeError:
+ parentTreeItem = None
+ # TODO:
+ print "The parent object of this object has not been
registered to "+\
+ "the TreeView inventory. It is not possible to add this
"+\
+ "object to the inventory at the moment. This needs to be
"+\
+ "fixed. (Obj: ",object,")."
- return
- if object._type == 'GSTables':
- icon = 'datasource'
- elif object._type == 'GSTable':
- icon = 'block'
- elif object._type == 'GSField':
- icon = 'entry'
+ return
+ if object._type == 'GSTables':
+ icon = 'datasource'
+ elif object._type == 'GSTable':
+ icon = 'block'
+ elif object._type == 'GSField':
+ icon = 'entry'
- object._treeItem = self.AppendItem(parentTreeItem,
- "%s" % object.getDescription())
- self.tree.SetPyData(object._treeItem, object)
- #self.tree.SetItemImage(object._treeItem, treeIconMap[icon])
-
-
+ object._treeItem = self.AppendItem(parentTreeItem,
+ "%s" % object.getDescription())
+ self.tree.SetPyData(object._treeItem, object)
+ #self.tree.SetItemImage(object._treeItem, treeIconMap[icon])
Modified: trunk/gnue-designer/src/schema/__init__.py
===================================================================
--- trunk/gnue-designer/src/schema/__init__.py 2006-04-03 19:53:03 UTC (rev
8343)
+++ trunk/gnue-designer/src/schema/__init__.py 2006-04-03 19:56:14 UTC (rev
8344)
@@ -31,15 +31,14 @@
class SchemaModuleProperties:
- module = 'schema'
- application = 'GNUe Schema'
- nickname = 'Schema'
- description = 'GNUe Schema Definition'
- xmlOpeningTag = 'schema'
+ module = 'schema'
+ application = 'GNUe Schema'
+ nickname = 'Schema'
+ description = 'GNUe Schema Definition'
+ xmlOpeningTag = 'schema'
- fileExtensions = { 'gsd': 'GNUe Schema Definition', }
+ fileExtensions = { 'gsd': 'GNUe Schema Definition', }
- defaultFileExtension = 'gsd'
+ defaultFileExtension = 'gsd'
properties = SchemaModuleProperties()
-
Modified: trunk/gnue-designer/src/schema/wizards/AddTable.py
===================================================================
--- trunk/gnue-designer/src/schema/wizards/AddTable.py 2006-04-03 19:53:03 UTC
(rev 8343)
+++ trunk/gnue-designer/src/schema/wizards/AddTable.py 2006-04-03 19:56:14 UTC
(rev 8344)
@@ -34,60 +34,60 @@
class AddTableWizard(FormTemplate):
- # The first step in our wizard.
- # The template parser will initially
- # call GetStep(FIRST_STEP).
- FIRST_STEP = '0'
+ # The first step in our wizard.
+ # The template parser will initially
+ # call GetStep(FIRST_STEP).
+ FIRST_STEP = '0'
- ###############
- #
- # Initialize any runtime variables
- #
- def Start(self, root, current):
- self.schema = root
- self.current = current
+ ###############
+ #
+ # Initialize any runtime variables
+ #
+ def Start(self, root, current):
+ self.schema = root
+ self.current = current
- ###############
- #
- # Return the markup for a specific page
- #
- def GetStep(self, stepCode):
-
+ ###############
#
- # Step #0 / Get Name
+ # Return the markup for a specific page
#
- if stepCode == '0':
+ def GetStep(self, stepCode):
- content = [WizardText(u_('This will insert a new table definition.')),
- WizardInput('name',label=u_('Table
Name:'),required=1,size=20) ]
+ #
+ # Step #0 / Get Name
+ #
+ if stepCode == '0':
- return { 'title': u_('Add Table'),
- 'content': content,
- 'prev': None,
- 'next': None }
+ content = [WizardText(u_('This will insert a new table
definition.')),
+ WizardInput('name',label=u_('Table
Name:'),required=1,size=20) ]
+ return { 'title': u_('Add Table'),
+ 'content': content,
+ 'prev': None,
+ 'next': None }
- ###############
- #
- # We have all the data, so generate our widget.
- #
- def Finalize(self):
- attrs = {'name': self.GetUniqueName(self.variables['name'] or 'Table1')}
- # Find form...
- tables = self.current['tables']
+ ###############
+ #
+ # We have all the data, so generate our widget.
+ #
+ def Finalize(self):
- table = self.AddElement('table', tables, attrs)
- self.AddElement('fields', table)
- self.AddElement('constraints', table)
- self.AddElement('indexes', table)
+ attrs = {'name': self.GetUniqueName(self.variables['name'] or
'Table1')}
+ # Find form...
+ tables = self.current['tables']
- return 1
+ table = self.AddElement('table', tables, attrs)
+ self.AddElement('fields', table)
+ self.AddElement('constraints', table)
+ self.AddElement('indexes', table)
+ return 1
+
############
#
# Basic information about this template
@@ -103,4 +103,3 @@
'Behavior': WIZARD,
'MenuLocation' : ('Insert', u_('Table'))
}
-
Modified: trunk/gnue-designer/src/schema/wizards/WriteSchema.py
===================================================================
--- trunk/gnue-designer/src/schema/wizards/WriteSchema.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/schema/wizards/WriteSchema.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -34,78 +34,78 @@
class WriteSchemaWizard(TemplateBase):
- # The first step in our wizard.
- # The template parser will initially
- # call GetStep(FIRST_STEP).
- FIRST_STEP = '0'
+ # The first step in our wizard.
+ # The template parser will initially
+ # call GetStep(FIRST_STEP).
+ FIRST_STEP = '0'
- ###############
- #
- # Initialize any runtime variables
- #
- def Start(self, root, current):
- self.schema = root
- self.current = current
+ ###############
+ #
+ # Initialize any runtime variables
+ #
+ def Start(self, root, current):
+ self.schema = root
+ self.current = current
- ###############
- #
- # Return the markup for a specific page
- #
- def GetStep(self, step):
-
- # 0 - Get Connection
- # 1 - Choose the tables which should be writte (todo)
- # 2 - Show conflicts and ask how to solve them (todo)
-
+ ###############
#
- # Step #1 / Get Connection
+ # Return the markup for a specific page
#
- if step == '0':
- return { 'title': 'Choose Database Connection',
- 'content': (WizardText('Welcome to the sample form wizard.'),
- WizardText('To what connection should this schema
be written?'),
- WizardInput('connection',label='Connection:',
required=1,
- set=self.GetAvailableConnections()),
- WizardText('You may be asked to login to this
connection.'),
- ),
- 'prev': None,
- 'next': None }
+ def GetStep(self, step):
+ # 0 - Get Connection
+ # 1 - Choose the tables which should be writte (todo)
+ # 2 - Show conflicts and ask how to solve them (todo)
+ #
+ # Step #1 / Get Connection
+ #
+ if step == '0':
+ return { 'title': 'Choose Database Connection',
+ 'content': (WizardText('Welcome to the sample form
wizard.'),
+ WizardText('To what connection should this
schema be written?'),
+
WizardInput('connection',label='Connection:', required=1,
+
set=self.GetAvailableConnections()),
+ WizardText('You may be asked to login to
this connection.'),
+ ),
+ 'prev': None,
+ 'next': None }
- ###############
- #
- # Verify contents of current step
- # Return None if no problems, otherwise
- # return a tuple of error message strings
- #
- def ValidateStep(self, stepCode):
- # The Simple wizard uses basic "required"
- # settings in the page markup, so doesn't
- # need any special validation.
- return None
+ ###############
+ #
+ # Verify contents of current step
+ # Return None if no problems, otherwise
+ # return a tuple of error message strings
+ #
+ def ValidateStep(self, stepCode):
+ # The Simple wizard uses basic "required"
+ # settings in the page markup, so doesn't
+ # need any special validation.
+ return None
- ###############
- #
- # We have all the data, so generate our form. This
- # is called after the user clicks the "Finish" button.
- # No more user input is allowed at this point.
- #
- def Finalize(self):
- con=self.GetTemporaryConnection(self.variables['connection'])
- con.writeSchema(self.schema,0)
+ ###############
+ #
+ # We have all the data, so generate our form. This
+ # is called after the user clicks the "Finish" button.
+ # No more user input is allowed at this point.
+ #
+ def Finalize(self):
- return 1
+ con=self.GetTemporaryConnection(self.variables['connection'])
+ con.writeSchema(self.schema,0)
+ return 1
+
+
############
#
# Basic information about this template
@@ -124,4 +124,3 @@
'Behavior': WIZARD,
'MenuLocation' : ('Extras',u_('Write Schema to Database'))
}
-
Modified: trunk/gnue-designer/src/templates/__init__.py
===================================================================
--- trunk/gnue-designer/src/templates/__init__.py 2006-04-03 19:53:03 UTC
(rev 8343)
+++ trunk/gnue-designer/src/templates/__init__.py 2006-04-03 19:56:14 UTC
(rev 8344)
@@ -39,22 +39,22 @@
#################################################################
def GetAvailablePackages():
- packages = []
- Tools = (
- 'navigator',
- 'forms',
- 'reports',
- 'schema')
-
- for tool in Tools:
- try:
- packages.append(dyn_import('gnue.designer.templates.%s' %tool))
- except ImportError:
- pass
+ packages = []
+ Tools = (
+ 'navigator',
+ 'forms',
+ 'reports',
+ 'schema')
- return packages
+ for tool in Tools:
+ try:
+ packages.append(dyn_import('gnue.designer.templates.%s' %tool))
+ except ImportError:
+ pass
+ return packages
+
#################################################################
#
# Return a list of the TemplateInformation dictionaries for all
@@ -63,21 +63,21 @@
#################################################################
def GetAvailableTemplates(package):
- templates = []
+ templates = []
- basedir = os.path.dirname(package.__file__)
- processed = [] # Base file names processed (e.g., base of Simply.py*
- # is Simple) This will keep us from importing Simple
- # three times if Simple.py, Simple.pyc, and Simple.lib
- # all exist.
+ basedir = os.path.dirname(package.__file__)
+ processed = [] # Base file names processed (e.g., base of Simply.py*
+ # is Simple) This will keep us from importing Simple
+ # three times if Simple.py, Simple.pyc, and Simple.lib
+ # all exist.
- for dir in dircache.listdir(basedir):
- base = string.split(dir,'.')[0]
- if not dir[0] in ('.','_') and not base in processed:
- processed.append(base)
- try:
- templates.append(dyn_import(
- '%s.%s' % (package.__name__,base)).TemplateInformation)
- except ImportError:
- pass
- return templates
+ for dir in dircache.listdir(basedir):
+ base = string.split(dir,'.')[0]
+ if not dir[0] in ('.','_') and not base in processed:
+ processed.append(base)
+ try:
+ templates.append(dyn_import(
+ '%s.%s' % (package.__name__,base)).TemplateInformation)
+ except ImportError:
+ pass
+ return templates
Modified: trunk/gnue-designer/src/templates/forms/FormBuilder.py
===================================================================
--- trunk/gnue-designer/src/templates/forms/FormBuilder.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/templates/forms/FormBuilder.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -50,572 +50,572 @@
class FormBuilderTemplate(FormTemplate):
- # The first step in our wizard.
- # The template parser will initially
- # call GetStep(FIRST_STEP).
- FIRST_STEP = '0'
- TYPEMAP = {'date' : 'date',
- 'time' : 'date',
- 'datetime': 'date',
- 'boolean' : 'boolean',
- 'number' : 'number',
- 'string' : 'text'}
+ # The first step in our wizard.
+ # The template parser will initially
+ # call GetStep(FIRST_STEP).
+ FIRST_STEP = '0'
+ TYPEMAP = {'date' : 'date',
+ 'time' : 'date',
+ 'datetime': 'date',
+ 'boolean' : 'boolean',
+ 'number' : 'number',
+ 'string' : 'text'}
- ###############
- #
- # Initialize any runtime variables
- #
- def Start(self, form, current):
- self.form = form
- self.current = current
+ ###############
+ #
+ # Initialize any runtime variables
+ #
+ def Start(self, form, current):
+ self.form = form
+ self.current = current
- # The first table can never have a master
- self.variables['hasmaster0'] = '0'
- self.variables['newPage0'] = '0'
+ # The first table can never have a master
+ self.variables['hasmaster0'] = '0'
+ self.variables['newPage0'] = '0'
- ###############
- #
- # Return the markup for a specific page
- #
- def GetStep(self, stepCode):
+ ###############
+ #
+ # Return the markup for a specific page
+ #
+ def GetStep(self, stepCode):
- try:
- step, iteration = string.split(stepCode,':')
- iteration = int(iteration)
- except ValueError:
- step = stepCode
+ try:
+ step, iteration = string.split(stepCode,':')
+ iteration = int(iteration)
+ except ValueError:
+ step = stepCode
- # Add another? loop logic
- if step == '1or8':
+ # Add another? loop logic
+ if step == '1or8':
- self.variables['newPage%s' % iteration] = self.variables['newPage']
- # If continue is set to 1, then go to step 1; otherwise, step 8
- if self.variables['continue'] == '1':
+ self.variables['newPage%s' % iteration] = self.variables['newPage']
+ # If continue is set to 1, then go to step 1; otherwise, step 8
+ if self.variables['continue'] == '1':
- step = '1'
+ step = '1'
- # If we are reusing the same connection, record that now and skip a
step
- if self.variables['singleconnection'] == '1':
- self.variables['connection%s' % iteration] =
self.variables['connection0']
- step = '2'
+ # If we are reusing the same connection, record that now and
skip a step
+ if self.variables['singleconnection'] == '1':
+ self.variables['connection%s' % iteration] =
self.variables['connection0']
+ step = '2'
- else:
- # We are done... record the total number of children
- self.variables['iterations'] = iteration
- step = '8'
+ else:
+ # We are done... record the total number of children
+ self.variables['iterations'] = iteration
+ step = '8'
- # Has Master? loop logic
- if step == '4or7':
- if self.variables['hasmaster%s' % iteration] == '1':
- step = '4'
- else:
- step = '7'
+ # Has Master? loop logic
+ if step == '4or7':
+ if self.variables['hasmaster%s' % iteration] == '1':
+ step = '4'
+ else:
+ step = '7'
- #
- # Step #0 / Get Title, et al
- #
- if step == '0':
+ #
+ # Step #0 / Get Title, et al
+ #
+ if step == '0':
- return { 'title': 'Basic Form Information',
- 'content': (WizardText('Welcome to the sample form wizard.'),
- WizardText('To create your form, I need to know
some basic information. \n\n'
- 'First, what shall I call your form?
This name will appear in '
- 'the title bar.'),
- WizardInput('title', label='Form Title:',
required=1,
- size=40),
- ),
- 'prev': None,
- 'next': '1:0' }
+ return { 'title': 'Basic Form Information',
+ 'content': (WizardText('Welcome to the sample form
wizard.'),
+ WizardText('To create your form, I need to
know some basic information. \n\n'
+ 'First, what shall I call your
form? This name will appear in '
+ 'the title bar.'),
+ WizardInput('title', label='Form Title:',
required=1,
+ size=40),
+ ),
+ 'prev': None,
+ 'next': '1:0' }
- #
- # Step #1 / Get Connection
- #
- if step == '1':
+ #
+ # Step #1 / Get Connection
+ #
+ if step == '1':
- if iteration == 0:
- # first time through ask about reusing same connection
- return { 'title': 'Connection Information',
- 'content': (WizardText('What connection contains the table
you wish to the form?'),
-
WizardInput('connection%s'%iteration,label='Connection:', required=1,
-
set=self.GetAvailableConnections()),
- WizardInput('singleconnection',
- label='Reuse this connection for all
tables?',
- required=1,set=(('1','Yes'),
- ('0','No')
- )),
- WizardText('You may be asked to login to this
connection.'),
- ),
- 'prev': '0', # Loop back
- 'next': '2:%s' % iteration }
+ if iteration == 0:
+ # first time through ask about reusing same connection
+ return { 'title': 'Connection Information',
+ 'content': (WizardText('What connection contains
the table you wish to the form?'),
+
WizardInput('connection%s'%iteration,label='Connection:', required=1,
+
set=self.GetAvailableConnections()),
+ WizardInput('singleconnection',
+ label='Reuse this connection
for all tables?',
+ required=1,set=(('1','Yes'),
+ ('0','No')
+ )),
+ WizardText('You may be asked to login
to this connection.'),
+ ),
+ 'prev': '0', # Loop back
+ 'next': '2:%s' % iteration }
- else:
+ else:
- return { 'title': 'Connection Information',
- 'content': (WizardText('What connection contains the table
you wish to the form?'),
-
WizardInput('connection%s'%iteration,label='Connection:', required=1,
-
set=self.GetAvailableConnections()),
- WizardText('You may be asked to login to this
connection.'),
- ),
- 'prev': '7:%s' % (iteration - 1), # Loop back
- 'next': '2:%s' % iteration }
+ return { 'title': 'Connection Information',
+ 'content': (WizardText('What connection contains
the table you wish to the form?'),
+
WizardInput('connection%s'%iteration,label='Connection:', required=1,
+
set=self.GetAvailableConnections()),
+ WizardText('You may be asked to login
to this connection.'),
+ ),
+ 'prev': '7:%s' % (iteration - 1), # Loop back
+ 'next': '2:%s' % iteration }
- #
- # Step #2 / Get Table
- #
- elif step == '2':
+ #
+ # Step #2 / Get Table
+ #
+ elif step == '2':
- # If using the same connection for all tables, skip question on Prev
- if iteration and self.variables['singleconnection'] == '1':
- prev = '1'
- elif iteration:
- prev = '7'
- else:
- prev = '0'
+ # If using the same connection for all tables, skip question on
Prev
+ if iteration and self.variables['singleconnection'] == '1':
+ prev = '1'
+ elif iteration:
+ prev = '7'
+ else:
+ prev = '0'
- # Do not ask about master/detail if we're iteration #1
- if iteration:
- return { 'title': 'Select Table/Source',
- 'content': (WizardText('Now, please select a table for your
form.'),
- WizardInput('table%s' % iteration,
- label='Table:', required=1, lines=5,
-
set=self.GetAvailableSources(self.variables['connection%s'%iteration])),
- WizardInput('hasmaster%s' % iteration,
- label='Will this table have a
master?',
- required=1,set=(('0','No'),
- ('1','Yes'),
- )),
- ),
- 'prev': '%s:%s' % (prev,iteration),
- 'next': '3:%s' % iteration }
+ # Do not ask about master/detail if we're iteration #1
+ if iteration:
+ return { 'title': 'Select Table/Source',
+ 'content': (WizardText('Now, please select a table
for your form.'),
+ WizardInput('table%s' % iteration,
+ label='Table:', required=1,
lines=5,
+
set=self.GetAvailableSources(self.variables['connection%s'%iteration])),
+ WizardInput('hasmaster%s' % iteration,
+ label='Will this table have
a master?',
+ required=1,set=(('0','No'),
+ ('1','Yes'),
+ )),
+ ),
+ 'prev': '%s:%s' % (prev,iteration),
+ 'next': '3:%s' % iteration }
- else:
- return { 'title': 'Select Table/Source',
- 'content': (WizardText('Now, please select a table for your
form.'),
- WizardInput('table%s' % iteration,
- label='Table:', required=1, lines=5,
-
set=self.GetAvailableSources(self.variables['connection%s'%iteration])),
- ),
- 'prev': '%s:%s' % (prev,iteration),
- 'next': '3:%s' % iteration }
+ else:
+ return { 'title': 'Select Table/Source',
+ 'content': (WizardText('Now, please select a table
for your form.'),
+ WizardInput('table%s' % iteration,
+ label='Table:', required=1,
lines=5,
+
set=self.GetAvailableSources(self.variables['connection%s'%iteration])),
+ ),
+ 'prev': '%s:%s' % (prev,iteration),
+ 'next': '3:%s' % iteration }
- #
- # Step #3 / Select fields to include
- #
- elif step == '3':
+ #
+ # Step #3 / Select fields to include
+ #
+ elif step == '3':
- return { 'title': 'Select Fields to Include',
- 'content': (WizardText('Which fields shall I include in your
form as entries?'),
- WizardInput('tablefields%s' % iteration,
- label='Columns:', required=1,
- maxSelections=-1, orderable=1,
- set=self.GetAvailableFields( \
-
self.variables['connection%s'%iteration],
- self.variables['table%s' %
iteration])),
- WizardInput('tablearrangement%s' % iteration,
- label='Arrangement Method:',
- required=1,
- set=(('left','Single Record with
Labels to Left'),
- ('above','Single Record with
Labels Above'),
- ('grid','Grid Format')))),
- 'prev': '2:%s' % iteration,
- 'next': '4or7:%s' % iteration }
+ return { 'title': 'Select Fields to Include',
+ 'content': (WizardText('Which fields shall I include in
your form as entries?'),
+ WizardInput('tablefields%s' % iteration,
+ label='Columns:', required=1,
+ maxSelections=-1, orderable=1,
+ set=self.GetAvailableFields( \
+
self.variables['connection%s'%iteration],
+ self.variables['table%s'
% iteration])),
+ WizardInput('tablearrangement%s' %
iteration,
+ label='Arrangement Method:',
+ required=1,
+ set=(('left','Single Record
with Labels to Left'),
+ ('above','Single Record
with Labels Above'),
+ ('grid','Grid Format')))),
+ 'prev': '2:%s' % iteration,
+ 'next': '4or7:%s' % iteration }
- #
- # Step #4 / Select Master Table
- #
- elif step == '4':
+ #
+ # Step #4 / Select Master Table
+ #
+ elif step == '4':
- set = []
- tables = {}
- for i in range(iteration):
+ set = []
+ tables = {}
+ for i in range(iteration):
- table = self.variables['table%s' % i]
+ table = self.variables['table%s' % i]
- # Append a "#2" to the table name if multiple sources use same table
- if tables.has_key(table):
- tables[table] += 1
- table += ' #%s' % tables[table]
- else:
- tables[table] = 1
+ # Append a "#2" to the table name if multiple sources use same
table
+ if tables.has_key(table):
+ tables[table] += 1
+ table += ' #%s' % tables[table]
+ else:
+ tables[table] = 1
- set.append( (i, table ) )
+ set.append( (i, table ) )
- # NOTE: mastertable# will be set to a NUMBER corresponding to the
datasource to
- # use. It is NOT set to an actual name! (i.e., the table to use is
- # self.variables['table%s' % mastertable#]
+ # NOTE: mastertable# will be set to a NUMBER corresponding to the
datasource to
+ # use. It is NOT set to an actual name! (i.e., the table to
use is
+ # self.variables['table%s' % mastertable#]
- return { 'title': 'Link to Master Table',
- 'content': (WizardText('Now, please select the table to be
the master of %s.' % self.variables['table%s'%iteration]),
- WizardInput('mastertable%s'%iteration,
label='Master Table:', required=1, lines=5,
- set=set), ),
- 'prev': '3:%s' % iteration,
- 'next': '5:%s' % iteration }
+ return { 'title': 'Link to Master Table',
+ 'content': (WizardText('Now, please select the table to
be the master of %s.' % self.variables['table%s'%iteration]),
+ WizardInput('mastertable%s'%iteration,
label='Master Table:', required=1, lines=5,
+ set=set), ),
+ 'prev': '3:%s' % iteration,
+ 'next': '5:%s' % iteration }
- #
- # Step #6 / Get Master Columns (primary keys)
- #
- elif step == '5':
+ #
+ # Step #6 / Get Master Columns (primary keys)
+ #
+ elif step == '5':
- return { 'title': 'Master key fields',
- 'content': (WizardText('Which master-level fields are the
primary keys?'),
- WizardInput('masterkeys%s' % iteration,
label='Columns:', required=1,
- maxSelections=-1, orderable=1,
- set=self.GetAvailableFields( \
- self.variables['connection%s'
% self.variables['mastertable%s' % iteration]],
- self.variables['table%s' %
self.variables['mastertable%s' % iteration]]))),
- 'prev': '4:%s' % iteration,
- 'next': '6:%s' % iteration }
+ return { 'title': 'Master key fields',
+ 'content': (WizardText('Which master-level fields are
the primary keys?'),
+ WizardInput('masterkeys%s' % iteration,
label='Columns:', required=1,
+ maxSelections=-1, orderable=1,
+ set=self.GetAvailableFields( \
+
self.variables['connection%s' % self.variables['mastertable%s' % iteration]],
+ self.variables['table%s'
% self.variables['mastertable%s' % iteration]]))),
+ 'prev': '4:%s' % iteration,
+ 'next': '6:%s' % iteration }
- #
- # Step #6 / Get Detail Columns (detail keys)
- #
- elif step == '6':
+ #
+ # Step #6 / Get Detail Columns (detail keys)
+ #
+ elif step == '6':
- # TODO: If the table changed between steps,
- # TODO: variables['fields'] should be cleared.
+ # TODO: If the table changed between steps,
+ # TODO: variables['fields'] should be cleared.
- return { 'title': 'Detail key fields',
- 'content': (WizardText('Which detail-level fields are the
foreign keys?'),
- WizardInput('detailkeys%s' % iteration,
label='Columns:', required=1,
- maxSelections=-1, orderable=1,
- set=self.GetAvailableFields( \
- self.variables['connection%s'
% iteration],
- self.variables['table%s' %
iteration]))),
- 'prev': '5:%s' % iteration,
- 'next': '7:%s' % iteration }
+ return { 'title': 'Detail key fields',
+ 'content': (WizardText('Which detail-level fields are
the foreign keys?'),
+ WizardInput('detailkeys%s' % iteration,
label='Columns:', required=1,
+ maxSelections=-1, orderable=1,
+ set=self.GetAvailableFields( \
+
self.variables['connection%s' % iteration],
+ self.variables['table%s'
% iteration]))),
+ 'prev': '5:%s' % iteration,
+ 'next': '7:%s' % iteration }
- #
- #
- # Step #7 / Get Master Columns to Include
- #
- elif step == '7':
+ #
+ #
+ # Step #7 / Get Master Columns to Include
+ #
+ elif step == '7':
- # If current table has no master, then skip the master/detail stuff
- if self.variables['hasmaster%s' % iteration] == '0':
- prev = '3'
- else:
- prev = '6'
+ # If current table has no master, then skip the master/detail stuff
+ if self.variables['hasmaster%s' % iteration] == '0':
+ prev = '3'
+ else:
+ prev = '6'
- # TODO: If the table changed between steps,
- # TODO: variables['fields'] should be cleared.
+ # TODO: If the table changed between steps,
+ # TODO: variables['fields'] should be cleared.
- return { 'title': 'Add Another Table?',
- 'content': (WizardInput('continue', label='Add Another
Table?',
- required=1,set=(('1','Yes'),
- ('0','No')
- )),
-# WizardInput('newPage%s' % (iteration+1),
- WizardInput('newPage',
- label='If yes, put this table on a
new page?',
- required=1,set=(('0','No'),
- ('1','Yes')
- )),),
- 'prev': '%s:%s' % (prev,iteration),
- 'next': '1or8:%s' % (iteration+1) }
+ return { 'title': 'Add Another Table?',
+ 'content': (WizardInput('continue', label='Add Another
Table?',
+ required=1,set=(('1','Yes'),
+ ('0','No')
+ )),
+ # WizardInput('newPage%s' % (iteration+1),
+ WizardInput('newPage',
+ label='If yes, put this table
on a new page?',
+ required=1,set=(('0','No'),
+ ('1','Yes')
+ )),),
+ 'prev': '%s:%s' % (prev,iteration),
+ 'next': '1or8:%s' % (iteration+1) }
- elif step == '8':
- return { 'title': "That's it!",
- 'content': (WizardText('Click finish to create your form?'),),
- 'prev': '7:%s' % (iteration-1),
- 'next': None }
+ elif step == '8':
+ return { 'title': "That's it!",
+ 'content': (WizardText('Click finish to create your
form?'),),
+ 'prev': '7:%s' % (iteration-1),
+ 'next': None }
- ###############
- #
- # Verify contents of current step
- # Return None if no problems, otherwise
- # return a tuple of error message strings
- #
- def ValidateStep(self, stepCode):
+ ###############
+ #
+ # Verify contents of current step
+ # Return None if no problems, otherwise
+ # return a tuple of error message strings
+ #
+ def ValidateStep(self, stepCode):
- # The Simple wizard uses basic "required"
- # settings in the page markup, so doesn't
- # need any special validation.
- return None
+ # The Simple wizard uses basic "required"
+ # settings in the page markup, so doesn't
+ # need any special validation.
+ return None
- ###############
- #
- # We have all the data, so generate our form. This
- # is called after the user clicks the "Finish" button.
- # No more user input is allowed at this point.
- #
- def Finalize(self):
- self.document.wizardName = TemplateInformation['Name']
+ ###############
+ #
+ # We have all the data, so generate our form. This
+ # is called after the user clicks the "Finish" button.
+ # No more user input is allowed at this point.
+ #
+ def Finalize(self):
+ self.document.wizardName = TemplateInformation['Name']
- logic = self.current['logic']
- layout = self.current['layout']
- page = self.current['page']
+ logic = self.current['logic']
+ layout = self.current['layout']
+ page = self.current['page']
- formwidth = 0
- formheight = 0
- basey = 0
- height = 0
- dataSourceArray = {}
- pageCounter = 1
+ formwidth = 0
+ formheight = 0
+ basey = 0
+ height = 0
+ dataSourceArray = {}
+ pageCounter = 1
- for count in range(self.variables['iterations']):
- if not page or self.variables['newPage%s' % count] == '1':
- pageCounter += 1
- page = self.AddElement('page', layout,
- { 'name': 'pg%s' % pageCounter })
- basey=0
- height=0
+ for count in range(self.variables['iterations']):
+ if not page or self.variables['newPage%s' % count] == '1':
+ pageCounter += 1
+ page = self.AddElement('page', layout,
+ { 'name': 'pg%s' % pageCounter })
+ basey=0
+ height=0
- tableKey = string.upper(self.variables['table%s' % count])
-
- attrs = { 'connection': self.variables['connection%s' % count],
- 'table': self.variables['table%s' % count],
- 'type': 'object',
- 'name': 'dts%s%s' % (tableKey,count) }
+ tableKey = string.upper(self.variables['table%s' % count])
- if self.variables['hasmaster%s' % count] == '1':
- attrs['master'] = dataSourceArray[self.variables['mastertable%s' %
count]].name
- attrs['masterlink'] = string.join(self.variables['masterkeys%s' %
count],',')
- attrs['detaillink'] = string.join(self.variables['detailkeys%s' %
count],',')
-
- datasource = self.AddElement('datasource', self.form, attrs)
- dataSourceArray[count] = datasource
+ attrs = { 'connection': self.variables['connection%s' % count],
+ 'table': self.variables['table%s' % count],
+ 'type': 'object',
+ 'name': 'dts%s%s' % (tableKey,count) }
+ if self.variables['hasmaster%s' % count] == '1':
+ attrs['master'] =
dataSourceArray[self.variables['mastertable%s' % count]].name
+ attrs['masterlink'] =
string.join(self.variables['masterkeys%s' % count],',')
+ attrs['detaillink'] =
string.join(self.variables['detailkeys%s' % count],',')
- # Is this a grid style form?
- multirecord = self.variables['tablearrangement%s' % count] == 'grid'
+ datasource = self.AddElement('datasource', self.form, attrs)
+ dataSourceArray[count] = datasource
- # Will labels appear above or to the left of the entries?
- # Note: this results in False for both "grid" and "above"
- leftlabels = self.variables['tablearrangement%s' % count] == 'left'
+ # Is this a grid style form?
+ multirecord = self.variables['tablearrangement%s' % count] ==
'grid'
- # We will need a block to hold our entries...
+ # Will labels appear above or to the left of the entries?
+ # Note: this results in False for both "grid" and "above"
+ leftlabels = self.variables['tablearrangement%s' % count] == 'left'
- # The basic attributes for a block
- attrs = {'name' : 'blk%s' % tableKey,
- 'datasource': datasource['name']}
- # If this is a multirecord form, set rows at the block level.
- if multirecord:
- attrs['rows'] = 10
+ # We will need a block to hold our entries...
- # Create the block
- block = self.AddElement('block', logic, attrs)
+ # The basic attributes for a block
+ attrs = {'name' : 'blk%s' % tableKey,
+ 'datasource': datasource['name']}
- schema = self.GetSourceSchema(self.variables['connection%s' % count],
- self.variables['table%s' % count])
+ # If this is a multirecord form, set rows at the block level.
+ if multirecord:
+ attrs['rows'] = 10
+ # Create the block
+ block = self.AddElement('block', logic, attrs)
- # Create the entries and labels...
+ schema = self.GetSourceSchema(self.variables['connection%s' %
count],
+ self.variables['table%s' % count])
- # Make a map of all the field schemas we will need
- # We will not actually create the entries at this point
- # because we want to keep in the order that the user
- # specified
- fields = {}
- for field in schema.findChildrenOfType ('GSField', False, True):
- if field.name in self.variables['tablefields%s' % count]:
- fields[field.name] = field
+ # Create the entries and labels...
- entryQueue = []
- labelQueue = []
- largestField = 0
- largestLabel = 0
- # First, let's make all the fields
- for name in self.variables['tablefields%s' % count]:
+ # Make a map of all the field schemas we will need
+ # We will not actually create the entries at this point
+ # because we want to keep in the order that the user
+ # specified
+ fields = {}
+ for field in schema.findChildrenOfType ('GSField', False, True):
+ if field.name in self.variables['tablefields%s' % count]:
+ fields[field.name] = field
- field = fields[name]
+ entryQueue = []
+ labelQueue = []
+ largestField = 0
+ largestLabel = 0
- # We will use the field name as the basis for all our
- # entry and label names. Capitalize the first letter
- # and strip all spaces...
- if len(field.name) == 1:
- fieldKey = string.upper(field.name)
- else:
- fieldKey = string.join(string.split(string.capwords( \
- string.replace(field.name,'_',' '))),'')
+ # First, let's make all the fields
+ for name in self.variables['tablefields%s' % count]:
- # Create a label. If the schema specified a label for a field,
- # use that as is. If not, use the field name, replacing any '_'
- # with spaces and tacking on a colon.
- text = hasattr(field,'label') and label or \
- string.capwords(string.replace(field.name,'_',' ')) + ':'
+ field = fields[name]
- # Add text, x, y to labelQueue
- # The x,y will be replaced by logic later on...
- labelQueue.append([text,0,0])
+ # We will use the field name as the basis for all our
+ # entry and label names. Capitalize the first letter
+ # and strip all spaces...
+ if len(field.name) == 1:
+ fieldKey = string.upper(field.name)
+ else:
+ fieldKey = string.join(string.split(string.capwords( \
+ string.replace(field.name,'_',' '))),'')
- # Keep track of the greatest label width
- largestLabel = max(len(text),largestLabel)
+ # Create a label. If the schema specified a label for a field,
+ # use that as is. If not, use the field name, replacing any
'_'
+ # with spaces and tacking on a colon.
+ text = hasattr(field,'label') and label or \
+ string.capwords(string.replace(field.name,'_',' ')) +
':'
- # Create an entry for this field.
+ # Add text, x, y to labelQueue
+ # The x,y will be replaced by logic later on...
+ labelQueue.append([text,0,0])
- attrs={ 'name': "fld%s" % fieldKey,
- 'field': field.name,
- 'typecast': self.TYPEMAP.get (field.type, 'text')}
+ # Keep track of the greatest label width
+ largestLabel = max(len(text),largestLabel)
- # If we have a length for the field, use this as the maxLength
- # for the entry. Also, adjust the display width if necessary.
- if hasattr(field,'length'):
- ln = max(min(field.length, 40),0) or 10
- attrs['maxLength'] = ln
- largestField = max(largestField, ln)
- else:
- largestField = max(largestField, 10)
+ # Create an entry for this field.
- # Create the entry element
- fld = self.AddElement('field', block, attrs)
+ attrs={ 'name': "fld%s" % fieldKey,
+ 'field': field.name,
+ 'typecast': self.TYPEMAP.get (field.type, 'text')}
- # and queue it so we can create entry's later
- entryQueue.append([fld, 0, 0] )
+ # If we have a length for the field, use this as the maxLength
+ # for the entry. Also, adjust the display width if necessary.
+ if hasattr(field,'length'):
+ ln = max(min(field.length, 40),0) or 10
+ attrs['maxLength'] = ln
+ largestField = max(largestField, ln)
+ else:
+ largestField = max(largestField, 10)
+ # Create the entry element
+ fld = self.AddElement('field', block, attrs)
- #
- # Rearrange the fields and labels to snugly fit the screen
- # based on the layout arrangement selected by the user.
- #
+ # and queue it so we can create entry's later
+ entryQueue.append([fld, 0, 0] )
- # Grid/multirecord layout
- if multirecord:
- height += 13
- width = 1
- x = 1
+ #
+ # Rearrange the fields and labels to snugly fit the screen
+ # based on the layout arrangement selected by the user.
+ #
- for i in range(len(entryQueue)):
- field = entryQueue[i][0]
- text = labelQueue[i][0]
- textLen = len(text)
+ # Grid/multirecord layout
+ if multirecord:
- labelQueue[i][1] = x
- labelQueue[i][2] = basey + 1
- entryQueue[i][1] = x
- entryQueue[i][2] = basey + 2
+ height += 13
+ width = 1
+ x = 1
- # If label width is larger than entry width, center the entry
- try:
- entryWidth = min(field['maxLength'],40)
- except KeyError:
- entryWidth = 10
- if entryWidth < textLen:
- entryQueue[i][1] += int((textLen - entryWidth)/2)
+ for i in range(len(entryQueue)):
+ field = entryQueue[i][0]
+ text = labelQueue[i][0]
+ textLen = len(text)
- # Calculate the starting x for the next label/entry
- dx = max(entryWidth, textLen) + 1
+ labelQueue[i][1] = x
+ labelQueue[i][2] = basey + 1
+ entryQueue[i][1] = x
+ entryQueue[i][2] = basey + 2
- # Increase the form width accordingly
- width += dx
- x += dx
- basey += 12
+ # If label width is larger than entry width, center the
entry
+ try:
+ entryWidth = min(field['maxLength'],40)
+ except KeyError:
+ entryWidth = 10
+ if entryWidth < textLen:
+ entryQueue[i][1] += int((textLen - entryWidth)/2)
- # Single Record layout (regardless of label location)
- else:
+ # Calculate the starting x for the next label/entry
+ dx = max(entryWidth, textLen) + 1
- # Assign the starting (x,y) values for labels (l) and fields (f)
- # as well as the delta (x,y) values.
- if leftlabels:
- # Labels to the left of the entries
- lx, ly, ldx, ldy = (1, 1, 0, 1)
- fx, fy, fdx, fdy = (largestLabel + 2, 1, 0, 1)
+ # Increase the form width accordingly
+ width += dx
+ x += dx
+ basey += 12
- # Set form width
- width = largestField + largestLabel + 3
+ # Single Record layout (regardless of label location)
+ else:
- else:
- # Labels above the entries
- lx, ly, ldx, ldy = (1, 1, 0, 3)
- fx, fy, fdx, fdy = (1, 2, 0, 3)
+ # Assign the starting (x,y) values for labels (l) and fields
(f)
+ # as well as the delta (x,y) values.
+ if leftlabels:
+ # Labels to the left of the entries
+ lx, ly, ldx, ldy = (1, 1, 0, 1)
+ fx, fy, fdx, fdy = (largestLabel + 2, 1, 0, 1)
- # Set the form width
- width = 2 + max(largestField, largestLabel)
+ # Set form width
+ width = largestField + largestLabel + 3
- # Rearrange
- height += fy+2-fdy
- by = basey
- for i in range(len(entryQueue)):
- labelQueue[i][1] = lx
- labelQueue[i][2] = by + ly
- entryQueue[i][1] = fx
- entryQueue[i][2] = by + fy
+ else:
+ # Labels above the entries
+ lx, ly, ldx, ldy = (1, 1, 0, 3)
+ fx, fy, fdx, fdy = (1, 2, 0, 3)
- ly = ly + ldy
- lx = lx + ldx
- fy = fy + fdy
- fx = fx + fdx
- height += fdy
- basey += fdy
+ # Set the form width
+ width = 2 + max(largestField, largestLabel)
- #
- # Finally, add the visual elements...
- #
- for i in range(len(entryQueue)):
+ # Rearrange
+ height += fy+2-fdy
+ by = basey
+ for i in range(len(entryQueue)):
+ labelQueue[i][1] = lx
+ labelQueue[i][2] = by + ly
+ entryQueue[i][1] = fx
+ entryQueue[i][2] = by + fy
- #
- # First, the label
- #
- text, x, y = labelQueue[i]
- self.AddElement( 'label', page,
- {'Char:x': x,
- 'Char:y': y,
- 'name': "lbl%s" % fieldKey,
- 'text': text,
- 'Char:width': len(text)})
+ ly = ly + ldy
+ lx = lx + ldx
+ fy = fy + fdy
+ fx = fx + fdx
+ height += fdy
+ basey += fdy
- #
- # And the entry...
- #
- field, x, y = entryQueue[i]
- attrs={'name': "ent%s" % field['name'][3:],
- 'field': field['name'],
- 'block': block['name'],
- 'Char:x': x,
- 'Char:y': y,
- 'Char:width': 10 }
+ #
+ # Finally, add the visual elements...
+ #
+ for i in range(len(entryQueue)):
- # If we have a length for the field, use this as the maxLength
- # for the entry. Also, adjust the display width if necessary.
- try:
- attrs['Char:width'] = min(field['maxLength'], 40)
- except KeyError:
- pass
+ #
+ # First, the label
+ #
+ text, x, y = labelQueue[i]
+ self.AddElement( 'label', page,
+ {'Char:x': x,
+ 'Char:y': y,
+ 'name': "lbl%s" % fieldKey,
+ 'text': text,
+ 'Char:width': len(text)})
- # Create the entry element
- self.AddElement('entry', page, attrs)
+ #
+ # And the entry...
+ #
+ field, x, y = entryQueue[i]
+ attrs={'name': "ent%s" % field['name'][3:],
+ 'field': field['name'],
+ 'block': block['name'],
+ 'Char:x': x,
+ 'Char:y': y,
+ 'Char:width': 10 }
+ # If we have a length for the field, use this as the maxLength
+ # for the entry. Also, adjust the display width if necessary.
+ try:
+ attrs['Char:width'] = min(field['maxLength'], 40)
+ except KeyError:
+ pass
- formwidth = max(formwidth, width)
- formheight = max(formheight, height)
+ # Create the entry element
+ self.AddElement('entry', page, attrs)
- #
- # Set the basic attributes of the form
- #
- self.form['title'] = self.variables['title']
- layout['Char:width'] = formwidth
- layout['Char:height'] = formheight
+ formwidth = max(formwidth, width)
+ formheight = max(formheight, height)
- return 1
+ #
+ # Set the basic attributes of the form
+ #
+ self.form['title'] = self.variables['title']
+ layout['Char:width'] = formwidth
+ layout['Char:height'] = formheight
+ return 1
+
+
############
#
# Basic information about this template
@@ -630,4 +630,3 @@
'Author' : 'The GNUe Designer Team',
'Behavior': WIZARD
}
-
Modified: trunk/gnue-designer/src/templates/forms/Simple.py
===================================================================
--- trunk/gnue-designer/src/templates/forms/Simple.py 2006-04-03 19:53:03 UTC
(rev 8343)
+++ trunk/gnue-designer/src/templates/forms/Simple.py 2006-04-03 19:56:14 UTC
(rev 8344)
@@ -45,361 +45,361 @@
class SimpleFormTemplate (FormTemplate):
- TYPEMAP = {'date' : 'date',
- 'time' : 'date',
- 'datetime': 'date',
- 'boolean' : 'boolean',
- 'number' : 'number',
- 'string' : 'text'}
+ TYPEMAP = {'date' : 'date',
+ 'time' : 'date',
+ 'datetime': 'date',
+ 'boolean' : 'boolean',
+ 'number' : 'number',
+ 'string' : 'text'}
- # The first step in our wizard.
- # The template parser will initially
- # call GetStep(FIRST_STEP).
- FIRST_STEP = '0'
+ # The first step in our wizard.
+ # The template parser will initially
+ # call GetStep(FIRST_STEP).
+ FIRST_STEP = '0'
- ###############
- #
- # Initialize any runtime variables
- #
- def Start(self, form, current):
- self.form = form
- self.current = current
+ ###############
+ #
+ # Initialize any runtime variables
+ #
+ def Start(self, form, current):
+ self.form = form
+ self.current = current
- ###############
- #
- # Return the markup for a specific page
- #
- def GetStep(self, stepCode):
-
+ ###############
#
- # Step #1 / Get Title, et al
+ # Return the markup for a specific page
#
- if stepCode == '0':
- return { 'title': 'Basic Form Information',
- 'content': (WizardText('Welcome to the sample form wizard.'),
- WizardText('To create your form, I need to know
some basic information.\n\n'
- 'First, what shall I call your form?
This name will appear in '
- 'the title bar.'),
- WizardInput('title', label='Form Title:',
required=1,
- size=40),
- WizardText('What connection should this form use
to connect to the database?'),
- WizardInput('connection',label='Connection:',
required=1,
- set=self.GetAvailableConnections()),
- WizardText('You may be asked to login to this
connection.'),
- ),
- 'prev': None,
- 'next': '1' }
+ def GetStep(self, stepCode):
+ #
+ # Step #1 / Get Title, et al
+ #
+ if stepCode == '0':
+ return { 'title': 'Basic Form Information',
+ 'content': (WizardText('Welcome to the sample form
wizard.'),
+ WizardText('To create your form, I need to
know some basic information.\n\n'
+ 'First, what shall I call your
form? This name will appear in '
+ 'the title bar.'),
+ WizardInput('title', label='Form Title:',
required=1,
+ size=40),
+ WizardText('What connection should this
form use to connect to the database?'),
+
WizardInput('connection',label='Connection:', required=1,
+
set=self.GetAvailableConnections()),
+ WizardText('You may be asked to login to
this connection.'),
+ ),
+ 'prev': None,
+ 'next': '1' }
- #
- # Step #2 / Get Base Table
- #
- elif stepCode == '1':
- # TODO: If the connection changed between steps,
- # TODO: variables['table'] and variables['fields']
- # TODO: should be cleared.
+ #
+ # Step #2 / Get Base Table
+ #
+ elif stepCode == '1':
- return { 'title': 'Select Base Table/Source',
- 'content': (WizardText('Now, please select the base table for
your form.'),
- WizardInput('table', label='Base Table:',
required=1, lines=5,
-
set=self.GetAvailableSources(self.variables['connection'])), ),
- 'prev': '0',
- 'next': '2' }
+ # TODO: If the connection changed between steps,
+ # TODO: variables['table'] and variables['fields']
+ # TODO: should be cleared.
+ return { 'title': 'Select Base Table/Source',
+ 'content': (WizardText('Now, please select the base
table for your form.'),
+ WizardInput('table', label='Base Table:',
required=1, lines=5,
+
set=self.GetAvailableSources(self.variables['connection'])), ),
+ 'prev': '0',
+ 'next': '2' }
- #
- # Step #3 / Get Columns to Include
- #
- elif stepCode == '2':
- # TODO: If the table changed between steps,
- # TODO: variables['fields'] should be cleared.
+ #
+ # Step #3 / Get Columns to Include
+ #
+ elif stepCode == '2':
- return { 'title': 'Select Fields to Include',
- 'content': (WizardText('Which fields shall I include in your
form?'),
- WizardInput('fields', label='Columns:',
required=1,
- maxSelections=-1, orderable=1,
- set=self.GetAvailableFields( \
- self.variables['connection'],
- self.variables['table'])),
- WizardInput('arrangement', label='Arrangement
Method:',
- required=1,
- set=(('left','Single Record with
Labels to Left'),
- ('above','Single Record with
Labels Above'),
- ('grid','Grid Format')))),
- 'prev': '1',
- 'next': None }
+ # TODO: If the table changed between steps,
+ # TODO: variables['fields'] should be cleared.
+ return { 'title': 'Select Fields to Include',
+ 'content': (WizardText('Which fields shall I include in
your form?'),
+ WizardInput('fields', label='Columns:',
required=1,
+ maxSelections=-1, orderable=1,
+ set=self.GetAvailableFields( \
+
self.variables['connection'],
+
self.variables['table'])),
+ WizardInput('arrangement',
label='Arrangement Method:',
+ required=1,
+ set=(('left','Single Record
with Labels to Left'),
+ ('above','Single Record
with Labels Above'),
+ ('grid','Grid Format')))),
+ 'prev': '1',
+ 'next': None }
- ###############
- #
- # Verify contents of current step
- # Return None if no problems, otherwise
- # return a tuple of error message strings
- #
- def ValidateStep(self, stepCode):
- # The Simple wizard uses basic "required"
- # settings in the page markup, so doesn't
- # need any special validation.
- return None
+ ###############
+ #
+ # Verify contents of current step
+ # Return None if no problems, otherwise
+ # return a tuple of error message strings
+ #
+ def ValidateStep(self, stepCode):
+ # The Simple wizard uses basic "required"
+ # settings in the page markup, so doesn't
+ # need any special validation.
+ return None
- ###############
- #
- # We have all the data, so generate our form. This
- # is called after the user clicks the "Finish" button.
- # No more user input is allowed at this point.
- #
- def Finalize(self):
- self.document.wizardName = TemplateInformation['Name']
-
- # We will use the table name as the basis for all our
- # object names. We will add a prefix based on the object
- # type to the table name. Capitalize the first letter and
- # strip all spaces...
- if len(self.variables['table']) == 1:
- tableKey = string.upper(self.variables['table'])
- else:
- tableKey = string.upper(self.variables['table'][0]) + \
- string.replace(self.variables['table'][1:],' ','_')
- # Is this a grid style form?
- multirecord = self.variables['arrangement'] == 'grid'
+ ###############
+ #
+ # We have all the data, so generate our form. This
+ # is called after the user clicks the "Finish" button.
+ # No more user input is allowed at this point.
+ #
+ def Finalize(self):
+ self.document.wizardName = TemplateInformation['Name']
- # Will labels appear above or to the left of the entries?
- # Note: this results in False for both "grid" and "above"
- leftlabels = self.variables['arrangement'] == 'left'
+ # We will use the table name as the basis for all our
+ # object names. We will add a prefix based on the object
+ # type to the table name. Capitalize the first letter and
+ # strip all spaces...
+ if len(self.variables['table']) == 1:
+ tableKey = string.upper(self.variables['table'])
+ else:
+ tableKey = string.upper(self.variables['table'][0]) + \
+ string.replace(self.variables['table'][1:],' ','_')
- # Set the basic attributes of the form
- self.form['title'] = self.variables['title']
+ # Is this a grid style form?
+ multirecord = self.variables['arrangement'] == 'grid'
- # Create a single datasource based on user's input
- datasource = self.AddElement('datasource', self.form,
- { 'connection': self.variables['connection'],
- 'table': self.variables['table'],
- 'type': 'object',
- 'name': 'dts%s' % tableKey })
+ # Will labels appear above or to the left of the entries?
+ # Note: this results in False for both "grid" and "above"
+ leftlabels = self.variables['arrangement'] == 'left'
- logic = self.current['logic']
- layout = self.current['layout']
- page = self.current['page'] or self.AddElement('page', layout,
- { 'name': 'pg%s' % tableKey })
+ # Set the basic attributes of the form
+ self.form['title'] = self.variables['title']
+ # Create a single datasource based on user's input
+ datasource = self.AddElement('datasource', self.form,
+ { 'connection': self.variables['connection'],
+ 'table': self.variables['table'],
+ 'type': 'object',
+ 'name': 'dts%s' % tableKey })
- # We will need a block to hold our entries...
+ logic = self.current['logic']
+ layout = self.current['layout']
+ page = self.current['page'] or self.AddElement('page', layout,
+ { 'name': 'pg%s' % tableKey })
- # The basic attributes for a block
- attrs = {'name' : 'blk%s' % tableKey,
- 'datasource': datasource.name}
- # If this is a multirecord form, set rows at the block level.
- if multirecord:
- attrs['rows'] = 10
+ # We will need a block to hold our entries...
- # Create the block
- block = self.AddElement('block', logic, attrs)
+ # The basic attributes for a block
+ attrs = {'name' : 'blk%s' % tableKey,
+ 'datasource': datasource.name}
- schema = self.GetSourceSchema(self.variables['connection'],
- self.variables['table'])
+ # If this is a multirecord form, set rows at the block level.
+ if multirecord:
+ attrs['rows'] = 10
+ # Create the block
+ block = self.AddElement('block', logic, attrs)
- # Create the entries and labels...
+ schema = self.GetSourceSchema(self.variables['connection'],
+ self.variables['table'])
- # Make a map of all the field schemas we will need
- # We will not actually create the entries at this point
- # because we want to keep in the order that the user
- # specified
- fields = {}
- for field in schema.findChildrenOfType ('GSField', False, True):
- if field.name in self.variables['fields']:
- fields[field.name] = field
+ # Create the entries and labels...
- entryQueue = []
- labelQueue = []
- largestField = 0
- largestLabel = 0
- # First, let's make all the fields
- for name in self.variables['fields']:
+ # Make a map of all the field schemas we will need
+ # We will not actually create the entries at this point
+ # because we want to keep in the order that the user
+ # specified
+ fields = {}
+ for field in schema.findChildrenOfType ('GSField', False, True):
+ if field.name in self.variables['fields']:
+ fields[field.name] = field
- field = fields[name]
+ entryQueue = []
+ labelQueue = []
+ largestField = 0
+ largestLabel = 0
- # We will use the field name as the basis for all our
- # entry and label names. Capitalize the first letter
- # and strip all spaces...
- if len(field.name) == 1:
- fieldKey = string.upper(field.name)
- else:
- fieldKey = string.join(string.split(string.capwords( \
- string.replace(field.name,'_',' '))),'')
+ # First, let's make all the fields
+ for name in self.variables['fields']:
- # Create a label. If the schema specified a label for a field,
- # use that as is. If not, use the field name, replacing any '_'
- # with spaces and tacking on a colon.
- text = hasattr(field,'label') and label or \
- string.capwords(string.replace(field.name,'_',' ')) + ':'
+ field = fields[name]
- # Add text, x, y to labelQueue
- # The x,y will be replaced by logic later on...
- labelQueue.append([text,0,0])
+ # We will use the field name as the basis for all our
+ # entry and label names. Capitalize the first letter
+ # and strip all spaces...
+ if len(field.name) == 1:
+ fieldKey = string.upper(field.name)
+ else:
+ fieldKey = string.join(string.split(string.capwords( \
+ string.replace(field.name,'_',' '))),'')
- # Keep track of the greatest label width
- largestLabel = max(len(text),largestLabel)
+ # Create a label. If the schema specified a label for a field,
+ # use that as is. If not, use the field name, replacing any '_'
+ # with spaces and tacking on a colon.
+ text = hasattr(field,'label') and label or \
+ string.capwords(string.replace(field.name,'_',' ')) + ':'
- # Create an entry for this field.
+ # Add text, x, y to labelQueue
+ # The x,y will be replaced by logic later on...
+ labelQueue.append([text,0,0])
- attrs={ 'name': "fld%s" % fieldKey,
- 'field': field.name,
- 'typecast': self.TYPEMAP.get (field.type, 'text')}
+ # Keep track of the greatest label width
+ largestLabel = max(len(text),largestLabel)
- # If we have a length for the field, use this as the maxLength
- # for the entry. Also, adjust the display width if necessary.
- if hasattr(field,'length'):
- ln = max(min(field.length, 40),0) or 10
+ # Create an entry for this field.
- ##ln = min(field.length, 40)
- attrs['maxLength'] = ln
- largestField = max(largestField, ln)
- else:
- largestField = max(largestField, 10)
+ attrs={ 'name': "fld%s" % fieldKey,
+ 'field': field.name,
+ 'typecast': self.TYPEMAP.get (field.type, 'text')}
- # Create the entry element
- fld = self.AddElement('field', block, attrs)
+ # If we have a length for the field, use this as the maxLength
+ # for the entry. Also, adjust the display width if necessary.
+ if hasattr(field,'length'):
+ ln = max(min(field.length, 40),0) or 10
- # and queue it so we can create entry's later
- entryQueue.append([fld, 0, 0] )
+ ##ln = min(field.length, 40)
+ attrs['maxLength'] = ln
+ largestField = max(largestField, ln)
+ else:
+ largestField = max(largestField, 10)
+ # Create the entry element
+ fld = self.AddElement('field', block, attrs)
- #
- # Rearrange the fields and labels to snugly fit the screen
- # based on the layout arrangement selected by the user.
- #
+ # and queue it so we can create entry's later
+ entryQueue.append([fld, 0, 0] )
- # Grid/multirecord layout
- if multirecord:
- height = 13
- width = 1
- x = 1
+ #
+ # Rearrange the fields and labels to snugly fit the screen
+ # based on the layout arrangement selected by the user.
+ #
- for i in range(len(entryQueue)):
- field = entryQueue[i][0]
- text = labelQueue[i][0]
- textLen = len(text)
+ # Grid/multirecord layout
+ if multirecord:
- labelQueue[i][1] = x
- labelQueue[i][2] = 1
- entryQueue[i][1] = x
- entryQueue[i][2] = 2
+ height = 13
+ width = 1
+ x = 1
- # If label width is larger than entry width, center the entry
- try:
- entryWidth = min(field['maxLength'],40)
- except KeyError:
- entryWidth = 10
- if entryWidth < textLen:
- entryQueue[i][1] += int((textLen - entryWidth)/2)
+ for i in range(len(entryQueue)):
+ field = entryQueue[i][0]
+ text = labelQueue[i][0]
+ textLen = len(text)
- # Calculate the starting x for the next label/entry
- dx = max(entryWidth, textLen) + 1
+ labelQueue[i][1] = x
+ labelQueue[i][2] = 1
+ entryQueue[i][1] = x
+ entryQueue[i][2] = 2
- # Increase the form width accordingly
- width += dx
- x += dx
+ # If label width is larger than entry width, center the entry
+ try:
+ entryWidth = min(field['maxLength'],40)
+ except KeyError:
+ entryWidth = 10
+ if entryWidth < textLen:
+ entryQueue[i][1] += int((textLen - entryWidth)/2)
- # Single Record layout (regardless of label location)
- else:
+ # Calculate the starting x for the next label/entry
+ dx = max(entryWidth, textLen) + 1
- # Assign the starting (x,y) values for labels (l) and fields (f)
- # as well as the delta (x,y) values.
- if leftlabels:
- # Labels to the left of the entries
- lx, ly, ldx, ldy = (1, 1, 0, 1)
- fx, fy, fdx, fdy = (largestLabel + 2, 1, 0, 1)
+ # Increase the form width accordingly
+ width += dx
+ x += dx
- # Set form width
- width = largestField + largestLabel + 3
+ # Single Record layout (regardless of label location)
+ else:
- else:
- # Labels above the entries
- lx, ly, ldx, ldy = (1, 1, 0, 3)
- fx, fy, fdx, fdy = (1, 2, 0, 3)
+ # Assign the starting (x,y) values for labels (l) and fields (f)
+ # as well as the delta (x,y) values.
+ if leftlabels:
+ # Labels to the left of the entries
+ lx, ly, ldx, ldy = (1, 1, 0, 1)
+ fx, fy, fdx, fdy = (largestLabel + 2, 1, 0, 1)
- # Set the form width
- width = 2 + max(largestField, largestLabel)
+ # Set form width
+ width = largestField + largestLabel + 3
- # Rearrange
- height = fy+2-fdy
- for i in range(len(entryQueue)):
- labelQueue[i][1] = lx
- labelQueue[i][2] = ly
- entryQueue[i][1] = fx
- entryQueue[i][2] = fy
+ else:
+ # Labels above the entries
+ lx, ly, ldx, ldy = (1, 1, 0, 3)
+ fx, fy, fdx, fdy = (1, 2, 0, 3)
- ly = ly + ldy
- lx = lx + ldx
- fy = fy + fdy
- fx = fx + fdx
- height += fdy
+ # Set the form width
+ width = 2 + max(largestField, largestLabel)
- #
- # Resize the layout screen to fit our form
- #
- layout['Char:width'] = width
- layout['Char:height'] = height
+ # Rearrange
+ height = fy+2-fdy
+ for i in range(len(entryQueue)):
+ labelQueue[i][1] = lx
+ labelQueue[i][2] = ly
+ entryQueue[i][1] = fx
+ entryQueue[i][2] = fy
+ ly = ly + ldy
+ lx = lx + ldx
+ fy = fy + fdy
+ fx = fx + fdx
+ height += fdy
- #
- # Finally, add the visual elements...
- #
- for i in range(len(entryQueue)):
+ #
+ # Resize the layout screen to fit our form
+ #
+ layout['Char:width'] = width
+ layout['Char:height'] = height
- #
- # First, the label
- #
- text, x, y = labelQueue[i]
- self.AddElement( 'label', page,
- {'Char:x': x,
- 'Char:y': y,
- 'name': "lbl%s" % (text[-1]==':' and text[:-1] or text),
- 'text': text,
- 'Char:width': len(text)})
- #
- # And the entry...
- #
- field, x, y = entryQueue[i]
- attrs={'name': "ent%s" % field['name'][3:],
- 'field': field['name'],
- 'block': block['name'],
- 'Char:x': x,
- 'Char:y': y,
- 'Char:width': 10 }
+ #
+ # Finally, add the visual elements...
+ #
+ for i in range(len(entryQueue)):
- # If we have a length for the field, use this as the maxLength
- # for the entry. Also, adjust the display width if necessary.
- try:
- attrs['Char:width'] = min(field['maxLength'], 40)
- except KeyError:
- pass
+ #
+ # First, the label
+ #
+ text, x, y = labelQueue[i]
+ self.AddElement( 'label', page,
+ {'Char:x': x,
+ 'Char:y': y,
+ 'name': "lbl%s" % (text[-1]==':' and text[:-1] or
text),
+ 'text': text,
+ 'Char:width': len(text)})
- # Create the entry element
- self.AddElement('entry', page, attrs)
+ #
+ # And the entry...
+ #
+ field, x, y = entryQueue[i]
+ attrs={'name': "ent%s" % field['name'][3:],
+ 'field': field['name'],
+ 'block': block['name'],
+ 'Char:x': x,
+ 'Char:y': y,
+ 'Char:width': 10 }
+ # If we have a length for the field, use this as the maxLength
+ # for the entry. Also, adjust the display width if necessary.
+ try:
+ attrs['Char:width'] = min(field['maxLength'], 40)
+ except KeyError:
+ pass
- # That's it... we're done.
- return 1
+ # Create the entry element
+ self.AddElement('entry', page, attrs)
+ # That's it... we're done.
+ return 1
+
+
############
#
# Basic information about this template
@@ -416,4 +416,3 @@
'Author' : 'The GNUe Designer Team',
'Behavior': WIZARD
}
-
Modified: trunk/gnue-designer/src/templates/forms/__init__.py
===================================================================
--- trunk/gnue-designer/src/templates/forms/__init__.py 2006-04-03 19:53:03 UTC
(rev 8343)
+++ trunk/gnue-designer/src/templates/forms/__init__.py 2006-04-03 19:56:14 UTC
(rev 8344)
@@ -31,4 +31,4 @@
TEMPLATES = ['FormBuilder', 'Simple',]
# Raises an import error if Forms isn't valid on this machine
-import gnue.forms as _test
\ No newline at end of file
+import gnue.forms as _test
Modified: trunk/gnue-designer/src/templates/reports/CharReport.py
===================================================================
--- trunk/gnue-designer/src/templates/reports/CharReport.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/templates/reports/CharReport.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -41,204 +41,204 @@
class CharReportTemplate(ReportTemplate):
- # The first step in our wizard.
- # The template parser will initially
- # call GetStep(FIRST_STEP).
- FIRST_STEP = '0'
+ # The first step in our wizard.
+ # The template parser will initially
+ # call GetStep(FIRST_STEP).
+ FIRST_STEP = '0'
- ###############
- #
- # Initialize any runtime variables
- #
- def Start(self, report, current):
- self.report = report
- self.current = current
-
-
- ###############
- #
- # Return the markup for a specific page
- #
- def GetStep(self, stepCode):
-
+ ###############
#
- # Step #1 / Get Title, et al
+ # Initialize any runtime variables
#
- if stepCode == '0':
- return { 'title': 'Basic Report Information',
- 'content': (WizardText('Welcome to the sample report
wizard.'),
- WizardText('To create your report, I need to know
some basic information.\n\n'
- 'First, what shall I call your report?
This name will appear in '
- 'the title bar.'),
- WizardInput('title', label='Report Title:',
required=1,
- size=40),
- WizardText('What connection should this report
use to connect to the database?'),
- WizardInput('connection',label='Connection:',
required=1,
- set=self.GetAvailableConnections()),
- WizardText('You may be asked to login to this
connection.'),
- ),
- 'prev': None,
- 'next': '1' }
+ def Start(self, report, current):
+ self.report = report
+ self.current = current
+ ###############
#
- # Step #2 / Get Base Table
+ # Return the markup for a specific page
#
- elif stepCode == '1':
+ def GetStep(self, stepCode):
- # TODO: If the connection changed between steps,
- # TODO: variables['table'] and variables['fields']
- # TODO: should be cleared.
+ #
+ # Step #1 / Get Title, et al
+ #
+ if stepCode == '0':
+ return { 'title': 'Basic Report Information',
+ 'content': (WizardText('Welcome to the sample report
wizard.'),
+ WizardText('To create your report, I need
to know some basic information.\n\n'
+ 'First, what shall I call your
report? This name will appear in '
+ 'the title bar.'),
+ WizardInput('title', label='Report Title:',
required=1,
+ size=40),
+ WizardText('What connection should this
report use to connect to the database?'),
+
WizardInput('connection',label='Connection:', required=1,
+
set=self.GetAvailableConnections()),
+ WizardText('You may be asked to login to
this connection.'),
+ ),
+ 'prev': None,
+ 'next': '1' }
- return { 'title': 'Select Base Table/Source',
- 'content': (WizardText('Now, please select the base table for
your report.'),
- WizardInput('table', label='Base Table:',
required=1, lines=5,
-
set=self.GetAvailableSources(self.variables['connection'])), ),
- 'prev': '0',
- 'next': '2' }
+ #
+ # Step #2 / Get Base Table
+ #
+ elif stepCode == '1':
- #
- # Step #3 / Get Columns to Include
- #
- elif stepCode == '2':
+ # TODO: If the connection changed between steps,
+ # TODO: variables['table'] and variables['fields']
+ # TODO: should be cleared.
- # TODO: If the table changed between steps,
- # TODO: variables['fields'] should be cleared.
+ return { 'title': 'Select Base Table/Source',
+ 'content': (WizardText('Now, please select the base
table for your report.'),
+ WizardInput('table', label='Base Table:',
required=1, lines=5,
+
set=self.GetAvailableSources(self.variables['connection'])), ),
+ 'prev': '0',
+ 'next': '2' }
- return { 'title': 'Select Fields to Include',
- 'content': (WizardText('Which fields shall I include in your
report?'),
- WizardInput('fields', label='Columns:',
required=1,
- maxSelections=-1, orderable=1,
- set=self.GetAvailableFields( \
- self.variables['connection'],
- self.variables['table'])), ),
- 'prev': '1',
- 'next': None }
+ #
+ # Step #3 / Get Columns to Include
+ #
+ elif stepCode == '2':
+ # TODO: If the table changed between steps,
+ # TODO: variables['fields'] should be cleared.
- ###############
- #
- # Verify contents of current step
- # Return None if no problems, otherwise
- # return a tuple of error message strings
- #
- def ValidateStep(self, stepCode):
+ return { 'title': 'Select Fields to Include',
+ 'content': (WizardText('Which fields shall I include in
your report?'),
+ WizardInput('fields', label='Columns:',
required=1,
+ maxSelections=-1, orderable=1,
+ set=self.GetAvailableFields( \
+
self.variables['connection'],
+
self.variables['table'])), ),
+ 'prev': '1',
+ 'next': None }
- # The Simple wizard uses basic "required"
- # settings in the page markup, so doesn't
- # need any special validation.
- return None
+ ###############
+ #
+ # Verify contents of current step
+ # Return None if no problems, otherwise
+ # return a tuple of error message strings
+ #
+ def ValidateStep(self, stepCode):
- ###############
- #
- # We have all the data, so generate our report. This
- # is called after the user clicks the "Finish" button.
- # No more user input is allowed at this point.
- #
- def Finalize(self):
- self.document.wizardName = TemplateInformation['Name']
+ # The Simple wizard uses basic "required"
+ # settings in the page markup, so doesn't
+ # need any special validation.
+ return None
- # We will use the table name as the basis for all our
- # object names. We will add a prefix based on the object
- # type to the table name. Capitalize the first letter and
- # strip all spaces...
- if len(self.variables['table']) == 1:
- tableKey = string.upper(self.variables['table'])
- else:
- tableKey = string.upper(self.variables['table'][0]) + \
- string.replace(self.variables['table'][1:],' ','_')
- # Get the common report objects
- report = self.report
- sources = self.current['sources']
- layout = self.current['layout']
- # Set the basic attributes of the report
- report['title'] = self.variables['title']
+ ###############
+ #
+ # We have all the data, so generate our report. This
+ # is called after the user clicks the "Finish" button.
+ # No more user input is allowed at this point.
+ #
+ def Finalize(self):
+ self.document.wizardName = TemplateInformation['Name']
- self.AddElement('trigger', report, {'name':"timestamp", 'type':"NAMED"}, \
- content ="from datetime import datetime \nreturn
datetime.now()")
+ # We will use the table name as the basis for all our
+ # object names. We will add a prefix based on the object
+ # type to the table name. Capitalize the first letter and
+ # strip all spaces...
+ if len(self.variables['table']) == 1:
+ tableKey = string.upper(self.variables['table'])
+ else:
+ tableKey = string.upper(self.variables['table'][0]) + \
+ string.replace(self.variables['table'][1:],' ','_')
- # Create a single datasource based on user's input
- datasource = self.AddElement('datasource', sources,
- { 'connection': self.variables['connection'],
- 'table': self.variables['table'],
- 'type': 'object',
- 'name': 'dts%s' % tableKey })
+ # Get the common report objects
+ report = self.report
+ sources = self.current['sources']
+ layout = self.current['layout']
- schema = self.GetSourceSchema(self.variables['connection'],
- self.variables['table'])
+ # Set the basic attributes of the report
+ report['title'] = self.variables['title']
- # Make a map of all the field schemas we will need
- # We will not actually create the entries at this point
- # because we want to keep in the order that the user
- # specified
- fields = {}
- for field in schema.findChildrenOfType ('GSField', False, True):
- if field.name in self.variables['fields']:
- fields[field.name] = field
+ self.AddElement('trigger', report, {'name':"timestamp",
'type':"NAMED"}, \
+ content ="from datetime import datetime \nreturn
datetime.now()")
- out_report = self.AddElement('out:chreport', layout, {'width':"80",
'height':"66"})
- out_pageheader = self.AddElement('out:pageheader', out_report,
{'height':"5"})
- self.AddElement('out:label', out_pageheader, {'width':"80",
'align':"center", 'x':"0", 'y':"1"}, \
- content=self.variables['title'])
+ # Create a single datasource based on user's input
+ datasource = self.AddElement('datasource', sources,
+ { 'connection': self.variables['connection'],
+ 'table': self.variables['table'],
+ 'type': 'object',
+ 'name': 'dts%s' % tableKey })
- start = 0
- for name in self.variables['fields']:
- field = fields[name]
- attrs = {}
- if hasattr (field, 'length'):
- length = field.length
- else:
- length = 10
- attrs ['width'] = length
- attrs['y'] = 3
- attrs['x'] = start
- if field.type == 'number':
- attrs['align'] = "right"
- start += length + 1
- self.AddElement('out:label', out_pageheader, attrs, content=field.name)
- attrs['y'] = 4
- self.AddElement('out:label', out_pageheader, attrs, content="-"*length)
+ schema = self.GetSourceSchema(self.variables['connection'],
+ self.variables['table'])
- section = self.AddElement('section', out_report, {'name': "detailes",
'source': datasource.name})
- out_detail = self.AddElement('out:detail', section, {'height':"2"})
+ # Make a map of all the field schemas we will need
+ # We will not actually create the entries at this point
+ # because we want to keep in the order that the user
+ # specified
+ fields = {}
+ for field in schema.findChildrenOfType ('GSField', False, True):
+ if field.name in self.variables['fields']:
+ fields[field.name] = field
- # Add each field
- start = 0
- for name in self.variables['fields']:
- field = fields[name]
- attrs = {}
- if hasattr (field, 'length'):
- length = field.length
- else:
- length = 10
- attrs ['width'] = length
- attrs['y'] = 0
- attrs['x'] = start
- if field.type == 'number':
- attrs['align'] = "right"
- start += length + 1
- out_label = self.AddElement('out:label', out_detail, attrs)
- self.AddElement('field', out_label, {'name':field.name})
+ out_report = self.AddElement('out:chreport', layout, {'width':"80",
'height':"66"})
+ out_pageheader = self.AddElement('out:pageheader', out_report,
{'height':"5"})
+ self.AddElement('out:label', out_pageheader, {'width':"80",
'align':"center", 'x':"0", 'y':"1"}, \
+ content=self.variables['title'])
- out_pagefooter = self.AddElement('out:pagefooter', out_report,
{'height':"2"})
- self.AddElement('out:label', out_pagefooter, {'width':"11", 'x':"0",
'y':"1"}, \
- content='Printed at:')
- out_label = self.AddElement('out:label', out_pagefooter, {'width':"25",
'x':"12", 'y':"1"})
- section = self.AddElement('section', out_label, {'name': "unbound"})
- formula = self.AddElement('formula', section, {'name':"stamp"})
- trigger = self.AddElement('trigger', formula, {'type':"On-Process",
'src':"timestamp"})
+ start = 0
+ for name in self.variables['fields']:
+ field = fields[name]
+ attrs = {}
+ if hasattr (field, 'length'):
+ length = field.length
+ else:
+ length = 10
+ attrs ['width'] = length
+ attrs['y'] = 3
+ attrs['x'] = start
+ if field.type == 'number':
+ attrs['align'] = "right"
+ start += length + 1
+ self.AddElement('out:label', out_pageheader, attrs,
content=field.name)
+ attrs['y'] = 4
+ self.AddElement('out:label', out_pageheader, attrs,
content="-"*length)
- # That's it... we're done.
- return 1
+ section = self.AddElement('section', out_report, {'name': "detailes",
'source': datasource.name})
+ out_detail = self.AddElement('out:detail', section, {'height':"2"})
+ # Add each field
+ start = 0
+ for name in self.variables['fields']:
+ field = fields[name]
+ attrs = {}
+ if hasattr (field, 'length'):
+ length = field.length
+ else:
+ length = 10
+ attrs ['width'] = length
+ attrs['y'] = 0
+ attrs['x'] = start
+ if field.type == 'number':
+ attrs['align'] = "right"
+ start += length + 1
+ out_label = self.AddElement('out:label', out_detail, attrs)
+ self.AddElement('field', out_label, {'name':field.name})
+ out_pagefooter = self.AddElement('out:pagefooter', out_report,
{'height':"2"})
+ self.AddElement('out:label', out_pagefooter, {'width':"11", 'x':"0",
'y':"1"}, \
+ content='Printed at:')
+ out_label = self.AddElement('out:label', out_pagefooter,
{'width':"25", 'x':"12", 'y':"1"})
+ section = self.AddElement('section', out_label, {'name': "unbound"})
+ formula = self.AddElement('formula', section, {'name':"stamp"})
+ trigger = self.AddElement('trigger', formula, {'type':"On-Process",
'src':"timestamp"})
+
+ # That's it... we're done.
+ return 1
+
+
############
#
# Basic information about this template
@@ -254,6 +254,3 @@
'Author' : 'The GNUe Designer Team',
'Behavior': WIZARD
}
-
-
-
Modified: trunk/gnue-designer/src/templates/reports/Labels.py
===================================================================
--- trunk/gnue-designer/src/templates/reports/Labels.py 2006-04-03 19:53:03 UTC
(rev 8343)
+++ trunk/gnue-designer/src/templates/reports/Labels.py 2006-04-03 19:56:14 UTC
(rev 8344)
@@ -41,155 +41,155 @@
class SimpleReportTemplate(ReportTemplate):
- # The first step in our wizard.
- # The template parser will initially
- # call GetStep(FIRST_STEP).
- FIRST_STEP = '0'
+ # The first step in our wizard.
+ # The template parser will initially
+ # call GetStep(FIRST_STEP).
+ FIRST_STEP = '0'
- ###############
- #
- # Initialize any runtime variables
- #
- def Start(self, report, current):
- self.report = report
- self.current = current
-
-
- ###############
- #
- # Return the markup for a specific page
- #
- def GetStep(self, stepCode):
-
+ ###############
#
- # Step #1 / Get Title, et al
+ # Initialize any runtime variables
#
- if stepCode == '0':
- return { 'title': 'Basic Report Information',
- 'content': (WizardText('Welcome to the labels wizard.'),
- WizardText('To create your report, I need to know
some basic information.\n\n'
- 'First, what connection should
this report use to connect to the database?'),
- WizardInput('connection',label='Connection:',
required=1,
- set=self.GetAvailableConnections()),
- WizardText('You may be asked to login to this
connection.'),
- ),
- 'prev': None,
- 'next': '1' }
+ def Start(self, report, current):
+ self.report = report
+ self.current = current
+ ###############
#
- # Step #2 / Get Base Table
+ # Return the markup for a specific page
#
- elif stepCode == '1':
+ def GetStep(self, stepCode):
- # TODO: If the connection changed between steps,
- # TODO: variables['table'] and variables['fields']
- # TODO: should be cleared.
+ #
+ # Step #1 / Get Title, et al
+ #
+ if stepCode == '0':
+ return { 'title': 'Basic Report Information',
+ 'content': (WizardText('Welcome to the labels wizard.'),
+ WizardText('To create your report, I need
to know some basic information.\n\n'
+ 'First, what connection
should this report use to connect to the database?'),
+
WizardInput('connection',label='Connection:', required=1,
+
set=self.GetAvailableConnections()),
+ WizardText('You may be asked to login to
this connection.'),
+ ),
+ 'prev': None,
+ 'next': '1' }
- return { 'title': 'Select Base Table/Source',
- 'content': (WizardText('Now, please select the base table for
your report.'),
- WizardInput('table', label='Base Table:',
required=1, lines=5,
-
set=self.GetAvailableSources(self.variables['connection'])), ),
- 'prev': '0',
- 'next': '2' }
+ #
+ # Step #2 / Get Base Table
+ #
+ elif stepCode == '1':
- #
- # Step #3 / Get Columns to Include
- #
- elif stepCode == '2':
+ # TODO: If the connection changed between steps,
+ # TODO: variables['table'] and variables['fields']
+ # TODO: should be cleared.
- # TODO: If the table changed between steps,
- # TODO: variables['fields'] should be cleared.
+ return { 'title': 'Select Base Table/Source',
+ 'content': (WizardText('Now, please select the base
table for your report.'),
+ WizardInput('table', label='Base Table:',
required=1, lines=5,
+
set=self.GetAvailableSources(self.variables['connection'])), ),
+ 'prev': '0',
+ 'next': '2' }
- return { 'title': 'Select Fields to Include',
- 'content': (WizardText('Which fields shall I include in your
report?'),
- WizardInput('fields', label='Columns:',
required=1,
- maxSelections=-1, orderable=1,
- set=self.GetAvailableFields( \
- self.variables['connection'],
- self.variables['table'])), ),
- 'prev': '1',
- 'next': None }
+ #
+ # Step #3 / Get Columns to Include
+ #
+ elif stepCode == '2':
+ # TODO: If the table changed between steps,
+ # TODO: variables['fields'] should be cleared.
- ###############
- #
- # Verify contents of current step
- # Return None if no problems, otherwise
- # return a tuple of error message strings
- #
- def ValidateStep(self, stepCode):
+ return { 'title': 'Select Fields to Include',
+ 'content': (WizardText('Which fields shall I include in
your report?'),
+ WizardInput('fields', label='Columns:',
required=1,
+ maxSelections=-1, orderable=1,
+ set=self.GetAvailableFields( \
+
self.variables['connection'],
+
self.variables['table'])), ),
+ 'prev': '1',
+ 'next': None }
- # The Simple wizard uses basic "required"
- # settings in the page markup, so doesn't
- # need any special validation.
- return None
+ ###############
+ #
+ # Verify contents of current step
+ # Return None if no problems, otherwise
+ # return a tuple of error message strings
+ #
+ def ValidateStep(self, stepCode):
- ###############
- #
- # We have all the data, so generate our report. This
- # is called after the user clicks the "Finish" button.
- # No more user input is allowed at this point.
- #
- def Finalize(self):
- self.document.wizardName = TemplateInformation['Name']
+ # The Simple wizard uses basic "required"
+ # settings in the page markup, so doesn't
+ # need any special validation.
+ return None
- # We will use the table name as the basis for all our
- # object names. We will add a prefix based on the object
- # type to the table name. Capitalize the first letter and
- # strip all spaces...
- if len(self.variables['table']) == 1:
- tableKey = string.upper(self.variables['table'])
- else:
- tableKey = string.upper(self.variables['table'][0]) + \
- string.replace(self.variables['table'][1:],' ','_')
- # Get the common report objects
- report = self.report
- sources = self.current['sources']
- layout = self.current['layout']
+ ###############
+ #
+ # We have all the data, so generate our report. This
+ # is called after the user clicks the "Finish" button.
+ # No more user input is allowed at this point.
+ #
+ def Finalize(self):
+ self.document.wizardName = TemplateInformation['Name']
+ # We will use the table name as the basis for all our
+ # object names. We will add a prefix based on the object
+ # type to the table name. Capitalize the first letter and
+ # strip all spaces...
+ if len(self.variables['table']) == 1:
+ tableKey = string.upper(self.variables['table'])
+ else:
+ tableKey = string.upper(self.variables['table'][0]) + \
+ string.replace(self.variables['table'][1:],' ','_')
- # Create a single datasource based on user's input
- datasource = self.AddElement('datasource', sources,
- { 'database': self.variables['connection'],
- 'table': self.variables['table'],
- 'type': 'object',
- 'name': 'dts%s' % tableKey })
- schema = self.GetSourceSchema(self.variables['connection'],
- self.variables['table'])
+ # Get the common report objects
+ report = self.report
+ sources = self.current['sources']
+ layout = self.current['layout']
- # Make a map of all the field schemas we will need
- # We will not actually create the entries at this point
- # because we want to keep in the order that the user
- # specified
- fields = {}
- for field in schema.findChildrenOfType ('GSField', False, True):
- if field.name in self.variables['fields']:
- fields[field.name] = field
- out_labels = self.AddElement('out:labels', layout, {})
- section = self.AddElement('section', out_labels, {'source':
datasource.name})
- out_label = self.AddElement('out:label', section, {})
- out_region = self.AddElement('out:region', out_label, {'name':"primary"})
+ # Create a single datasource based on user's input
+ datasource = self.AddElement('datasource', sources,
+ { 'database': self.variables['connection'],
+ 'table': self.variables['table'],
+ 'type': 'object',
+ 'name': 'dts%s' % tableKey })
- # Add each field
- for name in self.variables['fields']:
- field = fields[name]
- out_line = self.AddElement('out:line', out_region, {})
- self.AddElement('field', out_line, {'name':field.name})
+ schema = self.GetSourceSchema(self.variables['connection'],
+ self.variables['table'])
- # That's it... we're done.
- return 1
+ # Make a map of all the field schemas we will need
+ # We will not actually create the entries at this point
+ # because we want to keep in the order that the user
+ # specified
+ fields = {}
+ for field in schema.findChildrenOfType ('GSField', False, True):
+ if field.name in self.variables['fields']:
+ fields[field.name] = field
+ out_labels = self.AddElement('out:labels', layout, {})
+ section = self.AddElement('section', out_labels, {'source':
datasource.name})
+ out_label = self.AddElement('out:label', section, {})
+ out_region = self.AddElement('out:region', out_label,
{'name':"primary"})
+ # Add each field
+ for name in self.variables['fields']:
+ field = fields[name]
+ out_line = self.AddElement('out:line', out_region, {})
+ self.AddElement('field', out_line, {'name':field.name})
+
+ # That's it... we're done.
+ return 1
+
+
############
#
# Basic information about this template
@@ -205,6 +205,3 @@
'Author' : 'The GNUe Designer Team',
'Behavior': WIZARD
}
-
-
-
Modified: trunk/gnue-designer/src/templates/reports/MailMerge.py
===================================================================
--- trunk/gnue-designer/src/templates/reports/MailMerge.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/templates/reports/MailMerge.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -41,150 +41,150 @@
class SimpleReportTemplate(ReportTemplate):
- # The first step in our wizard.
- # The template parser will initially
- # call GetStep(FIRST_STEP).
- FIRST_STEP = '0'
+ # The first step in our wizard.
+ # The template parser will initially
+ # call GetStep(FIRST_STEP).
+ FIRST_STEP = '0'
- ###############
- #
- # Initialize any runtime variables
- #
- def Start(self, report, current):
- self.report = report
- self.current = current
-
-
- ###############
- #
- # Return the markup for a specific page
- #
- def GetStep(self, stepCode):
-
+ ###############
#
- # Step #1 / Get Title, et al
+ # Initialize any runtime variables
#
- if stepCode == '0':
- return { 'title': 'Basic Report Information',
- 'content': (WizardText('Welcome to the mailmerge wizard.'),
- WizardText('To create your report, I need to know
some basic information.\n\n'
- 'First, what connection should
this report use to connect to the database?'),
- WizardInput('connection',label='Connection:',
required=1,
- set=self.GetAvailableConnections()),
- WizardText('You may be asked to login to this
connection.'),
- ),
- 'prev': None,
- 'next': '1' }
+ def Start(self, report, current):
+ self.report = report
+ self.current = current
+ ###############
#
- # Step #2 / Get Base Table
+ # Return the markup for a specific page
#
- elif stepCode == '1':
+ def GetStep(self, stepCode):
- # TODO: If the connection changed between steps,
- # TODO: variables['table'] and variables['fields']
- # TODO: should be cleared.
+ #
+ # Step #1 / Get Title, et al
+ #
+ if stepCode == '0':
+ return { 'title': 'Basic Report Information',
+ 'content': (WizardText('Welcome to the mailmerge
wizard.'),
+ WizardText('To create your report, I need
to know some basic information.\n\n'
+ 'First, what connection
should this report use to connect to the database?'),
+
WizardInput('connection',label='Connection:', required=1,
+
set=self.GetAvailableConnections()),
+ WizardText('You may be asked to login to
this connection.'),
+ ),
+ 'prev': None,
+ 'next': '1' }
- return { 'title': 'Select Base Table/Source',
- 'content': (WizardText('Now, please select the base table for
your report.'),
- WizardInput('table', label='Base Table:',
required=1, lines=5,
-
set=self.GetAvailableSources(self.variables['connection'])), ),
- 'prev': '0',
- 'next': '2' }
+ #
+ # Step #2 / Get Base Table
+ #
+ elif stepCode == '1':
- #
- # Step #3 / Get Columns to Include
- #
- elif stepCode == '2':
+ # TODO: If the connection changed between steps,
+ # TODO: variables['table'] and variables['fields']
+ # TODO: should be cleared.
- # TODO: If the table changed between steps,
- # TODO: variables['fields'] should be cleared.
+ return { 'title': 'Select Base Table/Source',
+ 'content': (WizardText('Now, please select the base
table for your report.'),
+ WizardInput('table', label='Base Table:',
required=1, lines=5,
+
set=self.GetAvailableSources(self.variables['connection'])), ),
+ 'prev': '0',
+ 'next': '2' }
- return { 'title': 'Select Fields to Include',
- 'content': (WizardText('Which fields shall I include in your
report?'),
- WizardInput('fields', label='Columns:',
required=1,
- maxSelections=-1, orderable=1,
- set=self.GetAvailableFields( \
- self.variables['connection'],
- self.variables['table'])), ),
- 'prev': '1',
- 'next': None }
+ #
+ # Step #3 / Get Columns to Include
+ #
+ elif stepCode == '2':
+ # TODO: If the table changed between steps,
+ # TODO: variables['fields'] should be cleared.
- ###############
- #
- # Verify contents of current step
- # Return None if no problems, otherwise
- # return a tuple of error message strings
- #
- def ValidateStep(self, stepCode):
+ return { 'title': 'Select Fields to Include',
+ 'content': (WizardText('Which fields shall I include in
your report?'),
+ WizardInput('fields', label='Columns:',
required=1,
+ maxSelections=-1, orderable=1,
+ set=self.GetAvailableFields( \
+
self.variables['connection'],
+
self.variables['table'])), ),
+ 'prev': '1',
+ 'next': None }
- # The Simple wizard uses basic "required"
- # settings in the page markup, so doesn't
- # need any special validation.
- return None
+ ###############
+ #
+ # Verify contents of current step
+ # Return None if no problems, otherwise
+ # return a tuple of error message strings
+ #
+ def ValidateStep(self, stepCode):
- ###############
- #
- # We have all the data, so generate our report. This
- # is called after the user clicks the "Finish" button.
- # No more user input is allowed at this point.
- #
- def Finalize(self):
- self.document.wizardName = TemplateInformation['Name']
+ # The Simple wizard uses basic "required"
+ # settings in the page markup, so doesn't
+ # need any special validation.
+ return None
- # We will use the table name as the basis for all our
- # object names. We will add a prefix based on the object
- # type to the table name. Capitalize the first letter and
- # strip all spaces...
- if len(self.variables['table']) == 1:
- tableKey = string.upper(self.variables['table'])
- else:
- tableKey = string.upper(self.variables['table'][0]) + \
- string.replace(self.variables['table'][1:],' ','_')
- # Get the common report objects
- report = self.report
- sources = self.current['sources']
- layout = self.current['layout']
- # Create a single datasource based on user's input
- datasource = self.AddElement('datasource', sources,
- { 'database': self.variables['connection'],
- 'table': self.variables['table'],
- 'type': 'object',
- 'name': 'dts%s' % tableKey })
+ ###############
+ #
+ # We have all the data, so generate our report. This
+ # is called after the user clicks the "Finish" button.
+ # No more user input is allowed at this point.
+ #
+ def Finalize(self):
+ self.document.wizardName = TemplateInformation['Name']
- schema = self.GetSourceSchema(self.variables['connection'],
- self.variables['table'])
+ # We will use the table name as the basis for all our
+ # object names. We will add a prefix based on the object
+ # type to the table name. Capitalize the first letter and
+ # strip all spaces...
+ if len(self.variables['table']) == 1:
+ tableKey = string.upper(self.variables['table'])
+ else:
+ tableKey = string.upper(self.variables['table'][0]) + \
+ string.replace(self.variables['table'][1:],' ','_')
- # Make a map of all the field schemas we will need
- # We will not actually create the entries at this point
- # because we want to keep in the order that the user
- # specified
- fields = {}
- for field in schema.findChildrenOfType ('GSField', False, True):
- if field.name in self.variables['fields']:
- fields[field.name] = field
+ # Get the common report objects
+ report = self.report
+ sources = self.current['sources']
+ layout = self.current['layout']
- out_mailmerge = self.AddElement('out:mailmerge', layout, {})
- section = self.AddElement('section', out_mailmerge, {'source':
datasource.name})
- out_record = self.AddElement('out:record', section, {})
+ # Create a single datasource based on user's input
+ datasource = self.AddElement('datasource', sources,
+ { 'database': self.variables['connection'],
+ 'table': self.variables['table'],
+ 'type': 'object',
+ 'name': 'dts%s' % tableKey })
+ schema = self.GetSourceSchema(self.variables['connection'],
+ self.variables['table'])
+
+ # Make a map of all the field schemas we will need
+ # We will not actually create the entries at this point
+ # because we want to keep in the order that the user
+ # specified
+ fields = {}
+ for field in schema.findChildrenOfType ('GSField', False, True):
+ if field.name in self.variables['fields']:
+ fields[field.name] = field
+
+ out_mailmerge = self.AddElement('out:mailmerge', layout, {})
+ section = self.AddElement('section', out_mailmerge, {'source':
datasource.name})
+ out_record = self.AddElement('out:record', section, {})
+
# Add each field
- for name in self.variables['fields']:
- field = fields[name]
- out_field = self.AddElement('out:field', out_record, {'name':field.name})
- self.AddElement('field', out_field, {'name':field.name})
+ for name in self.variables['fields']:
+ field = fields[name]
+ out_field = self.AddElement('out:field', out_record,
{'name':field.name})
+ self.AddElement('field', out_field, {'name':field.name})
- # That's it... we're done.
- return 1
+ # That's it... we're done.
+ return 1
############
@@ -202,6 +202,3 @@
'Author' : 'The GNUe Designer Team',
'Behavior': WIZARD
}
-
-
-
Modified: trunk/gnue-designer/src/templates/reports/SimpleReport.py
===================================================================
--- trunk/gnue-designer/src/templates/reports/SimpleReport.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/templates/reports/SimpleReport.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -41,180 +41,180 @@
class SimpleReportTemplate(ReportTemplate):
- # The first step in our wizard.
- # The template parser will initially
- # call GetStep(FIRST_STEP).
- FIRST_STEP = '0'
+ # The first step in our wizard.
+ # The template parser will initially
+ # call GetStep(FIRST_STEP).
+ FIRST_STEP = '0'
- ###############
- #
- # Initialize any runtime variables
- #
- def Start(self, report, current):
- self.report = report
- self.current = current
-
-
- ###############
- #
- # Return the markup for a specific page
- #
- def GetStep(self, stepCode):
-
+ ###############
#
- # Step #1 / Get Title, et al
+ # Initialize any runtime variables
#
- if stepCode == '0':
- return { 'title': 'Basic Report Information',
- 'content': (WizardText('Welcome to the sample report
wizard.'),
- WizardText('To create your report, I need to know
some basic information.\n\n'
- 'First, what shall I call your report?
This name will appear in '
- 'the title bar.'),
- WizardInput('title', label='Report Title:',
required=1,
- size=40),
- WizardText('What connection should this report
use to connect to the database?'),
- WizardInput('connection',label='Connection:',
required=1,
- set=self.GetAvailableConnections()),
- WizardText('You may be asked to login to this
connection.'),
- ),
- 'prev': None,
- 'next': '1' }
+ def Start(self, report, current):
+ self.report = report
+ self.current = current
+ ###############
#
- # Step #2 / Get Base Table
+ # Return the markup for a specific page
#
- elif stepCode == '1':
+ def GetStep(self, stepCode):
- # TODO: If the connection changed between steps,
- # TODO: variables['table'] and variables['fields']
- # TODO: should be cleared.
+ #
+ # Step #1 / Get Title, et al
+ #
+ if stepCode == '0':
+ return { 'title': 'Basic Report Information',
+ 'content': (WizardText('Welcome to the sample report
wizard.'),
+ WizardText('To create your report, I need
to know some basic information.\n\n'
+ 'First, what shall I call your
report? This name will appear in '
+ 'the title bar.'),
+ WizardInput('title', label='Report Title:',
required=1,
+ size=40),
+ WizardText('What connection should this
report use to connect to the database?'),
+
WizardInput('connection',label='Connection:', required=1,
+
set=self.GetAvailableConnections()),
+ WizardText('You may be asked to login to
this connection.'),
+ ),
+ 'prev': None,
+ 'next': '1' }
- return { 'title': 'Select Base Table/Source',
- 'content': (WizardText('Now, please select the base table for
your report.'),
- WizardInput('table', label='Base Table:',
required=1, lines=5,
-
set=self.GetAvailableSources(self.variables['connection'])), ),
- 'prev': '0',
- 'next': '2' }
+ #
+ # Step #2 / Get Base Table
+ #
+ elif stepCode == '1':
- #
- # Step #3 / Get Columns to Include
- #
- elif stepCode == '2':
+ # TODO: If the connection changed between steps,
+ # TODO: variables['table'] and variables['fields']
+ # TODO: should be cleared.
- # TODO: If the table changed between steps,
- # TODO: variables['fields'] should be cleared.
+ return { 'title': 'Select Base Table/Source',
+ 'content': (WizardText('Now, please select the base
table for your report.'),
+ WizardInput('table', label='Base Table:',
required=1, lines=5,
+
set=self.GetAvailableSources(self.variables['connection'])), ),
+ 'prev': '0',
+ 'next': '2' }
- return { 'title': 'Select Fields to Include',
- 'content': (WizardText('Which fields shall I include in your
report?'),
- WizardInput('fields', label='Columns:',
required=1,
- maxSelections=-1, orderable=1,
- set=self.GetAvailableFields( \
- self.variables['connection'],
- self.variables['table'])), ),
- 'prev': '1',
- 'next': None }
+ #
+ # Step #3 / Get Columns to Include
+ #
+ elif stepCode == '2':
+ # TODO: If the table changed between steps,
+ # TODO: variables['fields'] should be cleared.
- ###############
- #
- # Verify contents of current step
- # Return None if no problems, otherwise
- # return a tuple of error message strings
- #
- def ValidateStep(self, stepCode):
+ return { 'title': 'Select Fields to Include',
+ 'content': (WizardText('Which fields shall I include in
your report?'),
+ WizardInput('fields', label='Columns:',
required=1,
+ maxSelections=-1, orderable=1,
+ set=self.GetAvailableFields( \
+
self.variables['connection'],
+
self.variables['table'])), ),
+ 'prev': '1',
+ 'next': None }
- # The Simple wizard uses basic "required"
- # settings in the page markup, so doesn't
- # need any special validation.
- return None
+ ###############
+ #
+ # Verify contents of current step
+ # Return None if no problems, otherwise
+ # return a tuple of error message strings
+ #
+ def ValidateStep(self, stepCode):
- ###############
- #
- # We have all the data, so generate our report. This
- # is called after the user clicks the "Finish" button.
- # No more user input is allowed at this point.
- #
- def Finalize(self):
- self.document.wizardName = TemplateInformation['Name']
+ # The Simple wizard uses basic "required"
+ # settings in the page markup, so doesn't
+ # need any special validation.
+ return None
- # We will use the table name as the basis for all our
- # object names. We will add a prefix based on the object
- # type to the table name. Capitalize the first letter and
- # strip all spaces...
- if len(self.variables['table']) == 1:
- tableKey = string.upper(self.variables['table'])
- else:
- tableKey = string.upper(self.variables['table'][0]) + \
- string.replace(self.variables['table'][1:],' ','_')
- # Get the common report objects
- report = self.report
- sources = self.current['sources']
- layout = self.current['layout']
- # Set the basic attributes of the report
- report['title'] = self.variables['title']
+ ###############
+ #
+ # We have all the data, so generate our report. This
+ # is called after the user clicks the "Finish" button.
+ # No more user input is allowed at this point.
+ #
+ def Finalize(self):
+ self.document.wizardName = TemplateInformation['Name']
- # Create a single datasource based on user's input
- datasource = self.AddElement('datasource', sources,
- { 'connection': self.variables['connection'],
- 'table': self.variables['table'],
- 'type': 'object',
- 'name': 'dts%s' % tableKey })
+ # We will use the table name as the basis for all our
+ # object names. We will add a prefix based on the object
+ # type to the table name. Capitalize the first letter and
+ # strip all spaces...
+ if len(self.variables['table']) == 1:
+ tableKey = string.upper(self.variables['table'])
+ else:
+ tableKey = string.upper(self.variables['table'][0]) + \
+ string.replace(self.variables['table'][1:],' ','_')
- schema = self.GetSourceSchema(self.variables['connection'],
- self.variables['table'])
+ # Get the common report objects
+ report = self.report
+ sources = self.current['sources']
+ layout = self.current['layout']
- # Make a map of all the field schemas we will need
- # We will not actually create the entries at this point
- # because we want to keep in the order that the user
- # specified
- fields = {}
- for field in schema.findChildrenOfType ('GSField', False, True):
- if field.name in self.variables['fields']:
- fields[field.name] = field
+ # Set the basic attributes of the report
+ report['title'] = self.variables['title']
- out_report = self.AddElement('out:report', layout, {})
- out_reportTitle = self.AddElement('out:reportTitle', out_report, {},
content=self.variables['title'])
- out_section = self.AddElement('out:section', out_report, {'break':"page"})
- out_table = self.AddElement('out:table', out_section, {'width':"100%"})
- out_tablehead = self.AddElement('out:tablehead', out_table, {})
+ # Create a single datasource based on user's input
+ datasource = self.AddElement('datasource', sources,
+ { 'connection': self.variables['connection'],
+ 'table': self.variables['table'],
+ 'type': 'object',
+ 'name': 'dts%s' % tableKey })
- for name in self.variables['fields']:
- field = fields[name]
- attrs = {}
- if hasattr (field, 'length'):
- attrs ['width'] = field.length
- if field.type == 'number':
- attrs['align'] = "right"
- elif field.type in ['date', 'time', 'datetime']:
- attrs['align'] = "center"
- out_colhead = self.AddElement('out:colhead', out_tablehead, attrs,
content=field.name)
+ schema = self.GetSourceSchema(self.variables['connection'],
+ self.variables['table'])
- section = self.AddElement('section', out_table, {'name': "detailes",
'source': datasource.name})
- out_row = self.AddElement('out:row', section, {})
+ # Make a map of all the field schemas we will need
+ # We will not actually create the entries at this point
+ # because we want to keep in the order that the user
+ # specified
+ fields = {}
+ for field in schema.findChildrenOfType ('GSField', False, True):
+ if field.name in self.variables['fields']:
+ fields[field.name] = field
- # Add each field
- for name in self.variables['fields']:
- field = fields[name]
- attrs = {}
- if field.type == 'number':
- attrs['align'] = "right"
- elif field.type in ['date', 'time', 'datetime']:
- attrs['align'] = "center"
- out_col = self.AddElement('out:col', out_row, attrs)
- self.AddElement('field', out_col, {'name':field.name})
+ out_report = self.AddElement('out:report', layout, {})
+ out_reportTitle = self.AddElement('out:reportTitle', out_report, {},
content=self.variables['title'])
+ out_section = self.AddElement('out:section', out_report,
{'break':"page"})
+ out_table = self.AddElement('out:table', out_section, {'width':"100%"})
+ out_tablehead = self.AddElement('out:tablehead', out_table, {})
- # That's it... we're done.
- return 1
+ for name in self.variables['fields']:
+ field = fields[name]
+ attrs = {}
+ if hasattr (field, 'length'):
+ attrs ['width'] = field.length
+ if field.type == 'number':
+ attrs['align'] = "right"
+ elif field.type in ['date', 'time', 'datetime']:
+ attrs['align'] = "center"
+ out_colhead = self.AddElement('out:colhead', out_tablehead, attrs,
content=field.name)
+ section = self.AddElement('section', out_table, {'name': "detailes",
'source': datasource.name})
+ out_row = self.AddElement('out:row', section, {})
+ # Add each field
+ for name in self.variables['fields']:
+ field = fields[name]
+ attrs = {}
+ if field.type == 'number':
+ attrs['align'] = "right"
+ elif field.type in ['date', 'time', 'datetime']:
+ attrs['align'] = "center"
+ out_col = self.AddElement('out:col', out_row, attrs)
+ self.AddElement('field', out_col, {'name':field.name})
+
+ # That's it... we're done.
+ return 1
+
+
############
#
# Basic information about this template
@@ -230,6 +230,3 @@
'Author' : 'The GNUe Designer Team',
'Behavior': WIZARD
}
-
-
-
Modified: trunk/gnue-designer/src/templates/reports/__init__.py
===================================================================
--- trunk/gnue-designer/src/templates/reports/__init__.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/templates/reports/__init__.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -32,4 +32,4 @@
# Raises an import error if Reports isn't valid on this machine
-import gnue.reports as _test
\ No newline at end of file
+import gnue.reports as _test
Modified: trunk/gnue-designer/src/templates/schema/Introspection.py
===================================================================
--- trunk/gnue-designer/src/templates/schema/Introspection.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/templates/schema/Introspection.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -42,185 +42,185 @@
class SchemaIntrospectionTemplate(SchemaTemplate):
- # The first step in our wizard.
- # The template parser will initially
- # call GetStep(FIRST_STEP).
- FIRST_STEP = '0'
+ # The first step in our wizard.
+ # The template parser will initially
+ # call GetStep(FIRST_STEP).
+ FIRST_STEP = '0'
- ###############
- #
- # Initialize any runtime variables
- #
- def Start(self, root, current):
- self.root = root
+ ###############
+ #
+ # Initialize any runtime variables
+ #
+ def Start(self, root, current):
+ self.root = root
- ###############
- #
- # Return the markup for a specific page
- #
- def GetStep(self, stepCode):
-
+ ###############
#
- # Step #1 / Get Title, et al
+ # Return the markup for a specific page
#
- if stepCode == '0':
- return { 'title': 'Basic Form Information',
- 'content': (WizardText('Welcome to the introspection schema
wizard.'),
- WizardText('To create your schema, I need to know
some basic information.\n\n'
- 'First, what shall I call this schema?
This name is for '
- 'informational use only.'),
- WizardInput('title', label='Schema Name:',
required=1,
- size=40),
- WizardText('What connection should we use to
connect to the database for introspection?'),
- WizardInput('connection',label='Connection:',
required=1,
- set=self.GetAvailableConnections()),
- WizardText('You may be asked to login to this
connection.'),
- ),
- 'prev': None,
- 'next': '1' }
+ def GetStep(self, stepCode):
+ #
+ # Step #1 / Get Title, et al
+ #
+ if stepCode == '0':
+ return { 'title': 'Basic Form Information',
+ 'content': (WizardText('Welcome to the introspection
schema wizard.'),
+ WizardText('To create your schema, I need
to know some basic information.\n\n'
+ 'First, what shall I call this
schema? This name is for '
+ 'informational use only.'),
+ WizardInput('title', label='Schema Name:',
required=1,
+ size=40),
+ WizardText('What connection should we use
to connect to the database for introspection?'),
+
WizardInput('connection',label='Connection:', required=1,
+
set=self.GetAvailableConnections()),
+ WizardText('You may be asked to login to
this connection.'),
+ ),
+ 'prev': None,
+ 'next': '1' }
- #
- # Step #2 / Get Tables to Include
- #
- elif stepCode == '1':
- return { 'title': 'Select Tables to Include',
- 'content': (WizardText('Which tables shall I include in your
schema?'),
- WizardInput('tables', label='Tables:', required=1,
- maxSelections=-1, orderable=1,
-
set=self.GetAvailableSources(self.variables['connection']))),
- 'prev': '1',
- 'next': None }
+ #
+ # Step #2 / Get Tables to Include
+ #
+ elif stepCode == '1':
+ return { 'title': 'Select Tables to Include',
+ 'content': (WizardText('Which tables shall I include in
your schema?'),
+ WizardInput('tables', label='Tables:',
required=1,
+ maxSelections=-1, orderable=1,
+
set=self.GetAvailableSources(self.variables['connection']))),
+ 'prev': '1',
+ 'next': None }
- ###############
- #
- # Verify contents of current step
- # Return None if no problems, otherwise
- # return a tuple of error message strings
- #
- def ValidateStep(self, stepCode):
- # The Simple wizard uses basic "required"
- # settings in the page markup, so doesn't
- # need any special validation.
- return None
+ ###############
+ #
+ # Verify contents of current step
+ # Return None if no problems, otherwise
+ # return a tuple of error message strings
+ #
+ def ValidateStep(self, stepCode):
+ # The Simple wizard uses basic "required"
+ # settings in the page markup, so doesn't
+ # need any special validation.
+ return None
- ###############
- #
- # We have all the data, so generate our schema. This
- # is called after the user clicks the "Finish" button.
- # No more user input is allowed at this point.
- #
- def Finalize(self):
- self.document.wizardName = TemplateInformation['Name']
- # Set the basic attributes of the schema
- self.ModifyElement(self.root, title=self.variables['title'])
+ ###############
+ #
+ # We have all the data, so generate our schema. This
+ # is called after the user clicks the "Finish" button.
+ # No more user input is allowed at this point.
+ #
+ def Finalize(self):
+ self.document.wizardName = TemplateInformation['Name']
- conn = self.variables['connection']
+ # Set the basic attributes of the schema
+ self.ModifyElement(self.root, title=self.variables['title'])
- # Sort the table names to create a prettier file.
- tablesorted = self.variables['tables']
- tablesorted.sort()
+ conn = self.variables['connection']
+ # Sort the table names to create a prettier file.
+ tablesorted = self.variables['tables']
+ tablesorted.sort()
- # Create the tables and fields...
- print "Adding <tables>"
- # FIXME: this code is kind of obsolete, since self.GetSourceSchema already
- # returns a complete GSTable object tree. So the only thing needed
- # here would be add a clone of that tree to the local object tree
- tables = self.root.findChildOfType('GSTables') #self.AddElement('tables',
self.root, {})
+ # Create the tables and fields...
+ print "Adding <tables>"
+ # FIXME: this code is kind of obsolete, since self.GetSourceSchema
already
+ # returns a complete GSTable object tree. So the only thing
needed
+ # here would be add a clone of that tree to the local object
tree
+ tables = self.root.findChildOfType('GSTables')
#self.AddElement('tables', self.root, {})
- # Create each table
- for tablename in tablesorted:
- print "Adding <table> %s" % tablename
- schema = self.GetSourceSchema(conn, tablename)
- table = self.AddElement( 'table', tables,
- { 'name': tablename } )
- try:
- primarykeys = schema.findChildOfType ('GSPrimaryKey')
- except:
- primarykeys = None
+ # Create each table
+ for tablename in tablesorted:
+ print "Adding <table> %s" % tablename
+ schema = self.GetSourceSchema(conn, tablename)
+ table = self.AddElement( 'table', tables,
+ { 'name': tablename } )
- fields = self.AddElement('fields', table, {})
+ try:
+ primarykeys = schema.findChildOfType ('GSPrimaryKey')
+ except:
+ primarykeys = None
- # Add each field
- for field in schema.findChildrenOfType ('GSField', False, True):
- print " Adding <field> %s" % field.name
- attrs = { 'name': field.name,
- 'type': field.type }
+ fields = self.AddElement('fields', table, {})
- # Add length if appropriate for this datatype
- # FIXME: this should be handled much more cleaner !!!
- try:
- if field.type != 'date':
- attrs['length'] = int(field.length)
- except AttributeError:
- if field.type == 'number':
- attrs['length'] = 12
- elif field.type == 'string':
- attrs['length'] = 200
+ # Add each field
+ for field in schema.findChildrenOfType ('GSField', False, True):
+ print " Adding <field> %s" % field.name
+ attrs = { 'name': field.name,
+ 'type': field.type }
- # ... precision
- try:
- attrs['precision'] = int(field.precision)
- except AttributeError:
- pass
+ # Add length if appropriate for this datatype
+ # FIXME: this should be handled much more cleaner !!!
+ try:
+ if field.type != 'date':
+ attrs['length'] = int(field.length)
+ except AttributeError:
+ if field.type == 'number':
+ attrs['length'] = 12
+ elif field.type == 'string':
+ attrs['length'] = 200
- # Add length if appropriate for this datatype
- try:
- attrs['nullable'] = field.nullable
- except AttributeError:
- attrs['nullable'] = 1
+ # ... precision
+ try:
+ attrs['precision'] = int(field.precision)
+ except AttributeError:
+ pass
- # ... default values?
- if hasattr(field,'defaulttype'):
- if field.defaulttype == 'serial':
- attrs['defaultwith'] = 'serial'
- if field.name in primarykeys and field.type == 'number':
- attrs['type'] = 'key'
- elif field.defaulttype == 'sequence':
- attrs['defaultwith'] = 'sequence'
- attrs['default'] = field.defaultval
- elif field.defaulttype == 'constant':
- attrs['defaultwith'] = 'constant'
- attrs['default'] = field.defaultval
+ # Add length if appropriate for this datatype
+ try:
+ attrs['nullable'] = field.nullable
+ except AttributeError:
+ attrs['nullable'] = 1
+ # ... default values?
+ if hasattr(field,'defaulttype'):
+ if field.defaulttype == 'serial':
+ attrs['defaultwith'] = 'serial'
+ if field.name in primarykeys and field.type ==
'number':
+ attrs['type'] = 'key'
+ elif field.defaulttype == 'sequence':
+ attrs['defaultwith'] = 'sequence'
+ attrs['default'] = field.defaultval
+ elif field.defaulttype == 'constant':
+ attrs['defaultwith'] = 'constant'
+ attrs['default'] = field.defaultval
- # Create the field element
- self.AddElement('field', fields, attrs)
- # Primary keys
- if primarykeys:
- pk = self.AddElement ('primarykey', table, {})
- pk.name='pk_%s' % tablename
- for field in primarykeys.findChildrenOfType ('GSPKField', False, True):
- self.AddElement('pkfield', pk, {'name': field})
+ # Create the field element
+ self.AddElement('field', fields, attrs)
- # Add misc tags
- # TODO: a GSTable instance as returned by GetSourceSchema () might
- # already contain indices and constraints too!
- self.AddElement ('constraints', table, {})
- self.AddElement ('indexes', table, {})
+ # Primary keys
+ if primarykeys:
+ pk = self.AddElement ('primarykey', table, {})
+ pk.name='pk_%s' % tablename
+ for field in primarykeys.findChildrenOfType ('GSPKField',
False, True):
+ self.AddElement('pkfield', pk, {'name': field})
+ # Add misc tags
+ # TODO: a GSTable instance as returned by GetSourceSchema () might
+ # already contain indices and constraints too!
+ self.AddElement ('constraints', table, {})
+ self.AddElement ('indexes', table, {})
- # That's it... we're done.
- return 1
+ # That's it... we're done.
+ return 1
+
############
#
# Basic information about this template
@@ -235,4 +235,3 @@
'Author' : 'The GNUe Designer Team',
'Behavior': WIZARD
}
-
Modified: trunk/gnue-designer/src/ui/wx/Base.py
===================================================================
--- trunk/gnue-designer/src/ui/wx/Base.py 2006-04-03 19:53:03 UTC (rev
8343)
+++ trunk/gnue-designer/src/ui/wx/Base.py 2006-04-03 19:56:14 UTC (rev
8344)
@@ -45,26 +45,26 @@
# wx Imports
# ---------------------------------------------------------------------------
try: # Force wx2.6 to load
- import wxselect
- wxselect.wx.VersionFinder.setpath(version="2.6")
+ import wxselect
+ wxselect.wx.VersionFinder.setpath(version="2.6")
except ImportError:
- pass
+ pass
try: # Make sure 2.6 did in fact load
- import wx
- if wx.__version__ < '2.6.1':
- raise ImportError
+ import wx
+ if wx.__version__ < '2.6.1':
+ raise ImportError
except ImportError:
- raise "GNUe Designer requires wxPython 2.6.1 or greater."
+ raise "GNUe Designer requires wxPython 2.6.1 or greater."
# Issue stability warning for old wx versions
if wx.__version__ < '2.6.2.1':
- print
- print "*" * 70
- print "WARNING: GNUe Designer is unstable on wxPython %s." % wx.__version__
- print " For a stable experience, please install 2.6.2.1 or better"
- print "*" * 70
- print
+ print
+ print "*" * 70
+ print "WARNING: GNUe Designer is unstable on wxPython %s." % wx.__version__
+ print " For a stable experience, please install 2.6.2.1 or better"
+ print "*" * 70
+ print
#----------------------------------------------------------------------------
@@ -81,219 +81,217 @@
class UIBase(wx.App):
- # ====================================================================
- #
- # Public methods
- #
- # ====================================================================
+ # ====================================================================
+ #
+ # Public methods
+ #
+ # ====================================================================
- def run(self):
- # Set form's wx app to be us
- setWxApp(self)
+ def run(self):
+ # Set form's wx app to be us
+ setWxApp(self)
- # Reuse the login handler from Form's wx driver
- # This has to happen after setWxApp, otherwise bad things happen
- from gnue.forms.uidrivers.wx import UILoginHandler
- self.app.getConnectionManager().setLoginHandler(UILoginHandler())
+ # Reuse the login handler from Form's wx driver
+ # This has to happen after setWxApp, otherwise bad things happen
+ from gnue.forms.uidrivers.wx import UILoginHandler
+ self.app.getConnectionManager().setLoginHandler(UILoginHandler())
- # Call wx's MainLoop
- self.app.init()
+ # Call wx's MainLoop
+ self.app.init()
- # TODO: Temp
- if wx.__version__ < '2.6.2.1':
- wx.MessageDialog(None, 'Designer may be unstable when used\nwith
wxWidgets %s. \nVersion 2.6.2.1 or better is recommended.' % wx.__version__)
+ # TODO: Temp
+ if wx.__version__ < '2.6.2.1':
+ wx.MessageDialog(None, 'Designer may be unstable when used\nwith
wxWidgets %s. \nVersion 2.6.2.1 or better is recommended.' % wx.__version__)
- self.MainLoop()
+ self.MainLoop()
- def createInstance(self, instance):
- from Instance import Instance
- return Instance(instance)
+ def createInstance(self, instance):
+ from Instance import Instance
+ return Instance(instance)
- def getIcon(self, name, w, h):
- path = os.path.join(iconlocation,"%s-%sx%s.png" % (name,w, h))
- if not os.path.exists(path):
- return None
- return wx.Image(path,
- wx.BITMAP_TYPE_PNG).ConvertToBitmap()
+ def getIcon(self, name, w, h):
+ path = os.path.join(iconlocation,"%s-%sx%s.png" % (name,w, h))
+ if not os.path.exists(path):
+ return None
+ return wx.Image(path,
+ wx.BITMAP_TYPE_PNG).ConvertToBitmap()
- def autoSizer(self, parent, child, direction=wx.VERTICAL):
- box = wx.BoxSizer(wx.VERTICAL)
- box.Add(child, 2, wx.EXPAND)
+ def autoSizer(self, parent, child, direction=wx.VERTICAL):
+ box = wx.BoxSizer(wx.VERTICAL)
+ box.Add(child, 2, wx.EXPAND)
- parent.SetAutoLayout(True)
- parent.SetSizer(box)
- parent.Layout()
+ parent.SetAutoLayout(True)
+ parent.SetSizer(box)
+ parent.Layout()
- #---------------------------------------------------------------------
- # Startup Splash Screen
- #---------------------------------------------------------------------
- def createStartupSplash(self):
- from startup.Startup import Startup
- self.__splash = Startup()
+ #---------------------------------------------------------------------
+ # Startup Splash Screen
+ #---------------------------------------------------------------------
+ def createStartupSplash(self):
+ from startup.Startup import Startup
+ self.__splash = Startup()
- def closeStartupSplash(self):
- self.__splash.pauseAndClose()
+ def closeStartupSplash(self):
+ self.__splash.pauseAndClose()
- #---------------------------------------------------------------------
- # Common dialogs
- #---------------------------------------------------------------------
- def dialogOk(self, text, title, parentWindow=None, icon="information",
_cancel=False):
- """
- icon can be "question", "information", or "warn"
- @rtype: boolean
- @returns: True
- """
- if _cancel:
- buttonStyle = wx.OK|wx.CANCEL
- else:
- buttonStyle = wx.OK
+ #---------------------------------------------------------------------
+ # Common dialogs
+ #---------------------------------------------------------------------
+ def dialogOk(self, text, title, parentWindow=None, icon="information",
_cancel=False):
+ """
+ icon can be "question", "information", or "warn"
+ @rtype: boolean
+ @returns: True
+ """
+ if _cancel:
+ buttonStyle = wx.OK|wx.CANCEL
+ else:
+ buttonStyle = wx.OK
- if icon == 'question':
- iconStyle = wx.ICON_QUESTION
- elif icon == "warn":
- iconStyle = wx.ICON_EXCLAMATION
- elif icon == 'information':
- iconStyle = wx.ICON_INFORMATION
- else:
- # TODO: assert? error?
- iconStyle = wx.ICON_INFORMATION
- return wx.MessageDialog(parentWindow or None, text, title,
- buttonStyle|iconStyle ).ShowModal() == wx.ID_OK
+ if icon == 'question':
+ iconStyle = wx.ICON_QUESTION
+ elif icon == "warn":
+ iconStyle = wx.ICON_EXCLAMATION
+ elif icon == 'information':
+ iconStyle = wx.ICON_INFORMATION
+ else:
+ # TODO: assert? error?
+ iconStyle = wx.ICON_INFORMATION
+ return wx.MessageDialog(parentWindow or None, text, title,
+ buttonStyle|iconStyle ).ShowModal() == wx.ID_OK
- def dialogCancel(self, text, title, parentWindow=None, icon="warn"):
- """
- icon can be "question", "information", or "warn"
- @rtype: boolean
- @returns: True
- """
- return self.dialogOk(text, title. parentWindow, icon, _cancel=True)
+ def dialogCancel(self, text, title, parentWindow=None, icon="warn"):
+ """
+ icon can be "question", "information", or "warn"
+ @rtype: boolean
+ @returns: True
+ """
+ return self.dialogOk(text, title. parentWindow, icon, _cancel=True)
- def dialogYesNo(self, text, title, parentWindow=None, icon="question"):
- """
- icon can be "question", "information", or "warn"
- @rtype: boolean
- @returns: True if user selected Yes, False otherwise.
- """
- if icon == 'question':
- iconStyle = wx.ICON_QUESTION
- elif icon == "warn":
- iconStyle = wx.ICON_EXCLAMATION
- elif icon == 'information':
- iconStyle = wx.ICON_INFORMATION
- else:
- # TODO: assert? error?
- iconStyle = wx.ICON_INFORMATION
+ def dialogYesNo(self, text, title, parentWindow=None, icon="question"):
+ """
+ icon can be "question", "information", or "warn"
+ @rtype: boolean
+ @returns: True if user selected Yes, False otherwise.
+ """
+ if icon == 'question':
+ iconStyle = wx.ICON_QUESTION
+ elif icon == "warn":
+ iconStyle = wx.ICON_EXCLAMATION
+ elif icon == 'information':
+ iconStyle = wx.ICON_INFORMATION
+ else:
+ # TODO: assert? error?
+ iconStyle = wx.ICON_INFORMATION
- return wx.MessageDialog(parentWindow or None, text, title,
- wx.YES_NO|iconStyle ).ShowModal() == wx.ID_YES
+ return wx.MessageDialog(parentWindow or None, text, title,
+ wx.YES_NO|iconStyle ).ShowModal() == wx.ID_YES
- def dialogYesNoCancel(self, text, title, parentWindow=None, icon="question"):
- """
- icon can be "question", "information", or "warn"
- @rtype: int
- @returns: True (1) if user selected Yes, False (0) if No, -1 if canceled.
- """
- if icon == 'question':
- iconStyle = wx.ICON_QUESTION
- elif icon == "warn":
- iconStyle = wx.ICON_EXCLAMATION
- elif icon == 'information':
- iconStyle = wx.ICON_INFORMATION
- else:
- # TODO: assert? error?
- iconStyle = wx.ICON_INFORMATION
+ def dialogYesNoCancel(self, text, title, parentWindow=None,
icon="question"):
+ """
+ icon can be "question", "information", or "warn"
+ @rtype: int
+ @returns: True (1) if user selected Yes, False (0) if No, -1 if
canceled.
+ """
+ if icon == 'question':
+ iconStyle = wx.ICON_QUESTION
+ elif icon == "warn":
+ iconStyle = wx.ICON_EXCLAMATION
+ elif icon == 'information':
+ iconStyle = wx.ICON_INFORMATION
+ else:
+ # TODO: assert? error?
+ iconStyle = wx.ICON_INFORMATION
- rv = wx.MessageDialog(parentWindow or None, text, title,
- wx.YES_NO|wx.CANCEL|iconStyle ).ShowModal()
- if rv == wx.ID_YES:
- return True
- elif rv == wx.ID_NO:
- return False
- else:
- return -1
+ rv = wx.MessageDialog(parentWindow or None, text, title,
+ wx.YES_NO|wx.CANCEL|iconStyle ).ShowModal()
+ if rv == wx.ID_YES:
+ return True
+ elif rv == wx.ID_NO:
+ return False
+ else:
+ return -1
- def dialogOpenFile(self, title, wildcards, parentWindow=None):
- """
- Prompts the user for a file to open.
+ def dialogOpenFile(self, title, wildcards, parentWindow=None):
+ """
+ Prompts the user for a file to open.
- wildcards is a tuple of tuples, such as:
- (('*.*','All Files'), ('*.py','Python Scripts'))
+ wildcards is a tuple of tuples, such as:
+ (('*.*','All Files'), ('*.py','Python Scripts'))
- @rtype: string
- @returns: None if no file selected, or a full
- path name otherwise.
- """
+ @rtype: string
+ @returns: None if no file selected, or a full
+ path name otherwise.
+ """
- wcstring = ""
- for extension, description in wildcards:
- wcstring += "%s (*.%s)|*.%s|" % (description, extension, extension)
+ wcstring = ""
+ for extension, description in wildcards:
+ wcstring += "%s (*.%s)|*.%s|" % (description, extension, extension)
- dlg = wx.FileDialog(parentWindow or None, title, defaultDir=os.getcwd(),
- wildcard = wcstring,
- style=wx.OPEN)
- if dlg.ShowModal() != wx.ID_OK:
- ret = None
- else:
- ret = dlg.GetPath()
+ dlg = wx.FileDialog(parentWindow or None, title,
defaultDir=os.getcwd(),
+ wildcard = wcstring,
+ style=wx.OPEN)
+ if dlg.ShowModal() != wx.ID_OK:
+ ret = None
+ else:
+ ret = dlg.GetPath()
- dlg.Destroy()
- return ret
+ dlg.Destroy()
+ return ret
- def dialogSaveFile(self,title, wildcards, parentWindow=None):
- """
- Prompts the user for a file name to save as.
+ def dialogSaveFile(self,title, wildcards, parentWindow=None):
+ """
+ Prompts the user for a file name to save as.
- @rtype: string
- @returns: None if no file selected, or a full
- path name otherwise.
- """
- wcstring = ""
- for extension, description in wildcards:
- wcstring += "%s (*.%s)|*.%s|" % (description, extension, extension)
- wcstring = wcstring[:-1]
+ @rtype: string
+ @returns: None if no file selected, or a full
+ path name otherwise.
+ """
+ wcstring = ""
+ for extension, description in wildcards:
+ wcstring += "%s (*.%s)|*.%s|" % (description, extension, extension)
+ wcstring = wcstring[:-1]
- dlg = wx.FileDialog(parentWindow or None, title,
- defaultDir=os.getcwd(),
- wildcard = wcstring,
- style=wx.SAVE)
- if dlg.ShowModal() != wx.ID_OK:
- return None
- else:
- return dlg.GetPath()
+ dlg = wx.FileDialog(parentWindow or None, title,
+ defaultDir=os.getcwd(),
+ wildcard = wcstring,
+ style=wx.SAVE)
+ if dlg.ShowModal() != wx.ID_OK:
+ return None
+ else:
+ return dlg.GetPath()
- # ====================================================================
- #
- # Internal Methods
- #
- # ====================================================================
+ # ====================================================================
+ #
+ # Internal Methods
+ #
+ # ====================================================================
- #---------------------------------------------------------------------
- # wx.App methods
- #---------------------------------------------------------------------
- def OnInit(self):
- """
- Standard wx.App OnInit function.
- Designer uses it to display the startup screen and
- load the initial editor instance
+ #---------------------------------------------------------------------
+ # wx.App methods
+ #---------------------------------------------------------------------
+ def OnInit(self):
+ """
+ Standard wx.App OnInit function.
+ Designer uses it to display the startup screen and
+ load the initial editor instance
- @rtype: boolean
- @return: Always True
- """
- return True
+ @rtype: boolean
+ @return: Always True
+ """
+ return True
- #---------------------------------------------------------------------
- # Misc internal methods
- #---------------------------------------------------------------------
- def __init__(self, app):
- print "__init__"
- self.app = app
- wx.App.__init__(self, False) # prevents IO redirect
- wx.InitAllImageHandlers()
-
-
+ #---------------------------------------------------------------------
+ # Misc internal methods
+ #---------------------------------------------------------------------
+ def __init__(self, app):
+ print "__init__"
+ self.app = app
+ wx.App.__init__(self, False) # prevents IO redirect
+ wx.InitAllImageHandlers()
Modified: trunk/gnue-designer/src/ui/wx/Instance.py
===================================================================
--- trunk/gnue-designer/src/ui/wx/Instance.py 2006-04-03 19:53:03 UTC (rev
8343)
+++ trunk/gnue-designer/src/ui/wx/Instance.py 2006-04-03 19:56:14 UTC (rev
8344)
@@ -57,14 +57,14 @@
# Determine the format for the application window's title
# (%s will be replaced with the document name)
if wx.Platform == "__WXMAC__":
- title_saved_format = '%s'
- title_unsaved_format = '%s (*)'
+ title_saved_format = '%s'
+ title_unsaved_format = '%s (*)'
elif wx.Platform == "__WXMSW__":
- title_saved_format = '%s - GNUe Designer'
- title_unsaved_format = '%s* - GNUe Designer'
+ title_saved_format = '%s - GNUe Designer'
+ title_unsaved_format = '%s* - GNUe Designer'
else:
- title_saved_format = '%s - GNUe Designer'
- title_unsaved_format = '%s - GNUe Designer [modified]'
+ title_saved_format = '%s - GNUe Designer'
+ title_unsaved_format = '%s - GNUe Designer [modified]'
#============================================================================
# UI Instance class
@@ -72,46 +72,46 @@
class Instance(wx.Frame):
- #==========================================================================
- # Public Methods
- #==========================================================================
-
- def createMenuBar(self):
- """
- Called by base.Instance to create a menu bar
- """
- menuBar = MenuBar(self.document)
- self.SetMenuBar(menuBar)
- return menuBar
+ #==========================================================================
+ # Public Methods
+ #==========================================================================
- def setTitle(self, title, unsaved=False):
- """
- Set the application's title
- """
- if unsaved:
- self.SetTitle(title_unsaved_format % title)
- else:
- self.SetTitle(title_saved_format % title)
+ def createMenuBar(self):
+ """
+ Called by base.Instance to create a menu bar
+ """
+ menuBar = MenuBar(self.document)
+ self.SetMenuBar(menuBar)
+ return menuBar
- def show(self):
- self.Show(True)
+ def setTitle(self, title, unsaved=False):
+ """
+ Set the application's title
+ """
+ if unsaved:
+ self.SetTitle(title_unsaved_format % title)
+ else:
+ self.SetTitle(title_saved_format % title)
- def hide(self):
- self.Show(False)
+ def show(self):
+ self.Show(True)
- def finalize(self):
- """
- Called by the base instance
- when all tools/etc have been initialized.
- We can assume the UI is ready for display at this point
- """
-
- # Build accelerator list
- accel = wx.AcceleratorTable(self.document.globalAccelerators)
- for child in [self] + self.document.globalAcceleratorListeners:
- child.SetAcceleratorTable(accel)
+ def hide(self):
+ self.Show(False)
- # TODO: debugging PyAUI... these may not be needed
+ def finalize(self):
+ """
+ Called by the base instance
+ when all tools/etc have been initialized.
+ We can assume the UI is ready for display at this point
+ """
+
+ # Build accelerator list
+ accel = wx.AcceleratorTable(self.document.globalAccelerators)
+ for child in [self] + self.document.globalAcceleratorListeners:
+ child.SetAcceleratorTable(accel)
+
+ # TODO: debugging PyAUI... these may not be needed
# # Fit the widgets to the screen
# self.Fit()
@@ -123,232 +123,232 @@
# RuntimeSettings.getint(self.document.runtime_section, 'x', -1),
# RuntimeSettings.getint(self.document.runtime_section, 'y', -1)))
- # Add the toolbar to the PyAUI manager
- self._auiMgr.AddPane(self.toolbar, PyAUI.PaneInfo().
- Name("PrimaryToolBar").Caption("GNUe Designer").
- ToolbarPane().Top())
+ # Add the toolbar to the PyAUI manager
+ self._auiMgr.AddPane(self.toolbar, PyAUI.PaneInfo().
+ Name("PrimaryToolBar").Caption("GNUe Designer").
+ ToolbarPane().Top())
- perspective = RuntimeSettings.get(self.document.runtime_section,
'aui-perspective','')
- if perspective:
- self._auiMgr.LoadPerspective(perspective)
+ perspective = RuntimeSettings.get(self.document.runtime_section,
'aui-perspective','')
+ if perspective:
+ self._auiMgr.LoadPerspective(perspective)
- self._auiMgr.Update()
+ self._auiMgr.Update()
- self.Show(True)
+ self.Show(True)
- # Removing this refresh causes a segfault,
- # but the PyAUI examples don't have it??
- self.Layout()
+ # Removing this refresh causes a segfault,
+ # but the PyAUI examples don't have it??
+ self.Layout()
- def createEditor(self, object, baseclass):
- """
- Create a new editor instance for a GObject
-
- object: GObject instance
- baseclass: a ToolBase-derived class that will be instantiated
- """
- tool = baseclass(object, self.document, self.editNotebook)
+ def createEditor(self, object, baseclass):
+ """
+ Create a new editor instance for a GObject
- if tool.icon in self._editorIconList:
- iconIndex = self._editorIconList.index(tool.icon)
- else:
- icon = self.document.app.ui.getIcon('editor_' + tool.icon,16,16)
- if not icon:
- print "WARNING: No icon named editor_%s-%sx%s.png" % (tool.icon, 16,16)
- iconIndex = -1
- else:
- iconIndex = len(self._editorIconList)
- self._editorIconList.append(tool.icon)
- print "Adding icon for %s" % tool.icon
- print icon.GetWidth(), icon.GetHeight()
- self._editorIcons.Add(icon)
+ object: GObject instance
+ baseclass: a ToolBase-derived class that will be instantiated
+ """
+ tool = baseclass(object, self.document, self.editNotebook)
- object._editorComponent = tool
- page = self.editNotebook.AddPage(tool, tool._caption, False, iconIndex)
+ if tool.icon in self._editorIconList:
+ iconIndex = self._editorIconList.index(tool.icon)
+ else:
+ icon = self.document.app.ui.getIcon('editor_' + tool.icon,16,16)
+ if not icon:
+ print "WARNING: No icon named editor_%s-%sx%s.png" %
(tool.icon, 16,16)
+ iconIndex = -1
+ else:
+ iconIndex = len(self._editorIconList)
+ self._editorIconList.append(tool.icon)
+ print "Adding icon for %s" % tool.icon
+ print icon.GetWidth(), icon.GetHeight()
+ self._editorIcons.Add(icon)
- def close(self):
- self.Destroy()
+ object._editorComponent = tool
+ page = self.editNotebook.AddPage(tool, tool._caption, False, iconIndex)
- def setStatus(self, text):
- self.statusbar.SetStatusText(text)
+ def close(self):
+ self.Destroy()
+ def setStatus(self, text):
+ self.statusbar.SetStatusText(text)
- # -------------------------------------------------------------------------
- # Create the tools
- # -------------------------------------------------------------------------
- def initTools(self):
- self.tools = []
- # Create a center notebook pane
- self.editNotebook = notebook = NotebookCtrl.NotebookCtrl(
- self,-1)
- notebook.SetImageList(self._editorIcons)
- notebook.EnableHiding()
- notebook.SetHighlightSelection()
- #notebook.SetUseFocusIndicator()
- notebook.SetDrawX(style=2)
- #notebook.SetImageToCloseButton()
- #notebook.SetTabHeight(20)
- notebook.EnableTabGradients()
- self._auiMgr.AddPane(notebook, PyAUI.PaneInfo().Name('Editor').\
- Caption('Editor').CenterPane())
#.MaxSize(10000,10000).MinSize(100,50))
+ # -------------------------------------------------------------------------
+ # Create the tools
+ # -------------------------------------------------------------------------
+ def initTools(self):
+ self.tools = []
- ##TODO: Experimenting with tabs at the top...
- ##TODO: Commenting out until
- ##notebooktabs = wx.Panel(self, -1)
- ##self._auiMgr.AddPane(notebooktabs, PyAUI.PaneInfo().Name('Notebook
Tabs').\
- ## Caption('Pages').CaptionVisible(False).Top()) #
.Floatable(False).Movable(False))
- ##
- ### This uses internal knowledge of NotebookCtrl to reparent the
- ### tab controls to their own dock
- ##notebook.nb.Reparent(notebooktabs)
- ##notebook.sizer.Remove(notebook.nb)
- ##box = wx.BoxSizer(wx.VERTICAL)
- ##box.Add(notebook.nb, 2, wx.EXPAND)
- ##
- ##notebooktabs.SetAutoLayout(True)
- ##notebooktabs.SetSizer(box)
- ##notebooktabs.Layout()
-
-
- #
- # Add each tool
- #
- leftrow = 0
- rightrow = 0
- for id, title, baseclass, hotkey, group in self.document._toolCache:
+ # Create a center notebook pane
+ self.editNotebook = notebook = NotebookCtrl.NotebookCtrl(
+ self,-1)
+ notebook.SetImageList(self._editorIcons)
+ notebook.EnableHiding()
+ notebook.SetHighlightSelection()
+ #notebook.SetUseFocusIndicator()
+ notebook.SetDrawX(style=2)
+ #notebook.SetImageToCloseButton()
+ #notebook.SetTabHeight(20)
+ notebook.EnableTabGradients()
+ self._auiMgr.AddPane(notebook, PyAUI.PaneInfo().Name('Editor').\
+ Caption('Editor').CenterPane())
#.MaxSize(10000,10000).MinSize(100,50))
- assert gDebug(2,'Adding tool %s [%s]' % (title,id))
+ ##TODO: Experimenting with tabs at the top...
+ ##TODO: Commenting out until
+ ##notebooktabs = wx.Panel(self, -1)
+ ##self._auiMgr.AddPane(notebooktabs, PyAUI.PaneInfo().Name('Notebook
Tabs').\
+ ## Caption('Pages').CaptionVisible(False).Top()) #
.Floatable(False).Movable(False))
+ ##
+ ### This uses internal knowledge of NotebookCtrl to reparent the
+ ### tab controls to their own dock
+ ##notebook.nb.Reparent(notebooktabs)
+ ##notebook.sizer.Remove(notebook.nb)
+ ##box = wx.BoxSizer(wx.VERTICAL)
+ ##box.Add(notebook.nb, 2, wx.EXPAND)
+ ##
+ ##notebooktabs.SetAutoLayout(True)
+ ##notebooktabs.SetSizer(box)
+ ##notebooktabs.Layout()
- indx = 0
- pos = baseclass.default_dock
- if '-' in pos:
- pos, indx = pos.split('-')
- indx = int(indx)
- tool = baseclass(id, title, self.document, self.document.rootObject,
self)
+ #
+ # Add each tool
+ #
+ leftrow = 0
+ rightrow = 0
+ for id, title, baseclass, hotkey, group in self.document._toolCache:
- # TODO: this isn't compatable with PyAUI
- tool._docked = RuntimeSettings.getint(self.document.runtime_section,
'%s-docked' % id, pos != 'frame')
- tool._dock_location = RuntimeSettings.get(self.document.runtime_section,
'%s-location' % id, (pos == 'frame' and 'left' or pos))
- tool._dock_index = RuntimeSettings.getint(self.document.runtime_section,
'%s-index' % id, indx)
- tool._visible = RuntimeSettings.getint(self.document.runtime_section,
'%s-visible' % id, tool.default_visible)
- tool._frame_x = RuntimeSettings.getint(self.document.runtime_section,
'%s-frame-x' % id, -1)
- tool._frame_y = RuntimeSettings.getint(self.document.runtime_section,
'%s-frame-y' % id, -1)
- tool._frame_width =
RuntimeSettings.getint(self.document.runtime_section, '%s-frame-width' % id,
200)
- tool._frame_height =
RuntimeSettings.getint(self.document.runtime_section, '%s-frame-height' % id,
150)
+ assert gDebug(2,'Adding tool %s [%s]' % (title,id))
- appd = (id, title, baseclass, hotkey, pos)
+ indx = 0
+ pos = baseclass.default_dock
+ if '-' in pos:
+ pos, indx = pos.split('-')
+ indx = int(indx)
- toolinfo = PyAUI.PaneInfo().Name(title).Caption(title) #.\
- #MinSize(100,100)).PinButton().MinimizeButton().CloseButton().\
- #Floatable().Dockable().MaxSize(10000,10000)
-
- if tool._docked:
- # Docked type
- if tool._dock_location == 'right':
- toolinfo.Right()
- else:
- toolinfo.Left()
- else:
- # Frame type
- toolinfo.Float()
+ tool = baseclass(id, title, self.document,
self.document.rootObject, self)
- if not tool._visible:
- toolinfo.Hide()
+ # TODO: this isn't compatable with PyAUI
+ tool._docked =
RuntimeSettings.getint(self.document.runtime_section, '%s-docked' % id, pos !=
'frame')
+ tool._dock_location =
RuntimeSettings.get(self.document.runtime_section, '%s-location' % id, (pos ==
'frame' and 'left' or pos))
+ tool._dock_index =
RuntimeSettings.getint(self.document.runtime_section, '%s-index' % id, indx)
+ tool._visible =
RuntimeSettings.getint(self.document.runtime_section, '%s-visible' % id,
tool.default_visible)
+ tool._frame_x =
RuntimeSettings.getint(self.document.runtime_section, '%s-frame-x' % id, -1)
+ tool._frame_y =
RuntimeSettings.getint(self.document.runtime_section, '%s-frame-y' % id, -1)
+ tool._frame_width =
RuntimeSettings.getint(self.document.runtime_section, '%s-frame-width' % id,
200)
+ tool._frame_height =
RuntimeSettings.getint(self.document.runtime_section, '%s-frame-height' % id,
150)
- self._auiMgr.AddPane(tool, toolinfo)
+ appd = (id, title, baseclass, hotkey, pos)
- # Keep track of the tools we created
- self.tools.append(tool)
+ toolinfo = PyAUI.PaneInfo().Name(title).Caption(title) #.\
+
#MinSize(100,100)).PinButton().MinimizeButton().CloseButton().\
+ #Floatable().Dockable().MaxSize(10000,10000)
- # Add ourselves to the Window menu
- self.document.menubar.addAction(location='View', text=title,
event='Tool:' + id,
- grouping=group, canToggle=1, canDisable=0,
- icon=None, hotkey=hotkey)
+ if tool._docked:
+ # Docked type
+ if tool._dock_location == 'right':
+ toolinfo.Right()
+ else:
+ toolinfo.Left()
+ else:
+ # Frame type
+ toolinfo.Float()
+ if not tool._visible:
+ toolinfo.Hide()
- self.document.__dict__[id] = tool
+ self._auiMgr.AddPane(tool, toolinfo)
+ # Keep track of the tools we created
+ self.tools.append(tool)
+
+ # Add ourselves to the Window menu
+ self.document.menubar.addAction(location='View', text=title,
event='Tool:' + id,
+ grouping=group, canToggle=1, canDisable=0,
+ icon=None, hotkey=hotkey)
+
+
+ self.document.__dict__[id] = tool
+
# if tool._visible:
# instance.dispatchEvent('Show:Tool:%s' % id)
# else:
# instance.dispatchEvent('Hide:Tool:%s' % id)
- #
+ #
- # -------------------------------------------------------------------------
- # Runtime settings support
- # -------------------------------------------------------------------------
- # Used by RuntimeSettings
- def getRuntimeSettings(self):
- x, y = self.GetPositionTuple()
- width, height = self.GetSizeTuple()
- settings = { 'x': abs(x),
- 'y': abs(y),
- 'height': height,
- 'width': width }
+ # -------------------------------------------------------------------------
+ # Runtime settings support
+ # -------------------------------------------------------------------------
+ # Used by RuntimeSettings
+ def getRuntimeSettings(self):
+ x, y = self.GetPositionTuple()
+ width, height = self.GetSizeTuple()
+ settings = { 'x': abs(x),
+ 'y': abs(y),
+ 'height': height,
+ 'width': width }
- return settings
+ return settings
- #==========================================================================
- # Private Methods
- #==========================================================================
- def __init__(self, instance):
- wx.Frame.__init__(self, None, -1, "", style=wx.DEFAULT_FRAME_STYLE |
- wx.SUNKEN_BORDER |
- wx.CLIP_CHILDREN)
+ #==========================================================================
+ # Private Methods
+ #==========================================================================
+ def __init__(self, instance):
+ wx.Frame.__init__(self, None, -1, "", style=wx.DEFAULT_FRAME_STYLE |
+ wx.SUNKEN_BORDER |
+ wx.CLIP_CHILDREN)
- self.document = instance
+ self.document = instance
- # Setup PyAUI (the docking framework)
- self._auiMgr = PyAUI.FrameManager(self)
- self._auiMgr.SetFrame(self)
- self._auiMgr.SetDockArt(MyDockArt())
+ # Setup PyAUI (the docking framework)
+ self._auiMgr = PyAUI.FrameManager(self)
+ self._auiMgr.SetFrame(self)
+ self._auiMgr.SetDockArt(MyDockArt())
- # Set our icon
- icon = Goat.getGoatIcon()
- self.SetIcon(icon)
+ # Set our icon
+ icon = Goat.getGoatIcon()
+ self.SetIcon(icon)
- # Just a sane default...
- self.SetMinSize(wx.Size(400, 300))
+ # Just a sane default...
+ self.SetMinSize(wx.Size(400, 300))
- # Create the status bar
- self.statusbar = self.CreateStatusBar()
- self.SetStatusText(u_('Welcome to GNUe Designer.'))
+ # Create the status bar
+ self.statusbar = self.CreateStatusBar()
+ self.SetStatusText(u_('Welcome to GNUe Designer.'))
- # Add the primary tool bar to the tool pane
- # DO NOT CALL self.SetToolbar, as it botches PyAUI
- self.toolbar = PrimaryToolBar(self, self.document)
+ # Add the primary tool bar to the tool pane
+ # DO NOT CALL self.SetToolbar, as it botches PyAUI
+ self.toolbar = PrimaryToolBar(self, self.document)
- # Let our base instance class handle closing the instance
- # TODO: This should actually catch the event and issue a GNUe event
- wx.EVT_CLOSE(self, self.document._OnClose)
+ # Let our base instance class handle closing the instance
+ # TODO: This should actually catch the event and issue a GNUe event
+ wx.EVT_CLOSE(self, self.document._OnClose)
- # I think PyAUI requires this...
- # (at least the demo code does)
- self.Bind(wx.EVT_ERASE_BACKGROUND, self._onEraseBackground)
+ # I think PyAUI requires this...
+ # (at least the demo code does)
+ self.Bind(wx.EVT_ERASE_BACKGROUND, self._onEraseBackground)
- # Miscellaneous variables used by other functions in this class...
-
- # Create an icon list for use by createEditor
- self._editorIcons = wx.ImageList(16, 16, True, 0)
- self._editorIconList = []
+ # Miscellaneous variables used by other functions in this class...
+ # Create an icon list for use by createEditor
+ self._editorIcons = wx.ImageList(16, 16, True, 0)
+ self._editorIconList = []
- def _onEraseBackground(self, event):
- event.Skip()
+ def _onEraseBackground(self, event):
+ event.Skip()
+
#============================================================================
# Our own PyAUI dock decorator
#============================================================================
-class MyDockArt(PyAUI.DefaultDockArt):
- def __init__(self, *arg, **parm):
- PyAUI.DefaultDockArt.__init__(self, *arg, **parm)
- self.SetFont(PyAUI.AUI_ART_CAPTION_FONT, wx.Font(9, wx.DEFAULT, wx.NORMAL,
wx.NORMAL, False))
\ No newline at end of file
+class MyDockArt(PyAUI.DefaultDockArt):
+ def __init__(self, *arg, **parm):
+ PyAUI.DefaultDockArt.__init__(self, *arg, **parm)
+ self.SetFont(PyAUI.AUI_ART_CAPTION_FONT, wx.Font(9, wx.DEFAULT,
wx.NORMAL, wx.NORMAL, False))
Modified: trunk/gnue-designer/src/ui/wx/MenuBar.py
===================================================================
--- trunk/gnue-designer/src/ui/wx/MenuBar.py 2006-04-03 19:53:03 UTC (rev
8343)
+++ trunk/gnue-designer/src/ui/wx/MenuBar.py 2006-04-03 19:56:14 UTC (rev
8344)
@@ -31,62 +31,59 @@
import wx
class MenuBar(wx.MenuBar):
- def __init__(self, instance):
- wx.MenuBar.__init__(self)
- self.document = instance
+ def __init__(self, instance):
+ wx.MenuBar.__init__(self)
+ self.document = instance
- self._locationToWx= {}
+ self._locationToWx= {}
- #
- # Return the wx.Menu(Item) associated with a location
- def getMenu(self, location):
- return self._locationToWx[location]
+ #
+ # Return the wx.Menu(Item) associated with a location
+ def getMenu(self, location):
+ return self._locationToWx[location]
- def createMenu(self, title, location):
- return self.createSubMenu(title, location, self)
+ def createMenu(self, title, location):
+ return self.createSubMenu(title, location, self)
- def createSubMenu(self, title, location, parent):
- menu = wx.Menu()
- self._locationToWx[location] = menu
- parent.AppendMenu(wx.NewId(), title, menu)
- return menu
+ def createSubMenu(self, title, location, parent):
+ menu = wx.Menu()
+ self._locationToWx[location] = menu
+ parent.AppendMenu(wx.NewId(), title, menu)
+ return menu
- def createSeparator(self, menu):
- menu.AppendSeparator()
+ def createSeparator(self, menu):
+ menu.AppendSeparator()
- def createMenuItem(self, menu, text, canToggle,
- canDisable, icon, hotkey, eventdata, help, action):
+ def createMenuItem(self, menu, text, canToggle,
+ canDisable, icon, hotkey, eventdata, help, action):
- mid = wx.NewId()
- if hotkey:
- text += '\t' + hotkey
- item = wx.MenuItem(menu, mid, text, help,
- (canToggle and [wx.ITEM_CHECK] or [wx.ITEM_NORMAL])[0])
- if canToggle:
- wx.EVT_MENU(self.document.ui, mid,
- lambda event, l=self.document, m=item, e=action, x=eventdata:
- l.dispatchEvent('%s:%s' % (m.IsChecked() and 'Show' or
'Hide',e), **x))
- self.document.registerEventListeners( {
- 'Show:%s' % action: lambda event, m=item: m.Check(1),
- 'Hide:%s' % action: lambda event, m=item: m.Check(0) })
- else:
- wx.EVT_MENU(self.document.ui, mid,
- lambda event, l=self.document, e=action, x=eventdata:
l.dispatchEvent(e, **x))
+ mid = wx.NewId()
+ if hotkey:
+ text += '\t' + hotkey
+ item = wx.MenuItem(menu, mid, text, help,
+ (canToggle and [wx.ITEM_CHECK] or [wx.ITEM_NORMAL])[0])
+ if canToggle:
+ wx.EVT_MENU(self.document.ui, mid,
+ lambda event, l=self.document, m=item, e=action, x=eventdata:
+ l.dispatchEvent('%s:%s' % (m.IsChecked() and 'Show' or
'Hide',e), **x))
+ self.document.registerEventListeners( {
+ 'Show:%s' % action: lambda event, m=item: m.Check(1),
+ 'Hide:%s' % action: lambda event, m=item: m.Check(0) })
+ else:
+ wx.EVT_MENU(self.document.ui, mid,
+ lambda event, l=self.document, e=action, x=eventdata:
l.dispatchEvent(e, **x))
- if canDisable:
- self.document.registerEventListeners( {
- 'Enable:%s' % action: lambda event, m=item: m.Enable(1),
- 'Disable:%s' % action: lambda event, m=item: m.Enable(0) })
- menu.AppendItem(item)
- return item
+ if canDisable:
+ self.document.registerEventListeners( {
+ 'Enable:%s' % action: lambda event, m=item: m.Enable(1),
+ 'Disable:%s' % action: lambda event, m=item: m.Enable(0)
})
+ menu.AppendItem(item)
+ return item
- #
- # Convenience methods to make the main menu bar appear to be a menu container
- #
- def AppendMenu(self, wxId, text, menu):
- self.Append(menu, text)
-
-
-
+ #
+ # Convenience methods to make the main menu bar appear to be a menu
container
+ #
+ def AppendMenu(self, wxId, text, menu):
+ self.Append(menu, text)
Modified: trunk/gnue-designer/src/ui/wx/startup/Startup.py
===================================================================
--- trunk/gnue-designer/src/ui/wx/startup/Startup.py 2006-04-03 19:53:03 UTC
(rev 8343)
+++ trunk/gnue-designer/src/ui/wx/startup/Startup.py 2006-04-03 19:56:14 UTC
(rev 8344)
@@ -32,61 +32,61 @@
from gnue.common.apps import GConfig
def _printStartupStatus(text):
- print ' * %s' % text
+ print ' * %s' % text
splashloc =
os.path.join(GConfig.getInstalledBase('designer_images','common_images')
,'designer', 'splash.png')
class Startup(wx.SplashScreen):
- def __init__(self):
- splashbitmap = wx.Image(splashloc,
- wx.BITMAP_TYPE_PNG).ConvertToBitmap()
+ def __init__(self):
+ splashbitmap = wx.Image(splashloc,
+ wx.BITMAP_TYPE_PNG).ConvertToBitmap()
- __builtin__.__dict__['gStartupStatus'] = self.startupStatus
- wx.SplashScreen.__init__(self, splashbitmap,
- wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_NO_TIMEOUT,400, None, -1,
- style=wx.SIMPLE_BORDER|wx.FRAME_NO_TASKBAR|wx.STAY_ON_TOP)
- self.text = 'Loading...'
- wx.EVT_PAINT(self.GetSplashWindow(), self.OnPaint)
- wx.EVT_CLOSE(self, self.destroy)
- self.timer = None
+ __builtin__.__dict__['gStartupStatus'] = self.startupStatus
+ wx.SplashScreen.__init__(self, splashbitmap,
+ wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_NO_TIMEOUT,400, None, -1,
+ style=wx.SIMPLE_BORDER|wx.FRAME_NO_TASKBAR|wx.STAY_ON_TOP)
+ self.text = 'Loading...'
+ wx.EVT_PAINT(self.GetSplashWindow(), self.OnPaint)
+ wx.EVT_CLOSE(self, self.destroy)
+ self.timer = None
- def pauseAndClose(self):
- self.Raise()
- gStartupStatus('Finalizing Settings')
- wx.FutureCall(100,self.setSettingsText)
- wx.FutureCall(1000,self.destroy)
+ def pauseAndClose(self):
+ self.Raise()
+ gStartupStatus('Finalizing Settings')
+ wx.FutureCall(100,self.setSettingsText)
+ wx.FutureCall(1000,self.destroy)
- def setSettingsText(self):
- # Fscking, bastardized GTK piece of damn crap
- gStartupStatus('Finalizing Settings')
+ def setSettingsText(self):
+ # Fscking, bastardized GTK piece of damn crap
+ gStartupStatus('Finalizing Settings')
- def destroy(self, event=None):
- self.hide()
- self.Destroy()
+ def destroy(self, event=None):
+ self.hide()
+ self.Destroy()
- def hide(self, event=None):
- __builtin__.__dict__['gStartupStatus'] = _printStartupStatus
- self.Show(0)
+ def hide(self, event=None):
+ __builtin__.__dict__['gStartupStatus'] = _printStartupStatus
+ self.Show(0)
- def startupStatus(self, text):
- self.drawText(wx.WHITE)
- self.text = "%s..." % text
- self.OnPaint()
+ def startupStatus(self, text):
+ self.drawText(wx.WHITE)
+ self.text = "%s..." % text
+ self.OnPaint()
- def drawText(self, color):
- # TODO: FIXME
- if sys.platform == "win32":
- print self.text
- return
- dc = wx.PaintDC(self.GetSplashWindow())
- dc.SetTextForeground(color)
- dc.BeginDrawing()
+ def drawText(self, color):
+ # TODO: FIXME
+ if sys.platform == "win32":
+ print self.text
+ return
+ dc = wx.PaintDC(self.GetSplashWindow())
+ dc.SetTextForeground(color)
+ dc.BeginDrawing()
## font = wx.Font(12, wx.NORMAL, wx.NORMAL, wx.NORMAL)
## dc.SetFont(font)
- dc.DrawText(self.text, 35, 225)
- dc.EndDrawing()
+ dc.DrawText(self.text, 35, 225)
+ dc.EndDrawing()
- def OnPaint(self, event=None):
- self.drawText(wx.BLACK)
- if event:
- event.Skip()
+ def OnPaint(self, event=None):
+ self.drawText(wx.BLACK)
+ if event:
+ event.Skip()
Modified: trunk/gnue-designer/src/ui/wx/startup/__init__.py
===================================================================
--- trunk/gnue-designer/src/ui/wx/startup/__init__.py 2006-04-03 19:53:03 UTC
(rev 8343)
+++ trunk/gnue-designer/src/ui/wx/startup/__init__.py 2006-04-03 19:56:14 UTC
(rev 8344)
@@ -1 +1 @@
-from Startup import Startup
\ No newline at end of file
+from Startup import Startup
Modified: trunk/gnue-designer/src/ui/wx/uihelpers/AdvancedSplash.py
===================================================================
--- trunk/gnue-designer/src/ui/wx/uihelpers/AdvancedSplash.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/ui/wx/uihelpers/AdvancedSplash.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -394,4 +394,3 @@
return stringstyle, integerstyle
-
\ No newline at end of file
Modified: trunk/gnue-designer/src/ui/wx/uihelpers/GridCellEditors.py
===================================================================
--- trunk/gnue-designer/src/ui/wx/uihelpers/GridCellEditors.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/ui/wx/uihelpers/GridCellEditors.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -40,266 +40,265 @@
#
#
class CharCellEditor (PyGridCellEditor):
- def __init__(self, grid, attributes):
- PyGridCellEditor.__init__(self)
- self.grid = grid
- self.attributes = attributes
- self.__created = 0
+ def __init__(self, grid, attributes):
+ PyGridCellEditor.__init__(self)
+ self.grid = grid
+ self.attributes = attributes
+ self.__created = 0
- def Create(self, parent, id, evtHandler):
- self.__created = 1
- assert gDebug(10,'Creating CharCellEditor')
- self._tc = wx.TextCtrl(parent, id, "")
- self._tc.SetInsertionPoint(0)
- self.SetControl(self._tc)
- if evtHandler:
- self._tc.PushEventHandler(evtHandler)
+ def Create(self, parent, id, evtHandler):
+ self.__created = 1
+ assert gDebug(10,'Creating CharCellEditor')
+ self._tc = wx.TextCtrl(parent, id, "")
+ self._tc.SetInsertionPoint(0)
+ self.SetControl(self._tc)
+ if evtHandler:
+ self._tc.PushEventHandler(evtHandler)
- def SetSize(self, rect):
- self._tc.SetDimensions(rect.x, rect.y, rect.width+2, rect.height+2)
+ def SetSize(self, rect):
+ self._tc.SetDimensions(rect.x, rect.y, rect.width+2, rect.height+2)
- def Show(self, show, attr):
- self.base_Show(show, attr)
+ def Show(self, show, attr):
+ self.base_Show(show, attr)
- def PaintBackground(self, rect, attr):
- pass
+ def PaintBackground(self, rect, attr):
+ pass
- def BeginEdit(self, row, col, grid):
- self.startValue = grid.GetTable().GetValue(row, col)
- self._tc.SetValue(self.startValue)
- self._tc.SetInsertionPointEnd()
- self._tc.SetFocus()
+ def BeginEdit(self, row, col, grid):
+ self.startValue = grid.GetTable().GetValue(row, col)
+ self._tc.SetValue(self.startValue)
+ self._tc.SetInsertionPointEnd()
+ self._tc.SetFocus()
- # For this example, select the text
- self._tc.SetSelection(0, self._tc.GetLastPosition())
+ # For this example, select the text
+ self._tc.SetSelection(0, self._tc.GetLastPosition())
- def EndEdit(self, row, col, grid):
- changed = False
+ def EndEdit(self, row, col, grid):
+ changed = False
- val = self._tc.GetValue()
- if val != self.startValue:
- changed = True
- grid.GetTable().SetValue(row, col, val) # update the table
+ val = self._tc.GetValue()
+ if val != self.startValue:
+ changed = True
+ grid.GetTable().SetValue(row, col, val) # update the table
- self.startValue = ''
- self._tc.SetValue('')
- return changed
+ self.startValue = ''
+ self._tc.SetValue('')
+ return changed
- def Reset(self):
- self._tc.SetValue(self.startValue)
- self._tc.SetInsertionPointEnd()
+ def Reset(self):
+ self._tc.SetValue(self.startValue)
+ self._tc.SetInsertionPointEnd()
- def IsAcceptedKey(self, evt):
- return (not (evt.ControlDown() or evt.AltDown()) and
- evt.GetKeyCode() != wx.WXK_SHIFT)
+ def IsAcceptedKey(self, evt):
+ return (not (evt.ControlDown() or evt.AltDown()) and
+ evt.GetKeyCode() != wx.WXK_SHIFT)
- def StartingKey(self, evt):
- assert gDebug(10, "Starting Key; created=%s" % self.__created)
- key = evt.GetKeyCode()
- ch = None
- if key in [wx.WXK_NUMPAD0, wx.WXK_NUMPAD1, wx.WXK_NUMPAD2, wx.WXK_NUMPAD3,
wx.WXK_NUMPAD4,
- wx.WXK_NUMPAD5, wx.WXK_NUMPAD6, wx.WXK_NUMPAD7, wx.WXK_NUMPAD8,
wx.WXK_NUMPAD9]:
- ch = ch = chr(ord('0') + key - wx.WXK_NUMPAD0)
+ def StartingKey(self, evt):
+ assert gDebug(10, "Starting Key; created=%s" % self.__created)
+ key = evt.GetKeyCode()
+ ch = None
+ if key in [wx.WXK_NUMPAD0, wx.WXK_NUMPAD1, wx.WXK_NUMPAD2,
wx.WXK_NUMPAD3, wx.WXK_NUMPAD4,
+ wx.WXK_NUMPAD5, wx.WXK_NUMPAD6, wx.WXK_NUMPAD7,
wx.WXK_NUMPAD8, wx.WXK_NUMPAD9]:
+ ch = ch = chr(ord('0') + key - wx.WXK_NUMPAD0)
- elif key < 256 and key >= 0 and chr(key):
- ch = chr(key)
- if not evt.ShiftDown():
- ch = string.lower(ch)
+ elif key < 256 and key >= 0 and chr(key):
+ ch = chr(key)
+ if not evt.ShiftDown():
+ ch = string.lower(ch)
- if ch is not None:
- # For this example, replace the text. Normally we would append it.
- #self._tc.AppendText(ch)
+ if ch is not None:
+ # For this example, replace the text. Normally we would append it.
+ #self._tc.AppendText(ch)
# self._tc.SetValue(ch)
- # self._tc.SetInsertionPointEnd()
- pass
- else:
- evt.Skip()
+ # self._tc.SetInsertionPointEnd()
+ pass
+ else:
+ evt.Skip()
- def StartingClick(self):
- pass
+ def StartingClick(self):
+ pass
- def Destroy(self):
- self.base_Destroy()
+ def Destroy(self):
+ self.base_Destroy()
- def Clone(self):
- return CharCellEditor(self.attributes)
+ def Clone(self):
+ return CharCellEditor(self.attributes)
class IntCellEditor (CharCellEditor):
- def __init__(self, grid, attributes):
- CharCellEditor.__init__(self, grid, attributes)
+ def __init__(self, grid, attributes):
+ CharCellEditor.__init__(self, grid, attributes)
- def Create(self, parent, id, evtHandler):
- CharCellEditor.Create(self, parent, id, evtHandler)
- wx.EVT_CHAR(self._tc, self.OnKeyPressed)
+ def Create(self, parent, id, evtHandler):
+ CharCellEditor.Create(self, parent, id, evtHandler)
+ wx.EVT_CHAR(self._tc, self.OnKeyPressed)
- def OnKeyPressed(self, evt):
- if (ord('0') <= evt.KeyCode() <= ord('9') or \
- evt.KeyCode() in (ord('-'), ord('+')) or \
- evt.KeyCode() < 32 or evt.KeyCode() > 126):
- evt.Skip()
+ def OnKeyPressed(self, evt):
+ if (ord('0') <= evt.KeyCode() <= ord('9') or \
+ evt.KeyCode() in (ord('-'), ord('+')) or \
+ evt.KeyCode() < 32 or evt.KeyCode() > 126):
+ evt.Skip()
- def StartingKey(self, evt):
- key = evt.GetKeyCode()
- ch = None
- if key in [wx.WXK_NUMPAD0, wx.WXK_NUMPAD1, wx.WXK_NUMPAD2, wx.WXK_NUMPAD3,
wx.WXK_NUMPAD4,
- wx.WXK_NUMPAD5, wx.WXK_NUMPAD6, wx.WXK_NUMPAD7, wx.WXK_NUMPAD8,
wx.WXK_NUMPAD9]:
- ch = ch = chr(ord('0') + key - wx.WXK_NUMPAD0)
+ def StartingKey(self, evt):
+ key = evt.GetKeyCode()
+ ch = None
+ if key in [wx.WXK_NUMPAD0, wx.WXK_NUMPAD1, wx.WXK_NUMPAD2,
wx.WXK_NUMPAD3, wx.WXK_NUMPAD4,
+ wx.WXK_NUMPAD5, wx.WXK_NUMPAD6, wx.WXK_NUMPAD7,
wx.WXK_NUMPAD8, wx.WXK_NUMPAD9]:
+ ch = ch = chr(ord('0') + key - wx.WXK_NUMPAD0)
- elif key < 256 and key >= 0 and chr(key):
- ch = chr(key)
- if not evt.ShiftDown():
- ch = string.lower(ch)
+ elif key < 256 and key >= 0 and chr(key):
+ ch = chr(key)
+ if not evt.ShiftDown():
+ ch = string.lower(ch)
- if '0' <= ch <= '9':
- # For this example, replace the text. Normally we would append it.
- #self._tc.AppendText(ch)
- pass
+ if '0' <= ch <= '9':
+ # For this example, replace the text. Normally we would append it.
+ #self._tc.AppendText(ch)
+ pass
# self._tc.SetValue(ch)
# self._tc.SetInsertionPointEnd()
- else:
- evt.Skip()
+ else:
+ evt.Skip()
class RestrictedCellEditor (CharCellEditor):
- def __init__(self, grid, attributes):
- CharCellEditor.__init__(self, grid, attributes)
- self.valueList = attributes['ValueSet'].keys()
+ def __init__(self, grid, attributes):
+ CharCellEditor.__init__(self, grid, attributes)
+ self.valueList = attributes['ValueSet'].keys()
- self.valueList.sort()
- self.selectionList = []
- self.valueMap = {}
+ self.valueList.sort()
+ self.selectionList = []
+ self.valueMap = {}
- i = 0
- if not (attributes.has_key('Required') and attributes['Required'] ):
- self.valueMap[''] = 0
- self.selectionList.append(' <Not Set> ')
- i = 1
+ i = 0
+ if not (attributes.has_key('Required') and attributes['Required'] ):
+ self.valueMap[''] = 0
+ self.selectionList.append(' <Not Set> ')
+ i = 1
- for v in self.valueList:
- self.valueMap[v] = i
- self.selectionList.append("%s" % (attributes['ValueSet'][v] or v))
- i = i + 1
+ for v in self.valueList:
+ self.valueMap[v] = i
+ self.selectionList.append("%s" % (attributes['ValueSet'][v] or v))
+ i = i + 1
- self.valueList.insert(0, '')
+ self.valueList.insert(0, '')
- def Create(self, parent, id, evtHandler):
- assert gDebug(10,'Creating CharCellEditor')
- self._tc = wx.ComboBox(parent, id, "", style=wx.CB_READONLY,
- choices=self.selectionList)
- self.SetControl(self._tc)
- if evtHandler:
- self._tc.PushEventHandler(evtHandler)
+ def Create(self, parent, id, evtHandler):
+ assert gDebug(10,'Creating CharCellEditor')
+ self._tc = wx.ComboBox(parent, id, "", style=wx.CB_READONLY,
+ choices=self.selectionList)
+ self.SetControl(self._tc)
+ if evtHandler:
+ self._tc.PushEventHandler(evtHandler)
- def BeginEdit(self, row, col, grid):
- self.startValue = grid.GetTable().GetValue(row, col)
- self._tc.SetSelection(self.valueMap[self.startValue])
- self._tc.SetFocus()
+ def BeginEdit(self, row, col, grid):
+ self.startValue = grid.GetTable().GetValue(row, col)
+ self._tc.SetSelection(self.valueMap[self.startValue])
+ self._tc.SetFocus()
- def EndEdit(self, row, col, grid):
- changed = False
+ def EndEdit(self, row, col, grid):
+ changed = False
- val = self.valueList[self._tc.GetSelection()]
- if val != self.startValue:
- changed = True
- grid.GetTable().SetValue(row, col, "%s" % val) # update the table
+ val = self.valueList[self._tc.GetSelection()]
+ if val != self.startValue:
+ changed = True
+ grid.GetTable().SetValue(row, col, "%s" % val) # update the table
- self.startValue = ''
- self._tc.SetSelection(0)
- return changed
+ self.startValue = ''
+ self._tc.SetSelection(0)
+ return changed
- def Reset(self):
- self._tc.SetSelection(self.valueMap[self.startValue])
- #self._tc.SetInsertionPointEnd()
+ def Reset(self):
+ self._tc.SetSelection(self.valueMap[self.startValue])
+ #self._tc.SetInsertionPointEnd()
- def StartingKey(self, evt):
- key = evt.GetKeyCode()
- ch = None
- if key in [wx.WXK_NUMPAD0, wx.WXK_NUMPAD1, wx.WXK_NUMPAD2, wx.WXK_NUMPAD3,
wx.WXK_NUMPAD4,
- wx.WXK_NUMPAD5, wx.WXK_NUMPAD6, wx.WXK_NUMPAD7, wx.WXK_NUMPAD8,
wx.WXK_NUMPAD9]:
- ch = ch = chr(ord('0') + key - wx.WXK_NUMPAD0)
+ def StartingKey(self, evt):
+ key = evt.GetKeyCode()
+ ch = None
+ if key in [wx.WXK_NUMPAD0, wx.WXK_NUMPAD1, wx.WXK_NUMPAD2,
wx.WXK_NUMPAD3, wx.WXK_NUMPAD4,
+ wx.WXK_NUMPAD5, wx.WXK_NUMPAD6, wx.WXK_NUMPAD7,
wx.WXK_NUMPAD8, wx.WXK_NUMPAD9]:
+ ch = ch = chr(ord('0') + key - wx.WXK_NUMPAD0)
- elif key < 256 and key >= 0 and chr(key):
- ch = chr(key)
- if not evt.ShiftDown():
- ch = string.lower(ch)
+ elif key < 256 and key >= 0 and chr(key):
+ ch = chr(key)
+ if not evt.ShiftDown():
+ ch = string.lower(ch)
- if ch is not None:
- # For this example, replace the text. Normally we would append it.
- #self._tc.AppendText(ch)
- pass
+ if ch is not None:
+ # For this example, replace the text. Normally we would append it.
+ #self._tc.AppendText(ch)
+ pass
# self._tc.SetValue(ch)
# self._tc.SetInsertionPointEnd()
- else:
- evt.Skip()
+ else:
+ evt.Skip()
class BoolCellEditor (CharCellEditor):
- def __init__(self, grid, attributes):
- CharCellEditor.__init__(self, grid, attributes)
+ def __init__(self, grid, attributes):
+ CharCellEditor.__init__(self, grid, attributes)
- self.selectionList = ['FALSE','TRUE']
+ self.selectionList = ['FALSE','TRUE']
- def Create(self, parent, id, evtHandler):
- self._tc = wx.ComboBox(parent, id, "", style=wx.CB_READONLY,
- choices=self.selectionList)
- self.SetControl(self._tc)
- if evtHandler:
- self._tc.PushEventHandler(evtHandler)
+ def Create(self, parent, id, evtHandler):
+ self._tc = wx.ComboBox(parent, id, "", style=wx.CB_READONLY,
+ choices=self.selectionList)
+ self.SetControl(self._tc)
+ if evtHandler:
+ self._tc.PushEventHandler(evtHandler)
- def BeginEdit(self, row, col, grid):
- self.startValue = grid.GetTable().GetValue(row, col)
-
- self._tc.SetValue(self.startValue)
- self._tc.SetFocus()
+ def BeginEdit(self, row, col, grid):
+ self.startValue = grid.GetTable().GetValue(row, col)
- def EndEdit(self, row, col, grid):
- changed = False
+ self._tc.SetValue(self.startValue)
+ self._tc.SetFocus()
- if self._tc.GetSelection():
- val = 'TRUE'
- else:
- val = 'FALSE'
- if val != self.startValue:
- changed = True
- grid.GetTable().SetValue(row, col, "%s" % val) # update the table
+ def EndEdit(self, row, col, grid):
+ changed = False
- self.startValue = ''
- self._tc.SetSelection(0)
- return changed
+ if self._tc.GetSelection():
+ val = 'TRUE'
+ else:
+ val = 'FALSE'
+ if val != self.startValue:
+ changed = True
+ grid.GetTable().SetValue(row, col, "%s" % val) # update the table
+ self.startValue = ''
+ self._tc.SetSelection(0)
+ return changed
- def Reset(self):
- self._tc.SetValue(self.startValue)
- #self._tc.SetInsertionPointEnd()
+ def Reset(self):
+ self._tc.SetValue(self.startValue)
+ #self._tc.SetInsertionPointEnd()
- def StartingKey(self, evt):
- key = evt.GetKeyCode()
- ch = None
- if key in [wx.WXK_NUMPAD0, wx.WXK_NUMPAD1, wx.WXK_NUMPAD2, wx.WXK_NUMPAD3,
wx.WXK_NUMPAD4,
- wx.WXK_NUMPAD5, wx.WXK_NUMPAD6, wx.WXK_NUMPAD7, wx.WXK_NUMPAD8,
wx.WXK_NUMPAD9]:
- ch = ch = chr(ord('0') + key - wx.WXK_NUMPAD0)
- elif key < 256 and key >= 0 and chr(key):
- ch = chr(key)
- if not evt.ShiftDown():
- ch = string.lower(ch)
+ def StartingKey(self, evt):
+ key = evt.GetKeyCode()
+ ch = None
+ if key in [wx.WXK_NUMPAD0, wx.WXK_NUMPAD1, wx.WXK_NUMPAD2,
wx.WXK_NUMPAD3, wx.WXK_NUMPAD4,
+ wx.WXK_NUMPAD5, wx.WXK_NUMPAD6, wx.WXK_NUMPAD7,
wx.WXK_NUMPAD8, wx.WXK_NUMPAD9]:
+ ch = ch = chr(ord('0') + key - wx.WXK_NUMPAD0)
- if ch is not None:
- # For this example, replace the text. Normally we would append it.
- #self._tc.AppendText(ch)
- pass
+ elif key < 256 and key >= 0 and chr(key):
+ ch = chr(key)
+ if not evt.ShiftDown():
+ ch = string.lower(ch)
+
+ if ch is not None:
+ # For this example, replace the text. Normally we would append it.
+ #self._tc.AppendText(ch)
+ pass
# self._tc.SetValue(ch)
# self._tc.SetInsertionPointEnd()
- else:
- evt.Skip()
-
+ else:
+ evt.Skip()
Modified: trunk/gnue-designer/src/ui/wx/uihelpers/NotebookCtrl.py
===================================================================
--- trunk/gnue-designer/src/ui/wx/uihelpers/NotebookCtrl.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/ui/wx/uihelpers/NotebookCtrl.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -1113,8 +1113,8 @@
self._timers.append(wx.Timer(self))
if select or self.GetSelection() == -1:
- self._selection = self.GetPageCount() - 1
-
+ self._selection = self.GetPageCount() - 1
+
self.Refresh()
@@ -3912,8 +3912,8 @@
if select:
if oldselection >= 0:
- self.bsizer.Show(self.GetPage(oldselection), False)
-
+ self.bsizer.Show(self.GetPage(oldselection), False)
+
self.nb.SetSelection(self.GetPageCount()-1)
self.bsizer.Layout()
else:
Modified: trunk/gnue-designer/src/ui/wx/uihelpers/PyAUI.py
===================================================================
--- trunk/gnue-designer/src/ui/wx/uihelpers/PyAUI.py 2006-04-03 19:53:03 UTC
(rev 8343)
+++ trunk/gnue-designer/src/ui/wx/uihelpers/PyAUI.py 2006-04-03 19:56:14 UTC
(rev 8344)
@@ -2043,9 +2043,9 @@
self.Bind(EVT_AUI_PANEBUTTON, self.OnPaneButton)
- def SetDockArt(self, art):
- assert isinstance(art, DefaultDockArt)
- self._art = art
+ def SetDockArt(self, art):
+ assert isinstance(art, DefaultDockArt)
+ self._art = art
def GetPaneByWidget(self, window):
"""
@@ -3203,7 +3203,7 @@
arr = FindDocks(docks, AUI_DOCK_CENTER, -1, -1, arr)
if len(arr) > 0:
for row in xrange(len(arr)):
- uiparts = self.LayoutAddDock(middle, arr[row], uiparts,
spacer_only)
+ uiparts = self.LayoutAddDock(middle, arr[row],
uiparts, spacer_only)
else:
# there are no center docks, add a background area
sizer_item = middle.Add((1, 1), 1, wx.EXPAND)
@@ -3914,7 +3914,7 @@
self._hint_wnd.Show()
if self._action == actionDragFloatingPane and
self._action_window:
- self._action_window.SetFocus()
+ self._action_window.SetFocus()
if self._flags & AUI_MGR_TRANSPARENT_HINT_FADE:
# start fade in timer
Modified: trunk/gnue-designer/src/ui/wx/uihelpers/PythonEditor.py
===================================================================
--- trunk/gnue-designer/src/ui/wx/uihelpers/PythonEditor.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/ui/wx/uihelpers/PythonEditor.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -326,10 +326,10 @@
self.PopupMenu(self.menu)
def SetViewEdge(self,check):
- if check:
- self.SetEdgeMode(wx_stc.STC_EDGE_LINE)
- else:
- self.SetEdgeMode(wx_stc.STC_EDGE_NONE)
+ if check:
+ self.SetEdgeMode(wx_stc.STC_EDGE_LINE)
+ else:
+ self.SetEdgeMode(wx_stc.STC_EDGE_NONE)
def FoldAll(self):
lineCount = self.GetLineCount()
@@ -752,4 +752,3 @@
return
inspect.formatargvalues(*inspect.getargvalues(func)).replace('self, ','')+'\n\n'
except:
return ''
-
Modified: trunk/gnue-designer/src/ui/wx/uihelpers/doccanvas/canvas.py
===================================================================
--- trunk/gnue-designer/src/ui/wx/uihelpers/doccanvas/canvas.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/ui/wx/uihelpers/doccanvas/canvas.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -144,11 +144,11 @@
# ---------------------------------------------------------------
def begin_refresh_batch(self):
"""
- When several refresh_scrolled_areas will be called sequentially,
- you can call this first to have them all batched together into
- one update, making the application look more responsive.
-
- Call end_refresh_batch() to apply the updates.
+ When several refresh_scrolled_areas will be called sequentially,
+ you can call this first to have them all batched together into
+ one update, making the application look more responsive.
+
+ Call end_refresh_batch() to apply the updates.
"""
self.__refresh_batch += 1
self.__refresh_batch_area = wx.Rect()
@@ -266,17 +266,17 @@
## Debugging code that makes it easy to see which areas are updating.
if 0:
- success = paintDC.Blit(bufferX, bufferY,
- bufferWidth, bufferHeight,
- paintDC,
- bufferX, bufferY,
- wx.SRC_INVERT)
- time.sleep(1)
- success = paintDC.Blit(bufferX, bufferY,
- bufferWidth, bufferHeight,
- paintDC,
- bufferX, bufferY,
- wx.SRC_INVERT)
+ success = paintDC.Blit(bufferX, bufferY,
+ bufferWidth, bufferHeight,
+ paintDC,
+ bufferX, bufferY,
+ wx.SRC_INVERT)
+ time.sleep(1)
+ success = paintDC.Blit(bufferX, bufferY,
+ bufferWidth, bufferHeight,
+ paintDC,
+ bufferX, bufferY,
+ wx.SRC_INVERT)
memoryDC.BeginDrawing()
@@ -298,42 +298,42 @@
def draw_widgets(self, dc):
- """
- Draw the individual widgets
- """
+ """
+ Draw the individual widgets
+ """
- updateRegion = self.GetUpdateRegion()
+ updateRegion = self.GetUpdateRegion()
- (scrollWindowOriginX,
- scrollWindowOriginY) = self.CalcUnscrolledPosition(0, 0)
+ (scrollWindowOriginX,
+ scrollWindowOriginY) = self.CalcUnscrolledPosition(0, 0)
- dcOriginX, dcOriginY = dc.GetDeviceOrigin()
+ dcOriginX, dcOriginY = dc.GetDeviceOrigin()
- # Draw widgets (in the reverse order they are stored in our list)
- for widget in self.ordered_widget_list[::-1]:
- refresh_area = widget.refresh_area
+ # Draw widgets (in the reverse order they are stored in our list)
+ for widget in self.ordered_widget_list[::-1]:
+ refresh_area = widget.refresh_area
- (objectX, objectY,
- objectWidth, objectHeight) = refresh_area.Get()
+ (objectX, objectY,
+ objectWidth, objectHeight) = refresh_area.Get()
- # Calculate the area, offset by the scrollwindow's origin
- area = wx.Rect(objectX - scrollWindowOriginX,
- objectY - scrollWindowOriginY,
- objectWidth, objectHeight)
+ # Calculate the area, offset by the scrollwindow's origin
+ area = wx.Rect(objectX - scrollWindowOriginX,
+ objectY - scrollWindowOriginY,
+ objectWidth, objectHeight)
- if (updateRegion.ContainsRect(area) != wx.OutRegion and
- widget.visible):
+ if (updateRegion.ContainsRect(area) != wx.OutRegion and
+ widget.visible):
- dc.SetDeviceOrigin(objectX + dcOriginX, objectY + dcOriginY)
- widget.draw(dc)
- dc.SetDeviceOrigin(dcOriginX, dcOriginY)
+ dc.SetDeviceOrigin(objectX + dcOriginX, objectY + dcOriginY)
+ widget.draw(dc)
+ dc.SetDeviceOrigin(dcOriginX, dcOriginY)
- # Draw a box around all the selected widgets
- if self.__selection_area is not None and not self.__hide_selection_frame:
- x, y, w, h = self.__selection_area.Get()
- self.__draw_selection_box(dc, x, y, w, h)
+ # Draw a box around all the selected widgets
+ if self.__selection_area is not None and not
self.__hide_selection_frame:
+ x, y, w, h = self.__selection_area.Get()
+ self.__draw_selection_box(dc, x, y, w, h)
def __draw_selection_box(self, dc, x, y, w, h, xor=False):
@@ -348,16 +348,16 @@
# Draw the main border
dc.SetBrush(wx.TRANSPARENT_BRUSH)
if xor:
- dc.SetPen(wx.Pen(wx.WHITE, 1, wx.DOT))
- dc.SetLogicalFunction(wx.XOR)
+ dc.SetPen(wx.Pen(wx.WHITE, 1, wx.DOT))
+ dc.SetLogicalFunction(wx.XOR)
else:
- dc.SetPen(wx.Pen(color_map['selectionframe']))
+ dc.SetPen(wx.Pen(color_map['selectionframe']))
dc.DrawRectangle(x, y, w, h)
# Draw the sizer grippers
if not xor:
- dc.SetBrush(wx.Brush(wx.WHITE))
+ dc.SetBrush(wx.Brush(wx.WHITE))
for bx, by, position in (
(x - 2, y - 2, 'resize-ul'), # upper left
@@ -373,7 +373,7 @@
rect = wx.Rect(bx,by,5,5)
dc.DrawRectangleRect(rect)
if not xor:
- add_hotspot((rect,position))
+ add_hotspot((rect,position))
# Add hotspot markers for the selection box
if not xor:
@@ -461,7 +461,7 @@
# ---------------------------------------------------------------
# Mouse events
# ---------------------------------------------------------------
- def __wx_mouse_left_down(self, event):
+ def __wx_mouse_left_down(self, event):
"""
Left Button Clicked (down)
"""
@@ -508,7 +508,7 @@
return True
- def __wx_mouse_left_up(self, event):
+ def __wx_mouse_left_up(self, event):
"""
Left Button Released
"""
@@ -557,8 +557,8 @@
pass
return True
-
- def __wx_mouse_left_double(self, event):
+
+ def __wx_mouse_left_double(self, event):
"""
Left Button double-clicked
"""
@@ -567,15 +567,15 @@
mode = self.__mouse_mode
current_action = self.__mouse_current_action
- if mode == 'normal':
+ if mode == 'normal':
widget = self.select_hit_test(x, y)
- if widget:
+ if widget:
widget.enter_edit_mode()
return True
-
-
- def __wx_mouse_right_down(self, event):
+
+
+ def __wx_mouse_right_down(self, event):
"""
Right Button Clicked (down)
"""
@@ -586,7 +586,7 @@
return True
- def __wx_mouse_right_up(self, event):
+ def __wx_mouse_right_up(self, event):
"""
Right Button Released
"""
@@ -598,7 +598,7 @@
return True
- def __wx_mouse_right_double(self, event):
+ def __wx_mouse_right_double(self, event):
"""
Right Button double-clicked
"""
@@ -608,9 +608,9 @@
current_action = self.__mouse_current_action
return True
-
- def __wx_mouse_motion(self, event):
+
+ def __wx_mouse_motion(self, event):
"""
Mouse cursor moved
"""
@@ -650,7 +650,7 @@
return True
- def __wx_mouse_wheel(self, event):
+ def __wx_mouse_wheel(self, event):
"""
Mouse wheel scrolled
"""
@@ -663,7 +663,7 @@
return True
-
+
# ---------------------------------------------------------------
# Get all selected widgets
# ---------------------------------------------------------------
@@ -932,31 +932,31 @@
# Drag and Drop support
# ---------------------------------------------------------------
def OnData(self, dataObject, x, y, result):
- """
- Handle default behavior of copy and move
- """
- # TODO: this is left over from SimpleCanvas.py... not used yet.
- if result == wx.DragMove or result == wx.DragCopy:
- if(self.internalDnDItem != None) and(result == wx.DragMove):
- assert(self.ordered_widget_list.count(self.internalDnDItem) == 1)
+ """
+ Handle default behavior of copy and move
+ """
+ # TODO: this is left over from SimpleCanvas.py... not used yet.
+ if result == wx.DragMove or result == wx.DragCopy:
+ if(self.internalDnDItem != None) and(result == wx.DragMove):
+ assert(self.ordered_widget_list.count(self.internalDnDItem) ==
1)
- widget = self.ConvertDataObjectToDrawableObject(dataObject, x,
y, True)
- x = widget.refresh_area.GetLeft()
- y = widget.refresh_area.GetTop()
+ widget = self.ConvertDataObjectToDrawableObject(dataObject, x,
y, True)
+ x = widget.refresh_area.GetLeft()
+ y = widget.refresh_area.GetTop()
- self.ordered_widget_list.remove(self.internalDnDItem)
- self.ordered_widget_list.insert(0, self.internalDnDItem)
- self.internalDnDItem.MoveTo(x, y)
- self.internalDnDItem.Show(True)
- else:
+ self.ordered_widget_list.remove(self.internalDnDItem)
+ self.ordered_widget_list.insert(0, self.internalDnDItem)
+ self.internalDnDItem.MoveTo(x, y)
+ self.internalDnDItem.Show(True)
+ else:
- widget = self.ConvertDataObjectToDrawableObject(dataObject, x,
y, False)
- x = widget.refresh_area.GetLeft()
- y = widget.refresh_area.GetTop()
+ widget = self.ConvertDataObjectToDrawableObject(dataObject, x,
y, False)
+ x = widget.refresh_area.GetLeft()
+ y = widget.refresh_area.GetTop()
- self.ordered_widget_list.insert(0, widget)
- widget.force_canvas_refresh()
- return result
+ self.ordered_widget_list.insert(0, widget)
+ widget.force_canvas_refresh()
+ return result
# ---------------------------------------------------------------
@@ -1040,4 +1040,3 @@
been selected from a mouse click.
"""
assert(False)
-
\ No newline at end of file
Modified: trunk/gnue-designer/src/ui/wx/uihelpers/doccanvas/colors.py
===================================================================
--- trunk/gnue-designer/src/ui/wx/uihelpers/doccanvas/colors.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/ui/wx/uihelpers/doccanvas/colors.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -30,7 +30,7 @@
color_map = {}
def build_color_map():
- if color_map:
+ if color_map:
return
color_map['selectionframe'] = wx.BLUE #
wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DHILIGHT)
color_map['selectedframe'] = wx.BLUE #
wx.SystemSettings_GetColour(wx.SYS_COLOUR_HOTLIGHT)
@@ -43,7 +43,7 @@
color_map['widgetlight'] =
wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DLIGHT)
color_map['widgetback'] = wx.WHITE
-def buildTermcolor_map():
+def buildTermcolor_map():
color_map['selectionframe'] = wx.BLUE #
wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNHIGHLIGHT)
color_map['selectedframe'] = wx.BLUE #
wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNHIGHLIGHT)
color_map['workspace'] =
wx.SystemSettings_GetColour(wx.SYS_COLOUR_APPWORKSPACE)
@@ -52,4 +52,3 @@
color_map['text'] = wx.WHITE
color_map['widget'] = wx.TRANSPARENT
color_map['widgetback'] = wx.WHITE
-
Modified: trunk/gnue-designer/src/ui/wx/uihelpers/doccanvas/dnd.py
===================================================================
--- trunk/gnue-designer/src/ui/wx/uihelpers/doccanvas/dnd.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/ui/wx/uihelpers/doccanvas/dnd.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -31,113 +31,112 @@
# A draggable image frame
# ===================================================================
class wxCanvasDragImage(wx.Frame):
- """
- A class similar to wx.DragImage except that it uses a shaped frame
- to display the image, and that it is always full screen.
- """
- def __init__(self, bitmap):
- super(wxCanvasDragImage, self).__init__(
- None, -1, "",
- style = wx.FRAME_SHAPED
- | wx.SIMPLE_BORDER
- | wx.FRAME_NO_TASKBAR
- | wx.STAY_ON_TOP)
- self.bmp = bitmap
- w, h = self.bmp.GetWidth(), self.bmp.GetHeight()
- self.SetClientSize((w, h) )
- self.hotspot = None
- self.window = None
+ """
+ A class similar to wx.DragImage except that it uses a shaped frame
+ to display the image, and that it is always full screen.
+ """
+ def __init__(self, bitmap):
+ super(wxCanvasDragImage, self).__init__(
+ None, -1, "",
+ style = wx.FRAME_SHAPED
+ | wx.SIMPLE_BORDER
+ | wx.FRAME_NO_TASKBAR
+ | wx.STAY_ON_TOP)
+ self.bmp = bitmap
+ w, h = self.bmp.GetWidth(), self.bmp.GetHeight()
+ self.SetClientSize((w, h) )
+ self.hotspot = None
+ self.window = None
- self.Bind(wx.EVT_PAINT, self.OnPaint)
+ self.Bind(wx.EVT_PAINT, self.OnPaint)
- if "__WXGTK__" in wx.PlatformInfo:
- # wxGTK requires that the window be created before you can
- # set its shape, so delay the call to SetWindowShape until
- # this event.
- self.Bind(wx.EVT_WINDOW_CREATE, self.SetWindowShape)
- else:
- # On wxMSW and wxMac the window has already been created, so go for it.
- self.SetWindowShape()
+ if "__WXGTK__" in wx.PlatformInfo:
+ # wxGTK requires that the window be created before you can
+ # set its shape, so delay the call to SetWindowShape until
+ # this event.
+ self.Bind(wx.EVT_WINDOW_CREATE, self.SetWindowShape)
+ else:
+ # On wxMSW and wxMac the window has already been created, so go
for it.
+ self.SetWindowShape()
- def SetWindowShape(self, evt=None, hotspot=None):
- # Use the bitmap's mask to determine the region
- rgn = wx.RegionFromBitmap(self.bmp)
- if hotspot is not None:
- # punch a hole in the region at the hotspot to allow mouse events
- # through to the window below
- rect = wx.Rect(hotspot.x-1, hotspot.y-1, 3, 3)
- rgn.SubtractRect(rect)
- self.SetShape(rgn)
+ def SetWindowShape(self, evt=None, hotspot=None):
+ # Use the bitmap's mask to determine the region
+ rgn = wx.RegionFromBitmap(self.bmp)
+ if hotspot is not None:
+ # punch a hole in the region at the hotspot to allow mouse events
+ # through to the window below
+ rect = wx.Rect(hotspot.x-1, hotspot.y-1, 3, 3)
+ rgn.SubtractRect(rect)
+ self.SetShape(rgn)
- def BeginDrag(self, hotspot, window, *ignoreOthers):
- self.hotspot = wx.Point(hotspot[0], hotspot[1])
- if "__WXGTK__" not in wx.PlatformInfo:
- self.SetWindowShape(hotspot = self.hotspot)
- self.window = window
- if self.window:
- self.window.CaptureMouse()
+ def BeginDrag(self, hotspot, window, *ignoreOthers):
+ self.hotspot = wx.Point(hotspot[0], hotspot[1])
+ if "__WXGTK__" not in wx.PlatformInfo:
+ self.SetWindowShape(hotspot = self.hotspot)
+ self.window = window
+ if self.window:
+ self.window.CaptureMouse()
- def EndDrag(self, doDestroy=True):
- if self.window and self.window.HasCapture():
- self.window.ReleaseMouse()
- self.Hide()
- if doDestroy:
- self.Destroy()
+ def EndDrag(self, doDestroy=True):
+ if self.window and self.window.HasCapture():
+ self.window.ReleaseMouse()
+ self.Hide()
+ if doDestroy:
+ self.Destroy()
- def Move(self, pt):
- """
- Move the image to a new location on screen. The pt parameter
- is a point in client coordinants relative to the window
- specifed in BeginDrag. (Only for compatibility with
- wx.DragImage, otherwise I would just use screen coordinants...)
- """
- pt2 = pt
- if self.window:
- pt2 = self.window.ClientToScreen(pt)
- self.SetPosition(pt2 - self.hotspot)
+ def Move(self, pt):
+ """
+ Move the image to a new location on screen. The pt parameter
+ is a point in client coordinants relative to the window
+ specifed in BeginDrag. (Only for compatibility with
+ wx.DragImage, otherwise I would just use screen coordinants...)
+ """
+ pt2 = pt
+ if self.window:
+ pt2 = self.window.ClientToScreen(pt)
+ self.SetPosition(pt2 - self.hotspot)
- def Show(self):
- wx.Frame.Show(self)
- self.Update()
+ def Show(self):
+ wx.Frame.Show(self)
+ self.Update()
- def OnPaint(self, evt):
- dc = wx.PaintDC(self)
- dc.DrawBitmap(self.bmp, 0, 0, True)
+ def OnPaint(self, evt):
+ dc = wx.PaintDC(self)
+ dc.DrawBitmap(self.bmp, 0, 0, True)
# ===================================================================
# A draggable drop source
# ===================================================================
class wxCanvasDropSource(wx.DropSource):
- def __init__(self, drawableObject, dataObject):
- super(wxCanvasDropSource, self).__init__(drawableObject.canvas)
- self.drawableObject = drawableObject
- self.SetData(dataObject)
+ def __init__(self, drawableObject, dataObject):
+ super(wxCanvasDropSource, self).__init__(drawableObject.canvas)
+ self.drawableObject = drawableObject
+ self.SetData(dataObject)
- def GiveFeedback(self, effect):
- windowX, windowY = wx.GetMousePosition()
- self.drawableObject.Show(effect != wx.DragMove)
- x, y = self.drawableObject.canvas.ScreenToClientXY(windowX, windowY)
- self.drawableObject.dragImage.Move((x, y))
- return False
+ def GiveFeedback(self, effect):
+ windowX, windowY = wx.GetMousePosition()
+ self.drawableObject.Show(effect != wx.DragMove)
+ x, y = self.drawableObject.canvas.ScreenToClientXY(windowX, windowY)
+ self.drawableObject.dragImage.Move((x, y))
+ return False
# ===================================================================
# A draggable drop target
# ===================================================================
class wxCanvasDropTarget(wx.PyDropTarget):
- def __init__(self, canvas, dropTargetDataObject):
- super(wxCanvasDropTarget, self).__init__()
- self.canvas = canvas
- self.dataObject = dropTargetDataObject
- self.SetDataObject(dropTargetDataObject)
+ def __init__(self, canvas, dropTargetDataObject):
+ super(wxCanvasDropTarget, self).__init__()
+ self.canvas = canvas
+ self.dataObject = dropTargetDataObject
+ self.SetDataObject(dropTargetDataObject)
- def OnData(self, x, y, result):
- """
- Delegate functionality to the canvas
- """
- if(self.GetData()):
- x, y = self.canvas.CalcUnscrolledPosition(x, y)
- result = self.canvas.OnData(self.dataObject, x, y, result)
- return result
-
+ def OnData(self, x, y, result):
+ """
+ Delegate functionality to the canvas
+ """
+ if(self.GetData()):
+ x, y = self.canvas.CalcUnscrolledPosition(x, y)
+ result = self.canvas.OnData(self.dataObject, x, y, result)
+ return result
Modified: trunk/gnue-designer/src/ui/wx/uihelpers/doccanvas/widget.py
===================================================================
--- trunk/gnue-designer/src/ui/wx/uihelpers/doccanvas/widget.py 2006-04-03
19:53:03 UTC (rev 8343)
+++ trunk/gnue-designer/src/ui/wx/uihelpers/doccanvas/widget.py 2006-04-03
19:56:14 UTC (rev 8344)
@@ -65,81 +65,81 @@
def show(self, show=True):
- # Make sure show is a Boolean
- show = bool(show)
+ # Make sure show is a Boolean
+ show = bool(show)
- if(show ^ self.visible):
- self.visible = show
- self.force_canvas_refresh()
- self.canvas.Update()
+ if(show ^ self.visible):
+ self.visible = show
+ self.force_canvas_refresh()
+ self.canvas.Update()
def ConvertToCanvasDeviceCoordinates(self, x, y):
- return self.canvas.CalcScrolledPosition(self.refresh_area.GetLeft() + x,
- self.refresh_area.GetTop() + y)
+ return self.canvas.CalcScrolledPosition(self.refresh_area.GetLeft() +
x,
+ self.refresh_area.GetTop() +
y)
def DoDrag(self, x, y):
- """
- Implement all the drag and drop functionality:
- """
+ """
+ Implement all the drag and drop functionality:
+ """
- """
- Create the dragImage and begin dragging over the full screen
- """
- offscreenBuffer = wx.EmptyBitmap(self.refresh_area.GetWidth(),
self.refresh_area.GetHeight())
- memoryDC = wx.MemoryDC()
- memoryDC.SelectObject(offscreenBuffer)
+ """
+ Create the dragImage and begin dragging over the full screen
+ """
+ offscreenBuffer = wx.EmptyBitmap(self.refresh_area.GetWidth(),
self.refresh_area.GetHeight())
+ memoryDC = wx.MemoryDC()
+ memoryDC.SelectObject(offscreenBuffer)
- memoryDC.BeginDrawing()
- memoryDC.Clear()
- self.draw(memoryDC)
+ memoryDC.BeginDrawing()
+ memoryDC.Clear()
+ self.draw(memoryDC)
- maskBitmap = wx.EmptyBitmap(self.refresh_area.GetWidth(),
self.refresh_area.GetHeight(), 1)
- memoryDC.SelectObject(maskBitmap)
+ maskBitmap = wx.EmptyBitmap(self.refresh_area.GetWidth(),
self.refresh_area.GetHeight(), 1)
+ memoryDC.SelectObject(maskBitmap)
- memoryDC.SetBackground(wx.BLACK_BRUSH)
- memoryDC.Clear()
+ memoryDC.SetBackground(wx.BLACK_BRUSH)
+ memoryDC.Clear()
- self.draw_mask(memoryDC)
- memoryDC.EndDrawing()
+ self.draw_mask(memoryDC)
+ memoryDC.EndDrawing()
- memoryDC.SelectObject(wx.NullBitmap)
+ memoryDC.SelectObject(wx.NullBitmap)
- if "__WXMAC__" in wx.PlatformInfo: # workaround for wxMac bug
- offscreenBuffer.SetMask(wx.Mask(maskBitmap, wx.BLACK))
- else:
- offscreenBuffer.SetMask(wx.Mask(maskBitmap))
+ if "__WXMAC__" in wx.PlatformInfo: # workaround for wxMac bug
+ offscreenBuffer.SetMask(wx.Mask(maskBitmap, wx.BLACK))
+ else:
+ offscreenBuffer.SetMask(wx.Mask(maskBitmap))
- """
- Create the dragImage and begin dragging
- """
- if "__WXGTK__" in wx.PlatformInfo:
- # The "hole punching" trick dosen't work on wxGTK, move the hostspot
- # to be just outside the image
- x, y = -1, -1
- self.dragImage = dnd.wxCanvasDragImage(offscreenBuffer)
+ """
+ Create the dragImage and begin dragging
+ """
+ if "__WXGTK__" in wx.PlatformInfo:
+ # The "hole punching" trick dosen't work on wxGTK, move the
hostspot
+ # to be just outside the image
+ x, y = -1, -1
+ self.dragImage = dnd.wxCanvasDragImage(offscreenBuffer)
- self.dragImage.BeginDrag(wx.Point(x,y), self.canvas, True)
- self.dragImage.Move(self.ConvertToCanvasDeviceCoordinates(x, y))
- self.dragImage.Show()
+ self.dragImage.BeginDrag(wx.Point(x,y), self.canvas, True)
+ self.dragImage.Move(self.ConvertToCanvasDeviceCoordinates(x, y))
+ self.dragImage.Show()
- """
- We need to keep a reference to the dataObject, rather than create
- it in the construction because wxCanvasDropSource doesn't own the
- data so the garbage collector will delete it.
- """
- dataObject = self.ConvertDrawableObjectToDataObject(x, y)
- dropSource = dnd.wxCanvasDropSource(self, dataObject)
+ """
+ We need to keep a reference to the dataObject, rather than create
+ it in the construction because wxCanvasDropSource doesn't own the
+ data so the garbage collector will delete it.
+ """
+ dataObject = self.ConvertDrawableObjectToDataObject(x, y)
+ dropSource = dnd.wxCanvasDropSource(self, dataObject)
- self.canvas.internalDnDItem = self
- result = dropSource.DoDragDrop(wx.Drag_AllowMove)
- self.canvas.internalDnDItem = None
- self.dragImage.Hide()
- self.dragImage.EndDrag()
- del self.dragImage
+ self.canvas.internalDnDItem = self
+ result = dropSource.DoDragDrop(wx.Drag_AllowMove)
+ self.canvas.internalDnDItem = None
+ self.dragImage.Hide()
+ self.dragImage.EndDrag()
+ del self.dragImage
def SizeDrag(self, dragRect, startDrag, endDrag):
- self.force_canvas_refresh()
- self.force_canvas_refresh()
+ self.force_canvas_refresh()
+ self.force_canvas_refresh()
def set_selected(self, selected=True):
"""
@@ -156,10 +156,10 @@
def recalc_metrics(self):
- """
- Force a recalculation of all metric information
- """
- self.calc_metrics()
+ """
+ Force a recalculation of all metric information
+ """
+ self.calc_metrics()
def force_canvas_refresh(self):
@@ -175,19 +175,19 @@
"""
self.draw_widget(dc)
if self.selected:
- self.draw_border(dc)
+ self.draw_border(dc)
self.draw_decorations(dc)
def text_edit(self, x, y, width, height, text, multiline=False):
- PopupTextEdit(self.canvas, self.__end_text_edit, x, y,
+ PopupTextEdit(self.canvas, self.__end_text_edit, x, y,
width, height, text).SetFocus()
- def __end_text_edit(self, success, text=None):
- if success:
+ def __end_text_edit(self, success, text=None):
+ if success:
self.end_text_edit(text)
- else:
+ else:
self.cancel_text_edit()
# ====================================================================
@@ -233,10 +233,10 @@
result = self.hit_test_area.Intersects(area)
if result:
- # If the entire dragRect is in an exclusion area, return false
- for exclusion in self.hit_test_exclusions:
- if exclusion.Intersect(area) == area:
- return False
+ # If the entire dragRect is in an exclusion area, return false
+ for exclusion in self.hit_test_exclusions:
+ if exclusion.Intersect(area) == area:
+ return False
return result
@@ -296,51 +296,51 @@
assert(False)
- def enter_edit_mode(self):
+ def enter_edit_mode(self):
"""
- Called when the user has asked to "edit" the widget, by
- double-clicking or pressing the equivalent hotkey.
+ Called when the user has asked to "edit" the widget, by
+ double-clicking or pressing the equivalent hotkey.
On widgets with text, this usually switches to an input box
- letting the user edit the text.
-
- If your widget has no concept of being editable, then
+ letting the user edit the text.
+
+ If your widget has no concept of being editable, then
you can leave this method as-is.
"""
pass
-
-
- def validate_text_edit(self, text):
+
+
+ def validate_text_edit(self, text):
"""
- Called when self.text_edit() has been called in your code, and
- the user has saved their edited changes.
-
+ Called when self.text_edit() has been called in your code, and
+ the user has saved their edited changes.
+
You should return True or False depending on if their
- entered value is considered valid. If you return True,
- then end_text_edit() is immediately called. Otherwise,
- the user is warned.
+ entered value is considered valid. If you return True,
+ then end_text_edit() is immediately called. Otherwise,
+ the user is warned.
"""
-
+
return True
-
- def end_text_edit(self, text):
+
+ def end_text_edit(self, text):
"""
- Called when self.text_edit() has been called in your code, and
- the user has saved their edited changes.
-
- If you never call self.text_edit(), there's no need to
+ Called when self.text_edit() has been called in your code, and
+ the user has saved their edited changes.
+
+ If you never call self.text_edit(), there's no need to
implement this method.
"""
assert(False)
- def cancel_text_edit(self, text):
+ def cancel_text_edit(self, text):
"""
- Called when self.text_edit() has been called in your code, and
- the user has canceled the edit.
-
- If you never call self.text_edit(), there's no need to
+ Called when self.text_edit() has been called in your code, and
+ the user has canceled the edit.
+
+ If you never call self.text_edit(), there's no need to
implement this method.
-
- Usually, there is no need for anything more than a NO-OP.
+
+ Usually, there is no need for anything more than a NO-OP.
"""
pass
[Prev in Thread] |
Current Thread |
[Next in Thread] |
- [gnue] r8344 - in trunk/gnue-designer/src: . base base/tools forms forms/LayoutEditor forms/LayoutEditor/renderers/Base forms/LayoutEditor/renderers/curses forms/LayoutEditor/renderers/native forms/PagePainter forms/PagePainter/skins forms/events forms/wizards navigator projects reports reports/Char reports/Default reports/Labels reports/MailMerge reports/SimpleTabulation reports/Standard schema schema/DiaEditor schema/wizards templates templates/forms templates/reports templates/schema ui/wx ui/wx/startup ui/wx/uihelpers ui/wx/uihelpers/doccanvas,
jcater <=