2 Registry that hides some of the details of registering for AT-SPI events and
3 starting and stopping the main program loop.
5 @todo: PP: when to destroy device listener?
8 @organization: IBM Corporation
9 @copyright: Copyright (c) 2005, 2007 IBM Corporation
12 This library is free software; you can redistribute it and/or
13 modify it under the terms of the GNU Library General Public
14 License as published by the Free Software Foundation; either
15 version 2 of the License, or (at your option) any later version.
17 This library is distributed in the hope that it will be useful,
18 but WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 Library General Public License for more details.
22 You should have received a copy of the GNU Library General Public
23 License along with this library; if not, write to the
24 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25 Boston, MA 02111-1307, USA.
27 Portions of this code originally licensed and copyright (c) 2005, 2007
28 IBM Corporation under the BSD license, available at
29 U{http://www.opensource.org/licenses/bsd-license.php}
40 import Accessibility__POA
45 class _Observer(object):
47 Parent class for all event observers. Dispatches all received events to the
48 L{Registry} that created this L{_Observer}. Provides basic reference counting
49 functionality needed by L{Registry} to determine when an L{_Observer} can be
50 released for garbage collection.
52 The reference counting provided by this class is independent of the reference
53 counting used by CORBA. Keeping the counts separate makes it easier for the
54 L{Registry} to detect when an L{_Observer} can be freed in the
55 L{Registry._unregisterObserver} method.
57 @ivar registry: Reference to the L{Registry} that created this L{_Observer}
58 @type registry: weakref.proxy to L{Registry}
59 @ivar ref_count: Reference count on this L{_Observer}
60 @type ref_count: integer
62 def __init__(self, registry):
64 Stores a reference to the creating L{Registry}. Intializes the reference
65 count on this object to zero.
67 @param registry: The L{Registry} that created this observer
68 @type registry: weakref.proxy to L{Registry}
70 self.registry = weakref.proxy(registry)
75 Increments the Python reference count on this L{_Observer} by one. This
76 method is called when a new client is registered in L{Registry} to receive
77 notification of an event type monitored by this L{_Observer}.
81 def clientUnref(self):
83 Decrements the pyatspi reference count on this L{_Observer} by one. This
84 method is called when a client is unregistered in L{Registry} to stop
85 receiving notifications of an event type monitored by this L{_Observer}.
89 def getClientRefCount(self):
91 @return: Current Python reference count on this L{_Observer}
97 '''Required by CORBA. Does nothing.'''
101 '''Required by CORBA. Does nothing.'''
104 class _DeviceObserver(_Observer, Accessibility__POA.DeviceEventListener):
106 Observes keyboard press and release events.
108 @ivar registry: The L{Registry} that created this observer
109 @type registry: L{Registry}
110 @ivar key_set: Set of keys to monitor
111 @type key_set: list of integer
112 @ivar mask: Watch for key events while these modifiers are held
114 @ivar kind: Kind of events to monitor
116 @ivar mode: Keyboard event mode
117 @type mode: Accessibility.EventListenerMode
119 def __init__(self, registry, synchronous, preemptive, global_):
121 Creates a mode object that defines when key events will be received from
122 the system. Stores all other information for later registration.
124 @param registry: The L{Registry} that created this observer
125 @type registry: L{Registry}
126 @param synchronous: Handle the key event synchronously?
127 @type synchronous: boolean
128 @param preemptive: Allow event to be consumed?
129 @type preemptive: boolean
130 @param global_: Watch for events on inaccessible applications too?
131 @type global_: boolean
133 _Observer.__init__(self, registry)
134 self.mode = Accessibility.EventListenerMode()
135 self.mode.preemptive = preemptive
136 self.mode.synchronous = synchronous
137 self.mode._global = global_
139 def register(self, dc, key_set, mask, kind):
141 Starts keyboard event monitoring.
143 @param dc: Reference to a device controller
144 @type dc: Accessibility.DeviceEventController
145 @param key_set: Set of keys to monitor
146 @type key_set: list of integer
147 @param mask: Integer modifier mask or an iterable over multiple masks to
149 @type mask: integer, iterable, or None
150 @param kind: Kind of events to monitor
154 # check if the mask is iterable
157 # register a single integer if not
158 dc.registerKeystrokeListener(self._this(), key_set, mask, kind,
162 dc.registerKeystrokeListener(self._this(), key_set, m, kind, self.mode)
164 def unregister(self, dc, key_set, mask, kind):
166 Stops keyboard event monitoring.
168 @param dc: Reference to a device controller
169 @type dc: Accessibility.DeviceEventController
170 @param key_set: Set of keys to monitor
171 @type key_set: list of integer
172 @param mask: Integer modifier mask or an iterable over multiple masks to
174 @type mask: integer, iterable, or None
175 @param kind: Kind of events to monitor
179 # check if the mask is iterable
182 # unregister a single integer if not
183 dc.deregisterKeystrokeListener(self._this(), key_set, mask, kind)
186 dc.deregisterKeystrokeListener(self._this(), key_set, m, kind)
188 def queryInterface(self, repo_id):
190 Reports that this class only implements the AT-SPI DeviceEventListener
191 interface. Required by AT-SPI.
193 @param repo_id: Request for an interface
194 @type repo_id: string
195 @return: The underlying CORBA object for the device event listener
196 @rtype: Accessibility.EventListener
198 if repo_id == utils.getInterfaceIID(Accessibility.DeviceEventListener):
203 def notifyEvent(self, ev):
205 Notifies the L{Registry} that an event has occurred. Wraps the raw event
206 object in our L{Event} class to support automatic ref and unref calls. An
207 observer can return True to indicate this event should not be allowed to pass
208 to other AT-SPI observers or the underlying application.
210 @param ev: Keyboard event
211 @type ev: Accessibility.DeviceEvent
212 @return: Should the event be consumed (True) or allowed to pass on to other
213 AT-SPI observers (False)?
216 # wrap the device event
217 ev = event.DeviceEvent(ev)
218 return self.registry.handleDeviceEvent(ev, self)
220 class _EventObserver(_Observer, Accessibility__POA.EventListener):
222 Observes all non-keyboard AT-SPI events. Can be reused across event types.
224 def register(self, reg, name):
226 Starts monitoring for the given event.
228 @param name: Name of the event to start monitoring
230 @param reg: Reference to the raw registry object
231 @type reg: Accessibility.Registry
233 reg.registerGlobalEventListener(self._this(), name)
235 def unregister(self, reg, name):
237 Stops monitoring for the given event.
239 @param name: Name of the event to stop monitoring
241 @param reg: Reference to the raw registry object
242 @type reg: Accessibility.Registry
244 reg.deregisterGlobalEventListener(self._this(), name)
246 def queryInterface(self, repo_id):
248 Reports that this class only implements the AT-SPI DeviceEventListener
249 interface. Required by AT-SPI.
251 @param repo_id: Request for an interface
252 @type repo_id: string
253 @return: The underlying CORBA object for the device event listener
254 @rtype: Accessibility.EventListener
256 if repo_id == utils.getInterfaceIID(Accessibility.EventListener):
261 def notifyEvent(self, ev):
263 Notifies the L{Registry} that an event has occurred. Wraps the raw event
264 object in our L{Event} class to support automatic ref and unref calls.
265 Aborts on any exception indicating the event could not be wrapped.
267 @param ev: AT-SPI event signal (anything but keyboard)
268 @type ev: Accessibility.Event
270 # wrap raw event so ref counts are correct before queueing
272 self.registry.handleEvent(ev)
274 class Registry(object):
276 Wraps the Accessibility.Registry to provide more Pythonic registration for
279 This object should be treated as a singleton, but such treatment is not
280 enforced. You can construct another instance of this object and give it a
281 reference to the Accessibility.Registry singleton. Doing so is harmless and
284 @ivar async: Should event dispatch to local listeners be decoupled from event
285 receiving from the registry?
287 @ivar reg: Reference to the real, wrapped registry object
288 @type reg: Accessibility.Registry
289 @ivar dev: Reference to the device controller
290 @type dev: Accessibility.DeviceEventController
291 @ivar queue: Queue of events awaiting local dispatch
292 @type queue: Queue.Queue
293 @ivar clients: Map of event names to client listeners
294 @type clients: dictionary
295 @ivar observers: Map of event names to AT-SPI L{_Observer} objects
296 @type observers: dictionary
298 def __init__(self, reg):
300 Stores a reference to the AT-SPI registry. Gets and stores a reference
301 to the DeviceEventController.
303 @param reg: Reference to the AT-SPI registry daemon
304 @type reg: Accessibility.Registry
308 self.dev = self.reg.getDeviceEventController()
309 self.queue = Queue.Queue()
315 @return: This instance of the registry
320 def start(self, async=False, gil=True):
322 Enter the main loop to start receiving and dispatching events.
324 @param async: Should event dispatch be asynchronous (decoupled) from
325 event receiving from the AT-SPI registry?
327 @param gil: Add an idle callback which releases the Python GIL for a few
328 milliseconds to allow other threads to run? Necessary if other threads
329 will be used in this process.
338 except KeyboardInterrupt, e:
339 # store the exception for later
340 releaseGIL.keyboard_exception = e
343 # make room for an exception if one occurs during the
344 releaseGIL.keyboard_exception = None
345 i = gobject.idle_add(releaseGIL)
347 # enter the main loop
351 # clear all observers
352 for name, ob in self.observers.items():
353 ob.unregister(self.reg, name)
355 gobject.source_remove(i)
356 if releaseGIL.keyboard_exception is not None:
357 # raise an keyboard exception we may have gotten earlier
358 raise releaseGIL.keyboard_exception
360 def stop(self, *args):
361 '''Quits the main loop.'''
365 # ignore errors when quitting (probably already quitting)
368 def getDesktopCount(self):
370 Gets the number of available desktops.
372 @return: Number of desktops
374 @raise LookupError: When the count cannot be retrieved
377 return self.reg.getDesktopCount()
381 def getDesktop(self, i):
383 Gets a reference to the i-th desktop.
385 @param i: Which desktop to get
387 @return: Desktop reference
388 @rtype: Accessibility.Desktop
389 @raise LookupError: When the i-th desktop cannot be retrieved
392 return self.reg.getDesktop(i)
396 def registerEventListener(self, client, *names):
398 Registers a new client callback for the given event names. Supports
399 registration for all subevents if only partial event name is specified.
400 Do not include a trailing colon.
402 For example, 'object' will register for all object events,
403 'object:property-change' will register for all property change events,
404 and 'object:property-change:accessible-parent' will register only for the
405 parent property change event.
407 Registered clients will not be automatically removed when the client dies.
408 To ensure the client is properly garbage collected, call
409 L{deregisterEventListener}.
411 @param client: Callable to be invoked when the event occurs
412 @type client: callable
413 @param names: List of full or partial event names
414 @type names: list of string
417 # store the callback for each specific event name
418 self._registerClients(client, name)
420 def deregisterEventListener(self, client, *names):
422 Unregisters an existing client callback for the given event names. Supports
423 unregistration for all subevents if only partial event name is specified.
424 Do not include a trailing colon.
426 This method must be called to ensure a client registered by
427 L{registerEventListener} is properly garbage collected.
429 @param client: Client callback to remove
430 @type client: callable
431 @param names: List of full or partial event names
432 @type names: list of string
433 @return: Were event names specified for which the given client was not
439 # remove the callback for each specific event name
440 missed |= self._unregisterClients(client, name)
443 def registerKeystrokeListener(self, client, key_set=[], mask=0,
444 kind=(constants.KEY_PRESSED_EVENT,
445 constants.KEY_RELEASED_EVENT),
446 synchronous=True, preemptive=True,
449 Registers a listener for key stroke events.
451 @param client: Callable to be invoked when the event occurs
452 @type client: callable
453 @param key_set: Set of hardware key codes to stop monitoring. Leave empty
454 to indicate all keys.
455 @type key_set: list of integer
456 @param mask: When the mask is None, the codes in the key_set will be
457 monitored only when no modifier is held. When the mask is an
458 integer, keys in the key_set will be monitored only when the modifiers in
459 the mask are held. When the mask is an iterable over more than one
460 integer, keys in the key_set will be monitored when any of the modifier
461 combinations in the set are held.
462 @type mask: integer, iterable, None
463 @param kind: Kind of events to watch, KEY_PRESSED_EVENT or
466 @param synchronous: Should the callback notification be synchronous, giving
467 the client the chance to consume the event?
468 @type synchronous: boolean
469 @param preemptive: Should the callback be allowed to preempt / consume the
471 @type preemptive: boolean
472 @param global_: Should callback occur even if an application not supporting
473 AT-SPI is in the foreground? (requires xevie)
474 @type global_: boolean
477 # see if we already have an observer for this client
478 ob = self.clients[client]
480 # create a new device observer for this client
481 ob = _DeviceObserver(self, synchronous, preemptive, global_)
482 # store the observer to client mapping, and the inverse
483 self.clients[ob] = client
484 self.clients[client] = ob
486 # None means all modifier combinations
487 mask = utils.allModifiers()
488 # register for new keystrokes on the observer
489 ob.register(self.dev, key_set, mask, kind)
491 def deregisterKeystrokeListener(self, client, key_set=[], mask=0,
492 kind=(constants.KEY_PRESSED_EVENT,
493 constants.KEY_RELEASED_EVENT)):
495 Deregisters a listener for key stroke events.
497 @param client: Callable to be invoked when the event occurs
498 @type client: callable
499 @param key_set: Set of hardware key codes to stop monitoring. Leave empty
500 to indicate all keys.
501 @type key_set: list of integer
502 @param mask: When the mask is None, the codes in the key_set will be
503 monitored only when no modifier is held. When the mask is an
504 integer, keys in the key_set will be monitored only when the modifiers in
505 the mask are held. When the mask is an iterable over more than one
506 integer, keys in the key_set will be monitored when any of the modifier
507 combinations in the set are held.
508 @type mask: integer, iterable, None
509 @param kind: Kind of events to stop watching, KEY_PRESSED_EVENT or
512 @raise KeyError: When the client isn't already registered for events
514 # see if we already have an observer for this client
515 ob = self.clients[client]
517 # None means all modifier combinations
518 mask = utils.allModifiers()
519 # register for new keystrokes on the observer
520 ob.unregister(self.dev, key_set, mask, kind)
522 def generateKeyboardEvent(self, keycode, keysym, kind):
524 Generates a keyboard event. One of the keycode or the keysym parameters
525 should be specified and the other should be None. The kind parameter is
526 required and should be one of the KEY_PRESS, KEY_RELEASE, KEY_PRESSRELEASE,
527 KEY_SYM, or KEY_STRING.
529 @param keycode: Hardware keycode or None
530 @type keycode: integer
531 @param keysym: Symbolic key string or None
533 @param kind: Kind of event to synthesize
537 self.dev.generateKeyboardEvent(keycode, '', kind)
539 self.dev.generateKeyboardEvent(None, keysym, kind)
541 def generateMouseEvent(self, x, y, name):
543 Generates a mouse event at the given absolute x and y coordinate. The kind
544 of event generated is specified by the name. For example, MOUSE_B1P
545 (button 1 press), MOUSE_REL (relative motion), MOUSE_B3D (butten 3
548 @param x: Horizontal coordinate, usually left-hand oriented
550 @param y: Vertical coordinate, usually left-hand oriented
552 @param name: Name of the event to generate
555 self.dev.generateMouseEvent(x, y, name)
557 def handleDeviceEvent(self, event, ob):
559 Dispatches L{event.DeviceEvent}s to registered clients. Clients are called
560 in the order they were registered for the given AT-SPI event. If any
561 client returns True, callbacks cease for the event for clients of this registry
562 instance. Clients of other registry instances and clients in other processes may
563 be affected depending on the values of synchronous and preemptive used when invoking
564 L{registerKeystrokeListener}.
566 @note: Asynchronous dispatch of device events is not supported.
568 @param event: AT-SPI device event
569 @type event: L{event.DeviceEvent}
570 @param ob: Observer that received the event
571 @type ob: L{_DeviceObserver}
573 @return: Should the event be consumed (True) or allowed to pass on to other
574 AT-SPI observers (False)?
578 # try to get the client registered for this event type
579 client = self.clients[ob]
581 # client may have unregistered recently, ignore event
583 # make the call to the client
585 return client(event) or event.consume
587 # print the exception, but don't let it stop notification
588 traceback.print_exc()
590 def handleEvent(self, event):
592 Handles an AT-SPI event by either queuing it for later dispatch when the
593 L{Registry.async} flag is set, or dispatching it immediately.
595 @param event: AT-SPI event
596 @type event: L{event.Event}
600 self.queue.put_nowait(event)
602 # dispatch immediately
603 self._dispatchEvent(event)
605 def _dispatchEvent(self, event):
607 Dispatches L{event.Event}s to registered clients. Clients are called in
608 the order they were registered for the given AT-SPI event. If any client
609 returns True, callbacks cease for the event for clients of this registry
610 instance. Clients of other registry instances and clients in other processes
613 @param event: AT-SPI event
614 @type event: L{event.Event}
618 # try to get the client registered for this event type
619 clients = self.clients[et.name]
622 # we may not have registered for the complete subtree of events
623 # if our tree does not list all of a certain type (e.g.
624 # object:state-changed:*); try again with klass and major only
625 if et.detail is not None:
626 # Strip the 'detail' field.
627 clients = self.clients['%s:%s:%s' % (et.klass, et.major, et.minor)]
628 elif et.minor is not None:
629 # The event could possibly be object:state-changed:*.
630 clients = self.clients['%s:%s' % (et.klass, et.major)]
632 # client may have unregistered recently, ignore event
634 # make the call to each client
636 for client in clients:
638 consume = client(event) or False
640 # print the exception, but don't let it stop notification
641 traceback.print_exc()
642 if consume or event.consume:
643 # don't allow further processing if a client returns True
646 def _registerClients(self, client, name):
648 Internal method that recursively associates a client with AT-SPI event
649 names. Allows a client to incompletely specify an event name in order to
650 register for subevents without specifying their full names manually.
652 @param client: Client callback to receive event notifications
653 @type client: callable
654 @param name: Partial or full event name
658 # look for an event name in our event tree dictionary
659 events = constants.EVENT_TREE[name]
661 # if the event name doesn't exist, it's a leaf event meaning there are
662 # no subtypes for that event
663 # add this client to the list of clients already in the dictionary
664 # using the event name as the key; if there are no clients yet for this
665 # event, insert an empty list into the dictionary before appending
667 et = event.EventType(name)
668 clients = self.clients.setdefault(et.name, [])
670 # if this succeeds, this client is already registered for the given
671 # event type, so ignore the request
672 clients.index(client)
674 # else register the client
675 clients.append(client)
676 self._registerObserver(name)
678 # if the event name does exist in the tree, there are subevents for
679 # this event; loop through them calling this method again to get to
682 self._registerClients(client, e)
684 def _unregisterClients(self, client, name):
686 Internal method that recursively unassociates a client with AT-SPI event
687 names. Allows a client to incompletely specify an event name in order to
688 unregister for subevents without specifying their full names manually.
690 @param client: Client callback to receive event notifications
691 @type client: callable
692 @param name: Partial or full event name
697 # look for an event name in our event tree dictionary
698 events = constants.EVENT_TREE[name]
701 # if the event name doesn't exist, it's a leaf event meaning there are
702 # no subtypes for that event
703 # get the list of registered clients and try to remove the one provided
704 et = event.EventType(name)
705 clients = self.clients[et.name]
706 clients.remove(client)
707 self._unregisterObserver(name)
708 except (ValueError, KeyError):
709 # ignore any exceptions indicating the client is not registered
712 # if the event name does exist in the tree, there are subevents for this
713 # event; loop through them calling this method again to get to the leaf
716 missed |= self._unregisterClients(client, e)
719 def _registerObserver(self, name):
721 Creates a new L{_Observer} to watch for events of the given type or
722 returns the existing observer if one is already registered. One
723 L{_Observer} is created for each leaf in the L{constants.EVENT_TREE} or
724 any event name not found in the tree.
726 @param name: Raw name of the event to observe
728 @return: L{_Observer} object that is monitoring the event
731 et = event.EventType(name)
733 # see if an observer already exists for this event
734 ob = self.observers[et.name]
736 # build a new observer if one does not exist
737 ob = _EventObserver(self)
738 # we have to register for the raw name because it may be different from
739 # the parsed name determined by EventType (e.g. trailing ':' might be
741 ob.register(self.reg, name)
742 self.observers[et.name] = ob
743 # increase our client ref count so we know someone new is watching for the
748 def _unregisterObserver(self, name):
750 Destroys an existing L{_Observer} for the given event type only if no
751 clients are registered for the events it is monitoring.
753 @param name: Name of the event to observe
755 @raise KeyError: When an observer for the given event is not regist
757 et = event.EventType(name)
758 # see if an observer already exists for this event
759 ob = self.observers[et.name]
761 if ob.getClientRefCount() == 0:
762 ob.unregister(self.reg, name)
763 del self.observers[et.name]