Skip to content
Browse files

Merge commit '3e74b545b158a44aac'

  • Loading branch information...
2 parents 1bf01cb + 3e74b54 commit 261c4a1de30acff5179864856d0ebf83f585c127 @amolenaar committed Apr 27, 2011
View
50 examples/list_classes.py 100755 → 100644
@@ -1,43 +1,51 @@
#!/usr/bin/python
-"""
-This script list classes and optionally attributes from UML model created
-with Gaphor.
-"""
+"""This script list classes and optionally attributes from UML model
+created with Gaphor."""
-import gaphor
-from gaphor.storage import storage
-import gaphor.UML as UML
-
-import optparse
import sys
+import optparse
+from gaphor import Application
+import gaphor.UML as UML
+
+#Setup command line options.
usage = 'usage: %prog [options] file.gaphor'
parser = optparse.OptionParser(usage=usage)
-parser.add_option('-a', '--attributes', dest='attrs', action='store_true',
- help='print classes attributes')
+parser.add_option('-a',\
+ '--attributes',\
+ dest='attrs',\
+ action='store_true',\
+ help='Print class attributes')
(options, args) = parser.parse_args()
if len(args) != 1:
parser.print_help()
sys.exit(1)
+#The model file to load.
model = args[0]
-# create UML object factory
-factory = UML.ElementFactory()
+#Create the Gaphor application object.
+Application.init()
-# load model from file
-storage.load(model, factory)
+#Get services we need.
+element_factory = Application.get_service('element_factory')
+file_manager = Application.get_service('file_manager')
-# find all classes using factory
-for cls in factory.select(lambda e: e.isKindOf(UML.Class)):
- print 'found class %s' % cls.name
+#Load model from file.
+file_manager.load(model)
+
+#Find all classes using factory select.
+for cls in element_factory.select(lambda e: e.isKindOf(UML.Class)):
+
+ print 'Found class %s' % cls.name
+
if options.attrs:
+
for attr in cls.ownedAttribute:
- print ' attr: %s' % attr.name
-
-# vim:sw=4:et:ai
+
+ print ' Attribute: %s' % attr.name
View
11 gaphor/UML/tests/test_uml2.py
@@ -119,13 +119,24 @@ def test_constraint(self):
def test_dependency(self):
+ """Testing Dependency elements in the meta-model"""
+
try:
element = self.factory.create(UML.Dependency)
except AttributeError:
self.fail('Dependency elements are not part of the meta-model')
+
+ client = self.factory.create(UML.Package)
+ supplier = self.factory.create(UML.Package)
+
+ element.client = client
+ element.supplier = supplier
+
+ self.assertTrue(client in element.source, 'DirectedRelationship.source does not contain client - %s' % element.client)
+ self.assertTrue(supplier in element.target, 'DirectedRelationship.target does not contain supplier - %s' % element.supplier)
def test_element_import(self):
View
13 gaphor/i18n.py
@@ -1,10 +1,7 @@
-# vim:sw=4:et
-"""
-Internationalization (i18n) support for Gaphor.
+"""Internationalization (i18n) support for Gaphor.
Here the _() function is defined that is used to translate text into
-your native language.
-"""
+your native language."""
__all__ = [ '_' ]
@@ -13,15 +10,15 @@
import gettext
import pkg_resources
-# default locale dir = site-base/gaphor/data/locale/<lang>/LC_MESSAGES/gaphor.mo
localedir = os.path.join(pkg_resources.get_distribution('gaphor').location, \
'gaphor', 'data', 'locale')
try:
+
catalog = gettext.Catalog('gaphor', localedir=localedir)
- #log.info('catalog = %s' % catalog.info())
_ = catalog.gettext
+
except IOError, e:
- #log.error('Could not load locale catalog', exc_info=True)
+
def _(s): return s
View
32 gaphor/services/filemanager.py
@@ -2,14 +2,15 @@
The file service is responsible for loading and saving the user data.
"""
+from logging import getLogger
+
import gtk
from zope import interface, component
from gaphor.interfaces import IService, IActionProvider, IServiceEvent
from gaphor.core import _, inject, action, build_action_group
from gaphor.storage import storage, verify
from gaphor import UML
-from logging import getLogger
from gaphor.misc.gidlethread import GIdleThread, Queue, QueueEmpty
from gaphor.misc.errorhandler import error_handler
from gaphor.misc.xmlwriter import XMLWriter
@@ -136,7 +137,10 @@ def get_recent_files(self):
"""Returns the recent file list from the properties service. This
method is used by the recent_files property."""
- return self.properties.get('recent-files', [])
+ try:
+ return self.properties.get('recent-files', [])
+ except component.interfaces.ComponentLookupError:
+ return []
def set_recent_files(self, recent_files):
"""Updates the properties service with the supplied list of recent
@@ -145,7 +149,10 @@ def set_recent_files(self, recent_files):
self.logger.info('Storing recent files')
self.logger.debug('Recent files are %s' % recent_files)
- self.properties.set('recent-files', recent_files)
+ try:
+ self.properties.set('recent-files', recent_files)
+ except component.interfaces.ComponentLookupError:
+ return
recent_files = property(get_recent_files, set_recent_files)
@@ -201,13 +208,17 @@ def load(self, filename):
self.logger.info('Loading file')
self.logger.debug('Path is %s' % filename)
- main_window = self.main_window
-
queue = Queue()
- status_window = StatusWindow(_('Loading...'),\
- _('Loading model from %s') % filename,\
- parent=main_window.window,\
- queue=queue)
+
+ try:
+ main_window = self.main_window
+ status_window = StatusWindow(_('Loading...'),\
+ _('Loading model from %s') % filename,\
+ parent=main_window.window,\
+ queue=queue)
+ except component.interfaces.ComponentLookupError:
+ status_window = None
+
try:
loader = storage.load_generator(filename.encode('utf-8'), self.element_factory)
worker = GIdleThread(loader, queue)
@@ -223,7 +234,8 @@ def load(self, filename):
error_handler(message=_('Error while loading model from file %s') % filename)
raise
finally:
- status_window.destroy()
+ if status_window is not None:
+ status_window.destroy()
def verify_orphans(self):
View
23 gaphor/services/helpservice.py
@@ -1,12 +1,11 @@
-"""
-About and help services. (help browser anyone?)
-"""
-
+"""About and help services. (help browser anyone?)"""
+from logging import getLogger
import os
import pkg_resources
import gtk
from zope import interface
+
from gaphor.application import Application
from gaphor.interfaces import IService, IActionProvider
from gaphor.core import _, inject, action, build_action_group
@@ -28,22 +27,24 @@ class HelpService(object):
"""
main_window = inject('main_window')
+ logger = getLogger('HelpService')
def __init__(self):
pass
def init(self, app):
+ self.logger.info('Starting')
self.action_group = build_action_group(self)
def shutdown(self):
- pass
+ self.logger.info('Shutting down')
@action(name='help-about', stock_id='gtk-about')
def about(self):
logo_file = os.path.join(pkg_resources.get_distribution('gaphor').location, 'gaphor', 'ui', 'pixmaps', 'logo.png')
logo = gtk.gdk.pixbuf_new_from_file(logo_file)
version = Application.distribution.version
- about = gtk.Dialog("About Gaphor", self.main_window.window, gtk.DIALOG_MODAL, (gtk.STOCK_OK, gtk.RESPONSE_OK))
+ about = gtk.Dialog(_('About Gaphor'), self.main_window.window, gtk.DIALOG_MODAL, (gtk.STOCK_OK, gtk.RESPONSE_OK))
about.set_default_response(gtk.RESPONSE_OK)
vbox = about.vbox
@@ -53,7 +54,6 @@ def about(self):
notebook = gtk.Notebook()
notebook.set_scrollable(True)
- #notebook.set_show_border(False)
notebook.set_border_width(4)
notebook.set_tab_pos(gtk.POS_BOTTOM)
vbox.pack_start(notebook)
@@ -67,20 +67,19 @@ def add_label(text, padding_x=0, padding_y=0):
label.set_justify(gtk.JUSTIFY_CENTER)
tab_vbox.pack_start(label)
- #add_label('<span size="xx-large" weight="bold">Gaphor</span>')
add_label('<span weight="bold">version %s</span>' % version)
add_label('<span variant="smallcaps">UML Modeling tool for GNOME</span>', 8, 8)
add_label('<span size="small">Copyright (c) 2001-2007 Arjan J. Molenaar</span>', 8, 8)
- #vbox.pack_start(gtk.HSeparator())
- notebook.append_page(tab_vbox, gtk.Label('About'))
+
+ notebook.append_page(tab_vbox, gtk.Label(_('About')))
tab_vbox = gtk.VBox()
add_label('This software is published\n'
'under the terms of the\n'
'<span weight="bold">GNU General Public License v2</span>.\n'
'See the COPYING file for details.', 0, 8)
- notebook.append_page(tab_vbox, gtk.Label('License'))
+ notebook.append_page(tab_vbox, gtk.Label(_('License')))
tab_vbox = gtk.VBox()
@@ -89,7 +88,7 @@ def add_label(text, padding_x=0, padding_y=0):
'Artur Wroblewski\n'
'Jeroen Vloothuis')
add_label('')
- notebook.append_page(tab_vbox, gtk.Label('Authors'))
+ notebook.append_page(tab_vbox, gtk.Label(_('Authors')))
vbox.show_all()
about.run()
View
34 gaphor/tests/test_application.py
@@ -1,30 +1,32 @@
-"""
-Application service test cases.
-"""
+"""Application service test cases."""
import unittest
+from zope import component
+
from gaphor import UML
from gaphor.application import Application
-from zope import component
from gaphor.interfaces import IService
-
class LoadServiceTestCase(unittest.TestCase):
+
+ """Test case for loading Gaphor services."""
+
def test_service_load(self):
- """
- Load services. At lease the undo_manager should be available after that.
- """
+ """Test loading services and querying utilities."""
+
Application.init(['undo_manager', 'file_manager', 'properties'])
- self.assertTrue(Application.get_service('undo_manager') is not None)
- self.assertTrue(Application.get_service('file_manager') is not None)
+ self.assertTrue(Application.get_service('undo_manager') is not None,\
+ 'Failed to load the undo manager service')
+
+ self.assertTrue(Application.get_service('file_manager') is not None,\
+ 'Failed to load the file manager service')
- # After that, services are also available as Utilities:
- self.assertTrue(component.queryUtility(IService, 'undo_manager') is not None)
- self.assertTrue(component.queryUtility(IService, 'file_manager') is not None)
+ self.assertTrue(component.queryUtility(IService, 'undo_manager') is not None,\
+ 'Failed to query the undo manager utility')
+
+ self.assertTrue(component.queryUtility(IService, 'file_manager') is not None,\
+ 'Failed to query the file manager utility')
Application.shutdown()
-
-
-# vim:sw=4:et:ai
View
135 gaphor/tests/test_transaction.py
@@ -1,6 +1,9 @@
+"""Unit tests for transactions in Gaphor."""
from unittest import TestCase
+
from zope.component.globalregistry import base
+
from gaphor.application import Application
from gaphor.transaction import Transaction, transactional, TransactionError
from gaphor.event import TransactionBegin, TransactionCommit, TransactionRollback
@@ -9,126 +12,152 @@
commits = []
rollbacks = []
-def handle_begins(ev):
- begins.append(ev)
+def handle_begins(event):
+ """Store TransactionBegin events in begins."""
+ begins.append(event)
-def handle_commits(ev):
- commits.append(ev)
-
-def handle_rollback(ev):
- rollbacks.append(ev)
+def handle_commits(event):
+ """Store TransactionCommit events in commits."""
+ commits.append(event)
+def handle_rollback(event):
+ """Store TransactionRollback events in rollbacks."""
+ rollbacks.append(event)
class TransactionTestCase(TestCase):
+ """Test case for transactions with the component registry
+ enabled."""
def setUp(self):
+ """Initialize Gaphor services and register transaction event
+ handlers."""
+
Application.init(services=['component_registry'])
+
component_registry = Application.get_service('component_registry')
+
component_registry.register_handler(handle_begins, [TransactionBegin])
component_registry.register_handler(handle_commits, [TransactionCommit])
component_registry.register_handler(handle_rollback, [TransactionRollback])
+
del begins[:]
del commits[:]
del rollbacks[:]
- assert not begins
- assert not commits
- assert not rollbacks
-
-
+
def tearDown(self):
+ """Finished with the test case. Unregister event handlers that
+ store transaction events."""
+
component_registry = Application.get_service('component_registry')
+
component_registry.unregister_handler(handle_begins, [TransactionBegin])
component_registry.unregister_handler(handle_commits, [TransactionCommit])
component_registry.unregister_handler(handle_rollback, [TransactionRollback])
def test_transaction_commit(self):
+ """Test committing a transaction."""
+
tx = Transaction()
- self.assertTrue(tx._stack)
- self.assertEquals(1, len(begins))
- self.assertEquals(0, len(commits))
- self.assertEquals(0, len(rollbacks))
+
+ self.assertTrue(tx._stack, 'Transaction has no stack')
+ self.assertEquals(1, len(begins), 'Incorrect number of TrasactionBegin events')
+ self.assertEquals(0, len(commits), 'Incorrect number of TransactionCommit events')
+ self.assertEquals(0, len(rollbacks), 'Incorrect number of TransactionRollback events')
tx.commit()
- self.assertEquals(1, len(begins))
- self.assertEquals(1, len(commits))
- self.assertEquals(0, len(rollbacks))
-
- self.assertFalse(tx._stack)
+
+ self.assertEquals(1, len(begins), 'Incorrect number of TrasactionBegin events')
+ self.assertEquals(1, len(commits), 'Incorrect number of TransactionCommit events')
+ self.assertEquals(0, len(rollbacks), 'Incorrect number of TransactionRollback events')
+ self.assertFalse(tx._stack, 'Transaction stack is not empty')
try:
tx.commit()
except TransactionError:
- pass # ok
+ pass
else:
- assert False, 'should not be reached'
+ self.fail('Commit should not have succeeded')
def test_transaction_rollback(self):
+ """Test rolling back a transaction."""
+
tx = Transaction()
- self.assertTrue(tx._stack)
- self.assertEquals(1, len(begins))
- self.assertEquals(0, len(commits))
- self.assertEquals(0, len(rollbacks))
+
+ self.assertTrue(tx._stack, 'Transaction has no stack')
+ self.assertEquals(1, len(begins), 'Incorrect number of TrasactionBegin events')
+ self.assertEquals(0, len(commits), 'Incorrect number of TransactionCommit events')
+ self.assertEquals(0, len(rollbacks), 'Incorrect number of TransactionRollback events')
tx.rollback()
- self.assertEquals(1, len(begins))
- self.assertEquals(0, len(commits))
- self.assertEquals(1, len(rollbacks))
+
+ self.assertEquals(1, len(begins), 'Incorrect number of TrasactionBegin events')
+ self.assertEquals(0, len(commits), 'Incorrect number of TransactionCommit events')
+ self.assertEquals(1, len(rollbacks), 'Incorrect number of TransactionRollback events')
- self.assertFalse(tx._stack)
+ self.assertFalse(tx._stack, 'Transaction stack is not empty')
def test_transaction_commit_after_rollback(self):
- tx = Transaction()
+ """Test committing one transaction after rolling back another
+ transaction."""
+
+ tx1 = Transaction()
tx2 = Transaction()
tx2.rollback()
-
- tx.commit()
- self.assertEquals(1, len(begins))
- self.assertEquals(0, len(commits))
- self.assertEquals(1, len(rollbacks))
+ tx1.commit()
+
+ self.assertEquals(1, len(begins), 'Incorrect number of TrasactionBegin events')
+ self.assertEquals(0, len(commits), 'Incorrect number of TransactionCommit events')
+ self.assertEquals(1, len(rollbacks), 'Incorrect number of TransactionRollback events')
def test_transaction_stack(self):
- tx = Transaction()
+ """Test the transaction stack."""
+
+ tx1 = Transaction()
tx2 = Transaction()
try:
- tx.commit()
+ tx1.commit()
except TransactionError, e:
- self.assertEquals('Transaction on stack is not the transaction being closed.', str(e))
+ pass
else:
- assert False, 'should not be reached'
+ self.fail('Commit should not have succeeded')
def test_transaction_context(self):
+ """Test the transaction context manager."""
+
with Transaction() as tx:
- self.assertTrue(isinstance(tx, Transaction))
- self.assertTrue(Transaction._stack)
- self.assertFalse(Transaction._stack)
+
+ self.assertTrue(isinstance(tx, Transaction), 'Context is not a Transaction instance')
+ self.assertTrue(Transaction._stack, 'Transaction instance has no stack inside a context')
+
+ self.assertFalse(Transaction._stack, 'Transaction stack should be empty')
def test_transaction_context_error(self):
+ """Test the transaction context manager with errors."""
+
try:
with Transaction():
- self.assertTrue(Transaction._stack)
- raise TypeError('some error')
+ raise TypeError('transaction error')
except TypeError, e:
- self.assertEquals('some error', str(e))
- self.assertFalse(Transaction._stack)
+ self.assertEquals('transaction error', str(e), 'Transaction context manager did no raise correct exception')
else:
- self.assertFalse(Transaction._stack)
- assert False, 'should not be reached'
-
+ self.fail('Transaction context manager did not raise exception when it should have')
+
class TransactionWithoutComponentRegistryTestCase(TestCase):
+ """Test case for transactions with no component registry."""
def test_transaction(self):
+ """Test basic transaction functionality."""
+
tx = Transaction()
tx.rollback()
tx = Transaction()
tx.commit()
-
-# vim:sw=4:et:ai
View
58 gaphor/ui/diagramtab.py
@@ -2,21 +2,24 @@
import gtk
from cairo import Matrix
-
from zope import component
+from etk.docking import DockItem
+
from gaphas.view import GtkView
+from gaphas.painter import PainterChain, ItemPainter, HandlePainter, \
+ FocusedItemPainter, ToolPainter, BoundingBoxPainter
+from gaphas.freehand import FreeHandPainter
+from gaphas import segment, guide
+
from gaphor import UML
from gaphor.core import _, inject, transactional, action, toggle_action, build_action_group
from gaphor.UML.interfaces import IAttributeChangeEvent, IElementDeleteEvent
from gaphor.diagram import get_diagram_item
from gaphor.diagram.items import DiagramItem
from gaphor.transaction import Transaction
from gaphor.ui.diagramtoolbox import DiagramToolbox
-from event import DiagramSelectionChange
+from gaphor.ui.event import DiagramSelectionChange
from gaphor.services.properties import IPropertyChangeEvent
-from etk.docking import DockItem
-
-from gaphas import segment, guide
class DiagramTab(object):
@@ -186,28 +189,35 @@ def delete_selected_items(self):
def set_drawing_style(self, sloppiness=0.0):
- """
- Set the drawing style for the diagram. 0.0 is straight, 2.0 is very sloppy.
- """
- assert self.view, 'First construct() the diagram tab'
- from gaphas.painter import PainterChain, ItemPainter, HandlePainter, \
- FocusedItemPainter, ToolPainter, BoundingBoxPainter
- from gaphas.freehand import FreeHandPainter
+ """Set the drawing style for the diagram. 0.0 is straight,
+ 2.0 is very sloppy. If the sloppiness is set to be anything
+ greater than 0.0, the FreeHandPainter instances will be used
+ for both the item painter and the box painter. Otherwise, by
+ default, the ItemPainter is used for the item and
+ BoundingBoxPainter for the box."""
+
view = self.view
+
if sloppiness:
- view.painter = PainterChain(). \
- append(FreeHandPainter(ItemPainter(), sloppiness=sloppiness)). \
- append(HandlePainter()). \
- append(FocusedItemPainter()). \
- append(ToolPainter())
- view.bounding_box_painter = FreeHandPainter(BoundingBoxPainter(), sloppiness=sloppiness)
+
+ item_painter = FreeHandPainter(ItemPainter(),\
+ sloppiness=sloppiness)
+ box_painter = FreeHandPainter(BoundingBoxPainter(),\
+ sloppiness=sloppiness)
+
else:
- view.painter = PainterChain(). \
- append(ItemPainter()). \
- append(HandlePainter()). \
- append(FocusedItemPainter()). \
- append(ToolPainter())
- view.bounding_box_painter = BoundingBoxPainter()
+
+ item_painter = ItemPainter()
+ box_painter = BoundingBoxPainter()
+
+ view.painter = PainterChain().\
+ append(item_painter).\
+ append(HandlePainter()).\
+ append(FocusedItemPainter()).\
+ append(ToolPainter())
+
+ view.bounding_box_painter = box_painter
+
view.queue_draw_refresh()
def may_remove_from_model(self, view):

0 comments on commit 261c4a1

Please sign in to comment.
Something went wrong with that request. Please try again.