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