Leakfixes from Padraig O'Briain for bug #361386 and bug #369377.
[platform/core/uifw/at-spi2-atk.git] / registryd / registry.c
1 /*
2  * AT-SPI - Assistive Technology Service Provider Interface
3  * (Gnome Accessibility Project; http://developer.gnome.org/projects/gap)
4  *
5  * Copyright 2001, 2002 Sun Microsystems Inc.,
6  * Copyright 2001, 2002 Ximian, Inc.
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the
20  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21  * Boston, MA 02111-1307, USA.
22  */
23
24 /* registry.c: the main accessibility service registry implementation */
25
26 #undef SPI_LISTENER_DEBUG
27 #undef SPI_DEBUG
28 #undef SPI_QUEUE_DEBUG
29
30 #include <config.h>
31 #ifdef SPI_DEBUG
32 #  include <stdio.h>
33 #endif
34
35 #include <bonobo/bonobo-exception.h>
36 #include "../libspi/spi-private.h"
37 #include "registry.h"
38
39 /* Our parent GObject type  */
40 #define PARENT_TYPE SPI_LISTENER_TYPE
41
42 /* A pointer to our parent object class */
43 static SpiListenerClass *spi_registry_parent_class;
44
45 static GQuark _deactivate_quark = 0;
46 static GQuark _activate_quark = 0;
47 static GQuark _state_quark = 0;
48 static GQuark _state_changed_focused_quark = 0;
49
50 int _dbg = 0;
51
52 typedef enum {
53   ETYPE_FOCUS,
54   ETYPE_OBJECT,
55   ETYPE_PROPERTY,
56   ETYPE_WINDOW,
57   ETYPE_TOOLKIT,
58   ETYPE_KEYBOARD,
59   ETYPE_MOUSE,
60   ETYPE_LAST_DEFINED
61 } EventTypeCategory;
62
63 typedef struct {
64   const char *event_name;
65   EventTypeCategory type_cat;
66   GQuark major;  /* from string segment[1] */
67   GQuark minor;  /* from string segment[1]+segment[2] */
68   GQuark detail; /* from string segment[3] (not concatenated) */
69 } EventTypeStruct;
70
71 typedef struct {
72   Accessibility_EventListener listener;
73   GQuark            event_type_quark;
74   EventTypeCategory event_type_cat;
75 } SpiListenerStruct;
76
77 static void
78 spi_registry_set_debug (const char *debug_flag_string)
79 {
80   if (debug_flag_string) 
81     _dbg = (int) g_ascii_strtod (debug_flag_string, NULL);
82 }
83
84 SpiListenerStruct *
85 spi_listener_struct_new (Accessibility_EventListener listener, CORBA_Environment *ev)
86 {
87   SpiListenerStruct *retval = g_malloc (sizeof (SpiListenerStruct));
88   retval->listener = bonobo_object_dup_ref (listener, ev);
89   return retval;
90 }
91
92
93 void
94 spi_listener_struct_free (SpiListenerStruct *ls, CORBA_Environment *ev)
95 {
96   bonobo_object_release_unref (ls->listener, ev);
97   g_free (ls);
98 }
99
100 static void
101 desktop_add_application (SpiDesktop *desktop,
102                          guint index, gpointer data)
103 {
104   BonoboObject *registry = BONOBO_OBJECT (data);
105   Accessibility_Event e;
106   CORBA_Environment ev;
107   Accessibility_Accessible a;
108   
109   CORBA_exception_init (&ev);
110   e.type = "object:children-changed:add";
111   e.source = BONOBO_OBJREF (desktop);
112   e.detail1 = index;
113   e.detail2 = 0;
114   a = Accessibility_Accessible_getChildAtIndex (BONOBO_OBJREF (desktop), 
115                                                 index, &ev);
116   /* FIXME
117   spi_init_any_object (&e.any_data, a);
118   */
119   spi_init_any_nil (&e.any_data,
120                     e.source,
121                     Accessibility_ROLE_DESKTOP_FRAME,
122                     "");
123
124   Accessibility_Registry_notifyEvent (BONOBO_OBJREF (registry),
125                                       &e, &ev);
126   bonobo_object_release_unref (a, &ev);
127   CORBA_exception_free (&ev);
128 }
129
130
131
132 static void
133 desktop_remove_application (SpiDesktop *desktop,
134                             guint index, gpointer data)
135 {
136   BonoboObject *registry = BONOBO_OBJECT (data);
137   Accessibility_Event e;
138   /* Accessibility_Accessible a; FIXME */
139   CORBA_Environment ev;
140   
141   CORBA_exception_init (&ev);
142
143   e.type = "object:children-changed:remove";
144   e.source = BONOBO_OBJREF (desktop);
145   e.detail1 = index;
146   e.detail2 = 0;
147   /* FIXME
148   a = Accessibility_Accessible_getChildAtIndex (BONOBO_OBJREF (desktop), 
149                                                 index, &ev);
150   spi_init_any_object (&e.any_data, a);
151   */
152   spi_init_any_nil (&e.any_data,
153                     e.source,
154                     Accessibility_ROLE_DESKTOP_FRAME,
155                     "");
156   /* Accessibility_Accessible_unref (a, &ev); */
157   Accessibility_Registry_notifyEvent (BONOBO_OBJREF (registry),
158                                       &e, &ev);
159   Accessibility_Desktop_unref (e.source, &ev);
160   CORBA_exception_free (&ev);
161 }
162
163
164 static void
165 spi_registry_object_finalize (GObject *object)
166 {
167   DBG (1, g_warning ("spi_registry_object_finalize called\n"));
168   g_object_unref (SPI_REGISTRY (object)->de_controller);
169
170   G_OBJECT_CLASS (spi_registry_parent_class)->finalize (object);
171 }
172
173 static long
174 _get_unique_id (void)
175 {
176   static long id = 0;
177
178   return ++id;
179 }
180
181 /**
182  * registerApplication:
183  * @application: a reference to the requesting @Application
184  * return values: void
185  *
186  * Register a new application with the accessibility broker.
187  *
188  **/
189 static void
190 impl_accessibility_registry_register_application (PortableServer_Servant servant,
191                                                   const Accessibility_Application application,
192                                                   CORBA_Environment * ev)
193 {
194   SpiRegistry *registry = SPI_REGISTRY (bonobo_object_from_servant (servant));
195
196 #ifdef SPI_DEBUG
197   fprintf (stderr, "registering app %p\n", application);
198 #endif
199   spi_desktop_add_application (registry->desktop, application);
200
201   Accessibility_Application__set_id (application, _get_unique_id (), ev);
202
203   /*
204    * TODO: change the implementation below to a WM-aware one;
205    * e.g. don't add all apps to the SpiDesktop
206    */
207 }
208
209 #ifdef USE_A_HASH_IN_FUTURE
210 static gint
211 compare_corba_objects (gconstpointer p1, gconstpointer p2)
212 {
213   CORBA_Environment ev;
214   gint retval;
215
216 #ifdef SPI_DEBUG
217   fprintf (stderr, "comparing %p to %p\n",
218            p1, p2);
219 #endif
220   
221   retval = !CORBA_Object_is_equivalent ((CORBA_Object) p1, (CORBA_Object) p2, &ev);
222   return retval;  
223 }
224 #endif
225
226 static void
227 register_with_toolkits (SpiRegistry *spi_registry_bonobo_object, EventTypeStruct *etype, CORBA_Environment *ev)
228 {
229   gint n_desktops;
230   gint n_apps;
231   gint i, j;
232   Accessibility_Desktop desktop;
233   Accessibility_Application app;
234   Accessibility_Registry registry;
235   registry  = BONOBO_OBJREF (spi_registry_bonobo_object);
236
237   /* for each app in each desktop, call ...Application_registerToolkitEventListener */
238
239   n_desktops = Accessibility_Registry_getDesktopCount (registry, ev);
240
241   for (i=0; i<n_desktops; ++i)
242     {
243       desktop = Accessibility_Registry_getDesktop (registry, i, ev);
244       n_apps = Accessibility_Desktop__get_childCount (desktop, ev);
245       for (j=0; j<n_apps; ++j)
246         {
247           app = (Accessibility_Application) Accessibility_Desktop_getChildAtIndex (desktop,
248                                                                                    j,
249                                                                                    ev);
250           Accessibility_Application_registerToolkitEventListener (app,
251                                                                   registry,
252                                                                   CORBA_string_dup (etype->event_name),
253                                                                   ev);
254         }
255     }
256 }
257
258 #ifdef USE_A_HASH_IN_FUTURE
259
260 static gint
261 compare_listener_quarks (gconstpointer p1, gconstpointer p2)
262 {
263         return (((SpiListenerStruct *)p2)->event_type_quark !=
264                 ((SpiListenerStruct *)p1)->event_type_quark);
265 }
266
267 static gint
268 compare_listener_corbaref (gconstpointer p1, gconstpointer p2)
269 {
270   return compare_corba_objects (((SpiListenerStruct *)p2)->listener,
271                                 ((SpiListenerStruct *)p1)->listener);
272 }
273 #endif
274
275 static void
276 parse_event_type (EventTypeStruct *etype, const char *event_name)
277 {
278   gchar **split_string;
279   gchar *s;
280
281   split_string = g_strsplit (event_name, ":", 4);
282   etype->event_name = event_name;
283
284   if (!g_ascii_strncasecmp (event_name, "focus:", 6))
285     {
286       etype->type_cat = ETYPE_FOCUS;
287     }
288   else if (!g_ascii_strncasecmp (event_name, "mouse:", 6))
289     {
290       etype->type_cat = ETYPE_MOUSE;
291     }
292   else if (!g_ascii_strncasecmp (event_name, "object:", 7))
293     {
294       etype->type_cat = ETYPE_OBJECT;
295     }
296   else if (!g_ascii_strncasecmp (event_name, "window:", 7))
297     {
298       etype->type_cat = ETYPE_WINDOW;
299     }
300   else if (!g_ascii_strncasecmp (event_name, "keyboard:", 9))
301     {
302       etype->type_cat = ETYPE_KEYBOARD;
303     }
304   else
305     {
306       etype->type_cat = ETYPE_TOOLKIT;
307     }
308
309   if (split_string[1])
310     {
311       etype->major = g_quark_from_string (split_string[1]);
312       if (split_string[2])
313         {
314           etype->minor = g_quark_from_string (s = g_strconcat (split_string[1], split_string[2], NULL));
315           g_free (s);
316           if (split_string[3])
317             {
318               etype->detail = g_quark_from_string (split_string[3]);
319             }
320           else
321             {
322               etype->detail = g_quark_from_static_string ("");
323             }
324         }
325       else
326         {
327           etype->minor = etype->major;
328           etype->detail = g_quark_from_static_string (""); /*etype->major;*/
329         }
330     }
331   else
332     {
333       etype->major = g_quark_from_static_string ("");
334       etype->minor = etype->major;
335       etype->detail = etype->major;
336     }
337
338   g_strfreev (split_string);
339 }
340
341 /**
342  * deregisterApplication:
343  * @application: a reference to the @Application
344  * to be deregistered.
345  * return values: void
346  *
347  * De-register an application previously registered with the broker.
348  *
349  **/
350 static void
351 impl_accessibility_registry_deregister_application (PortableServer_Servant servant,
352                                                     const Accessibility_Application application,
353                                                     CORBA_Environment * ev)
354 {
355   SpiRegistry *registry = SPI_REGISTRY (bonobo_object_from_servant (servant));
356
357   spi_desktop_remove_application (registry->desktop, application);
358
359 #ifdef SPI_DEBUG
360   fprintf (stderr, "de-registered app %p\n", application);
361 #endif
362 }
363
364 static GList **
365 get_listener_list (SpiRegistry      *registry,
366                    EventTypeCategory cat)
367 {
368   GList **ret;
369   
370   switch (cat)
371     {
372       case ETYPE_OBJECT:
373       case ETYPE_PROPERTY:
374       case ETYPE_FOCUS:
375       case ETYPE_KEYBOARD:
376         ret = &registry->object_listeners;
377         break;
378       case ETYPE_WINDOW:
379         ret = &registry->window_listeners;
380         break;
381       case ETYPE_MOUSE:
382       case ETYPE_TOOLKIT:
383         ret = &registry->toolkit_listeners;
384         break;
385       default:
386         ret = NULL;
387         break;
388     }
389   return ret;
390 }
391
392 /*
393  * CORBA Accessibility::Registry::registerGlobalEventListener method implementation
394  */
395 static void
396 impl_accessibility_registry_register_global_event_listener (
397         PortableServer_Servant      servant,
398         Accessibility_EventListener listener,
399         const CORBA_char           *event_name,
400         CORBA_Environment          *ev)
401 {
402   SpiRegistry *registry = SPI_REGISTRY (bonobo_object_from_servant (servant)); 
403   SpiListenerStruct *ls = spi_listener_struct_new (listener, ev);
404   EventTypeStruct etype;
405   GList          **list;
406
407 #ifdef SPI_LISTENER_DEBUG
408   fprintf (stderr, "registering for events of type %s\n", event_name);
409 #endif
410
411   /* parse, check major event type and add listener accordingly */
412   parse_event_type (&etype, event_name);
413   ls->event_type_quark = etype.minor;
414   ls->event_type_cat = etype.type_cat;
415
416   list = get_listener_list (registry, etype.type_cat);
417
418   if (list)
419     {
420       *list = g_list_prepend (*list, ls);
421
422       if (etype.type_cat == ETYPE_TOOLKIT)
423         {
424           register_with_toolkits (registry, &etype, ev);
425         }
426     }
427   else
428     {
429       spi_listener_struct_free (ls, ev);
430     }
431 }
432
433 typedef struct {
434   gboolean                    remove_all;
435   Accessibility_EventListener listener;
436   EventTypeStruct             etype;
437 } RemoveListenerClosure;
438
439 static SpiReEntrantContinue
440 remove_listener_cb (GList * const *list, gpointer user_data)
441 {
442   SpiListenerStruct *ls = (SpiListenerStruct *) (*list)->data;
443   CORBA_Environment  ev;
444   RemoveListenerClosure *cl = user_data;
445
446   CORBA_exception_init (&ev);
447
448   if (cl->remove_all || (((cl->etype.minor == ls->event_type_quark) || 
449                          (cl->etype.major == ls->event_type_quark)) &&
450                          cl->etype.type_cat == ls->event_type_cat ) )
451   {
452     if (CORBA_Object_is_equivalent (ls->listener, cl->listener, &ev))
453       {
454         spi_re_entrant_list_delete_link (list);
455         spi_listener_struct_free (ls, &ev);
456       }
457   }
458
459   CORBA_exception_free (&ev);
460
461   return SPI_RE_ENTRANT_CONTINUE;
462 }
463
464 /*
465  * CORBA Accessibility::Registry::deregisterGlobalEventListenerAll method implementation
466  */
467 static void
468 impl_accessibility_registry_deregister_global_event_listener_all (
469         PortableServer_Servant      servant,
470         Accessibility_EventListener listener,
471         CORBA_Environment          *ev)
472 {
473   int i;
474   GList **lists[3];
475   SpiRegistry *registry = SPI_REGISTRY (bonobo_object_from_servant (servant));
476   RemoveListenerClosure cl = { 0, };
477
478   lists[0] = &registry->object_listeners;
479   lists[1] = &registry->window_listeners;
480   lists[2] = &registry->toolkit_listeners;
481
482   cl.remove_all = TRUE;
483   cl.listener = listener;
484
485   for (i = 0; i < sizeof (lists) / sizeof (lists[0]); i++)
486     {
487       spi_re_entrant_list_foreach (lists [i], remove_listener_cb, &cl);
488     }
489 }
490
491
492 /*
493  * CORBA Accessibility::Registry::deregisterGlobalEventListener method implementation
494  */
495 static void
496 impl_accessibility_registry_deregister_global_event_listener (
497         PortableServer_Servant      servant,
498         Accessibility_EventListener listener,
499         const CORBA_char           *event_name,
500         CORBA_Environment          *ev)
501 {
502   SpiRegistry    *registry;
503   RemoveListenerClosure cl = { 0, };
504
505   registry = SPI_REGISTRY (bonobo_object_from_servant (servant));
506
507   cl.remove_all = FALSE;
508   parse_event_type (&cl.etype, (char *) event_name);
509   cl.listener = listener;
510
511   spi_re_entrant_list_foreach (get_listener_list (registry, cl.etype.type_cat),
512                                 remove_listener_cb, &cl);
513 }
514
515
516 /**
517  * getDesktopCount:
518  * return values: a short integer indicating the current number of
519  * @Desktops.
520  *
521  * Get the current number of desktops.
522  *
523  **/
524 static short
525 impl_accessibility_registry_get_desktop_count (PortableServer_Servant servant,
526                                                CORBA_Environment * ev)
527 {
528   /* TODO: implement support for multiple virtual desktops */
529   CORBA_short n_desktops;
530   n_desktops = (CORBA_short) 1;
531   return n_desktops;
532 }
533
534
535 /**
536  * getDesktop:
537  * @n: the index of the requested @Desktop.
538  * return values: a reference to the requested @Desktop.
539  *
540  * Get the nth accessible desktop.
541  *
542  **/
543 static Accessibility_Desktop
544 impl_accessibility_registry_get_desktop (PortableServer_Servant servant,
545                                          const CORBA_short n,
546                                          CORBA_Environment * ev)
547 {
548   SpiRegistry *registry = SPI_REGISTRY (bonobo_object_from_servant (servant));
549
550   /* TODO: implement support for multiple virtual desktops */
551   if (n == 0)
552     {
553       return (Accessibility_Desktop)
554         bonobo_object_dup_ref (BONOBO_OBJREF (registry->desktop), ev);
555     }
556   else
557     {
558       return (Accessibility_Desktop) CORBA_OBJECT_NIL;
559     }
560 }
561
562
563 /**
564  * getDesktopList:
565  * return values: a sequence containing references to
566  * the @Desktops.
567  *
568  * Get a list of accessible desktops.
569  *
570  **/
571 static Accessibility_DesktopSeq *
572 impl_accessibility_registry_get_desktop_list (PortableServer_Servant servant,
573                                               CORBA_Environment * ev)
574 {
575   SpiRegistry *registry = SPI_REGISTRY (bonobo_object_from_servant (servant));
576   Accessibility_DesktopSeq *desktops;
577
578   desktops = Accessibility_DesktopSeq__alloc ();
579   desktops->_length = desktops->_maximum = 1;
580   desktops->_buffer = Accessibility_DesktopSeq_allocbuf (desktops->_length);
581   desktops->_buffer [0] = bonobo_object_dup_ref (BONOBO_OBJREF (registry->desktop), ev);
582
583   return desktops;
584 }
585
586
587 static Accessibility_DeviceEventController
588 impl_accessibility_registry_get_device_event_controller (PortableServer_Servant servant,
589                                                          CORBA_Environment     *ev)
590 {
591   SpiRegistry *registry = SPI_REGISTRY (bonobo_object_from_servant (servant));
592
593   if (!registry->de_controller)
594     {
595       registry->de_controller = spi_device_event_controller_new (registry);
596     }
597
598   return bonobo_object_dup_ref (BONOBO_OBJREF (registry->de_controller), ev);
599 }
600
601 typedef struct {
602   CORBA_Environment  *ev;
603   Bonobo_Unknown      source;
604   EventTypeStruct     etype;
605   Accessibility_Event *e_out;
606 } NotifyContext;
607
608 static SpiReEntrantContinue
609 notify_listeners_cb (GList * const *list, gpointer user_data)
610 {
611   SpiListenerStruct *ls;
612   NotifyContext     *ctx = user_data;
613
614   ls = (*list)->data;
615
616 #ifdef SPI_LISTENER_DEBUG
617   fprintf (stderr, "event quarks: %lx %lx %lx\n", ls->event_type_quark, ctx->etype.major, ctx->etype.minor);
618   fprintf (stderr, "event name: %s\n", ctx->etype.event_name);
619 #endif
620   if ((ls->event_type_quark == ctx->etype.major) ||
621       (ls->event_type_quark == ctx->etype.minor))
622     {
623 #ifdef SPI_DEBUG
624       CORBA_string s;
625       fprintf (stderr, "notifying listener %d\n", 0);
626 /* g_list_index (list, l->data)); */
627       s = Accessibility_Accessible__get_name (ctx->source, ctx->ev);
628       fprintf (stderr, "event source name %s\n", s);
629       CORBA_free (s);
630       if (BONOBO_EX (ctx->ev))
631         {
632           CORBA_exception_free (ctx->ev);
633           return SPI_RE_ENTRANT_CONTINUE;
634         }
635 #endif
636       
637       ctx->e_out->source = ctx->source;
638       
639       if ((*list) && (*list)->data == ls)
640         {
641           Accessibility_EventListener_notifyEvent (
642             (Accessibility_EventListener) ls->listener, ctx->e_out, ctx->ev);
643           if (ctx->ev->_major != CORBA_NO_EXCEPTION)
644             {
645               DBG (1, g_warning ("Accessibility app error: exception during "
646                         "event notification: %s\n",
647                         CORBA_exception_id (ctx->ev)));
648               CORBA_exception_free (ctx->ev);
649               /* FIXME: check that this item is removed from the list
650                * on system exception by a 'broken' listener */
651             }
652         }
653     }  
654
655   return SPI_RE_ENTRANT_CONTINUE;
656 }
657
658 static void
659 registry_emit_event (SpiRegistry *registry, NotifyContext *ctx)
660 {
661   GList       **list = get_listener_list (registry, ctx->etype.type_cat);
662
663   if (list && *list)
664     {
665     
666       spi_re_entrant_list_foreach (list, notify_listeners_cb, ctx);
667     }
668 }
669
670 static NotifyContext*
671 registry_clone_notify_context (NotifyContext *ctx)
672 {
673   NotifyContext *new_ctx = g_new0 (NotifyContext, 1);
674
675   new_ctx->ev = NULL;
676   new_ctx->source = bonobo_object_dup_ref (ctx->source, NULL); 
677   new_ctx->etype.event_name = CORBA_string_dup (ctx->etype.event_name);
678   new_ctx->etype.type_cat = ctx->etype.type_cat;
679   new_ctx->etype.major = ctx->etype.major;
680   new_ctx->etype.minor = ctx->etype.minor;
681   new_ctx->etype.detail = ctx->etype.detail;
682   new_ctx->e_out = ORBit_copy_value (ctx->e_out, TC_Accessibility_Event);
683   return new_ctx;
684 }
685
686 static void
687 registry_flush_event_queue (SpiRegistry       *registry,
688                             gboolean      discard,
689                             CORBA_Environment *ev)
690 {
691   NotifyContext *q_ctx;
692   while (!g_queue_is_empty (registry->deferred_event_queue)) {
693     q_ctx = g_queue_pop_tail (registry->deferred_event_queue);
694 #ifdef SPI_QUEUE_DEBUG
695     fprintf (stderr, "%s! %s [n=%d] %p\n", (discard ? "discard" : "pop"), 
696              q_ctx->etype.event_name, 
697              (int) registry->deferred_event_queue->length, q_ctx);
698 #endif
699     if (!discard)  {
700       q_ctx->ev = ev;
701       registry_emit_event (registry, q_ctx);
702     }
703     if (discard &&
704         (q_ctx->etype.type_cat == ETYPE_OBJECT) && 
705         (q_ctx->etype.major == _state_quark) &&
706         (q_ctx->etype.minor == _state_changed_focused_quark)) {
707         registry->focus_object = q_ctx->source;
708 #ifdef SPI_QUEUE_DEBUG
709         fprintf (stderr, "discard!: set focus_object %p\n", registry->focus_object);
710 #endif
711     }
712     else {
713       bonobo_object_release_unref (q_ctx->source, NULL);
714     }
715     CORBA_free ((void *)q_ctx->etype.event_name);
716     CORBA_free (q_ctx->e_out);
717     g_free (q_ctx);
718   }
719   registry->is_queueing = FALSE;
720 }
721
722 static gboolean
723 registry_timeout_flush_queue (gpointer data)
724 {
725   SpiRegistry *registry = data;
726   CORBA_Environment ev;
727 #ifdef SPI_QUEUE_DEBUG
728   fprintf (stderr, "timeout! flushing queue...\n");
729 #endif
730   CORBA_exception_init (&ev);
731   registry->queue_handler_id = 0;
732   registry_flush_event_queue (registry, FALSE, &ev);
733   return FALSE;
734 }
735
736 static gboolean
737 registry_discard_on_event (SpiRegistry *registry, NotifyContext *ctx)
738 {
739   gboolean retval = FALSE;
740   NotifyContext *q_ctx = g_queue_peek_tail (registry->deferred_event_queue);
741   if ((q_ctx != NULL) &&
742       (ctx->etype.type_cat == ETYPE_WINDOW) && 
743       (ctx->etype.major == _activate_quark)) {
744     if (CORBA_Object_is_equivalent (ctx->source, q_ctx->source, NULL)) {
745       retval = TRUE;
746     }
747   }
748   return retval;
749 }
750
751 static gboolean
752 registry_reset_on_event (SpiRegistry *registry, NotifyContext *ctx)
753 {
754   return (ctx->etype.type_cat == ETYPE_WINDOW) ? TRUE : FALSE;
755 }
756
757 #ifdef SPI_QUEUE_DEBUG
758 #include <sys/time.h>
759 #endif
760
761 static void
762 registry_start_queue (SpiRegistry *registry)
763 {
764 #ifdef SPI_QUEUE_DEBUG
765     struct timeval tp;
766     gettimeofday (&tp, NULL);
767     fprintf (stderr, "start queueing at %i.%.6i\n", tp.tv_sec, tp.tv_usec);
768 #endif
769     if (registry->queue_handler_id != 0)
770       g_source_remove (registry->queue_handler_id);
771        
772     if (registry->focus_object)
773       {
774 #ifdef SPI_QUEUE_DEBUG
775         fprintf (stderr, "registry_start_queue: release focus_object %p\n", registry->focus_object);
776 #endif
777         bonobo_object_release_unref (registry->focus_object, NULL);
778         registry->focus_object = NULL;
779       }
780     registry->queue_handler_id = g_timeout_add_full (G_PRIORITY_HIGH_IDLE, 
781                                                      registry->exit_notify_timeout,
782                                                      registry_timeout_flush_queue, registry, 
783                                                      NULL);
784     registry->is_queueing = TRUE;
785 }
786
787 static gboolean
788 registry_discard_event (SpiRegistry *registry,  NotifyContext *ctx)
789 {
790   gboolean ret = FALSE;
791
792   if (ctx->etype.type_cat == ETYPE_FOCUS)
793     {
794       if (registry->focus_object)
795         {
796           if (CORBA_Object_is_equivalent (registry->focus_object, ctx->source, NULL))
797             {
798               ret = TRUE;
799             }
800 #ifdef SPI_QUEUE_DEBUG
801           fprintf (stderr, "registry_discard_event: release focus_object %p\n", registry->focus_object);
802 #endif
803           bonobo_object_release_unref (registry->focus_object, NULL);
804           registry->focus_object = NULL;
805         }
806     }
807   return ret; 
808 }
809
810 static gboolean
811 registry_defer_on_event (SpiRegistry *registry, NotifyContext *ctx)
812 {
813   gboolean defer = FALSE;
814   if ((ctx->etype.type_cat == ETYPE_WINDOW) && 
815       (ctx->etype.major == _deactivate_quark)) {
816     defer = TRUE;
817     registry_start_queue (registry);
818   }
819   /* defer all object:state-change events after a window:deactivate */
820   else if ((ctx->etype.type_cat == ETYPE_FOCUS) ||
821            ((ctx->etype.type_cat == ETYPE_OBJECT) && 
822            (ctx->etype.major == _state_quark))) {
823     defer = TRUE;
824   }
825   return defer;
826 }
827
828 static gboolean
829 registry_queue_event (SpiRegistry *registry, NotifyContext *ctx)
830 {
831 #ifdef SPI_QUEUE_DEBUG
832     if (ctx->etype.type_cat != ETYPE_MOUSE)
833       fprintf (stderr, "push! %s %p\n", ctx->etype.event_name, ctx);
834 #endif    
835   if (registry->is_queueing)
836     {
837       NotifyContext *q_ctx = registry_clone_notify_context (ctx);
838
839       g_queue_push_head (registry->deferred_event_queue, q_ctx);
840
841       return FALSE;
842     }
843   else
844     {
845       return TRUE; 
846     }
847 }
848
849 /**
850  * Dispose of event in one of several ways:
851  * 1) discard;
852  * 2) initiate queuing and push onto queue (below)
853  * 3) push on existing queue to either pop on timeout or on subsequent event
854  * 4) pass-through immediately
855  * 5) pass-through, discarding queued events
856  * 6) emit queued events and then pass through
857  **/
858 static gboolean
859 registry_filter_event (SpiRegistry *registry, NotifyContext *ctx,
860                        CORBA_Environment *ev)
861 {
862   g_assert (ctx != NULL);
863
864   if (registry_discard_event (registry, ctx))
865     return FALSE;
866
867   if (registry_defer_on_event (registry, ctx)) { /* #2, #3 */
868     if (registry->is_queueing) {
869       return registry_queue_event (registry, ctx);
870     }
871     else { /* #4a */
872       return TRUE;
873     }
874   } 
875   else if (registry_reset_on_event (registry, ctx)) { /* #5, #6 */
876     gboolean discard = registry_discard_on_event (registry, ctx);
877 #ifdef SPI_QUEUE_DEBUG
878     fprintf (stderr, "event %s caused reset, discard=%d\n",
879              ctx->etype.event_name, (int) discard);
880       {
881         struct timeval tp;
882         gettimeofday (&tp, NULL);
883         fprintf (stderr, "event at %i.%.6i\n", tp.tv_sec, tp.tv_usec);
884       }
885 #endif    
886     registry_flush_event_queue (registry, discard, ev);
887     return (discard ? FALSE : TRUE);
888   }
889   else { /* #4b */
890     return TRUE;
891   }
892 }
893
894 static void
895 impl_registry_notify_event (PortableServer_Servant     servant,
896                             const Accessibility_Event *e,
897                             CORBA_Environment         *ev)
898 {
899   SpiRegistry  *registry;
900   NotifyContext ctx;
901   static int level = 0;
902
903   level++;
904   registry = SPI_REGISTRY (bonobo_object_from_servant (servant));
905
906   parse_event_type (&ctx.etype, e->type);
907
908   ctx.ev = ev;
909   ctx.e_out = (Accessibility_Event *)e;
910   ctx.source = e->source;
911
912 #ifdef SPI_QUEUE_DEBUG
913     if (ctx.etype.type_cat != ETYPE_MOUSE)
914       fprintf (stderr, "filter! %s level: %d\n", ctx.etype.event_name, level);
915 #endif    
916   if (registry_filter_event (registry, &ctx, ev)) {
917 #ifdef SPI_QUEUE_DEBUG
918     if (ctx.etype.type_cat != ETYPE_MOUSE)
919       fprintf (stderr, "emit! %s level: %d\n", ctx.etype.event_name, level);
920 #endif    
921     registry_emit_event (registry, &ctx);
922   }
923   level--;
924 }
925
926 static void
927 spi_registry_class_init (SpiRegistryClass *klass)
928 {
929   GObjectClass * object_class = (GObjectClass *) klass;
930   POA_Accessibility_Registry__epv *epv = &klass->epv;
931
932   spi_registry_parent_class = g_type_class_ref (SPI_LISTENER_TYPE);
933   
934   object_class->finalize = spi_registry_object_finalize;
935
936   klass->parent_class.epv.notifyEvent   = impl_registry_notify_event;
937   
938   epv->registerApplication              = impl_accessibility_registry_register_application;
939   epv->deregisterApplication            = impl_accessibility_registry_deregister_application;
940   epv->registerGlobalEventListener      = impl_accessibility_registry_register_global_event_listener;
941   epv->deregisterGlobalEventListener    = impl_accessibility_registry_deregister_global_event_listener;
942   epv->deregisterGlobalEventListenerAll = impl_accessibility_registry_deregister_global_event_listener_all;
943   epv->getDeviceEventController         = impl_accessibility_registry_get_device_event_controller;
944   epv->getDesktopCount                  = impl_accessibility_registry_get_desktop_count;
945   epv->getDesktop                       = impl_accessibility_registry_get_desktop;
946   epv->getDesktopList                   = impl_accessibility_registry_get_desktop_list;
947   _deactivate_quark = g_quark_from_static_string ("deactivate");
948   _activate_quark = g_quark_from_static_string ("activate");
949   _state_quark = g_quark_from_static_string ("state-changed");
950   _state_changed_focused_quark = g_quark_from_static_string ("state-changedfocused");
951 }
952
953 static void
954 spi_registry_init (SpiRegistry *registry)
955 {
956   spi_registry_set_debug (g_getenv ("AT_SPI_DEBUG"));
957   /*
958    * TODO: FIXME, this module makes the foolish assumptions that
959    * registryd uses the same display as the apps, and that the
960    * DISPLAY environment variable is set.
961    */
962   gdk_init (NULL, NULL);
963
964   registry->object_listeners = NULL;
965   registry->window_listeners = NULL;
966   registry->toolkit_listeners = NULL;
967   registry->deferred_event_queue = g_queue_new ();
968   registry->exit_notify_timeout = 200;
969   registry->queue_handler_id  = 0;
970   /*
971    * The focus_object is set when a state-change:focused event is discarded
972    * after a window:deactivate event is received because a window:activate
973    * event has been received for the same window within the timeout period.
974    * The focus object is used to suppress a focus event for that object.
975    * It is released when a window:deactivate event is received.
976    */ 
977   registry->focus_object = NULL;
978   registry->desktop = spi_desktop_new ();
979   /* Register callback notification for application addition and removal */
980   g_signal_connect (G_OBJECT (registry->desktop),
981                     "application_added",
982                     G_CALLBACK (desktop_add_application),
983                     registry);
984
985   g_signal_connect (G_OBJECT (registry->desktop),
986                     "application_removed",
987                     G_CALLBACK (desktop_remove_application),
988                     registry);
989
990   registry->de_controller = spi_device_event_controller_new (registry);
991 }
992
993 BONOBO_TYPE_FUNC_FULL (SpiRegistry,
994                        Accessibility_Registry,
995                        PARENT_TYPE,
996                        spi_registry)
997
998 SpiRegistry *
999 spi_registry_new (void)
1000 {
1001   SpiRegistry *retval = g_object_new (SPI_REGISTRY_TYPE, NULL);
1002   bonobo_object_set_immortal (BONOBO_OBJECT (retval), TRUE);
1003   return retval;
1004 }