Don't create a sub-directory for the socket when running as root
[platform/core/uifw/at-spi2-atk.git] / atk-adaptor / bridge.c
1 /*
2  * AT-SPI - Assistive Technology Service Provider Interface
3  * (Gnome Accessibility Project; http://developer.gnome.org/projects/gap)
4  *
5  * Copyright 2008, 2009 Codethink Ltd.
6  * Copyright 2001, 2002, 2003 Sun Microsystems Inc.,
7  * Copyright 2001, 2002, 2003 Ximian, Inc.
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Library General Public
11  * License as published by the Free Software Foundation; either
12  * version 2 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Library General Public License for more details.
18  *
19  * You should have received a copy of the GNU Library General Public
20  * License along with this library; if not, write to the
21  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22  * Boston, MA 02111-1307, USA.
23  */
24
25 #define _GNU_SOURCE
26 #include "config.h"
27
28 #include <unistd.h>
29 #include <stdlib.h>
30 #include <stdio.h>
31 #include <stdarg.h>
32 #include <string.h>
33 #include<sys/stat.h>
34 #include <atk/atk.h>
35
36 #include <droute/droute.h>
37 #include <atspi/atspi.h>
38 #include <atk-bridge.h>
39
40 #include "bridge.h"
41 #include "event.h"
42 #include "adaptors.h"
43 #include "object.h"
44 #include "accessible-stateset.h"
45
46 #include "accessible-register.h"
47 #include "accessible-leasing.h"
48 #include "accessible-cache.h"
49
50 #include "spi-dbus.h"
51
52 /*---------------------------------------------------------------------------*/
53
54 static DBusHandlerResult
55 signal_filter (DBusConnection *bus, DBusMessage *message, void *user_data);
56
57 SpiBridge *spi_global_app_data = NULL;
58
59 static gboolean inited = FALSE;
60
61 /*---------------------------------------------------------------------------*/
62
63 static void
64 add_event (const char *bus_name, const char *event)
65 {
66   event_data *evdata;
67   gchar **data;
68
69   spi_atk_add_client (bus_name);
70   evdata = (event_data *) g_malloc (sizeof (*evdata));
71   if (!evdata)
72     return;
73   data = g_strsplit (event, ":", 3);
74   if (!data)
75     {
76       g_free (evdata);
77       return;
78     }
79   evdata->bus_name = g_strdup (bus_name);
80   evdata->data = data;
81   spi_global_app_data->events = g_list_append (spi_global_app_data->events, evdata);
82 }
83
84 static GSList *clients = NULL;
85
86 static void
87 tally_event_reply ()
88 {
89   static int replies_received = 0;
90
91   replies_received++;
92   if (replies_received == 3)
93   {
94     if (!clients)
95       spi_atk_deregister_event_listeners ();
96     spi_global_app_data->events_initialized = TRUE;
97   }
98 }
99
100 static void
101 get_events_reply (DBusPendingCall *pending, void *user_data)
102 {
103   DBusMessage *reply = dbus_pending_call_steal_reply (pending);
104   DBusMessageIter iter, iter_array, iter_struct;
105
106   if (!reply)
107     goto done;
108
109   if (strcmp (dbus_message_get_signature (reply), "a(ss)") != 0)
110     {
111       g_warning ("atk-bridge: GetRegisteredEvents returned message with unknown signature");
112       goto done;
113     }
114
115   dbus_message_iter_init (reply, &iter);
116   dbus_message_iter_recurse (&iter, &iter_array);
117   while (dbus_message_iter_get_arg_type (&iter_array) != DBUS_TYPE_INVALID)
118     {
119       char *bus_name, *event;
120       dbus_message_iter_recurse (&iter_array, &iter_struct);
121       dbus_message_iter_get_basic (&iter_struct, &bus_name);
122       dbus_message_iter_next (&iter_struct);
123       dbus_message_iter_get_basic (&iter_struct, &event);
124       add_event (bus_name, event);
125       dbus_message_iter_next (&iter_array);
126     }
127
128 done:
129   if (reply)
130     dbus_message_unref (reply);
131   if (pending)
132     dbus_pending_call_unref (pending);
133
134   tally_event_reply ();
135 }
136
137 static void
138 get_device_events_reply (DBusPendingCall *pending, void *user_data)
139 {
140   DBusMessage *reply = dbus_pending_call_steal_reply (pending);
141   DBusMessageIter iter, iter_array, iter_struct;
142
143   if (!reply)
144     goto done;
145
146   if (strncmp (dbus_message_get_signature (reply), "a(s", 3) != 0)
147     {
148       g_warning ("atk-bridge: get_device_events_reply: unknown signature");
149       goto done;
150     }
151
152   dbus_message_iter_init (reply, &iter);
153   dbus_message_iter_recurse (&iter, &iter_array);
154   while (dbus_message_iter_get_arg_type (&iter_array) != DBUS_TYPE_INVALID)
155     {
156       char *bus_name;
157       dbus_message_iter_recurse (&iter_array, &iter_struct);
158       dbus_message_iter_get_basic (&iter_struct, &bus_name);
159       spi_atk_add_client (bus_name);
160       dbus_message_iter_next (&iter_array);
161     }
162
163 done:
164   if (reply)
165     dbus_message_unref (reply);
166   if (pending)
167     dbus_pending_call_unref (pending);
168
169   tally_event_reply ();
170 }
171
172 static void
173 get_registered_event_listeners (SpiBridge *app)
174 {
175   DBusMessage *message;
176   DBusPendingCall *pending = NULL;
177
178   message = dbus_message_new_method_call (SPI_DBUS_NAME_REGISTRY,
179                                          ATSPI_DBUS_PATH_REGISTRY,
180                                          ATSPI_DBUS_INTERFACE_REGISTRY,
181                                          "GetRegisteredEvents");
182   if (!message)
183     return;
184
185   dbus_connection_send_with_reply (app->bus, message, &pending, -1);
186   dbus_message_unref (message);
187   if (!pending)
188     {
189       spi_global_app_data->events_initialized = TRUE;
190       return;
191     }
192   dbus_pending_call_set_notify (pending, get_events_reply, NULL, NULL);
193
194   message = dbus_message_new_method_call (SPI_DBUS_NAME_REGISTRY,
195                                          ATSPI_DBUS_PATH_DEC,
196                                          ATSPI_DBUS_INTERFACE_DEC,
197                                          "GetKeystrokeListeners");
198   if (!message)
199     return;
200   pending = NULL;
201   dbus_connection_send_with_reply (app->bus, message, &pending, -1);
202   dbus_message_unref (message);
203   if (!pending)
204     {
205       spi_global_app_data->events_initialized = TRUE;
206       return;
207     }
208   dbus_pending_call_set_notify (pending, get_device_events_reply, NULL, NULL);
209
210   message = dbus_message_new_method_call (SPI_DBUS_NAME_REGISTRY,
211                                          ATSPI_DBUS_PATH_DEC,
212                                          ATSPI_DBUS_INTERFACE_DEC,
213                                          "GetDeviceEventListeners");
214   if (!message)
215     return;
216   pending = NULL;
217   dbus_connection_send_with_reply (app->bus, message, &pending, -1);
218   dbus_message_unref (message);
219   if (!pending)
220     {
221       spi_global_app_data->events_initialized = TRUE;
222       return;
223     }
224   dbus_pending_call_set_notify (pending, get_device_events_reply, NULL, NULL);
225 }
226
227 static void
228 register_reply (DBusPendingCall *pending, void *user_data)
229 {
230   DBusMessage *reply;
231   SpiBridge *app = user_data;
232
233   reply = dbus_pending_call_steal_reply (pending);
234   dbus_pending_call_unref (pending);
235   if (reply)
236     {
237       gchar *app_name, *obj_path;
238
239       if (strcmp (dbus_message_get_signature (reply), "(so)") != 0)
240         {
241           g_warning ("AT-SPI: Could not obtain desktop path or name\n");
242         }
243       else
244         {
245           DBusMessageIter iter, iter_struct;
246           dbus_message_iter_init (reply, &iter);
247           dbus_message_iter_recurse (&iter, &iter_struct);
248           dbus_message_iter_get_basic (&iter_struct, &app_name);
249           dbus_message_iter_next (&iter_struct);
250           dbus_message_iter_get_basic (&iter_struct, &obj_path);
251
252           app->desktop_name = g_strdup (app_name);
253           app->desktop_path = g_strdup (obj_path);
254         }
255     }
256   else
257     {
258       g_warning ("AT-SPI: Could not embed inside desktop");
259       return;
260     }
261   dbus_message_unref (reply);
262
263   get_registered_event_listeners (spi_global_app_data);
264 }
265
266 static gboolean
267 register_application (SpiBridge * app)
268 {
269   DBusMessage *message;
270   DBusMessageIter iter;
271   DBusError error;
272   DBusPendingCall *pending;
273
274   dbus_error_init (&error);
275
276   /* These will be overridden when we get a reply, but in practice these
277      defaults should always be correct */
278   app->desktop_name = ATSPI_DBUS_NAME_REGISTRY;
279   app->desktop_path = ATSPI_DBUS_PATH_ROOT;
280
281   message = dbus_message_new_method_call (SPI_DBUS_NAME_REGISTRY,
282                                           ATSPI_DBUS_PATH_ROOT,
283                                           ATSPI_DBUS_INTERFACE_SOCKET,
284                                           "Embed");
285
286   dbus_message_iter_init_append (message, &iter);
287   spi_object_append_reference (&iter, app->root);
288   
289     if (!dbus_connection_send_with_reply (app->bus, message, &pending, -1)
290         || !pending)
291     {
292         return FALSE;
293     }
294
295     dbus_pending_call_set_notify (pending, register_reply, app, NULL);
296
297   if (message)
298     dbus_message_unref (message);
299
300 #ifndef DISABLE_P2P
301   if (getuid () != 0)
302   {
303     app->app_tmp_dir = g_build_filename (g_get_user_runtime_dir (),
304                                          "at-spi2-XXXXXX", NULL);
305     if (!g_mkdtemp (app->app_tmp_dir))
306     {
307       g_free (app->app_tmp_dir);
308       app->app_tmp_dir = NULL;
309       return FALSE;
310     }
311   }
312
313   if (app->app_tmp_dir)
314     app->app_bus_addr = g_strdup_printf ("unix:path=%s/socket", app->app_tmp_dir);
315   else
316     app->app_bus_addr = g_strdup_printf ("unix:path=%s/at-spi2-socket-%d",
317                                          g_get_user_runtime_dir (), getpid ());
318 #endif
319
320   return TRUE;
321 }
322
323 /*---------------------------------------------------------------------------*/
324
325 static void
326 deregister_application (SpiBridge * app)
327 {
328   DBusMessage *message;
329   DBusMessageIter iter;
330   DBusError error;
331   const char *uname;
332
333   dbus_error_init (&error);
334
335   message = dbus_message_new_method_call (SPI_DBUS_NAME_REGISTRY,
336                                           ATSPI_DBUS_PATH_REGISTRY,
337                                           ATSPI_DBUS_INTERFACE_REGISTRY,
338                                           "DeregisterApplication");
339   dbus_message_set_no_reply (message, TRUE);
340
341   uname = dbus_bus_get_unique_name (app->bus);
342
343   dbus_message_iter_init_append (message, &iter);
344   dbus_message_iter_append_basic (&iter, DBUS_TYPE_STRING, &uname);
345   dbus_connection_send (app->bus, message, NULL);
346   if (message)
347     dbus_message_unref (message);
348
349   if (app->app_bus_addr)
350   {
351     unlink (app->app_bus_addr);
352     g_free (app->app_bus_addr);
353     app->app_bus_addr = NULL;
354   }
355
356   if (app->app_tmp_dir)
357   {
358     rmdir (app->app_tmp_dir);
359     g_free (app->app_tmp_dir);
360     app->app_tmp_dir = NULL;
361   }
362 }
363
364 /*---------------------------------------------------------------------------*/
365
366 /*---------------------------------------------------------------------------*/
367
368 static AtkPlugClass *plug_class;
369 static AtkSocketClass *socket_class;
370
371 static gchar *
372 get_plug_id (AtkPlug * plug)
373 {
374   const char *uname = dbus_bus_get_unique_name (spi_global_app_data->bus);
375   gchar *path;
376   GString *str = g_string_new (NULL);
377
378   path = spi_register_object_to_path (spi_global_register, G_OBJECT (plug));
379   g_string_printf (str, "%s:%s", uname, path);
380   g_free (path);
381   return g_string_free (str, FALSE);
382 }
383
384 AtkStateSet *
385 socket_ref_state_set (AtkObject *accessible)
386 {
387   char *child_name, *child_path;
388   AtkSocket *socket = ATK_SOCKET (accessible);
389   int count = 0;
390   int j;
391   int v;
392   DBusMessage *message, *reply;
393   DBusMessageIter iter, iter_array;
394   AtkStateSet *set;
395
396   set = atk_state_set_new ();
397
398   if (!socket->embedded_plug_id)
399     return set;
400
401   child_name = g_strdup (socket->embedded_plug_id);
402   if (!child_name)
403     return set;
404   child_path = g_utf8_strchr (child_name + 1, -1, ':');
405   if (!child_path)
406     {
407       g_free (child_name);
408       return set;
409     }
410   *(child_path++) = '\0';
411   message = dbus_message_new_method_call (child_name, child_path, ATSPI_DBUS_INTERFACE_ACCESSIBLE, "GetState");
412   g_free (child_name);
413   reply = dbus_connection_send_with_reply_and_block (spi_global_app_data->bus, message, 1, NULL);
414   dbus_message_unref (message);
415   if (reply == NULL)
416     return set;
417   if (strcmp (dbus_message_get_signature (reply), "au") != 0)
418     {
419       dbus_message_unref (reply);
420       return set;
421     }
422
423   dbus_message_iter_init (reply, &iter);
424   dbus_message_iter_recurse (&iter, &iter_array);
425   do
426     {
427       dbus_message_iter_get_basic (&iter_array, &v);
428       for (j = 0; j < 32; j++)
429         {
430           if (v & (1 << j))
431             {
432               AtkState state = spi_atk_state_from_spi_state ((count << 5) + j);
433               atk_state_set_add_state (set, state);
434             }
435         }
436       count++;
437     }
438   while (dbus_message_iter_next (&iter_array));
439   dbus_message_unref (reply);
440   return set;
441 }
442
443 static void
444 socket_embed_hook (AtkSocket * socket, gchar * plug_id)
445 {
446   AtkObject *accessible = ATK_OBJECT(socket);
447   gchar *plug_name, *plug_path;
448   AtkObjectClass *klass;
449
450   /* Force registration */
451   gchar *path = spi_register_object_to_path (spi_global_register, G_OBJECT (accessible));
452   /* Let the plug know that it has been embedded */
453   plug_name = g_strdup (plug_id);
454   if (!plug_name)
455     {
456       g_free (path);
457       return;
458     }
459   plug_path = g_utf8_strchr (plug_name + 1, -1, ':');
460   if (plug_path)
461     {
462       DBusMessage *message;
463       *(plug_path++) = '\0';
464       message = dbus_message_new_method_call (plug_name, plug_path, ATSPI_DBUS_INTERFACE_SOCKET, "Embedded");
465       dbus_message_append_args (message, DBUS_TYPE_STRING, &path, DBUS_TYPE_INVALID);
466       dbus_connection_send (spi_global_app_data->bus, message, NULL);
467     }
468   g_free (plug_name);
469   g_free (path);
470
471   klass = ATK_OBJECT_GET_CLASS (accessible);
472   klass->ref_state_set = socket_ref_state_set;
473 }
474
475 static void
476 install_plug_hooks ()
477 {
478   gpointer data;
479
480   data = g_type_class_ref (ATK_TYPE_PLUG);
481   plug_class = ATK_PLUG_CLASS (data);
482   data = g_type_class_ref (ATK_TYPE_SOCKET);
483   socket_class = ATK_SOCKET_CLASS (data);
484   plug_class->get_object_id = get_plug_id;
485   socket_class->embed = socket_embed_hook;
486 }
487
488 static guint
489 get_ancestral_uid (guint pid)
490 {
491   FILE *fp;
492   char buf [80];
493   int ppid = 0;
494   int uid = 0;
495   gboolean got_ppid = 0;
496   gboolean got_uid = 0;
497
498   sprintf (buf, "/proc/%d/status", pid);
499   fp = fopen (buf, "r");
500   if (!fp)
501     return 0;
502   while ((!got_ppid || !got_uid) && fgets (buf, sizeof (buf), fp))
503   {
504     if (sscanf (buf, "PPid:\t%d", &ppid) == 1)
505       got_ppid = TRUE;
506     else if (sscanf (buf, "Uid:\t%d", &uid) == 1)
507       got_uid = TRUE;
508   }
509   fclose (fp);
510
511   if (!got_ppid || !got_uid)
512     return 0;
513   if (uid != 0)
514     return uid;
515   if (ppid == 0 || ppid == 1)
516     return 0;
517   return get_ancestral_uid (ppid);
518 }
519
520 static dbus_bool_t
521 user_check (DBusConnection *bus, unsigned long uid, void *data)
522 {
523   if (uid == getuid () || uid == geteuid ())
524     return TRUE;
525   if (getuid () == 0)
526     return get_ancestral_uid (getpid ()) == uid;
527   return FALSE;
528 }
529
530 static void
531 new_connection_cb (DBusServer *server, DBusConnection *con, void *data)
532 {
533   dbus_connection_set_unix_user_function (con, user_check, NULL, NULL);
534   dbus_connection_ref(con);
535   atspi_dbus_connection_setup_with_g_main(con, NULL);
536   droute_intercept_dbus (con);
537   droute_context_register (spi_global_app_data->droute, con);
538
539   spi_global_app_data->direct_connections = g_list_append (spi_global_app_data->direct_connections, con);
540 }
541
542 static int
543 setup_bus (void)
544 {
545 #ifndef DISABLE_P2P
546   DBusServer *server;
547   DBusError err;
548
549   if (!spi_global_app_data->app_bus_addr)
550     return -1;
551
552   dbus_error_init(&err);
553   server = dbus_server_listen(spi_global_app_data->app_bus_addr, &err);
554   if (server == NULL)
555   {
556     g_warning ("atk-bridge: Couldn't listen on dbus server: %s", err.message);
557     dbus_error_init (&err);
558     spi_global_app_data->app_bus_addr [0] = '\0';
559     g_main_context_unref (spi_global_app_data->main_context);
560     spi_global_app_data->main_context = NULL;
561     return -1;
562   }
563
564   atspi_dbus_server_setup_with_g_main(server, NULL);
565   dbus_server_set_new_connection_function(server, new_connection_cb, NULL, NULL);
566
567   spi_global_app_data->server = server;
568 #endif
569
570   return 0;
571 }
572
573
574 gchar *atspi_dbus_name = NULL;
575 static gboolean atspi_no_register = FALSE;
576
577 static GOptionEntry atspi_option_entries[] = {
578   {"atspi-dbus-name", 0, 0, G_OPTION_ARG_STRING, &atspi_dbus_name,
579    "D-Bus bus name to register as", NULL},
580   {"atspi-no-register", 0, 0, G_OPTION_ARG_NONE, &atspi_no_register,
581    "Do not register with Registry Daemon", NULL},
582   {NULL}
583 };
584
585 static gchar *
586 introspect_children_cb (const char *path, void *data)
587 {
588   if (!strcmp (path, "/org/a11y/atspi/accessible"))
589     {
590       return g_strdup ("<node name=\"root\"/>\n");
591       /* TODO: Should we place the whole hierarchy here? */
592     }
593   return NULL;
594 }
595
596 static void
597 handle_event_listener_registered (DBusConnection *bus, DBusMessage *message,
598                                   void *user_data)
599 {
600   const char *name;
601   char *sender;
602
603   if (!dbus_message_get_args (message, NULL, DBUS_TYPE_STRING, &sender,
604     DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID))
605     return;
606
607   add_event (sender, name);
608 }
609
610 static void
611 remove_events (const char *bus_name, const char *event)
612 {
613   gchar **remove_data;
614   GList *list;
615
616   remove_data = g_strsplit (event, ":", 3);
617   if (!remove_data)
618     {
619       return;
620     }
621
622   for (list = spi_global_app_data->events; list;)
623     {
624       event_data *evdata = list->data;
625       if (!g_strcmp0 (evdata->bus_name, bus_name) &&
626           spi_event_is_subtype (evdata->data, remove_data))
627         {
628           GList *events = spi_global_app_data->events;
629           list = list->next;
630           g_strfreev (evdata->data);
631           g_free (evdata->bus_name);
632           g_free (evdata);
633           spi_global_app_data->events = g_list_remove (events, evdata);
634         }
635       else
636         {
637           list = list->next;
638         }
639     }
640
641   g_strfreev (remove_data);
642 }
643
644 static void
645 handle_event_listener_deregistered (DBusConnection *bus, DBusMessage *message,
646                                     void *user_data)
647 {
648   gchar *name;
649   char *sender;
650
651   if (!dbus_message_get_args (message, NULL, DBUS_TYPE_STRING, &sender,
652                               DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID))
653     return;
654
655   remove_events (sender, name);
656 }
657
658 static void
659 handle_device_listener_registered (DBusConnection *bus, DBusMessage *message,
660                                     void *user_data)
661 {
662   char *sender;
663   DBusMessageIter iter, iter_struct;
664
665   if (strncmp (dbus_message_get_signature (message), "(s", 2) != 0)
666     {
667       g_warning ("atk-bridge: handle_device_listener_register: unknown signature");
668       return;
669     }
670
671   dbus_message_iter_init (message, &iter);
672   dbus_message_iter_recurse (&iter, &iter_struct);
673   dbus_message_iter_get_basic (&iter_struct, &sender);
674   spi_atk_add_client (sender);
675 }
676
677 static DBusHandlerResult
678 signal_filter (DBusConnection *bus, DBusMessage *message, void *user_data)
679 {
680   const char *interface = dbus_message_get_interface (message);
681   const char *member = dbus_message_get_member (message);
682   DBusHandlerResult result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
683
684   if (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_SIGNAL)
685     return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
686
687   if (!strcmp (interface, ATSPI_DBUS_INTERFACE_REGISTRY))
688     {
689       result = DBUS_HANDLER_RESULT_HANDLED;
690       if (!strcmp (member, "EventListenerRegistered"))
691         handle_event_listener_registered (bus, message, user_data);
692       else if (!strcmp (member, "EventListenerDeregistered"))
693         handle_event_listener_deregistered (bus, message, user_data);
694       else
695         result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
696     }
697   else if (!strcmp (interface, ATSPI_DBUS_INTERFACE_DEVICE_EVENT_LISTENER))
698     {
699       result = DBUS_HANDLER_RESULT_HANDLED;
700       if (!strcmp (member, "KeystrokeListenerRegistered"))
701         handle_device_listener_registered (bus, message, user_data);
702       else if (!strcmp (member, "DeviceListenerRegistered"))
703         handle_device_listener_registered (bus, message, user_data);
704       else
705         result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
706     }
707
708   if (!g_strcmp0(interface, DBUS_INTERFACE_DBUS) &&
709       !g_strcmp0(member, "NameOwnerChanged"))
710     {
711       char *name, *old, *new;
712       result = DBUS_HANDLER_RESULT_HANDLED;
713       if (dbus_message_get_args (message, NULL,
714                                  DBUS_TYPE_STRING, &name,
715                                  DBUS_TYPE_STRING, &old,
716                                  DBUS_TYPE_STRING, &new,
717                                  DBUS_TYPE_INVALID))
718         {
719           if (*old != '\0' && *new == '\0')
720               spi_atk_remove_client (old);
721         }
722     }
723
724   return result;
725 }
726
727 /*
728  * Checks the status of the environment variables
729  *
730  * At this moment it only checks NO_AT_BRIDGE
731  *
732  * Returns TRUE if there isn't anything on the environment preventing
733  * you to load the bridge, FALSE otherwise
734  */
735 static gboolean
736 check_envvar (void)
737 {
738   const gchar *envvar;
739
740   envvar = g_getenv ("NO_AT_BRIDGE");
741
742   if (envvar && atoi (envvar) == 1)
743     return FALSE;
744   else
745     return TRUE;
746 }
747
748 /*
749  * spi_app_init
750  *
751  * The following needs to be initialized.
752  *
753  * - DRoute for routing message to their accessible objects.
754  * - Event handlers for emmitting signals on specific ATK events.
755  * - setup the bus for p2p communication
756  * - Application registration with the AT-SPI registry.
757  *
758  */
759 int
760 atk_bridge_adaptor_init (gint * argc, gchar ** argv[])
761 {
762   GOptionContext *opt;
763   GError *err = NULL;
764   DBusError error;
765   AtkObject *root;
766   gboolean load_bridge;
767   DRoutePath *treepath, *accpath;
768
769   load_bridge = check_envvar ();
770   if (inited && !load_bridge)
771     g_warning ("ATK Bridge is disabled but a11y has already been enabled.");
772
773   if (inited || !load_bridge)
774     return 0;
775
776   inited = TRUE;
777
778   root = atk_get_root ();
779   g_warn_if_fail (root);
780   if (!root)
781     {
782       inited = FALSE;
783       return -1;
784     }
785
786   /* Parse command line options */
787   opt = g_option_context_new (NULL);
788   g_option_context_add_main_entries (opt, atspi_option_entries, NULL);
789   g_option_context_set_ignore_unknown_options (opt, TRUE);
790   if (!g_option_context_parse (opt, argc, argv, &err))
791     g_warning ("AT-SPI Option parsing failed: %s\n", err->message);
792   g_option_context_free (opt);
793
794   /* Allocate global data and do ATK initializations */
795   spi_global_app_data = g_new0 (SpiBridge, 1);
796   spi_global_app_data->root = g_object_ref (root);
797
798   /* Set up D-Bus connection and register bus name */
799   dbus_error_init (&error);
800   spi_global_app_data->bus = atspi_get_a11y_bus ();
801   if (!spi_global_app_data->bus)
802     {
803       g_free (spi_global_app_data);
804       spi_global_app_data = NULL;
805       inited = FALSE;
806       return -1;
807     }
808
809   if (atspi_dbus_name != NULL)
810     {
811       if (dbus_bus_request_name
812           (spi_global_app_data->bus, atspi_dbus_name, 0, &error))
813         {
814           g_print ("AT-SPI Recieved D-Bus name - %s\n", atspi_dbus_name);
815         }
816       else
817         {
818           g_print
819             ("AT-SPI D-Bus name requested but could not be allocated - %s\n",
820              atspi_dbus_name);
821         }
822     }
823
824   spi_global_app_data->main_context = g_main_context_new ();
825
826   atspi_dbus_connection_setup_with_g_main (spi_global_app_data->bus, NULL);
827
828   /* Hook our plug-and socket functions */
829   install_plug_hooks ();
830
831   /* 
832    * Create the leasing, register and cache objects.
833    * The order is important here, the cache depends on the
834    * register object.
835    */
836   spi_global_register = g_object_new (SPI_REGISTER_TYPE, NULL);
837   spi_global_leasing  = g_object_new (SPI_LEASING_TYPE, NULL);
838   spi_global_cache    = g_object_new (SPI_CACHE_TYPE, NULL);
839
840   /* Register droute for routing AT-SPI messages */
841   spi_global_app_data->droute =
842     droute_new ();
843
844   treepath = droute_add_one (spi_global_app_data->droute,
845                              "/org/a11y/atspi/cache", spi_global_cache);
846
847   if (!treepath)
848     {
849       g_warning ("atk-bridge: Error in droute_add_one().  Already running?");
850       return -1;
851     }
852
853   accpath = droute_add_many (spi_global_app_data->droute,
854                              "/org/a11y/atspi/accessible",
855                              NULL,
856                              introspect_children_cb,
857                              NULL,
858                              (DRouteGetDatumFunction)
859                              spi_global_register_path_to_object);
860
861
862   /* Register all interfaces with droute and set up application accessible db */
863   spi_initialize_cache (treepath);
864   spi_initialize_accessible (accpath);
865   spi_initialize_application (accpath);
866   spi_initialize_action (accpath);
867   spi_initialize_collection (accpath);
868   spi_initialize_component (accpath);
869   spi_initialize_document (accpath);
870   spi_initialize_editabletext (accpath);
871   spi_initialize_hyperlink (accpath);
872   spi_initialize_hypertext (accpath);
873   spi_initialize_image (accpath);
874   spi_initialize_selection (accpath);
875   spi_initialize_socket (accpath);
876   spi_initialize_table (accpath);
877   spi_initialize_text (accpath);
878   spi_initialize_value (accpath);
879
880   droute_context_register (spi_global_app_data->droute,
881                            spi_global_app_data->bus);
882
883   /* Register methods to send D-Bus signals on certain ATK events */
884   if (clients)
885     spi_atk_register_event_listeners ();
886
887   /* Set up filter and match rules to catch signals */
888   dbus_bus_add_match (spi_global_app_data->bus, "type='signal', interface='org.a11y.atspi.Registry', sender='org.a11y.atspi.Registry'", NULL);
889   dbus_bus_add_match (spi_global_app_data->bus, "type='signal', interface='org.a11y.atspi.DeviceEventListener', sender='org.a11y.atspi.Registry'", NULL);
890   dbus_connection_add_filter (spi_global_app_data->bus, signal_filter, NULL,
891                               NULL);
892
893   /* Register this app by sending a signal out to AT-SPI registry daemon */
894   if (!atspi_no_register && (!root || !ATK_IS_PLUG (root)))
895     register_application (spi_global_app_data);
896   else
897     get_registered_event_listeners (spi_global_app_data);
898
899   setup_bus();
900
901   return 0;
902 }
903
904 void
905 atk_bridge_adaptor_cleanup (void)
906 {
907   GList *l;
908   GSList *ls;
909
910   g_return_if_fail (inited);
911
912   if (!spi_global_app_data)
913       return;
914
915   spi_atk_tidy_windows ();
916   spi_atk_deregister_event_listeners ();
917
918   deregister_application (spi_global_app_data);
919
920   if (spi_global_app_data->bus)
921     {
922       dbus_connection_remove_filter (spi_global_app_data->bus, signal_filter, NULL);
923       droute_context_unregister (spi_global_app_data->droute, spi_global_app_data->bus);
924       dbus_connection_unref (spi_global_app_data->bus);
925     }
926
927   for (l = spi_global_app_data->direct_connections; l; l = l->next)
928     {
929       DBusConnection *connection;
930
931       connection = l->data;
932
933       droute_context_unregister (spi_global_app_data->droute, connection);
934       droute_unintercept_dbus (connection);
935       dbus_connection_unref (connection);
936     }
937   g_list_free (spi_global_app_data->direct_connections);
938
939   for (ls = clients; ls; ls = ls->next)
940     g_free (l->data);
941   g_slist_free (clients);
942   clients = NULL;
943
944   g_object_unref (spi_global_cache);
945   g_object_unref (spi_global_leasing);
946   g_object_unref (spi_global_register);
947
948   if (spi_global_app_data->main_context)
949     g_main_context_unref (spi_global_app_data->main_context);
950
951   droute_free (spi_global_app_data->droute);
952
953   g_free (spi_global_app_data);
954   spi_global_app_data = NULL;
955
956   inited = FALSE;
957 }
958
959 /*---------------------------------------------------------------------------*/
960
961 static gchar *name_match_tmpl =
962        "type='signal', interface='org.freedesktop.DBus', member='NameOwnerChanged', arg0='%s'";
963
964 void
965 spi_atk_add_client (const char *bus_name)
966 {
967   GSList *l;
968   gchar *match;
969
970   for (l = clients; l; l = l->next)
971   {
972     if (!g_strcmp0 (l->data, bus_name))
973       return;
974   }
975   if (!clients)
976     spi_atk_register_event_listeners ();
977   clients = g_slist_append (clients, g_strdup (bus_name));
978   match = g_strdup_printf (name_match_tmpl, bus_name);
979   dbus_bus_add_match (spi_global_app_data->bus, match, NULL);
980   g_free (match);
981 }
982
983 void
984 spi_atk_remove_client (const char *bus_name)
985 {
986   GSList *l;
987   GSList *next_node;
988
989   l = clients;
990   while (l)
991   {
992     next_node = l->next;
993
994     if (!g_strcmp0 (l->data, bus_name))
995     {
996       gchar *match = g_strdup_printf (name_match_tmpl, l->data);
997       dbus_bus_remove_match (spi_global_app_data->bus, match, NULL);
998   g_free (match);
999       g_free (l->data);
1000       clients = g_slist_delete_link (clients, l);
1001       if (!clients)
1002         spi_atk_deregister_event_listeners ();
1003     }
1004
1005     l = next_node;
1006   }
1007 }
1008
1009 /*END------------------------------------------------------------------------*/