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