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