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