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