spec file, manifest and gbs.conf adapted for Tizen
[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       strcmp (signature, "ss") != 0)
701   {
702     g_warning ("got RegisterEvent with invalid signature '%s'", signature);
703     return;
704   }
705
706   dbus_message_iter_init (message, &iter);
707   add_event_from_iter (&iter);
708 }
709
710 static void
711 free_property_definition (void *data)
712 {
713   AtspiPropertyDefinition *pd = data;
714
715   g_free (pd->name);
716   g_free (pd);
717 }
718
719 static void
720 remove_events (const char *bus_name, const char *event)
721 {
722   gchar **remove_data;
723   GList *list;
724
725   remove_data = g_strsplit (event, ":", 3);
726   if (!remove_data)
727     {
728       return;
729     }
730
731   for (list = spi_global_app_data->events; list;)
732     {
733       event_data *evdata = list->data;
734       if (!g_strcmp0 (evdata->bus_name, bus_name) &&
735           spi_event_is_subtype (evdata->data, remove_data))
736         {
737           GList *events = spi_global_app_data->events;
738           g_strfreev (evdata->data);
739           g_free (evdata->bus_name);
740           g_slist_free_full (evdata->properties, free_property_definition);
741           g_free (evdata);
742           if (list->prev)
743             {
744               GList *next = list->next;
745               list->prev = g_list_remove (list->prev, evdata);
746               list = next;
747             }
748           else
749             {
750               spi_global_app_data->events = g_list_remove (events, evdata);
751               list = spi_global_app_data->events;
752             }
753         }
754       else
755         {
756           list = list->next;
757         }
758     }
759
760   g_strfreev (remove_data);
761 }
762
763 static void
764 handle_event_listener_deregistered (DBusConnection *bus, DBusMessage *message,
765                                     void *user_data)
766 {
767   gchar *name;
768   char *sender;
769
770   if (!dbus_message_get_args (message, NULL, DBUS_TYPE_STRING, &sender,
771                               DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID))
772     return;
773
774   remove_events (sender, name);
775 }
776
777 static void
778 handle_device_listener_registered (DBusConnection *bus, DBusMessage *message,
779                                     void *user_data)
780 {
781   char *sender;
782   DBusMessageIter iter, iter_struct;
783
784   if (strncmp (dbus_message_get_signature (message), "(s", 2) != 0)
785     {
786       g_warning ("atk-bridge: handle_device_listener_register: unknown signature");
787       return;
788     }
789
790   dbus_message_iter_init (message, &iter);
791   dbus_message_iter_recurse (&iter, &iter_struct);
792   dbus_message_iter_get_basic (&iter_struct, &sender);
793   spi_atk_add_client (sender);
794 }
795
796 static DBusHandlerResult
797 signal_filter (DBusConnection *bus, DBusMessage *message, void *user_data)
798 {
799   const char *interface = dbus_message_get_interface (message);
800   const char *member = dbus_message_get_member (message);
801   DBusHandlerResult result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
802   static gboolean registry_lost = FALSE;
803
804   if (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_SIGNAL)
805     return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
806
807   if (!strcmp (interface, ATSPI_DBUS_INTERFACE_REGISTRY))
808     {
809       result = DBUS_HANDLER_RESULT_HANDLED;
810       if (!strcmp (member, "EventListenerRegistered"))
811         handle_event_listener_registered (bus, message, user_data);
812       else if (!strcmp (member, "EventListenerDeregistered"))
813         handle_event_listener_deregistered (bus, message, user_data);
814       else
815         result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
816     }
817   else if (!strcmp (interface, ATSPI_DBUS_INTERFACE_DEVICE_EVENT_LISTENER))
818     {
819       result = DBUS_HANDLER_RESULT_HANDLED;
820       if (!strcmp (member, "KeystrokeListenerRegistered"))
821         handle_device_listener_registered (bus, message, user_data);
822       else if (!strcmp (member, "DeviceListenerRegistered"))
823         handle_device_listener_registered (bus, message, user_data);
824       else
825         result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
826     }
827
828   if (!g_strcmp0(interface, DBUS_INTERFACE_DBUS) &&
829       !g_strcmp0(member, "NameOwnerChanged"))
830     {
831       char *name, *old, *new;
832       if (dbus_message_get_args (message, NULL,
833                                  DBUS_TYPE_STRING, &name,
834                                  DBUS_TYPE_STRING, &old,
835                                  DBUS_TYPE_STRING, &new,
836                                  DBUS_TYPE_INVALID))
837         {
838           if (!strcmp (name, "org.a11y.atspi.Registry"))
839             {
840               if (registry_lost && !old[0])
841                 {
842                   register_application (spi_global_app_data);
843                   registry_lost = FALSE;
844                 }
845               else if (!new[0])
846                 registry_lost = TRUE;
847             }
848           else if (*old != '\0' && *new == '\0')
849               spi_atk_remove_client (old);
850         }
851     }
852
853   return result;
854 }
855
856 int
857 spi_atk_create_socket (SpiBridge *app)
858 {
859 #ifndef DISABLE_P2P
860   DBusServer *server;
861   DBusError error;
862
863   if (getuid () != 0)
864   {
865     app->app_tmp_dir = g_build_filename (g_get_user_runtime_dir (),
866                                          "at-spi2-XXXXXX", NULL);
867     if (!g_mkdtemp (app->app_tmp_dir))
868     {
869       g_free (app->app_tmp_dir);
870       app->app_tmp_dir = NULL;
871       return FALSE;
872     }
873   }
874
875   if (app->app_tmp_dir)
876     app->app_bus_addr = g_strdup_printf ("unix:path=%s/socket", app->app_tmp_dir);
877   else
878     app->app_bus_addr = g_strdup_printf ("unix:path=%s/at-spi2-socket-%d",
879                                          g_get_user_runtime_dir (), getpid ());
880
881   if (!spi_global_app_data->app_bus_addr)
882     return -1;
883
884   dbus_error_init(&error);
885   server = dbus_server_listen(spi_global_app_data->app_bus_addr, &error);
886   if (server == NULL)
887   {
888     g_warning ("atk-bridge: Couldn't listen on dbus server: %s", error.message);
889     dbus_error_free (&error);
890     spi_global_app_data->app_bus_addr [0] = '\0';
891     g_main_context_unref (spi_global_app_data->main_context);
892     spi_global_app_data->main_context = NULL;
893     return -1;
894   }
895
896   atspi_dbus_server_setup_with_g_main(server, NULL);
897   dbus_server_set_new_connection_function(server, new_connection_cb, NULL, NULL);
898
899   spi_global_app_data->server = server;
900 #endif
901
902   return 0;
903 }
904
905 /*
906  * Checks the status of the environment variables
907  *
908  * At this moment it only checks NO_AT_BRIDGE
909  *
910  * Returns TRUE if there isn't anything on the environment preventing
911  * you to load the bridge, FALSE otherwise
912  */
913 static gboolean
914 check_envvar (void)
915 {
916   const gchar *envvar;
917
918   envvar = g_getenv ("NO_AT_BRIDGE");
919
920   if (envvar && atoi (envvar) == 1)
921     return FALSE;
922   else
923     return TRUE;
924 }
925
926 void
927 spi_atk_activate ()
928 {
929   DRoutePath *treepath;
930
931   spi_atk_register_event_listeners ();
932   if (!spi_global_cache)
933     {
934       spi_global_cache    = g_object_new (SPI_CACHE_TYPE, NULL);
935       treepath = droute_add_one (spi_global_app_data->droute,
936                                  "/org/a11y/atspi/cache", spi_global_cache);
937
938       if (!treepath)
939         {
940           g_warning ("atk-bridge: Error in droute_add_one().  Already running?");
941           return;
942         }
943       spi_initialize_cache (treepath);
944       if (spi_global_app_data->bus)
945         droute_path_register (treepath, spi_global_app_data->bus);
946     }
947 }
948
949 /*
950  * spi_app_init
951  *
952  * The following needs to be initialized.
953  *
954  * - DRoute for routing message to their accessible objects.
955  * - Event handlers for emmitting signals on specific ATK events.
956  * - setup the bus for p2p communication
957  * - Application registration with the AT-SPI registry.
958  *
959  */
960 int
961 atk_bridge_adaptor_init (gint * argc, gchar ** argv[])
962 {
963   GOptionContext *opt;
964   GError *err = NULL;
965   DBusError error;
966   AtkObject *root;
967   gboolean load_bridge;
968   DRoutePath *accpath;
969
970   load_bridge = check_envvar ();
971   if (inited && !load_bridge)
972     g_warning ("ATK Bridge is disabled but a11y has already been enabled.");
973
974   if (inited || !load_bridge)
975     return 0;
976
977   inited = TRUE;
978
979   root = atk_get_root ();
980   g_warn_if_fail (root);
981   if (!root)
982     {
983       inited = FALSE;
984       return -1;
985     }
986
987   /* Parse command line options */
988   opt = g_option_context_new (NULL);
989   g_option_context_add_main_entries (opt, atspi_option_entries, NULL);
990   g_option_context_set_ignore_unknown_options (opt, TRUE);
991   if (!g_option_context_parse (opt, argc, argv, &err))
992     {
993       g_warning ("AT-SPI Option parsing failed: %s\n", err->message);
994       g_error_free (err);
995     }
996   g_option_context_free (opt);
997
998   /* Allocate global data and do ATK initializations */
999   spi_global_app_data = g_new0 (SpiBridge, 1);
1000   spi_global_app_data->root = g_object_ref (root);
1001
1002   /* Set up D-Bus connection and register bus name */
1003   dbus_error_init (&error);
1004   spi_global_app_data->bus = atspi_get_a11y_bus ();
1005   if (!spi_global_app_data->bus)
1006     {
1007       g_free (spi_global_app_data);
1008       spi_global_app_data = NULL;
1009       inited = FALSE;
1010       return -1;
1011     }
1012
1013   if (atspi_dbus_name != NULL)
1014     {
1015       if (dbus_bus_request_name
1016           (spi_global_app_data->bus, atspi_dbus_name, 0, &error))
1017         {
1018           g_print ("AT-SPI Recieved D-Bus name - %s\n", atspi_dbus_name);
1019         }
1020       else
1021         {
1022           g_print
1023             ("AT-SPI D-Bus name requested but could not be allocated - %s\n",
1024              atspi_dbus_name);
1025         }
1026     }
1027
1028   spi_global_app_data->main_context = g_main_context_new ();
1029
1030   atspi_dbus_connection_setup_with_g_main (spi_global_app_data->bus, NULL);
1031
1032   /* Hook our plug-and socket functions */
1033   install_plug_hooks ();
1034
1035   /* 
1036    * Create the leasing, register and cache objects.
1037    * The order is important here, the cache depends on the
1038    * register object.
1039    */
1040   spi_global_register = g_object_new (SPI_REGISTER_TYPE, NULL);
1041   spi_global_leasing  = g_object_new (SPI_LEASING_TYPE, NULL);
1042
1043   /* Register droute for routing AT-SPI messages */
1044   spi_global_app_data->droute =
1045     droute_new ();
1046
1047   accpath = droute_add_many (spi_global_app_data->droute,
1048                              "/org/a11y/atspi/accessible",
1049                              NULL,
1050                              introspect_children_cb,
1051                              NULL,
1052                              (DRouteGetDatumFunction)
1053                              spi_global_register_path_to_object);
1054
1055
1056   /* Register all interfaces with droute and set up application accessible db */
1057   spi_initialize_accessible (accpath);
1058   spi_initialize_application (accpath);
1059   spi_initialize_action (accpath);
1060   spi_initialize_collection (accpath);
1061   spi_initialize_component (accpath);
1062   spi_initialize_document (accpath);
1063   spi_initialize_editabletext (accpath);
1064   spi_initialize_hyperlink (accpath);
1065   spi_initialize_hypertext (accpath);
1066   spi_initialize_image (accpath);
1067   spi_initialize_selection (accpath);
1068   spi_initialize_socket (accpath);
1069   spi_initialize_table (accpath);
1070   spi_initialize_table_cell (accpath);
1071   spi_initialize_text (accpath);
1072   spi_initialize_value (accpath);
1073
1074   droute_context_register (spi_global_app_data->droute,
1075                            spi_global_app_data->bus);
1076
1077   /* Register methods to send D-Bus signals on certain ATK events */
1078   if (clients)
1079     spi_atk_activate ();
1080
1081   /* Set up filter and match rules to catch signals */
1082   dbus_bus_add_match (spi_global_app_data->bus, "type='signal', interface='org.a11y.atspi.Registry', sender='org.a11y.atspi.Registry'", NULL);
1083   dbus_bus_add_match (spi_global_app_data->bus, "type='signal', interface='org.a11y.atspi.DeviceEventListener', sender='org.a11y.atspi.Registry'", NULL);
1084   dbus_bus_add_match (spi_global_app_data->bus, "type='signal', arg0='org.a11y.atspi.Registry', interface='org.freedesktop.DBus', member='NameOwnerChanged'", NULL);
1085   dbus_connection_add_filter (spi_global_app_data->bus, signal_filter, NULL,
1086                               NULL);
1087
1088   /* Register this app by sending a signal out to AT-SPI registry daemon */
1089   if (!atspi_no_register && (!root || !ATK_IS_PLUG (root)))
1090     register_application (spi_global_app_data);
1091   else
1092     get_registered_event_listeners (spi_global_app_data);
1093
1094   dbus_error_free (&error);
1095   return 0;
1096 }
1097
1098 void
1099 atk_bridge_adaptor_cleanup (void)
1100 {
1101   GList *l;
1102   GSList *ls;
1103
1104   if (!inited)
1105     return;
1106
1107   if (!spi_global_app_data)
1108       return;
1109
1110   spi_atk_tidy_windows ();
1111   spi_atk_deregister_event_listeners ();
1112
1113   deregister_application (spi_global_app_data);
1114
1115   if (spi_global_app_data->bus)
1116     {
1117       dbus_connection_remove_filter (spi_global_app_data->bus, signal_filter, NULL);
1118       droute_context_unregister (spi_global_app_data->droute, spi_global_app_data->bus);
1119       dbus_connection_close (spi_global_app_data->bus);
1120       dbus_connection_unref (spi_global_app_data->bus);
1121       spi_global_app_data->bus = NULL;
1122     }
1123
1124   for (l = spi_global_app_data->direct_connections; l; l = l->next)
1125     {
1126       DBusConnection *connection;
1127
1128       connection = l->data;
1129
1130       droute_context_unregister (spi_global_app_data->droute, connection);
1131       droute_unintercept_dbus (connection);
1132       dbus_connection_close (connection);
1133       dbus_connection_unref (connection);
1134     }
1135   g_list_free (spi_global_app_data->direct_connections);
1136   spi_global_app_data->direct_connections = NULL;
1137
1138   for (ls = clients; ls; ls = ls->next)
1139     g_free (ls->data);
1140   g_slist_free (clients);
1141   clients = NULL;
1142
1143   g_clear_object (&spi_global_cache);
1144   g_clear_object (&spi_global_leasing);
1145   g_clear_object (&spi_global_register);
1146
1147   if (spi_global_app_data->main_context)
1148     g_main_context_unref (spi_global_app_data->main_context);
1149
1150   droute_free (spi_global_app_data->droute);
1151
1152   g_free (spi_global_app_data);
1153   spi_global_app_data = NULL;
1154
1155   inited = FALSE;
1156 }
1157
1158 /*---------------------------------------------------------------------------*/
1159
1160 static gchar *name_match_tmpl =
1161        "type='signal', interface='org.freedesktop.DBus', member='NameOwnerChanged', arg0='%s'";
1162
1163 void
1164 spi_atk_add_client (const char *bus_name)
1165 {
1166   GSList *l;
1167   gchar *match;
1168
1169   for (l = clients; l; l = l->next)
1170   {
1171     if (!g_strcmp0 (l->data, bus_name))
1172       return;
1173   }
1174   if (!clients)
1175     spi_atk_activate ();
1176   clients = g_slist_append (clients, g_strdup (bus_name));
1177   match = g_strdup_printf (name_match_tmpl, bus_name);
1178   dbus_bus_add_match (spi_global_app_data->bus, match, NULL);
1179   g_free (match);
1180 }
1181
1182 void
1183 spi_atk_remove_client (const char *bus_name)
1184 {
1185   GSList *l;
1186   GSList *next_node;
1187
1188   l = clients;
1189   while (l)
1190   {
1191     next_node = l->next;
1192
1193     if (!g_strcmp0 (l->data, bus_name))
1194     {
1195       gchar *match = g_strdup_printf (name_match_tmpl, l->data);
1196       dbus_bus_remove_match (spi_global_app_data->bus, match, NULL);
1197   g_free (match);
1198       g_free (l->data);
1199       clients = g_slist_delete_link (clients, l);
1200       if (!clients)
1201         spi_atk_deregister_event_listeners ();
1202       return;
1203     }
1204
1205     l = next_node;
1206   }
1207 }
1208
1209 void
1210 spi_atk_add_interface (DRoutePath *path,
1211                        const char *name,
1212                        const char *introspect,
1213                        const DRouteMethod   *methods,
1214                        const DRouteProperty *properties)
1215 {
1216   droute_path_add_interface (path, name, introspect, methods, properties);
1217
1218   if (properties)
1219   {
1220     if (!spi_global_app_data->property_hash)
1221       spi_global_app_data->property_hash = g_hash_table_new_full (g_str_hash,
1222                                                                   g_str_equal,
1223                                                                   g_free, NULL);
1224     g_hash_table_insert (spi_global_app_data->property_hash, g_strdup (name),
1225                          (gpointer) properties);
1226   }
1227 }
1228 /*END------------------------------------------------------------------------*/