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