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