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