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