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