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