bridge: drive-by list usage fixes
[platform/core/uifw/at-spi2-atk.git] / atk-adaptor / bridge.c
1 /*
2  * AT-SPI - Assistive Technology Service Provider Interface
3  * (Gnome Accessibility Project; http://developer.gnome.org/projects/gap)
4  *
5  * Copyright 2008, 2009 Codethink Ltd.
6  * Copyright 2001, 2002, 2003 Sun Microsystems Inc.,
7  * Copyright 2001, 2002, 2003 Ximian, Inc.
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Library General Public
11  * License as published by the Free Software Foundation; either
12  * version 2 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Library General Public License for more details.
18  *
19  * You should have received a copy of the GNU Library General Public
20  * License along with this library; if not, write to the
21  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22  * Boston, MA 02111-1307, USA.
23  */
24
25 #define _GNU_SOURCE
26 #include "config.h"
27
28 #include <X11/Xlib.h>
29 #include <X11/Xatom.h>
30 #include <unistd.h>
31 #include <stdlib.h>
32 #include <stdio.h>
33 #include <stdarg.h>
34 #include <string.h>
35 #include<sys/stat.h>
36 #include <atk/atk.h>
37
38 #include <droute/droute.h>
39 #include <gmodule.h>
40 #include <glib/gi18n.h>
41 #include <atspi/atspi.h>
42
43 #include "bridge.h"
44 #include "event.h"
45 #include "adaptors.h"
46 #include "object.h"
47 #include "accessible-stateset.h"
48
49 #include "accessible-register.h"
50 #include "accessible-leasing.h"
51 #include "accessible-cache.h"
52
53 #include "spi-dbus.h"
54
55 /*---------------------------------------------------------------------------*/
56
57 static DBusHandlerResult
58 signal_filter (DBusConnection *bus, DBusMessage *message, void *user_data);
59
60 SpiBridge *spi_global_app_data = NULL;
61
62 /*static Display *bridge_display = NULL;*/
63
64 /*---------------------------------------------------------------------------*/
65
66 /*
67  * Returns a 'canonicalized' value for DISPLAY,
68  * with the screen number stripped off if present.
69  *
70  */
71 static const gchar *
72 spi_display_name (void)
73 {
74   static const char *canonical_display_name = NULL;
75   if (!canonical_display_name)
76     {
77       const gchar *display_env = g_getenv ("AT_SPI_DISPLAY");
78       if (!display_env)
79         {
80           display_env = g_getenv ("DISPLAY");
81           if (!display_env || !display_env[0])
82             canonical_display_name = ":0";
83           else
84             {
85               gchar *display_p, *screen_p;
86               canonical_display_name = g_strdup (display_env);
87               display_p = strrchr (canonical_display_name, ':');
88               screen_p = strrchr (canonical_display_name, '.');
89               if (screen_p && display_p && (screen_p > display_p))
90                 {
91                   *screen_p = '\0';
92                 }
93             }
94         }
95       else
96         {
97           canonical_display_name = display_env;
98         }
99     }
100   return canonical_display_name;
101 }
102
103 /*---------------------------------------------------------------------------*/
104
105 static void
106 set_reply (DBusPendingCall *pending, void *user_data)
107 {
108     void **replyptr = (void **)user_data;
109
110     *replyptr = dbus_pending_call_steal_reply (pending);
111   dbus_pending_call_unref (pending);
112 }
113
114 /*---------------------------------------------------------------------------*/
115
116 static void
117 add_event (const char *bus_name, const char *event)
118 {
119   event_data *evdata;
120   gchar **data;
121   GList *new_list;
122
123   spi_atk_add_client (bus_name);
124   evdata = (event_data *) g_malloc (sizeof (*evdata));
125   if (!evdata)
126     return;
127   data = g_strsplit (event, ":", 3);
128   if (!data)
129     {
130       g_free (evdata);
131       return;
132     }
133   evdata->bus_name = g_strdup (bus_name);
134   evdata->data = data;
135   new_list = g_list_append (spi_global_app_data->events, evdata);
136   if (new_list)
137     spi_global_app_data->events = new_list;
138 }
139
140 static GSList *clients = NULL;
141
142 static void
143 tally_event_reply ()
144 {
145   static int replies_received = 0;
146
147   replies_received++;
148   if (replies_received == 3)
149   {
150     if (!clients)
151       spi_atk_deregister_event_listeners ();
152     spi_global_app_data->events_initialized = TRUE;
153   }
154 }
155
156 static void
157 get_events_reply (DBusPendingCall *pending, void *user_data)
158 {
159   DBusMessage *reply = dbus_pending_call_steal_reply (pending);
160   DBusMessageIter iter, iter_array, iter_struct;
161
162   if (!reply)
163     goto done;
164
165   if (strcmp (dbus_message_get_signature (reply), "a(ss)") != 0)
166     {
167       g_warning ("atk-bridge: GetRegisteredEvents returned message with unknown signature");
168       goto done;
169     }
170
171   dbus_message_iter_init (reply, &iter);
172   dbus_message_iter_recurse (&iter, &iter_array);
173   while (dbus_message_iter_get_arg_type (&iter_array) != DBUS_TYPE_INVALID)
174     {
175       char *bus_name, *event;
176       dbus_message_iter_recurse (&iter_array, &iter_struct);
177       dbus_message_iter_get_basic (&iter_struct, &bus_name);
178       dbus_message_iter_next (&iter_struct);
179       dbus_message_iter_get_basic (&iter_struct, &event);
180       add_event (bus_name, event);
181       dbus_message_iter_next (&iter_array);
182     }
183
184 done:
185   if (reply)
186     dbus_message_unref (reply);
187   if (pending)
188     dbus_pending_call_unref (pending);
189
190   tally_event_reply ();
191 }
192
193 static void
194 get_device_events_reply (DBusPendingCall *pending, void *user_data)
195 {
196   DBusMessage *reply = dbus_pending_call_steal_reply (pending);
197   DBusMessageIter iter, iter_array, iter_struct;
198
199   if (!reply)
200     goto done;
201
202   if (strncmp (dbus_message_get_signature (reply), "a(s", 3) != 0)
203     {
204       g_warning ("atk-bridge: get_device_events_reply: unknown signature");
205       goto done;
206     }
207
208   dbus_message_iter_init (reply, &iter);
209   dbus_message_iter_recurse (&iter, &iter_array);
210   while (dbus_message_iter_get_arg_type (&iter_array) != DBUS_TYPE_INVALID)
211     {
212       char *bus_name;
213       dbus_message_iter_recurse (&iter_array, &iter_struct);
214       dbus_message_iter_get_basic (&iter_struct, &bus_name);
215       spi_atk_add_client (bus_name);
216       dbus_message_iter_next (&iter_array);
217     }
218
219 done:
220   if (reply)
221     dbus_message_unref (reply);
222   if (pending)
223     dbus_pending_call_unref (pending);
224
225   tally_event_reply ();
226 }
227
228 static void
229 get_registered_event_listeners (SpiBridge *app)
230 {
231   DBusMessage *message;
232   DBusPendingCall *pending = NULL;
233
234   message = dbus_message_new_method_call (SPI_DBUS_NAME_REGISTRY,
235                                          ATSPI_DBUS_PATH_REGISTRY,
236                                          ATSPI_DBUS_INTERFACE_REGISTRY,
237                                          "GetRegisteredEvents");
238   if (!message)
239     return;
240
241   dbus_connection_send_with_reply (app->bus, message, &pending, -1);
242   dbus_message_unref (message);
243   if (!pending)
244     {
245       spi_global_app_data->events_initialized = TRUE;
246       return;
247     }
248   dbus_pending_call_set_notify (pending, get_events_reply, NULL, NULL);
249
250   message = dbus_message_new_method_call (SPI_DBUS_NAME_REGISTRY,
251                                          ATSPI_DBUS_PATH_DEC,
252                                          ATSPI_DBUS_INTERFACE_DEC,
253                                          "GetKeystrokeListeners");
254   if (!message)
255     return;
256   pending = NULL;
257   dbus_connection_send_with_reply (app->bus, message, &pending, -1);
258   dbus_message_unref (message);
259   if (!pending)
260     {
261       spi_global_app_data->events_initialized = TRUE;
262       return;
263     }
264   dbus_pending_call_set_notify (pending, get_device_events_reply, NULL, NULL);
265
266   message = dbus_message_new_method_call (SPI_DBUS_NAME_REGISTRY,
267                                          ATSPI_DBUS_PATH_DEC,
268                                          ATSPI_DBUS_INTERFACE_DEC,
269                                          "GetDeviceEventListeners");
270   if (!message)
271     return;
272   pending = NULL;
273   dbus_connection_send_with_reply (app->bus, message, &pending, -1);
274   dbus_message_unref (message);
275   if (!pending)
276     {
277       spi_global_app_data->events_initialized = TRUE;
278       return;
279     }
280   dbus_pending_call_set_notify (pending, get_device_events_reply, NULL, NULL);
281 }
282
283 static void
284 register_reply (DBusPendingCall *pending, void *user_data)
285 {
286   DBusMessage *reply;
287   SpiBridge *app = user_data;
288   DBusMessage *message;
289
290   reply = dbus_pending_call_steal_reply (pending);
291   dbus_pending_call_unref (pending);
292   if (reply)
293     {
294       gchar *app_name, *obj_path;
295
296       if (strcmp (dbus_message_get_signature (reply), "(so)") != 0)
297         {
298           g_warning ("AT-SPI: Could not obtain desktop path or name\n");
299         }
300       else
301         {
302           DBusMessageIter iter, iter_struct;
303           dbus_message_iter_init (reply, &iter);
304           dbus_message_iter_recurse (&iter, &iter_struct);
305           dbus_message_iter_get_basic (&iter_struct, &app_name);
306           dbus_message_iter_next (&iter_struct);
307           dbus_message_iter_get_basic (&iter_struct, &obj_path);
308
309           app->desktop_name = g_strdup (app_name);
310           app->desktop_path = g_strdup (obj_path);
311         }
312     }
313   else
314     {
315       g_warning ("AT-SPI: Could not embed inside desktop");
316       return;
317     }
318   dbus_message_unref (reply);
319
320   get_registered_event_listeners (spi_global_app_data);
321 }
322
323 static gboolean
324 register_application (SpiBridge * app)
325 {
326   DBusMessage *message, *reply;
327   DBusMessageIter iter;
328   DBusError error;
329   DBusPendingCall *pending;
330   const int max_addr_length = 128; /* should be long enough */
331
332   dbus_error_init (&error);
333
334   /* These will be overridden when we get a reply, but in practice these
335      defaults should always be correct */
336   app->desktop_name = ATSPI_DBUS_NAME_REGISTRY;
337   app->desktop_path = ATSPI_DBUS_PATH_ROOT;
338
339   message = dbus_message_new_method_call (SPI_DBUS_NAME_REGISTRY,
340                                           ATSPI_DBUS_PATH_ROOT,
341                                           ATSPI_DBUS_INTERFACE_SOCKET,
342                                           "Embed");
343
344   dbus_message_iter_init_append (message, &iter);
345   spi_object_append_reference (&iter, app->root);
346   
347     if (!dbus_connection_send_with_reply (app->bus, message, &pending, -1)
348         || !pending)
349     {
350         return FALSE;
351     }
352
353     dbus_pending_call_set_notify (pending, register_reply, app, NULL);
354
355   if (message)
356     dbus_message_unref (message);
357
358   /* could this be better, we accept some amount of race in getting the temp name*/
359   /* make sure the directory exists */
360   mkdir ("/tmp/at-spi2/", S_IRWXU|S_IRWXG|S_IRWXO|S_ISVTX);
361   chmod ("/tmp/at-spi2/", S_IRWXU|S_IRWXG|S_IRWXO|S_ISVTX);
362   app->app_bus_addr = g_malloc(max_addr_length * sizeof(char));
363 #ifndef DISABLE_P2P
364   sprintf (app->app_bus_addr, "unix:path=/tmp/at-spi2/socket-%d-%d", getpid(),
365            rand());
366 #else
367   app->app_bus_addr [0] = '\0';
368 #endif
369
370   return TRUE;
371 }
372
373 /*---------------------------------------------------------------------------*/
374
375 static void
376 deregister_application (SpiBridge * app)
377 {
378   DBusMessage *message;
379   DBusMessageIter iter;
380   DBusError error;
381   const char *uname;
382
383   dbus_error_init (&error);
384
385   message = dbus_message_new_method_call (SPI_DBUS_NAME_REGISTRY,
386                                           ATSPI_DBUS_PATH_REGISTRY,
387                                           ATSPI_DBUS_INTERFACE_REGISTRY,
388                                           "DeregisterApplication");
389   dbus_message_set_no_reply (message, TRUE);
390
391   uname = dbus_bus_get_unique_name (app->bus);
392
393   dbus_message_iter_init_append (message, &iter);
394   dbus_message_iter_append_basic (&iter, DBUS_TYPE_STRING, &uname);
395   dbus_connection_send (app->bus, message, NULL);
396   if (message)
397     dbus_message_unref (message);
398 }
399
400 /*---------------------------------------------------------------------------*/
401
402 /*---------------------------------------------------------------------------*/
403
404 static AtkPlugClass *plug_class;
405 static AtkSocketClass *socket_class;
406
407 static gchar *
408 get_plug_id (AtkPlug * plug)
409 {
410   const char *uname = dbus_bus_get_unique_name (spi_global_app_data->bus);
411   gchar *path;
412   GString *str = g_string_new (NULL);
413
414   path = spi_register_object_to_path (spi_global_register, G_OBJECT (plug));
415   g_string_printf (str, "%s:%s", uname, path);
416   g_free (path);
417   return g_string_free (str, FALSE);
418 }
419
420 AtkStateSet *
421 socket_ref_state_set (AtkObject *accessible)
422 {
423   char *child_name, *child_path;
424   AtkSocket *socket = ATK_SOCKET (accessible);
425   int count = 0;
426   int j;
427   int v;
428   DBusMessage *message, *reply;
429   DBusMessageIter iter, iter_array;
430   AtkStateSet *set;
431
432   set = atk_state_set_new ();
433
434   if (!socket->embedded_plug_id)
435     return set;
436
437   child_name = g_strdup (socket->embedded_plug_id);
438   if (!child_name)
439     return set;
440   child_path = g_utf8_strchr (child_name + 1, -1, ':');
441   if (!child_path)
442     {
443       g_free (child_name);
444       return set;
445     }
446   *(child_path++) = '\0';
447   message = dbus_message_new_method_call (child_name, child_path, ATSPI_DBUS_INTERFACE_ACCESSIBLE, "GetState");
448   g_free (child_name);
449   reply = dbus_connection_send_with_reply_and_block (spi_global_app_data->bus, message, 1, NULL);
450   dbus_message_unref (message);
451   if (reply == NULL)
452     return set;
453   if (strcmp (dbus_message_get_signature (reply), "au") != 0)
454     {
455       dbus_message_unref (reply);
456       return set;
457     }
458
459   dbus_message_iter_init (reply, &iter);
460   dbus_message_iter_recurse (&iter, &iter_array);
461   do
462     {
463       dbus_message_iter_get_basic (&iter_array, &v);
464       for (j = 0; j < 32; j++)
465         {
466           if (v & (1 << j))
467             {
468               AtkState state = spi_atk_state_from_spi_state ((count << 5) + j);
469               atk_state_set_add_state (set, state);
470             }
471         }
472       count++;
473     }
474   while (dbus_message_iter_next (&iter_array));
475   dbus_message_unref (reply);
476   return set;
477 }
478
479 static void
480 socket_embed_hook (AtkSocket * socket, gchar * plug_id)
481 {
482   AtkObject *accessible = ATK_OBJECT(socket);
483   gchar *plug_name, *plug_path;
484   AtkObjectClass *klass;
485
486   /* Force registration */
487   gchar *path = spi_register_object_to_path (spi_global_register, G_OBJECT (accessible));
488   /* Let the plug know that it has been embedded */
489   plug_name = g_strdup (plug_id);
490   if (!plug_name)
491     {
492       g_free (path);
493       return;
494     }
495   plug_path = g_utf8_strchr (plug_name + 1, -1, ':');
496   if (plug_path)
497     {
498       DBusMessage *message;
499       *(plug_path++) = '\0';
500       message = dbus_message_new_method_call (plug_name, plug_path, ATSPI_DBUS_INTERFACE_SOCKET, "Embedded");
501       dbus_message_append_args (message, DBUS_TYPE_STRING, &path, DBUS_TYPE_INVALID);
502       dbus_connection_send (spi_global_app_data->bus, message, NULL);
503     }
504   g_free (plug_name);
505   g_free (path);
506
507   klass = ATK_OBJECT_GET_CLASS (accessible);
508   klass->ref_state_set = socket_ref_state_set;
509 }
510
511 static void
512 install_plug_hooks ()
513 {
514   gpointer data;
515
516   data = g_type_class_ref (ATK_TYPE_PLUG);
517   plug_class = ATK_PLUG_CLASS (data);
518   data = g_type_class_ref (ATK_TYPE_SOCKET);
519   socket_class = ATK_SOCKET_CLASS (data);
520   plug_class->get_object_id = get_plug_id;
521   socket_class->embed = socket_embed_hook;
522 }
523
524 static uint
525 get_ancestral_uid (uint pid)
526 {
527   FILE *fp;
528   char buf [80];
529   int ppid = 0;
530   int uid = 0;
531   gboolean got_ppid = 0;
532   gboolean got_uid = 0;
533
534   sprintf (buf, "/proc/%d/status", pid);
535   fp = fopen (buf, "r");
536   if (!fp)
537     return 0;
538   while ((!got_ppid || !got_uid) && fgets (buf, sizeof (buf), fp))
539   {
540     if (sscanf (buf, "PPid:\t%d", &ppid) == 1)
541       got_ppid = TRUE;
542     else if (sscanf (buf, "Uid:\t%d", &uid) == 1)
543       got_uid = TRUE;
544   }
545   fclose (fp);
546
547   if (!got_ppid || !got_uid)
548     return 0;
549   if (uid != 0)
550     return uid;
551   if (ppid == 0 || ppid == 1)
552     return 0;
553   return get_ancestral_uid (ppid);
554 }
555
556 static dbus_bool_t
557 user_check (DBusConnection *bus, unsigned long uid, void *data)
558 {
559   if (uid == getuid () || uid == geteuid ())
560     return TRUE;
561   if (getuid () == 0)
562     return get_ancestral_uid (getpid ()) == uid;
563   return FALSE;
564 }
565
566 static void
567 new_connection_cb (DBusServer *server, DBusConnection *con, void *data)
568 {
569   GList *new_list;
570
571   dbus_connection_set_unix_user_function (con, user_check, NULL, NULL);
572   dbus_connection_ref(con);
573   atspi_dbus_connection_setup_with_g_main(con, NULL);
574   droute_intercept_dbus (con);
575   droute_context_register (spi_global_app_data->droute, con);
576
577   spi_global_app_data->direct_connections = g_list_append (spi_global_app_data->direct_connections, con);
578 }
579
580 static int
581 setup_bus (void)
582 {
583 #ifndef DISABLE_P2P
584   DBusServer *server;
585   DBusError err;
586
587   dbus_error_init(&err);
588   server = dbus_server_listen(spi_global_app_data->app_bus_addr, &err);
589   if (server == NULL)
590   {
591     g_warning (_("atk-bridge: Couldn't listen on dbus server: %s"), err.message);
592     dbus_error_init (&err);
593     spi_global_app_data->app_bus_addr [0] = '\0';
594     g_main_context_unref (spi_global_app_data->main_context);
595     spi_global_app_data->main_context = NULL;
596     return -1;
597   }
598
599   atspi_dbus_server_setup_with_g_main(server, NULL);
600   dbus_server_set_new_connection_function(server, new_connection_cb, NULL, NULL);
601
602   spi_global_app_data->server = server;
603 #endif
604
605   return 0;
606 }
607
608
609 gchar *atspi_dbus_name = NULL;
610 static gboolean atspi_no_register = FALSE;
611
612 static GOptionEntry atspi_option_entries[] = {
613   {"atspi-dbus-name", 0, 0, G_OPTION_ARG_STRING, &atspi_dbus_name,
614    "D-Bus bus name to register as", NULL},
615   {"atspi-no-register", 0, 0, G_OPTION_ARG_NONE, &atspi_no_register,
616    "Do not register with Registry Daemon", NULL},
617   {NULL}
618 };
619
620 static gchar *
621 introspect_children_cb (const char *path, void *data)
622 {
623   if (!strcmp (path, "/org/a11y/atspi/accessible"))
624     {
625       return g_strdup ("<node name=\"root\"/>\n");
626       /* TODO: Should we place the whole hierarchy here? */
627     }
628   return NULL;
629 }
630
631 static void
632 handle_event_listener_registered (DBusConnection *bus, DBusMessage *message,
633                                   void *user_data)
634 {
635   const char *name;
636   char *sender;
637
638   if (!dbus_message_get_args (message, NULL, DBUS_TYPE_STRING, &sender,
639     DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID))
640     return;
641
642   add_event (sender, name);
643 }
644
645 static void
646 remove_events (const char *bus_name, const char *event)
647 {
648   event_data *evdata;
649   gchar **remove_data;
650   GList *list;
651
652   remove_data = g_strsplit (event, ":", 3);
653   if (!remove_data)
654     {
655       return;
656     }
657
658   for (list = spi_global_app_data->events; list;)
659     {
660       event_data *evdata = list->data;
661       if (!g_strcmp0 (evdata->bus_name, bus_name) &&
662           spi_event_is_subtype (evdata->data, remove_data))
663         {
664           GList *events = spi_global_app_data->events;
665           list = list->next;
666           g_strfreev (evdata->data);
667           g_free (evdata->bus_name);
668           g_free (evdata);
669           spi_global_app_data->events = g_list_remove (events, evdata);
670         }
671       else
672         {
673           list = list->next;
674         }
675     }
676
677   g_strfreev (remove_data);
678 }
679
680 static void
681 handle_event_listener_deregistered (DBusConnection *bus, DBusMessage *message,
682                                     void *user_data)
683 {
684   const char *orig_name;
685   gchar *name;
686   char *sender;
687
688   if (!dbus_message_get_args (message, NULL, DBUS_TYPE_STRING, &sender,
689                               DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID))
690     return;
691
692   remove_events (sender, name);
693 }
694
695 static void
696 handle_device_listener_registered (DBusConnection *bus, DBusMessage *message,
697                                     void *user_data)
698 {
699   char *sender;
700   DBusMessageIter iter, iter_struct;
701
702   if (strncmp (dbus_message_get_signature (message), "(s", 2) != 0)
703     {
704       g_warning ("atk-bridge: handle_device_listener_register: unknown signature");
705       return;
706     }
707
708   dbus_message_iter_init (message, &iter);
709   dbus_message_iter_recurse (&iter, &iter_struct);
710   dbus_message_iter_get_basic (&iter_struct, &sender);
711   spi_atk_add_client (sender);
712 }
713
714 static DBusHandlerResult
715 signal_filter (DBusConnection *bus, DBusMessage *message, void *user_data)
716 {
717   const char *interface = dbus_message_get_interface (message);
718   const char *member = dbus_message_get_member (message);
719   DBusHandlerResult result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
720
721   if (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_SIGNAL)
722     return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
723
724   if (!strcmp (interface, ATSPI_DBUS_INTERFACE_REGISTRY))
725     {
726       result = DBUS_HANDLER_RESULT_HANDLED;
727       if (!strcmp (member, "EventListenerRegistered"))
728         handle_event_listener_registered (bus, message, user_data);
729       else if (!strcmp (member, "EventListenerDeregistered"))
730         handle_event_listener_deregistered (bus, message, user_data);
731       else
732         result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
733     }
734   else if (!strcmp (interface, ATSPI_DBUS_INTERFACE_DEVICE_EVENT_LISTENER))
735     {
736       result = DBUS_HANDLER_RESULT_HANDLED;
737       if (!strcmp (member, "KeystrokeListenerRegistered"))
738         handle_device_listener_registered (bus, message, user_data);
739       else if (!strcmp (member, "DeviceListenerRegistered"))
740         handle_device_listener_registered (bus, message, user_data);
741       else
742         result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
743     }
744
745   if (!g_strcmp0(interface, DBUS_INTERFACE_DBUS) &&
746       !g_strcmp0(member, "NameOwnerChanged"))
747     {
748       char *name, *old, *new;
749       result = DBUS_HANDLER_RESULT_HANDLED;
750       if (dbus_message_get_args (message, NULL,
751                                  DBUS_TYPE_STRING, &name,
752                                  DBUS_TYPE_STRING, &old,
753                                  DBUS_TYPE_STRING, &new,
754                                  DBUS_TYPE_INVALID))
755         {
756           if (*old != '\0' && *new == '\0')
757               spi_atk_remove_client (old);
758         }
759     }
760
761   return result;
762 }
763
764 /*
765  * spi_app_init
766  *
767  * The following needs to be initialized.
768  *
769  * - DRoute for routing message to their accessible objects.
770  * - Event handlers for emmitting signals on specific ATK events.
771  * - setup the bus for p2p communication
772  * - Application registration with the AT-SPI registry.
773  *
774  */
775 static int
776 adaptor_init (gint * argc, gchar ** argv[])
777 {
778   GOptionContext *opt;
779   GError *err = NULL;
780   DBusError error;
781   AtkObject *root;
782   gchar *introspection_directory;
783   static gboolean inited = FALSE;
784
785   if (inited)
786     return 0;
787
788   inited = TRUE;
789
790   DRoutePath *treepath, *accpath;
791
792   root = atk_get_root ();
793   g_warn_if_fail (root);
794   if (!root)
795     {
796       inited = FALSE;
797       return -1;
798     }
799
800   /* Parse command line options */
801   opt = g_option_context_new (NULL);
802   g_option_context_add_main_entries (opt, atspi_option_entries, NULL);
803   g_option_context_set_ignore_unknown_options (opt, TRUE);
804   if (!g_option_context_parse (opt, argc, argv, &err))
805     g_warning ("AT-SPI Option parsing failed: %s\n", err->message);
806   g_option_context_free (opt);
807
808   /* Allocate global data and do ATK initializations */
809   spi_global_app_data = g_new0 (SpiBridge, 1);
810   spi_global_app_data->root = g_object_ref (root);
811
812   /* Set up D-Bus connection and register bus name */
813   dbus_error_init (&error);
814   spi_global_app_data->bus = atspi_get_a11y_bus ();
815   if (!spi_global_app_data->bus)
816     {
817       g_free (spi_global_app_data);
818       spi_global_app_data = NULL;
819       inited = FALSE;
820       return -1;
821     }
822
823   if (atspi_dbus_name != NULL)
824     {
825       if (dbus_bus_request_name
826           (spi_global_app_data->bus, atspi_dbus_name, 0, &error))
827         {
828           g_print ("AT-SPI Recieved D-Bus name - %s\n", atspi_dbus_name);
829         }
830       else
831         {
832           g_print
833             ("AT-SPI D-Bus name requested but could not be allocated - %s\n",
834              atspi_dbus_name);
835         }
836     }
837
838   spi_global_app_data->main_context = g_main_context_new ();
839
840   atspi_dbus_connection_setup_with_g_main (spi_global_app_data->bus, NULL);
841
842   /* Hook our plug-and socket functions */
843   install_plug_hooks ();
844
845   /* 
846    * Create the leasing, register and cache objects.
847    * The order is important here, the cache depends on the
848    * register object.
849    */
850   spi_global_register = g_object_new (SPI_REGISTER_TYPE, NULL);
851   spi_global_leasing  = g_object_new (SPI_LEASING_TYPE, NULL);
852   spi_global_cache    = g_object_new (SPI_CACHE_TYPE, NULL);
853
854   /* Register droute for routing AT-SPI messages */
855   spi_global_app_data->droute =
856     droute_new ();
857
858   treepath = droute_add_one (spi_global_app_data->droute,
859                              "/org/a11y/atspi/cache", spi_global_cache);
860
861   if (!treepath)
862     {
863       g_warning ("atk-bridge: Error in droute_add_one().  Already running?");
864       return -1;
865     }
866
867   accpath = droute_add_many (spi_global_app_data->droute,
868                              "/org/a11y/atspi/accessible",
869                              NULL,
870                              introspect_children_cb,
871                              NULL,
872                              (DRouteGetDatumFunction)
873                              spi_global_register_path_to_object);
874
875
876   /* Register all interfaces with droute and set up application accessible db */
877   spi_initialize_cache (treepath);
878   spi_initialize_accessible (accpath);
879   spi_initialize_application (accpath);
880   spi_initialize_action (accpath);
881   spi_initialize_collection (accpath);
882   spi_initialize_component (accpath);
883   spi_initialize_document (accpath);
884   spi_initialize_editabletext (accpath);
885   spi_initialize_hyperlink (accpath);
886   spi_initialize_hypertext (accpath);
887   spi_initialize_image (accpath);
888   spi_initialize_selection (accpath);
889   spi_initialize_socket (accpath);
890   spi_initialize_table (accpath);
891   spi_initialize_text (accpath);
892   spi_initialize_value (accpath);
893
894   droute_context_register (spi_global_app_data->droute,
895                            spi_global_app_data->bus);
896
897   /* Register methods to send D-Bus signals on certain ATK events */
898   spi_atk_register_event_listeners ();
899
900   /* Set up filter and match rules to catch signals */
901   dbus_bus_add_match (spi_global_app_data->bus, "type='signal', interface='org.a11y.atspi.Registry', sender='org.a11y.atspi.Registry'", NULL);
902   dbus_bus_add_match (spi_global_app_data->bus, "type='signal', interface='org.a11y.atspi.DeviceEventListener', sender='org.a11y.atspi.Registry'", NULL);
903   dbus_connection_add_filter (spi_global_app_data->bus, signal_filter, NULL,
904                               NULL);
905
906   /* Register this app by sending a signal out to AT-SPI registry daemon */
907   if (!atspi_no_register && (!root || !ATK_IS_PLUG (root)))
908     register_application (spi_global_app_data);
909   else
910     get_registered_event_listeners (spi_global_app_data);
911
912   setup_bus();
913
914   return 0;
915 }
916
917 /*---------------------------------------------------------------------------*/
918
919 int
920 gtk_module_init (gint * argc, gchar ** argv[])
921 {
922   const gchar *load_bridge = g_getenv ("NO_AT_BRIDGE");
923
924   if (!load_bridge || g_ascii_strtod (load_bridge, NULL) == 0)
925     {
926       return adaptor_init (argc, argv);
927     }
928   return 0;
929 }
930
931 gchar*
932 g_module_check_init (GModule *module)
933 {
934   g_module_make_resident (module);
935
936   return NULL;
937 }
938
939 void
940 gnome_accessibility_module_init (void)
941 {
942   const gchar *load_bridge = g_getenv ("NO_AT_BRIDGE");
943
944   if (!load_bridge || g_ascii_strtod (load_bridge, NULL) == 0)
945     {
946       adaptor_init (NULL, NULL);
947
948       if (g_getenv ("AT_SPI_DEBUG"))
949         {
950           g_print ("Atk Accessibility bridge initialized\n");
951         }
952     }
953 }
954
955 void
956 gnome_accessibility_module_shutdown (void)
957 {
958   GList *l;
959   GSList *ls;
960
961   if (!spi_global_app_data)
962       return;
963
964   spi_atk_tidy_windows ();
965   spi_atk_deregister_event_listeners ();
966
967   deregister_application (spi_global_app_data);
968
969   if (spi_global_app_data->bus)
970     {
971       dbus_connection_remove_filter (spi_global_app_data->bus, signal_filter, NULL);
972       droute_context_unregister (spi_global_app_data->droute, spi_global_app_data->bus);
973       dbus_connection_unref (spi_global_app_data->bus);
974     }
975
976   for (l = spi_global_app_data->direct_connections; l; l = l->next)
977     {
978       DBusConnection *connection;
979
980       connection = l->data;
981
982       droute_context_unregister (spi_global_app_data->droute, connection);
983       droute_unintercept_dbus (connection);
984       dbus_connection_unref (connection);
985     }
986   g_list_free (spi_global_app_data->direct_connections);
987
988   for (ls = clients; ls; ls = ls->next)
989     g_free (l->data);
990   g_slist_free (clients);
991   clients = NULL;
992
993   g_object_unref (spi_global_cache);
994   g_object_unref (spi_global_leasing);
995   g_object_unref (spi_global_register);
996
997   if (spi_global_app_data->main_context)
998     g_main_context_unref (spi_global_app_data->main_context);
999
1000   droute_free (spi_global_app_data->droute);
1001
1002   g_free (spi_global_app_data);
1003   spi_global_app_data = NULL;
1004
1005   /* Not currently creating an XDisplay */
1006 #if 0
1007   if (bridge_display)
1008     XCloseDisplay (bridge_display);
1009 #endif
1010 }
1011
1012 static gchar *name_match_tmpl =
1013        "type='signal', interface='org.freedesktop.DBus', member='NameOwnerChanged', arg0='%s'";
1014
1015 void
1016 spi_atk_add_client (const char *bus_name)
1017 {
1018   GSList *l;
1019   gchar *match;
1020
1021   for (l = clients; l; l = l->next)
1022   {
1023     if (!g_strcmp0 (l->data, bus_name))
1024       return;
1025   }
1026   if (!clients && spi_global_app_data->events_initialized)
1027     spi_atk_register_event_listeners ();
1028   clients = g_slist_append (clients, g_strdup (bus_name));
1029   match = g_strdup_printf (name_match_tmpl, bus_name);
1030   dbus_bus_add_match (spi_global_app_data->bus, match, NULL);
1031   g_free (match);
1032 }
1033
1034 void
1035 spi_atk_remove_client (const char *bus_name)
1036 {
1037   GSList *l;
1038   GSList *next_node;
1039
1040   l = clients;
1041   while (l)
1042   {
1043     next_node = l->next;
1044
1045     if (!g_strcmp0 (l->data, bus_name))
1046     {
1047       gchar *match = g_strdup_printf (name_match_tmpl, l->data);
1048       dbus_bus_remove_match (spi_global_app_data->bus, match, NULL);
1049   g_free (match);
1050       g_free (l->data);
1051       clients = g_slist_delete_link (clients, l);
1052       if (!clients)
1053         spi_atk_deregister_event_listeners ();
1054     }
1055
1056     l = next_node;
1057   }
1058 }
1059
1060 /*END------------------------------------------------------------------------*/