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