Don't return DBUS_HANDLER_RESULT_HANDLED for NameOwnerChanged signals
[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       if (dbus_message_get_args (message, NULL,
684                                  DBUS_TYPE_STRING, &name,
685                                  DBUS_TYPE_STRING, &old,
686                                  DBUS_TYPE_STRING, &new,
687                                  DBUS_TYPE_INVALID))
688         {
689           if (*old != '\0' && *new == '\0')
690               spi_atk_remove_client (old);
691         }
692     }
693
694   return result;
695 }
696
697 int
698 spi_atk_create_socket (SpiBridge *app)
699 {
700 #ifndef DISABLE_P2P
701   DBusServer *server;
702   DBusError err;
703
704   if (getuid () != 0)
705   {
706     app->app_tmp_dir = g_build_filename (g_get_user_runtime_dir (),
707                                          "at-spi2-XXXXXX", NULL);
708     if (!g_mkdtemp (app->app_tmp_dir))
709     {
710       g_free (app->app_tmp_dir);
711       app->app_tmp_dir = NULL;
712       return FALSE;
713     }
714   }
715
716   if (app->app_tmp_dir)
717     app->app_bus_addr = g_strdup_printf ("unix:path=%s/socket", app->app_tmp_dir);
718   else
719     app->app_bus_addr = g_strdup_printf ("unix:path=%s/at-spi2-socket-%d",
720                                          g_get_user_runtime_dir (), getpid ());
721
722   if (!spi_global_app_data->app_bus_addr)
723     return -1;
724
725   dbus_error_init(&err);
726   server = dbus_server_listen(spi_global_app_data->app_bus_addr, &err);
727   if (server == NULL)
728   {
729     g_warning ("atk-bridge: Couldn't listen on dbus server: %s", err.message);
730     dbus_error_init (&err);
731     spi_global_app_data->app_bus_addr [0] = '\0';
732     g_main_context_unref (spi_global_app_data->main_context);
733     spi_global_app_data->main_context = NULL;
734     return -1;
735   }
736
737   atspi_dbus_server_setup_with_g_main(server, NULL);
738   dbus_server_set_new_connection_function(server, new_connection_cb, NULL, NULL);
739
740   spi_global_app_data->server = server;
741 #endif
742
743   return 0;
744 }
745
746 /*
747  * Checks the status of the environment variables
748  *
749  * At this moment it only checks NO_AT_BRIDGE
750  *
751  * Returns TRUE if there isn't anything on the environment preventing
752  * you to load the bridge, FALSE otherwise
753  */
754 static gboolean
755 check_envvar (void)
756 {
757   const gchar *envvar;
758
759   envvar = g_getenv ("NO_AT_BRIDGE");
760
761   if (envvar && atoi (envvar) == 1)
762     return FALSE;
763   else
764     return TRUE;
765 }
766
767 void
768 spi_atk_activate ()
769 {
770   DRoutePath *treepath;
771
772   spi_atk_register_event_listeners ();
773   if (!spi_global_cache)
774     {
775       spi_global_cache    = g_object_new (SPI_CACHE_TYPE, NULL);
776       treepath = droute_add_one (spi_global_app_data->droute,
777                                  "/org/a11y/atspi/cache", spi_global_cache);
778
779       if (!treepath)
780         {
781           g_warning ("atk-bridge: Error in droute_add_one().  Already running?");
782           return;
783         }
784       spi_initialize_cache (treepath);
785       if (spi_global_app_data->bus)
786         droute_path_register (treepath, spi_global_app_data->bus);
787     }
788 }
789
790 /*
791  * spi_app_init
792  *
793  * The following needs to be initialized.
794  *
795  * - DRoute for routing message to their accessible objects.
796  * - Event handlers for emmitting signals on specific ATK events.
797  * - setup the bus for p2p communication
798  * - Application registration with the AT-SPI registry.
799  *
800  */
801 int
802 atk_bridge_adaptor_init (gint * argc, gchar ** argv[])
803 {
804   GOptionContext *opt;
805   GError *err = NULL;
806   DBusError error;
807   AtkObject *root;
808   gboolean load_bridge;
809   DRoutePath *accpath;
810
811   load_bridge = check_envvar ();
812   if (inited && !load_bridge)
813     g_warning ("ATK Bridge is disabled but a11y has already been enabled.");
814
815   if (inited || !load_bridge)
816     return 0;
817
818   inited = TRUE;
819
820   root = atk_get_root ();
821   g_warn_if_fail (root);
822   if (!root)
823     {
824       inited = FALSE;
825       return -1;
826     }
827
828   /* Parse command line options */
829   opt = g_option_context_new (NULL);
830   g_option_context_add_main_entries (opt, atspi_option_entries, NULL);
831   g_option_context_set_ignore_unknown_options (opt, TRUE);
832   if (!g_option_context_parse (opt, argc, argv, &err))
833     {
834       g_warning ("AT-SPI Option parsing failed: %s\n", err->message);
835       g_error_free (err);
836     }
837   g_option_context_free (opt);
838
839   /* Allocate global data and do ATK initializations */
840   spi_global_app_data = g_new0 (SpiBridge, 1);
841   spi_global_app_data->root = g_object_ref (root);
842
843   /* Set up D-Bus connection and register bus name */
844   dbus_error_init (&error);
845   spi_global_app_data->bus = atspi_get_a11y_bus ();
846   if (!spi_global_app_data->bus)
847     {
848       g_free (spi_global_app_data);
849       spi_global_app_data = NULL;
850       inited = FALSE;
851       return -1;
852     }
853
854   if (atspi_dbus_name != NULL)
855     {
856       if (dbus_bus_request_name
857           (spi_global_app_data->bus, atspi_dbus_name, 0, &error))
858         {
859           g_print ("AT-SPI Recieved D-Bus name - %s\n", atspi_dbus_name);
860         }
861       else
862         {
863           g_print
864             ("AT-SPI D-Bus name requested but could not be allocated - %s\n",
865              atspi_dbus_name);
866         }
867     }
868
869   spi_global_app_data->main_context = g_main_context_new ();
870
871   atspi_dbus_connection_setup_with_g_main (spi_global_app_data->bus, NULL);
872
873   /* Hook our plug-and socket functions */
874   install_plug_hooks ();
875
876   /* 
877    * Create the leasing, register and cache objects.
878    * The order is important here, the cache depends on the
879    * register object.
880    */
881   spi_global_register = g_object_new (SPI_REGISTER_TYPE, NULL);
882   spi_global_leasing  = g_object_new (SPI_LEASING_TYPE, NULL);
883
884   /* Register droute for routing AT-SPI messages */
885   spi_global_app_data->droute =
886     droute_new ();
887
888   accpath = droute_add_many (spi_global_app_data->droute,
889                              "/org/a11y/atspi/accessible",
890                              NULL,
891                              introspect_children_cb,
892                              NULL,
893                              (DRouteGetDatumFunction)
894                              spi_global_register_path_to_object);
895
896
897   /* Register all interfaces with droute and set up application accessible db */
898   spi_initialize_accessible (accpath);
899   spi_initialize_application (accpath);
900   spi_initialize_action (accpath);
901   spi_initialize_collection (accpath);
902   spi_initialize_component (accpath);
903   spi_initialize_document (accpath);
904   spi_initialize_editabletext (accpath);
905   spi_initialize_hyperlink (accpath);
906   spi_initialize_hypertext (accpath);
907   spi_initialize_image (accpath);
908   spi_initialize_selection (accpath);
909   spi_initialize_socket (accpath);
910   spi_initialize_table (accpath);
911   spi_initialize_text (accpath);
912   spi_initialize_value (accpath);
913
914   droute_context_register (spi_global_app_data->droute,
915                            spi_global_app_data->bus);
916
917   /* Register methods to send D-Bus signals on certain ATK events */
918   if (clients)
919     spi_atk_activate ();
920
921   /* Set up filter and match rules to catch signals */
922   dbus_bus_add_match (spi_global_app_data->bus, "type='signal', interface='org.a11y.atspi.Registry', sender='org.a11y.atspi.Registry'", NULL);
923   dbus_bus_add_match (spi_global_app_data->bus, "type='signal', interface='org.a11y.atspi.DeviceEventListener', sender='org.a11y.atspi.Registry'", NULL);
924   dbus_connection_add_filter (spi_global_app_data->bus, signal_filter, NULL,
925                               NULL);
926
927   /* Register this app by sending a signal out to AT-SPI registry daemon */
928   if (!atspi_no_register && (!root || !ATK_IS_PLUG (root)))
929     register_application (spi_global_app_data);
930   else
931     get_registered_event_listeners (spi_global_app_data);
932
933   return 0;
934 }
935
936 void
937 atk_bridge_adaptor_cleanup (void)
938 {
939   GList *l;
940   GSList *ls;
941
942   if (!inited)
943     return;
944
945   if (!spi_global_app_data)
946       return;
947
948   spi_atk_tidy_windows ();
949   spi_atk_deregister_event_listeners ();
950
951   deregister_application (spi_global_app_data);
952
953   if (spi_global_app_data->bus)
954     {
955       dbus_connection_remove_filter (spi_global_app_data->bus, signal_filter, NULL);
956       droute_context_unregister (spi_global_app_data->droute, spi_global_app_data->bus);
957       dbus_connection_close (spi_global_app_data->bus);
958       dbus_connection_unref (spi_global_app_data->bus);
959       spi_global_app_data->bus = NULL;
960     }
961
962   for (l = spi_global_app_data->direct_connections; l; l = l->next)
963     {
964       DBusConnection *connection;
965
966       connection = l->data;
967
968       droute_context_unregister (spi_global_app_data->droute, connection);
969       droute_unintercept_dbus (connection);
970       dbus_connection_close (connection);
971       dbus_connection_unref (connection);
972     }
973   g_list_free (spi_global_app_data->direct_connections);
974   spi_global_app_data->direct_connections = NULL;
975
976   for (ls = clients; ls; ls = ls->next)
977     g_free (ls->data);
978   g_slist_free (clients);
979   clients = NULL;
980
981   g_clear_object (&spi_global_cache);
982   g_clear_object (&spi_global_leasing);
983   g_clear_object (&spi_global_register);
984
985   if (spi_global_app_data->main_context)
986     g_main_context_unref (spi_global_app_data->main_context);
987
988   droute_free (spi_global_app_data->droute);
989
990   g_free (spi_global_app_data);
991   spi_global_app_data = NULL;
992
993   inited = FALSE;
994 }
995
996 /*---------------------------------------------------------------------------*/
997
998 static gchar *name_match_tmpl =
999        "type='signal', interface='org.freedesktop.DBus', member='NameOwnerChanged', arg0='%s'";
1000
1001 void
1002 spi_atk_add_client (const char *bus_name)
1003 {
1004   GSList *l;
1005   gchar *match;
1006
1007   for (l = clients; l; l = l->next)
1008   {
1009     if (!g_strcmp0 (l->data, bus_name))
1010       return;
1011   }
1012   if (!clients)
1013     spi_atk_activate ();
1014   clients = g_slist_append (clients, g_strdup (bus_name));
1015   match = g_strdup_printf (name_match_tmpl, bus_name);
1016   dbus_bus_add_match (spi_global_app_data->bus, match, NULL);
1017   g_free (match);
1018 }
1019
1020 void
1021 spi_atk_remove_client (const char *bus_name)
1022 {
1023   GSList *l;
1024   GSList *next_node;
1025
1026   l = clients;
1027   while (l)
1028   {
1029     next_node = l->next;
1030
1031     if (!g_strcmp0 (l->data, bus_name))
1032     {
1033       gchar *match = g_strdup_printf (name_match_tmpl, l->data);
1034       dbus_bus_remove_match (spi_global_app_data->bus, match, NULL);
1035   g_free (match);
1036       g_free (l->data);
1037       clients = g_slist_delete_link (clients, l);
1038       if (!clients)
1039         spi_atk_deregister_event_listeners ();
1040       return;
1041     }
1042
1043     l = next_node;
1044   }
1045 }
1046
1047 /*END------------------------------------------------------------------------*/