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