* registry.py: Fixed bug #436982 again (Patch from Eitan)
[platform/core/uifw/at-spi2-atk.git] / pyatspi / registry.py
1 '''
2 Registry that hides some of the details of registering for AT-SPI events and
3 starting and stopping the main program loop.
4
5 @todo: PP: when to destroy device listener?
6
7 @author: Peter Parente
8 @organization: IBM Corporation
9 @copyright: Copyright (c) 2005, 2007 IBM Corporation
10 @license: LGPL
11
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.
16
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.
21
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.
26
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}
30 '''
31 import signal
32 import time
33 import weakref
34 import Queue
35 import traceback
36 import ORBit
37 import bonobo
38 import gobject
39 import Accessibility
40 import Accessibility__POA
41 import utils
42 import constants
43 import event
44
45 class _Observer(object):
46   '''
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. 
51   
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.
56   
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
61   '''
62   def __init__(self, registry):
63     '''
64     Stores a reference to the creating L{Registry}. Intializes the reference
65     count on this object to zero.
66     
67     @param registry: The L{Registry} that created this observer
68     @type registry: weakref.proxy to L{Registry}
69     '''
70     self.registry = weakref.proxy(registry)
71     self.ref_count = 0
72
73   def clientRef(self):
74     '''
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}.
78     '''
79     self.ref_count += 1
80     
81   def clientUnref(self):
82     '''    
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}.
86     '''
87     self.ref_count -= 1
88     
89   def getClientRefCount(self):
90     '''
91     @return: Current Python reference count on this L{_Observer}
92     @rtype: integer
93     '''
94     return self.ref_count
95   
96   def ref(self): 
97     '''Required by CORBA. Does nothing.'''
98     pass
99     
100   def unref(self): 
101     '''Required by CORBA. Does nothing.'''
102     pass
103
104 class _DeviceObserver(_Observer, Accessibility__POA.DeviceEventListener):
105   '''
106   Observes keyboard press and release events.
107   
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
113   @type mask: integer
114   @ivar kind: Kind of events to monitor
115   @type kind: integer
116   @ivar mode: Keyboard event mode
117   @type mode: Accessibility.EventListenerMode
118   '''
119   def __init__(self, registry, synchronous, preemptive, global_):
120     '''
121     Creates a mode object that defines when key events will be received from 
122     the system. Stores all other information for later registration.
123     
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
132     '''
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_    
138    
139   def register(self, dc, key_set, mask, kind):
140     '''
141     Starts keyboard event monitoring.
142     
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
148       unapply all at once
149     @type mask: integer, iterable, or None
150     @param kind: Kind of events to monitor
151     @type kind: integer
152     '''
153     try:
154       # check if the mask is iterable
155       iter(mask)
156     except TypeError:
157       # register a single integer if not
158       dc.registerKeystrokeListener(self._this(), key_set, mask, kind, 
159                                    self.mode)
160     else:
161       for m in mask:
162         dc.registerKeystrokeListener(self._this(), key_set, m, kind, self.mode)
163
164   def unregister(self, dc, key_set, mask, kind):
165     '''
166     Stops keyboard event monitoring.
167     
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
173       unapply all at once
174     @type mask: integer, iterable, or None
175     @param kind: Kind of events to monitor
176     @type kind: integer
177     '''
178     try:
179       # check if the mask is iterable
180       iter(mask)
181     except TypeError:
182       # unregister a single integer if not
183       dc.deregisterKeystrokeListener(self._this(), key_set, mask, kind)
184     else:
185       for m in mask:
186         dc.deregisterKeystrokeListener(self._this(), key_set, m, kind)
187       
188   def queryInterface(self, repo_id):
189     '''
190     Reports that this class only implements the AT-SPI DeviceEventListener 
191     interface. Required by AT-SPI.
192     
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
197     '''
198     if repo_id == utils.getInterfaceIID(Accessibility.DeviceEventListener):
199       return self._this()
200     else:
201       return None
202
203   def notifyEvent(self, ev):
204     '''
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 set the L{Event} consume flag to True to indicate this event
208     should not be allowed to pass to other AT-SPI observers or the underlying
209     application.
210     
211     @param ev: Keyboard event
212     @type ev: Accessibility.DeviceEvent
213     @return: Should the event be consumed (True) or allowed to pass on to other
214       AT-SPI observers (False)?
215     @rtype: boolean
216     '''
217     # wrap the device event
218     ev = event.DeviceEvent(ev)
219     self.registry.handleDeviceEvent(ev, self)
220     return ev.consume
221
222 class _EventObserver(_Observer, Accessibility__POA.EventListener):
223   '''
224   Observes all non-keyboard AT-SPI events. Can be reused across event types.
225   '''
226   def register(self, reg, name):
227     '''
228     Starts monitoring for the given event.
229     
230     @param name: Name of the event to start monitoring
231     @type name: string
232     @param reg: Reference to the raw registry object
233     @type reg: Accessibility.Registry
234     '''
235     reg.registerGlobalEventListener(self._this(), name)
236     
237   def unregister(self, reg, name):
238     '''
239     Stops monitoring for the given event.
240     
241     @param name: Name of the event to stop monitoring
242     @type name: string
243     @param reg: Reference to the raw registry object
244     @type reg: Accessibility.Registry
245     '''
246     reg.deregisterGlobalEventListener(self._this(), name)
247
248   def queryInterface(self, repo_id):
249     '''
250     Reports that this class only implements the AT-SPI DeviceEventListener 
251     interface. Required by AT-SPI.
252
253     @param repo_id: Request for an interface 
254     @type repo_id: string
255     @return: The underlying CORBA object for the device event listener
256     @rtype: Accessibility.EventListener
257     '''
258     if repo_id == utils.getInterfaceIID(Accessibility.EventListener):
259       return self._this()
260     else:
261       return None
262
263   def notifyEvent(self, ev):
264     '''
265     Notifies the L{Registry} that an event has occurred. Wraps the raw event 
266     object in our L{Event} class to support automatic ref and unref calls.
267     Aborts on any exception indicating the event could not be wrapped.
268     
269     @param ev: AT-SPI event signal (anything but keyboard)
270     @type ev: Accessibility.Event
271     '''
272     # wrap raw event so ref counts are correct before queueing
273     ev = event.Event(ev)
274     self.registry.handleEvent(ev)
275
276 class Registry(object):
277   '''
278   Wraps the Accessibility.Registry to provide more Pythonic registration for
279   events. 
280   
281   This object should be treated as a singleton, but such treatment is not
282   enforced. You can construct another instance of this object and give it a
283   reference to the Accessibility.Registry singleton. Doing so is harmless and
284   has no point.
285   
286   @ivar async: Should event dispatch to local listeners be decoupled from event
287     receiving from the registry?
288   @type async: boolean
289   @ivar reg: Reference to the real, wrapped registry object
290   @type reg: Accessibility.Registry
291   @ivar dev: Reference to the device controller
292   @type dev: Accessibility.DeviceEventController
293   @ivar queue: Queue of events awaiting local dispatch
294   @type queue: Queue.Queue
295   @ivar clients: Map of event names to client listeners
296   @type clients: dictionary
297   @ivar observers: Map of event names to AT-SPI L{_Observer} objects
298   @type observers: dictionary
299   '''
300   def __init__(self, reg):
301     '''
302     Stores a reference to the AT-SPI registry. Gets and stores a reference
303     to the DeviceEventController.
304     
305     @param reg: Reference to the AT-SPI registry daemon
306     @type reg: Accessibility.Registry
307     '''
308     self.async = None
309     self.reg = reg
310     self.dev = self.reg.getDeviceEventController()
311     self.queue = Queue.Queue()
312     self.clients = {}
313     self.observers = {}
314     
315   def __call__(self):
316     '''
317     @return: This instance of the registry
318     @rtype: L{Registry}
319     '''
320     return self
321   
322   def start(self, async=False, gil=True):
323     '''
324     Enter the main loop to start receiving and dispatching events.
325     
326     @param async: Should event dispatch be asynchronous (decoupled) from 
327       event receiving from the AT-SPI registry?
328     @type async: boolean
329     @param gil: Add an idle callback which releases the Python GIL for a few
330       milliseconds to allow other threads to run? Necessary if other threads
331       will be used in this process.
332     @type gil: boolean
333     '''
334     self.async = async
335     
336     if gil:
337       def releaseGIL():
338         try:
339           time.sleep(1e-5)
340         except KeyboardInterrupt, e:
341           # store the exception for later
342           releaseGIL.keyboard_exception = e
343           self.stop()
344         return True
345       # make room for an exception if one occurs during the 
346       releaseGIL.keyboard_exception = None
347       i = gobject.idle_add(releaseGIL)
348       
349     # enter the main loop
350     try:
351       bonobo.main()
352     finally:
353       # clear all observers
354       for name, ob in self.observers.items():
355         ob.unregister(self.reg, name)
356       if gil:
357         gobject.source_remove(i)
358         if releaseGIL.keyboard_exception is not None:
359           # raise an keyboard exception we may have gotten earlier
360           raise releaseGIL.keyboard_exception
361
362   def stop(self, *args):
363     '''Quits the main loop.'''
364     try:
365       bonobo.main_quit()
366     except RuntimeError:
367       # ignore errors when quitting (probably already quitting)
368       pass
369     
370   def getDesktopCount(self):
371     '''
372     Gets the number of available desktops.
373     
374     @return: Number of desktops
375     @rtype: integer
376     @raise LookupError: When the count cannot be retrieved
377     '''
378     try:
379       return self.reg.getDesktopCount()
380     except Exception:
381       raise LookupError
382     
383   def getDesktop(self, i):
384     '''
385     Gets a reference to the i-th desktop.
386     
387     @param i: Which desktop to get
388     @type i: integer
389     @return: Desktop reference
390     @rtype: Accessibility.Desktop
391     @raise LookupError: When the i-th desktop cannot be retrieved
392     '''
393     try:
394       return self.reg.getDesktop(i)
395     except Exception, e:
396       raise LookupError(e)
397     
398   def registerEventListener(self, client, *names):
399     '''
400     Registers a new client callback for the given event names. Supports 
401     registration for all subevents if only partial event name is specified.
402     Do not include a trailing colon.
403     
404     For example, 'object' will register for all object events, 
405     'object:property-change' will register for all property change events,
406     and 'object:property-change:accessible-parent' will register only for the
407     parent property change event.
408     
409     Registered clients will not be automatically removed when the client dies.
410     To ensure the client is properly garbage collected, call 
411     L{deregisterEventListener}.
412
413     @param client: Callable to be invoked when the event occurs
414     @type client: callable
415     @param names: List of full or partial event names
416     @type names: list of string
417     '''
418     for name in names:
419       # store the callback for each specific event name
420       self._registerClients(client, name)
421
422   def deregisterEventListener(self, client, *names):
423     '''
424     Unregisters an existing client callback for the given event names. Supports 
425     unregistration for all subevents if only partial event name is specified.
426     Do not include a trailing colon.
427     
428     This method must be called to ensure a client registered by
429     L{registerEventListener} is properly garbage collected.
430
431     @param client: Client callback to remove
432     @type client: callable
433     @param names: List of full or partial event names
434     @type names: list of string
435     @return: Were event names specified for which the given client was not
436       registered?
437     @rtype: boolean
438     '''
439     missed = False
440     for name in names:
441       # remove the callback for each specific event name
442       missed |= self._unregisterClients(client, name)
443     return missed
444
445   def registerKeystrokeListener(self, client, key_set=[], mask=0, 
446                                 kind=(constants.KEY_PRESSED_EVENT, 
447                                       constants.KEY_RELEASED_EVENT),
448                                 synchronous=True, preemptive=True, 
449                                 global_=False):
450     '''
451     Registers a listener for key stroke events.
452     
453     @param client: Callable to be invoked when the event occurs
454     @type client: callable
455     @param key_set: Set of hardware key codes to stop monitoring. Leave empty
456       to indicate all keys.
457     @type key_set: list of integer
458     @param mask: When the mask is None, the codes in the key_set will be 
459       monitored only when no modifier is held. When the mask is an 
460       integer, keys in the key_set will be monitored only when the modifiers in
461       the mask are held. When the mask is an iterable over more than one 
462       integer, keys in the key_set will be monitored when any of the modifier
463       combinations in the set are held.
464     @type mask: integer, iterable, None
465     @param kind: Kind of events to watch, KEY_PRESSED_EVENT or 
466       KEY_RELEASED_EVENT.
467     @type kind: list
468     @param synchronous: Should the callback notification be synchronous, giving
469       the client the chance to consume the event?
470     @type synchronous: boolean
471     @param preemptive: Should the callback be allowed to preempt / consume the
472       event?
473     @type preemptive: boolean
474     @param global_: Should callback occur even if an application not supporting
475       AT-SPI is in the foreground? (requires xevie)
476     @type global_: boolean
477     '''
478     try:
479       # see if we already have an observer for this client
480       ob = self.clients[client]
481     except KeyError:
482       # create a new device observer for this client
483       ob = _DeviceObserver(self, synchronous, preemptive, global_)
484       # store the observer to client mapping, and the inverse
485       self.clients[ob] = client
486       self.clients[client] = ob
487     if mask is None:
488       # None means all modifier combinations
489       mask = utils.allModifiers()
490     # register for new keystrokes on the observer
491     ob.register(self.dev, key_set, mask, kind)
492
493   def deregisterKeystrokeListener(self, client, key_set=[], mask=0, 
494                                   kind=(constants.KEY_PRESSED_EVENT, 
495                                         constants.KEY_RELEASED_EVENT)):
496     '''
497     Deregisters a listener for key stroke events.
498     
499     @param client: Callable to be invoked when the event occurs
500     @type client: callable
501     @param key_set: Set of hardware key codes to stop monitoring. Leave empty
502       to indicate all keys.
503     @type key_set: list of integer
504     @param mask: When the mask is None, the codes in the key_set will be 
505       monitored only when no modifier is held. When the mask is an 
506       integer, keys in the key_set will be monitored only when the modifiers in
507       the mask are held. When the mask is an iterable over more than one 
508       integer, keys in the key_set will be monitored when any of the modifier
509       combinations in the set are held.
510     @type mask: integer, iterable, None
511     @param kind: Kind of events to stop watching, KEY_PRESSED_EVENT or 
512       KEY_RELEASED_EVENT.
513     @type kind: list
514     @raise KeyError: When the client isn't already registered for events
515     '''
516     # see if we already have an observer for this client
517     ob = self.clients[client]
518     if mask is None:
519       # None means all modifier combinations
520       mask = utils.allModifiers()
521     # register for new keystrokes on the observer
522     ob.unregister(self.dev, key_set, mask, kind)
523
524   def generateKeyboardEvent(self, keycode, keysym, kind):
525     '''
526     Generates a keyboard event. One of the keycode or the keysym parameters
527     should be specified and the other should be None. The kind parameter is 
528     required and should be one of the KEY_PRESS, KEY_RELEASE, KEY_PRESSRELEASE,
529     KEY_SYM, or KEY_STRING.
530     
531     @param keycode: Hardware keycode or None
532     @type keycode: integer
533     @param keysym: Symbolic key string or None
534     @type keysym: string
535     @param kind: Kind of event to synthesize
536     @type kind: integer
537     '''
538     if keysym is None:
539       self.dev.generateKeyboardEvent(keycode, '', kind)
540     else:
541       self.dev.generateKeyboardEvent(None, keysym, kind)
542   
543   def generateMouseEvent(self, x, y, name):
544     '''
545     Generates a mouse event at the given absolute x and y coordinate. The kind
546     of event generated is specified by the name. For example, MOUSE_B1P 
547     (button 1 press), MOUSE_REL (relative motion), MOUSE_B3D (butten 3 
548     double-click).
549     
550     @param x: Horizontal coordinate, usually left-hand oriented
551     @type x: integer
552     @param y: Vertical coordinate, usually left-hand oriented
553     @type y: integer
554     @param name: Name of the event to generate
555     @type name: string
556     '''
557     self.dev.generateMouseEvent(x, y, name)
558     
559   def handleDeviceEvent(self, event, ob):
560     '''
561     Dispatches L{event.DeviceEvent}s to registered clients. Clients are called
562     in the order they were registered for the given AT-SPI event. If any
563     client sets the L{event.DeviceEvent.consume} flag to True, callbacks cease
564     for the event for clients of this registry instance. Clients of other
565     registry instances and clients in other processes may be affected
566     depending on the values of synchronous and preemptive used when invoking
567     L{registerKeystrokeListener}. 
568     
569     @note: Asynchronous dispatch of device events is not supported.
570     
571     @param event: AT-SPI device event
572     @type event: L{event.DeviceEvent}
573     @param ob: Observer that received the event
574     @type ob: L{_DeviceObserver}
575     '''
576     try:
577       # try to get the client registered for this event type
578       client = self.clients[ob]
579     except KeyError:
580       # client may have unregistered recently, ignore event
581       return
582     # make the call to the client
583     try:
584       client(event)
585     except Exception:
586       # print the exception, but don't let it stop notification
587       traceback.print_exc()
588  
589   def handleEvent(self, event):
590     '''    
591     Handles an AT-SPI event by either queuing it for later dispatch when the
592     L{Registry.async} flag is set, or dispatching it immediately.
593
594     @param event: AT-SPI event
595     @type event: L{event.Event}
596     '''
597     if self.async:
598       # queue for now
599       self.queue.put_nowait(event)
600     else:
601       # dispatch immediately
602       self._dispatchEvent(event)
603
604   def _dispatchEvent(self, event):
605     '''
606     Dispatches L{event.Event}s to registered clients. Clients are called in
607     the order they were registered for the given AT-SPI event. If any client
608     sets the L{Event} consume flag to True, callbacks cease for the event for
609     clients of this registry instance. Clients of other registry instances and
610     clients in other processes are unaffected.
611
612     @param event: AT-SPI event
613     @type event: L{event.Event}
614     '''
615     try:
616       # try to get the client registered for this event type
617       clients = self.clients[event.type.name]
618     except KeyError:
619       # client may have unregistered recently, ignore event
620       return
621     # make the call to each client
622     for client in clients:
623       try:
624         client(event)
625       except Exception:
626         # print the exception, but don't let it stop notification
627         traceback.print_exc()
628       if event.consume:
629         # don't allow further processing if the consume flag is set
630         break
631
632   def _registerClients(self, client, name):
633     '''
634     Internal method that recursively associates a client with AT-SPI event 
635     names. Allows a client to incompletely specify an event name in order to 
636     register for subevents without specifying their full names manually.
637     
638     @param client: Client callback to receive event notifications
639     @type client: callable
640     @param name: Partial or full event name
641     @type name: string
642     '''
643     try:
644       # look for an event name in our event tree dictionary
645       events = constants.EVENT_TREE[name]
646     except KeyError:
647       # if the event name doesn't exist, it's a leaf event meaning there are
648       # no subtypes for that event
649       # add this client to the list of clients already in the dictionary 
650       # using the event name as the key; if there are no clients yet for this 
651       # event, insert an empty list into the dictionary before appending 
652       # the client
653       et = event.EventType(name)
654       clients = self.clients.setdefault(et.name, [])
655       try:
656         # if this succeeds, this client is already registered for the given
657         # event type, so ignore the request
658         clients.index(client)
659       except ValueError:
660         # else register the client
661         clients.append(client)
662         self._registerObserver(name)
663     else:
664         # if the event name does exist in the tree, there are subevents for
665         # this event; loop through them calling this method again to get to
666         # the leaf events
667         for e in events:
668           self._registerClients(client, e)
669       
670   def _unregisterClients(self, client, name):
671     '''
672     Internal method that recursively unassociates a client with AT-SPI event 
673     names. Allows a client to incompletely specify an event name in order to 
674     unregister for subevents without specifying their full names manually.
675     
676     @param client: Client callback to receive event notifications
677     @type client: callable
678     @param name: Partial or full event name
679     @type name: string
680     '''
681     missed = False
682     try:
683       # look for an event name in our event tree dictionary
684       events = constants.EVENT_TREE[name]
685     except KeyError:
686       try:
687         # if the event name doesn't exist, it's a leaf event meaning there are
688         # no subtypes for that event
689         # get the list of registered clients and try to remove the one provided
690         et = event.EventType(name)
691         clients = self.clients[et.name]
692         clients.remove(client)
693         self._unregisterObserver(name)
694       except (ValueError, KeyError):
695         # ignore any exceptions indicating the client is not registered
696         missed = True
697       return missed
698     # if the event name does exist in the tree, there are subevents for this 
699     # event; loop through them calling this method again to get to the leaf
700     # events
701     for e in events:
702       missed |= self._unregisterClients(client, e)
703     return missed
704   
705   def _registerObserver(self, name):
706     '''    
707     Creates a new L{_Observer} to watch for events of the given type or
708     returns the existing observer if one is already registered. One
709     L{_Observer} is created for each leaf in the L{constants.EVENT_TREE} or
710     any event name not found in the tree.
711    
712     @param name: Raw name of the event to observe
713     @type name: string
714     @return: L{_Observer} object that is monitoring the event
715     @rtype: L{_Observer}
716     '''
717     et = event.EventType(name)
718     try:
719       # see if an observer already exists for this event
720       ob = self.observers[et.name]
721     except KeyError:
722       # build a new observer if one does not exist
723       ob = _EventObserver(self)
724       # we have to register for the raw name because it may be different from
725       # the parsed name determined by EventType (e.g. trailing ':' might be 
726       # missing)
727       ob.register(self.reg, name)
728       self.observers[et.name] = ob
729     # increase our client ref count so we know someone new is watching for the 
730     # event
731     ob.clientRef()
732     return ob
733     
734   def _unregisterObserver(self, name):
735     '''    
736     Destroys an existing L{_Observer} for the given event type only if no
737     clients are registered for the events it is monitoring.
738     
739     @param name: Name of the event to observe
740     @type name: string
741     @raise KeyError: When an observer for the given event is not regist
742     '''
743     et = event.EventType(name)
744     # see if an observer already exists for this event
745     ob = self.observers[et.name]
746     ob.clientUnref()
747     if ob.getClientRefCount() == 0:
748       ob.unregister(self.reg, name)
749       del self.observers[et.name]