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