[pyatspi2] Some clean-ups for Python 3



commit 8ca032024fa27a41ce27b88667361792f07a05cf
Author: Mike Gorse <mgorse suse com>
Date:   Fri Apr 27 17:28:30 2012 -0500

    Some clean-ups for Python 3
    
    Use spaces consistently (expand tabs in some places)
    Fix a few syntax issues
    Remove some old code that should be no longer needed, including code
    that referenced dbus-python

 pyatspi/Accessibility.py |   33 ++--
 pyatspi/deviceevent.py   |  375 ----------------------------------------------
 pyatspi/enum.py          |    4 +-
 pyatspi/registry.py      |   14 +-
 pyatspi/state.py         |   41 +-----
 pyatspi/text.py          |    2 +-
 pyatspi/utils.py         |    2 +-
 7 files changed, 27 insertions(+), 444 deletions(-)
---
diff --git a/pyatspi/Accessibility.py b/pyatspi/Accessibility.py
index 214cd4c..928d566 100644
--- a/pyatspi/Accessibility.py
+++ b/pyatspi/Accessibility.py
@@ -30,9 +30,9 @@ def Accessible_getitem(self, i):
         len=self.get_child_count()
         if i < 0:
                 i = len + i
-	if i < 0 or i >= len:
-		raise IndexError
-	return self.get_child_at_index(i)
+        if i < 0 or i >= len:
+                raise IndexError
+        return self.get_child_at_index(i)
 
 def Accessible_str(self):
         '''
@@ -47,10 +47,10 @@ def Accessible_str(self):
                 return '[DEAD]'
         
 def pointToList(point):
-	return (point.x, point.y)
+        return (point.x, point.y)
 
 def rectToList(rect):
-	return (rect.x, rect.y, rect.width, rect.height)
+        return (rect.x, rect.y, rect.width, rect.height)
 
 # TODO: Figure out how to override Atspi.Rect constructor and remove this class
 class BoundingBox(list):
@@ -84,23 +84,23 @@ class BoundingBox(list):
         height = property(fget=_get_height, fset=_set_height)
 
 def getBoundingBox(rect):
-	return BoundingBox (rect.x, rect.y, rect.width, rect.height)
+        return BoundingBox (rect.x, rect.y, rect.width, rect.height)
 
 def attributeListToHash(list):
-	ret = dict()
-	for item in list:
+        ret = dict()
+        for item in list:
                 [key, val] = item.split(":")
-		ret[key] = val
-	return ret
+                ret[key] = val
+        return ret
 
 def getInterface(func, obj):
-	ret = func(obj)
-	if ret:
-		return ret
-	raise NotImplementedError
+        ret = func(obj)
+        if ret:
+                return ret
+        raise NotImplementedError
 
 def hashToAttributeList(h):
-	return [x + ":" + h[x] for x in h.keys()]
+        return [x + ":" + h[x] for x in h.keys()]
 
 def getEventType(event):
         try:
@@ -388,6 +388,5 @@ KEY_RELEASE = Atspi.KeySynthType.RELEASE
 KEY_STRING = Atspi.KeySynthType.STRING
 KEY_SYM = Atspi.KeySynthType.SYM
 
-### misc ###
+### cache ###
 cache = Atspi.Cache
-setTimeout = Atspi.set_timeout
diff --git a/pyatspi/deviceevent.py b/pyatspi/deviceevent.py
index 7061985..72d066a 100644
--- a/pyatspi/deviceevent.py
+++ b/pyatspi/deviceevent.py
@@ -15,9 +15,6 @@
 from interfaces import *
 import registry
 
-import dbus as _dbus
-import dbus.service as _service
-
 from enum import Enum as _Enum
 
 import traceback
@@ -253,375 +250,3 @@ class KeyDefinition(list):
         def _set_unused(self, val):
                 self[3] = val
         unused = property(fget=_get_unused, fset=_set_unused)
-
-#------------------------------------------------------------------------------
-
-class DeviceEventController(object):
-        """
-        The interface via which clients request notification of device
-        events, and through which device events may be simulated.
-        """
-
-        def __init__ (self, connection):
-                dec_object = connection.get_object(ATSPI_REGISTRY_NAME,
-                                                   ATSPI_DEVICE_EVENT_CONTROLLER_PATH)
-                self._dec = _dbus.Interface(dec_object, ATSPI_DEVICE_EVENT_CONTROLLER_INTERFACE)
-
-        def registerKeystrokeListener(self,
-                                      event_listener,
-                                      keys,
-                                      event_mask,
-                                      key_event_types,
-                                      event_listener_mode):
-                """
-                Register to intercept keyboard events, and either pass them on
-                or consume them.
-                @param : listener
-                A DeviceEventListener which will intercept key events. 
-                @param : keys
-                A list of KeyDefinition indicating which keys to intercept, or KEYSET_ALL_KEYS.
-                @param : mask
-                A ControllerEventMask bitmask for filtering the intercepted key events.
-                @param : type
-                A list of KeyEventType
-                @param : mode
-                An EventListenerMode indicating whether the listener should receive
-                the events synchronously, potentially consuming them, or just
-                be notified asynchronously of those events that have been generated.
-
-                @return True if the DeviceEventListener was successfully registered
-                for the requested KeySet, ControllerEventMask, event types, and
-                EventListenerMode; otherwise returns False.
-                """
-                func = self._dec.get_dbus_method("RegisterKeystrokeListener")
-                return func(event_listener,
-                            _dbus.Array(keys, signature="(iisi)"),
-                            event_mask,
-                            key_event_types,
-                            event_listener_mode)
-
-        def deregisterKeystrokeListener(self,
-                                        event_listener,
-                                        keys,
-                                        event_mask,
-                                        key_event_types):
-                """
-                De-register a previously registered keyboard eventlistener.
-                @param : listener
-                A DeviceEventListener which will intercept key events.
-                @param : keys
-                A list of KeyDefinition indicating which keys to intercept, or KEYSET_ALL_KEYS.
-                @param : mask
-                A ControllerEventMask filtering the intercepted key events.
-                @param : type
-                A list of KeyEventType
-                """
-                func = self._dec.get_dbus_method("DeregisterKeystrokeListener")
-                return func(event_listener,
-                            keys,
-                            event_mask,
-                            key_event_types)
-
-        def registerDeviceEventListener(self,
-                                        event_listener,
-                                        event_types):
-                """
-                Register to intercept events, and either pass them on or consume
-                them. To listen to keyboard events use registerKeystrokeListener
-                instead. 
-                @param : listener
-                A DeviceEventListener which will intercept events.
-                @param : typeseq
-                A list of EventType indicating which event types to listen for.
-                @return True if successful, False if not
-                """
-                func = self._dec.get_dbus_method("RegisterDeviceEventListener")
-                return func(event_listener, event_types)
-
-        def deregisterDeviceEventListener(self,
-                                          event_listener,
-                                          event_types):
-                """
-                De-register a previously registered keyboard eventlistener.
-                @param : listener
-                A DeviceEventListener which will intercept events.
-                @param : typeseq
-                A List of EventType indicating which event types to stop listening
-                for.
-                """
-                func = self._dec.get_dbus_method("DeregisterDeviceEventListener")
-                return func(event_listener, event_types)
-
-        def notifyListenersSync(self, event):
-                """
-                Notify the Registry instance that a device event has taken place,
-                and allow pre-emptive listeners the opportunity to 'consume'
-                the event and thus prevent its further issuance/forwarding. This
-                is the method used by accessibility bridges to forward "toolkit
-                dependent" device events to the Registry from the application's
-                process space.
-                @return True if the event was consumed by a (pre-emptive) listener,
-                False if not (in which case the device event will be forwarded
-                as normal to any application which would normally receive it,
-                e.g. the currently active application in the case of mouse or
-                keyboard events).
-                """
-                func = self._dec.get_dbus_method("NotifyListenersSync")
-                return func(event)
-
-        def notifyListenersAsync(self, event):
-                """
-                Notify the Registry instance that a device event has taken place
-                in an asynchronous manner. This is the method used by accessibility
-                bridges to forward "toolkit dependent" device events to the Registry
-                from the application's process space. If the event in question
-                is potentially pre-emptible. notifyListenersSync should be used
-                instead.
-                """
-                func = self._dec.get_dbus_method("NotifyListenersAsync")
-                return func(event)
-
-        def generateKeyboardEvent(self, keycode, keystring, type):
-                """
-                Synthesize a keyboard event.
-                @param : keycode
-                A long integer indicating the keycode of the keypress to be synthesized.
-                @param : keystring
-                an optional UTF-8 string indicating a complex keyboard input
-                event.
-                @param : type
-                A KeySynthType indicating the type of event(s) to be synthesized:
-                a key press, release, press-release pair, or a complex input
-                string (for instance from an internationalized or complex text
-                input method, or a composed character).
-                """
-                func = self._dec.get_dbus_method("GenerateKeyboardEvent")
-                return func(keycode, keystring, type)
-
-        def generateMouseEvent(self, x, y, name):
-                """
-                Synthesize a mouse event.
-                @param : x
-                A long integer indicating the screen x coord for the mouse event.
-                @param : y
-                A long integer indicating the screen y coord for the mouse event.
-                @param : name
-                A string indicating the type of mouse event, e.g. "button1up"
-                """
-                func = self._dec.get_dbus_method("GenerateMouseEvent")
-                return func(x, y, name)
-
-#------------------------------------------------------------------------------
-
-class KeyboardDeviceEventListener(_service.Object):
-        """
-        Observes keyboard press and release events.
-
-        @ivar registry: The L{Registry} that created this observer
-        @type registry: L{Registry}
-        @ivar key_set: Set of keys to monitor
-        @type key_set: list of integer
-        @ivar mask: Watch for key events while these modifiers are held
-        @type mask: integer
-        @ivar kind: Kind of events to monitor
-        @type kind: integer
-        @ivar mode: Keyboard event mode
-        @type mode: Accessibility.EventListenerMode
-        """
-
-        _next_listener_id = 0
-
-        def _get_unique_path (self):
-                KeyboardDeviceEventListener._next_listener_id += 1
-                return "/org/a11y/atspi/keyeventlistener/%d" % (KeyboardDeviceEventListener._next_listener_id,)
-
-        def __init__(self, registry, synchronous, preemptive, global_):
-                """
-                Creates a mode object that defines when key events will be received from 
-                the system. Stores all other information for later registration.
-
-                @param registry: The L{Registry} that created this observer
-                @type registry: L{Registry}
-                @param synchronous: Handle the key event synchronously?
-                @type synchronous: boolean
-                @param preemptive: Allow event to be consumed?
-                @type preemptive: boolean
-                @param global_: Watch for events on inaccessible applications too?
-                @type global_: boolean
-                """
-                self._upath = self._get_unique_path()
-                _service.Object.__init__(self, registry._bus, self._upath)
-                self.mode = EventListenerMode(synchronous, preemptive, global_)
-                self._registry = registry
-
-        def register(self, dc, key_set, mask, kind):
-                """
-                Starts keyboard event monitoring.
-
-                @param dc: Reference to a device controller
-                @type dc: Accessibility.DeviceEventController
-                @param key_set: Set of keys to monitor
-                @type key_set: list of integer
-                @param mask: Integer modifier mask or an iterable over multiple masks to
-                        unapply all at once
-                @type mask: integer, iterable, or None
-                @param kind: Kind of events to monitor
-                @type kind: integer
-                """
-                try:
-                        # check if the mask is iterable
-                        iter(mask)
-                except TypeError:
-                        # register a single integer if not
-                        dc.registerKeystrokeListener(self._upath, key_set, mask, kind, self.mode)
-                else:
-                        for m in mask:
-                                dc.registerKeystrokeListener(self._upath, key_set, m, kind, self.mode)
-
-        def unregister(self, dc, key_set, mask, kind):
-                """
-                Stops keyboard event monitoring.
-
-                @param dc: Reference to a device controller
-                @type dc: Accessibility.DeviceEventController
-                @param key_set: Set of keys to monitor
-                @type key_set: list of integer
-                @param mask: Integer modifier mask or an iterable over multiple masks to
-                        unapply all at once
-                @type mask: integer, iterable, or None
-                @param kind: Kind of events to monitor
-                @type kind: integer
-                """
-                try:
-                        # check if the mask is iterable
-                        iter(mask)
-                except TypeError:
-                        # unregister a single integer if not
-                        dc.deregisterKeystrokeListener(self._upath, key_set, mask, kind)
-                else:
-                        for m in mask:
-                                dc.deregisterKeystrokeListener(self._upath, key_set, m, kind)
-
-        @_service.method(dbus_interface=ATSPI_DEVICE_EVENT_LISTENER_INTERFACE,
-                         in_signature="(uinnisb)",
-                         out_signature="b")
-        def NotifyEvent(self, ev):
-                """
-                Notifies the L{Registry} that an event has occurred. Wraps the raw event 
-                object in our L{Event} class to support automatic ref and unref calls. An
-                observer can return True to indicate this event should not be allowed to pass 
-                to other AT-SPI observers or the underlying application.
-
-                @param ev: Keyboard event
-                @type ev: Accessibility.DeviceEvent
-                @return: Should the event be consumed (True) or allowed to pass on to other
-                        AT-SPI observers (False)?
-                @rtype: boolean
-                """
-                # TODO Find out where the exceptions are falling in to.
-                try:
-                        # wrap the device event
-                        event = DeviceEvent(*ev)
-                        ret = self._registry._handleDeviceEvent(event, self)
-			return ret
-                except Exception, e:
-                        import traceback
-                        traceback.print_exc()
-                        return False
-
-#------------------------------------------------------------------------------
-
-class _DeviceEventRegister (object):
-        
-        def __init__ (self):
-                self._bus = SyncAccessibilityBus (registry.Registry())
-                self.dev = DeviceEventController (self._bus)
-                self.deviceClients = {}
-
-        def registerKeystrokeListener(self,
-                                      client,
-                                      key_set=[],
-                                      mask=0,
-                                      kind=(KEY_PRESSED_EVENT, KEY_RELEASED_EVENT),
-                                      synchronous=True,
-                                      preemptive=True,
-                                      global_=False):
-                try:
-                        # see if we already have an observer for this client
-                        ob = self.deviceClients[client]
-                except KeyError:
-                        # create a new device observer for this client
-                        ob = KeyboardDeviceEventListener(self, synchronous, preemptive, global_)
-                        # store the observer to client mapping, and the inverse
-                        self.deviceClients[ob] = client
-                        self.deviceClients[client] = ob
-                if mask is None:
-                        # None means all modifier combinations
-                        mask = allModifiers()
-                # register for new keystrokes on the observer
-                ob.register(self.dev, key_set, mask, kind)
-
-        def deregisterKeystrokeListener(self,
-                                        client,
-                                        key_set=[],
-                                        mask=0,
-                                        kind=(KEY_PRESSED_EVENT, KEY_RELEASED_EVENT)):
-                # see if we already have an observer for this client
-                ob = self.deviceClients[client]
-                if mask is None:
-                        # None means all modifier combinations
-                        mask = allModifiers()
-                # register for new keystrokes on the observer
-                ob.unregister(self.dev, key_set, mask, kind)
-
-        def _handleDeviceEvent(self, event, ob):
-                try:
-                        # try to get the client registered for this event type
-                        client = self.deviceClients[ob]
-                except KeyError:
-                        # client may have unregistered recently, ignore event
-                        return False
-                # make the call to the client
-                try:
-                        return client(event) or event.consume
-                except Exception:
-                        # print the exception, but don't let it stop notification
-                        traceback.print_exc()
-
-        def generateKeyboardEvent(self, keycode, keysym, kind):
-                if keysym is None:
-                        self.dev.generateKeyboardEvent(keycode, '', kind)
-                else:
-                        self.dev.generateKeyboardEvent(None, keysym, kind)
-
-        def generateMouseEvent(self, x, y, name):
-                self.dev.generateMouseEvent(_dbus.Int32(x), _dbus.Int32(y), name)
-
-#------------------------------------------------------------------------------
-
-class _NullDeviceEventRegister (object):
-        
-        def registerKeystrokeListener(self,
-                                      client,
-                                      key_set=[],
-                                      mask=0,
-                                      kind=(KEY_PRESSED_EVENT, KEY_RELEASED_EVENT),
-                                      synchronous=True,
-                                      preemptive=True,
-                                      global_=False):
-                pass
-
-        def deregisterKeystrokeListener(self,
-                                        client,
-                                        key_set=[],
-                                        mask=0,
-                                        kind=(KEY_PRESSED_EVENT, KEY_RELEASED_EVENT)):
-                pass
-
-        def generateKeyboardEvent(self, keycode, keysym, kind):
-                pass
-
-        def generateMouseEvent(self, x, y, name):
-                pass
-
-#END---------------------------------------------------------------------------
diff --git a/pyatspi/enum.py b/pyatspi/enum.py
index 605cbc8..30f4acd 100644
--- a/pyatspi/enum.py
+++ b/pyatspi/enum.py
@@ -12,15 +12,13 @@
 #along with this program; if not, write to the Free Software
 #Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 
-from dbus.types import UInt32
-
 __all__ = [
            "Enum",
           ]
 
 #------------------------------------------------------------------------------
 
-class Enum(UInt32):
+class Enum(int):
         def __str__(self):
                 return self._enum_lookup[int(self)]
 
diff --git a/pyatspi/registry.py b/pyatspi/registry.py
index 0a3a1c9..ae64ed8 100644
--- a/pyatspi/registry.py
+++ b/pyatspi/registry.py
@@ -23,9 +23,9 @@
 #------------------------------------------------------------------------------
 
 __all__ = ["Registry",
-	   "MAIN_LOOP_GLIB",
-	   "MAIN_LOOP_NONE",
-	   "set_default_registry"]
+           "MAIN_LOOP_GLIB",
+           "MAIN_LOOP_NONE",
+           "set_default_registry"]
 
 import os as _os
 from gi.repository import Atspi
@@ -79,7 +79,7 @@ class Registry(object):
                 self.app_event_register = None
                 self.desktop = None
 
-		self.main_loop = GObject.MainLoop()
+                self.main_loop = GObject.MainLoop()
 
         def __call__(self):
                 """
@@ -111,10 +111,10 @@ class Registry(object):
 
                 self.has_implementations = True
 
-		# TODO: Move to libatspi
+                # TODO: Move to libatspi
                 _os.environ["AT_SPI_CLIENT"] = "1"
 
-		self.async = False	# not fully supported yet
+                self.async = False	# not fully supported yet
                 self.started = False
                 self.event_listeners = dict()
 
@@ -141,7 +141,7 @@ class Registry(object):
                         def releaseGIL():
                                 try:
                                         time.sleep(1e-2)
-                                except KeyboardInterrupt, e:
+                                except KeyboardInterrupt as e:
                                         # store the exception for later
                                         releaseGIL.keyboard_exception = e
                                         self.stop()
diff --git a/pyatspi/state.py b/pyatspi/state.py
index b90afc9..d804150 100644
--- a/pyatspi/state.py
+++ b/pyatspi/state.py
@@ -127,51 +127,12 @@ STATE_VALUE_TO_NAME = dict(((value, name[6:].lower().replace('_', ' '))
 
 #------------------------------------------------------------------------------
 
-def _marshal_state_set(bitfield):
-        """
-        The D-Bus protocol has a stateset object passed
-        as a 64bit bitfield. The Bits are passed as two 32bit
-        integers.
-
-        This function marshals the D-Bus message into a 
-        StateSet object that corresponds to these states.
-        """
-        (lower, upper) = bitfield
-
-        states = []
-
-        pos = 0
-        while (lower):
-                if (1L)&lower:
-                        states.append(StateType(pos))
-                pos+=1
-                lower >>= 1
-
-        pos = 32
-        while (upper):
-                if (1L)&upper:
-                        states.append(StateType(pos))
-                pos+=1
-                upper >>= 1
-
-        return StateSet(*states)
-
-#------------------------------------------------------------------------------
-
 def stateset_init(self, *states):
 	GObject.GObject.__init__(self)
 	map(self.add, states)
 
-# TODO: Probably remove this hack for 2.2, since BGO#646581 is fixed
-def StateSet_getStates(self):
-        ret = []
-        for i in range(0, 64):
-                if (self.states & (1 << i)):
-                        ret.append(Atspi.StateType(i))
-        return ret
-
 StateSet = Atspi.StateSet
-StateSet.getStates = StateSet_getStates
+StateSet.getStates = StateSet.get_states
 StateSet.isEmpty = StateSet.is_empty
 StateSet.raw = lambda x: x
 StateSet.unref = lambda x: None
diff --git a/pyatspi/text.py b/pyatspi/text.py
index 0274d2b..3375597 100644
--- a/pyatspi/text.py
+++ b/pyatspi/text.py
@@ -202,7 +202,7 @@ class Text:
                 """
                 [attrs, startOffset, endOffset] = Atspi.Text.get_attributes(self.obj, offset)
                 arr = [key + ':' + value for key, value in attrs.items()]
-		str = ';'.join (arr)
+                str = ';'.join (arr)
                 return [str, startOffset, endOffset]
 
         def getBoundedRanges(self, x, y, width, height, coordType, xClipType, yClipType):
diff --git a/pyatspi/utils.py b/pyatspi/utils.py
index d5754ac..f620c7b 100644
--- a/pyatspi/utils.py
+++ b/pyatspi/utils.py
@@ -55,7 +55,7 @@ def clearCache():
         pass
 
 def printCache():
-        print "Print cache function is deprecated";
+        print("Print cache function is deprecated")
 
 def getInterfaceIID(obj):
         """



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