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