commit-gnue
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[gnue] r8976 - trunk/gnue-common/src/events


From: jcater
Subject: [gnue] r8976 - trunk/gnue-common/src/events
Date: Fri, 3 Nov 2006 20:38:59 -0600 (CST)

Author: jcater
Date: 2006-11-03 20:38:58 -0600 (Fri, 03 Nov 2006)
New Revision: 8976

Modified:
   trunk/gnue-common/src/events/Event.py
   trunk/gnue-common/src/events/EventAware.py
   trunk/gnue-common/src/events/EventController.py
Log:
cleaned up events, adding new-style property() and removing duplicate code 
where appropriate/possible (should not break compatability with other tools)

Modified: trunk/gnue-common/src/events/Event.py
===================================================================
--- trunk/gnue-common/src/events/Event.py       2006-11-04 00:18:30 UTC (rev 
8975)
+++ trunk/gnue-common/src/events/Event.py       2006-11-04 02:38:58 UTC (rev 
8976)
@@ -32,151 +32,164 @@
 # =============================================================================
 
 class Event(object):
-  """
-  An Event is the actual event object passed back and forth between the event
-  listeners.
+    """
+    An Event is the actual event object passed back and forth between the event
+    listeners.
 
-  Any parameters passed to the Event's __init__ are added as attributes of the
-  event. The first attribute, however, should always be the case-sensitive
-  event name.
+    Any parameters passed to the Event's __init__ are added as attributes of 
the
+    event. The first attribute, however, should always be the case-sensitive
+    event name.
 
-  Creating an Event:
+    Creating an Event:
 
-  >>> myEvent = Event('myEventName', color='Blue', x=1, y=2)
-  >>> myEvent.color
-  'Blue'
-  >>> myEvent.x
-  1
-  >>> myEvent.y
-  2
-  """
+    >>> myEvent = Event('myEventName', color='Blue', x=1, y=2)
+    >>> myEvent.color
+    'Blue'
+    >>> myEvent.x
+    1
+    >>> myEvent.y
+    2
+    """
 
-  # ---------------------------------------------------------------------------
-  # Constructor
-  # ---------------------------------------------------------------------------
+    # 
---------------------------------------------------------------------------
+    # Constructor
+    # 
---------------------------------------------------------------------------
 
-  def __init__ (self, event, data = None, **parms):
-    """
-    @param event: The name of the event. GNUe event listeners register the
-      names of the events they wish to receive.
-    @param data: B{OBSOLETE: Do not use}
-    @param parms: Allows the event to accept any argument names you like.
-      Examples would be things like::
-        caller = self
-        x = 15
-        vals = {'name': 'Bob', 'title': 'Mr'}
-    """
+    def __init__ (self, event, data = None, **parms):
+        """
+        @param event: The name of the event. GNUe event listeners register the
+          names of the events they wish to receive.
+        @param data: B{OBSOLETE: Do not use}
+        @param parms: Allows the event to accept any argument names you like.
+          Examples would be things like::
+            caller = self
+            x = 15
+            vals = {'name': 'Bob', 'title': 'Mr'}
+        """
 
-    self.__dict__.update (parms)
+        self.__dict__.update (parms)
 
-    # TODO: Get rid of data=    
-    self.data          = data
+        # TODO: Get rid of data=    
+        self.data          = data
 
-    self.__event__     = event
-    self.__result__    = None
-    self.__dropped__   = 0
-    self.__error__     = 0
-    self.__errortext__ = ""
-    self.__after__     = []
+        self.__event__     = event
+        self.__result__    = None
+        self.__dropped__   = 0
+        self.__error__     = 0
+        self.__errortext__ = ""
+        self.__after__     = []
 
 
-  # ---------------------------------------------------------------------------
-  # Nice string representation
-  # ---------------------------------------------------------------------------
+    # 
---------------------------------------------------------------------------
+    # Nice string representation
+    # 
---------------------------------------------------------------------------
 
-  def __repr__ (self):
+    def __repr__ (self):
 
-    return "<Event %s at %s>" % (self.__event__, id (self))
+        return "<Event %s at %s>" % (self.__event__, id (self))
 
 
-  # ---------------------------------------------------------------------------
-  # Get the result value stored in the event
-  # ---------------------------------------------------------------------------
+    # 
---------------------------------------------------------------------------
+    # Get the result value stored in the event
+    # 
---------------------------------------------------------------------------
 
-  def getResult (self):
-    """
-    Returns the result value stored in the event by the L{setResult} function.
+    def getResult (self):
+        """
+        Returns the result value stored in the event by the L{setResult} 
function.
 
-    @return: The result value of the event.
-    """
+        @return: The result value of the event.
+        """
 
-    return self.__result__
+        return self.__result__
 
 
-  # ---------------------------------------------------------------------------
-  # Set the result value for the event
-  # ---------------------------------------------------------------------------
+    # 
---------------------------------------------------------------------------
+    # Set the result value for the event
+    # 
---------------------------------------------------------------------------
 
-  def setResult (self, value):
-    """
-    Can be used by an event listener to assign a return value to an event. The
-    result will be returned by the event controller's
-    L{dispatchEvent<gnue.common.events.EventController.EventController>}
-    function. It can also be obtained by the L{getResult} function.
+    def setResult (self, value):
+        """
+        Can be used by an event listener to assign a return value to an event. 
The
+        result will be returned by the event controller's
+        L{dispatchEvent<gnue.common.events.EventController.EventController>}
+        function. It can also be obtained by the L{getResult} function.
 
-    @param value: The result value to assign to the event. It can be anything
-      that is concidered valid python.
-    """
+        @param value: The result value to assign to the event. It can be 
anything
+          that is concidered valid python.
+        """
 
-    self.__result__ = value
+        self.__result__ = value
 
 
-  # ---------------------------------------------------------------------------
-  # Get the name of the event
-  # ---------------------------------------------------------------------------
+    result = property(getResult, setResult)
 
-  def getEvent (self):
-    """
-    Returns the name of the event.
 
-    @return: The name of the event
-    """
+    # 
---------------------------------------------------------------------------
+    # Get the name of the event
+    # 
---------------------------------------------------------------------------
 
-    return self.__event__
+    def getEvent (self):
+        """
+        Returns the name of the event.
 
+        @return: The name of the event
+        """
 
-  # ---------------------------------------------------------------------------
-  # Drop the event
-  # ---------------------------------------------------------------------------
+        return self.__event__
+    
+    
+    event = property(getEvent, None)
 
-  def drop (self):
-    """
-    Drop the event; no additional event listeners will recieve the event.
-    """
 
-    self.__dropped__ = 1
+    # 
---------------------------------------------------------------------------
+    # Drop the event
+    # 
---------------------------------------------------------------------------
 
+    def drop (self):
+        """
+        Drop the event; no additional event listeners will recieve the event.
+        """
 
-  # ---------------------------------------------------------------------------
-  # Set the event's error flag and drop the event
-  # ---------------------------------------------------------------------------
+        self.__dropped__ = True
 
-  def setError (self, text = ""):
-    """
-    Set the event's error flag and drop it (see L{drop}).
 
-    @param text: Text describing the error.
-    """
+    # 
---------------------------------------------------------------------------
+    # Set the event's error flag and drop the event
+    # 
---------------------------------------------------------------------------
 
-    self.__error__     = 1
-    self.__errortext__ = text
+    def setError (self, text = ""):
+        """
+        Set the event's error flag and drop it (see L{drop}).
 
+        @param text: Text describing the error.
+        """
 
-  # ---------------------------------------------------------------------------
-  # Add an event to the event queue
-  # ---------------------------------------------------------------------------
+        self.__error__     = 1
+        self.__errortext__ = text
 
-  def dispatchAfter (self, *args, **parms):
-    """
-    Adds an event to the event queue that will be dispatched upon this events
-    completion. The arguments to this function match those used in creating an
-    event.
 
-    Sample Usage:
+    def getError(self): 
+        return self.__error__ and (self.__errortext__ or 'Unnamed Error') or 
None
 
-    >>> from gnue.common.events.Event import *
-    >>> myEvent = Event ('myEventName', color = 'Blue', x = 1, y = 2)
-    >>> myEvent.dispatchAfter ('theNextEvent', name = 'FSF')
-    """    
 
-    self.__after__.append ((args, parms))
+    error = property(getError, setError)
+
+
+    # 
---------------------------------------------------------------------------
+    # Add an event to the event queue
+    # 
---------------------------------------------------------------------------
+
+    def dispatchAfter (self, *args, **parms):
+        """
+        Adds an event to the event queue that will be dispatched upon this 
events
+        completion. The arguments to this function match those used in 
creating an
+        event.
+
+        Sample Usage:
+
+        >>> from gnue.common.events.Event import *
+        >>> myEvent = Event ('myEventName', color = 'Blue', x = 1, y = 2)
+        >>> myEvent.dispatchAfter ('theNextEvent', name = 'FSF')
+        """    
+
+        self.__after__.append ((args, parms))

Modified: trunk/gnue-common/src/events/EventAware.py
===================================================================
--- trunk/gnue-common/src/events/EventAware.py  2006-11-04 00:18:30 UTC (rev 
8975)
+++ trunk/gnue-common/src/events/EventAware.py  2006-11-04 02:38:58 UTC (rev 
8976)
@@ -32,33 +32,37 @@
 # =============================================================================
 
 class EventAware(object):
-  """
-  The base class for an object that sends and receives events
+    """
+    The base class for an object that sends and receives events
 
-  Sample Usage::
+    Sample Usage::
 
-    from gnue.common import events
-    class myClass (events.EventAware):
-      def __init__ (self)
-        self.eventController = events.EventController()
-        events.EventAware.__init__(self, self.eventController)
-        self.registerEventListeners( {
-                             'myEvent1'           : self.eventOneHandler,
-                             'myEvent2'           : self.eventTwoHandler,
-                             })
+      from gnue.common import events
+      class MyClass (events.EventAware):
+          def __init__ (self)
+              self.eventController = events.EventController()
+              events.EventAware.__init__(self, self.eventController)
+              self.register_listener('myEvent1', self.eventOneHandler)
+              self.register_listener('myEvent2', self.eventTwoHandler)
     
-      def eventOneHandler(self, event)
-        print "I'm an event named ", event.getEvent()
+        def eventOneHandler(self, event)
+            print "I'm an event named ", event.event
     
-      def eventTwoHandler(self, event)
-        print "My event is named ", event.getEvent()
-  """
+        def eventTwoHandler(self, event)
+            print "My event is named ", event.event
+          
+      test = MyClass()
+      test.dispatch_event('myEvent2')
+    
+    """
 
-  # ---------------------------------------------------------------------------
-  # Constructor
-  # ---------------------------------------------------------------------------
+    # 
---------------------------------------------------------------------------
+    # Constructor
+    # 
---------------------------------------------------------------------------
 
-  def __init__ (self, controller):
-
-    self.dispatchEvent          = controller.dispatchEvent
-    self.registerEventListeners = controller.registerEventListeners
+    def __init__ (self, controller, *args, **kwargs):
+ 
+        self.dispatchEvent = self.dispatch_event = controller.dispatch_event
+        self.registerEventListeners = self.register_listeners = 
controller.register_listeners
+        self.register_listener = controller.register_listener
+    

Modified: trunk/gnue-common/src/events/EventController.py
===================================================================
--- trunk/gnue-common/src/events/EventController.py     2006-11-04 00:18:30 UTC 
(rev 8975)
+++ trunk/gnue-common/src/events/EventController.py     2006-11-04 02:38:58 UTC 
(rev 8976)
@@ -7,7 +7,7 @@
 # GNU Enterprise is free software; you can redistribute it
 # and/or modify it under the terms of the GNU General Public
 # License as published by the Free Software Foundation; either
-# version 2, or (at your option) any later version.
+# version 2, or(at your option) any later version.
 #
 # GNU Enterprise is distributed in the hope that it will be
 # useful, but WITHOUT ANY WARRANTY; without even the implied
@@ -36,125 +36,133 @@
 # =============================================================================
 
 class EventController(object):
-  """
-  An EventController is responsible for dispatching events to registered
-  listeners.
-  """
+    """
+    An EventController is responsible for dispatching events to registered
+    listeners.
+    """
 
-  # ---------------------------------------------------------------------------
-  # Constructor
-  # ---------------------------------------------------------------------------
+    # 
---------------------------------------------------------------------------
+    # Constructor
+    # 
---------------------------------------------------------------------------
 
-  def __init__ (self):
+    def __init__(self, *args, **kwargs):
 
-    self.__caching = False
-    self.__incomingEvents = {}
+      self.__caching = False
+      self.__registered_events = {}
 
-  
-  # ---------------------------------------------------------------------------
-  # Nice string representation
-  # ---------------------------------------------------------------------------
 
-  def __repr__ (self):
+    # 
---------------------------------------------------------------------------
+    # Register listeners
+    # 
---------------------------------------------------------------------------
 
-    return "<EventController at %s>" % (id (self))
+    def register_listeners(self, events):
+        """
+        Registers an event listener for a dictionary of events
+    
+        @param events: A dictionary of {'eventName': listenerFuction} pairs
+        """
 
+        checktype(events, dict)
 
-  # ---------------------------------------------------------------------------
-  # Register a listener for a specific event
-  # ---------------------------------------------------------------------------
+        for event, listener in events.iteritems():
+            self.register_listener(event, listener)
 
-  def registerEventListeners (self, events):
-    """
-    Registers an event listener for a specific event
+
+    def register_listener(self, event, listener): 
+        """
+        Registers an event listener for a specific event
     
-    @param events: A dictionary of {'eventName': listenerFuction} pairs
-    """
+        @param event: The string representation of the event
+        @param listener: The method to call for the event
+        @param filter: A method to call prior to dispatching the event to this 
listener. 
+                       If it returns False, then the listener isn't called. 
+        """
+        try: 
+            self.__registered_events[event].append(listener)
+        except KeyError: 
+            self.__registered_events[event] = [listener]
 
-    checktype (events, dict)
 
-    for (event, listener) in events.items ():
-      self.__incomingEvents.setdefault (event, []).append (listener)
+    # 
---------------------------------------------------------------------------
+    # Start storing events rather than dispatching them
+    # 
---------------------------------------------------------------------------
 
+    def start_event_cache(self):
+        """
+        Causes the event controller to start storing events rather than 
dispatching
+        them. It will continue to store events until L{stopCachingEvents} is
+        called.
+        """
 
-  # ---------------------------------------------------------------------------
-  # Start storing events rather than dispatching them
-  # ---------------------------------------------------------------------------
+        self.__caching = True
+        self.__cache = []
 
-  def startCachingEvents (self):
-    """
-    Causes the event controller to start storing events rather than dispatching
-    them. It will continue to store events until L{stopCachingEvents} is
-    called.
-    """
 
-    self.__caching = True
-    self.__cache = []
+    # 
---------------------------------------------------------------------------
+    # Stop storing events
+    # 
---------------------------------------------------------------------------
 
+    def stop_event_cache(self):
+        """
+        Notifies the event controller that is should start processing events 
again.
+        Any previously cached events are dispatched.
+        """
 
-  # ---------------------------------------------------------------------------
-  # Stop storing events
-  # ---------------------------------------------------------------------------
-
-  def stopCachingEvents (self):
-    """
-    Notifies the event controller that is should start processing events again.
-    Any previously cached events are dispatched.
-    """
-
-    self.__caching = False
-    cache = self.__cache
-    del self.__cache
+        self.__caching = False
+        cache = self.__cache
+        del self.__cache
     
-    for event, arg, parms in cache:
-      self.dispatchEvent (event, *arg, **parms)
+        for event, arg, kwargs in cache:
+          self.dispatch_event(event, *arg, **kwargs)
 
 
-  # ---------------------------------------------------------------------------
-  # Dispatch or cache a given event
-  # ---------------------------------------------------------------------------
+    # 
---------------------------------------------------------------------------
+    # Dispatch or cache a given event
+    # 
---------------------------------------------------------------------------
 
-  def dispatchEvent (self, event, *args, **parms):
-    """
-    Dispatch or cache the given event.
+    def dispatch_event(self, event, *args, **kwargs):
+        """
+        Dispatch or cache the given event.
 
-    @param event: L{Event} object or text identifying the type of event to be
-      cached or dispatched.
-    @returns: the event object's __result__ attribute
-    """
+        @param event: L{Event} object or text identifying the type of event to 
be
+          cached or dispatched.  If text-style event names are used, then 
name-based 
+          parameters are passing into the inline Event() conversion.
+         
+        @returns: the event object's __result__ attribute
+        """
 
-    if self.__caching:
-      self.__cache.append ((event, args, parms))
-      return
+        if self.__caching:
+            self.__cache.append((event, args, kwargs))
+            return
 
-    incoming = self.__incomingEvents
+        registered_events = self.__registered_events
 
-    # This improves performance a lot if there is no event listener
-    if not incoming:
-        return
+        # Improve performance if there is no event listener
+        if not registered_events:
+            return
 
-    if not hasattr(event, '__event__'):
-        event = Event(event, *args, **parms)
+        if not isinstance(event, Event): 
+            event = Event(event, *args, **kwargs)
 
-    handlers = []
 
-    if incoming.has_key('__before__'):
-        handlers.extend(incoming['__before__'])
+        for key in ('___before__', event.__event__, '__after__'):
+            for handler in registered_events.get(key, ()): 
+                handler(event)
+                if event.__error__ or event.__dropped__: 
+                    break
 
-    if incoming.has_key(event.__event__):
-        handlers.extend(incoming[event.__event__])
+        if event.__after__:
+            for args, kwargs in event.__after__:
+                self.dispatch_event(*args, **kwargs)
 
-    if incoming.has_key('__after__'):
-        handlers.extend(incoming['__after__'])
+        return event.__result__
 
-    if handlers:
-        for handler in handlers:
-            handler(event)
-            if event.__error__ or event.__dropped__:
-                break
 
-    if event.__after__:
-        for args, parms in event.__after__:
-            self.dispatchEvent(*args, **parms)
-
-    return event.__result__
+    # -------------------------------------------------------------------
+    # For compatability (DEPRECATED)
+    # -------------------------------------------------------------------
+    registerEventListeners=register_listeners
+    dispatchEvent = dispatch_event
+    startCachingEvents = start_event_cache
+    stopCachingEvents = stop_event_cache
+    
\ No newline at end of file





reply via email to

[Prev in Thread] Current Thread [Next in Thread]