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