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