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