2003-06-25 Padraig O'Briain <padraig.obriain@sun.com>
[platform/core/uifw/at-spi2-atk.git] / test / simple-at.c
1 /*
2  * AT-SPI - Assistive Technology Service Provider Interface
3  * (Gnome Accessibility Project; http://developer.gnome.org/projects/gap)
4  *
5  * Copyright 2001, 2002 Sun Microsystems Inc.,
6  * Copyright 2001, 2002 Ximian, Inc.
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the
20  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21  * Boston, MA 02111-1307, USA.
22  */
23 #include <stdio.h>
24 #include <strings.h>
25 #include <stdlib.h>
26 #include <ctype.h>
27 #include <unistd.h>
28 #include <sys/socket.h>
29 #include <netinet/in.h>
30 #include <sys/un.h>
31 #undef MAGNIFIER_ENABLED
32 #include "../cspi/spi-private.h" /* A hack for now */
33
34 #define PRINT_TREE
35
36 static void report_focus_event    (const AccessibleEvent *event, void *user_data);
37 static void report_generic_event  (const AccessibleEvent *event, void *user_data);
38 static void report_window_event  (const AccessibleEvent *event, void *user_data);
39 static void report_text_event     (const AccessibleEvent *event, void *user_data);
40 static void report_button_press   (const AccessibleEvent *event, void *user_data);
41 static void check_property_change (const AccessibleEvent *event, void *user_data);
42 static SPIBoolean report_command_key_event  (const AccessibleKeystroke *stroke, void *user_data);
43 static SPIBoolean report_ordinary_key_event (const AccessibleKeystroke *stroke, void *user_data);
44 static void get_environment_vars (void);
45
46 static int _festival_init ();
47 static void _festival_say (const char *text, const char *voice, SPIBoolean shutup);
48 static void _festival_write (const char *buff, int fd);
49
50 #ifdef PRINT_TREE
51 static void print_accessible_tree (Accessible *accessible, char *prefix);
52 #endif
53
54 #ifdef MAGNIFIER_ENABLED
55 static SPIBoolean use_magnifier = FALSE;
56 #endif
57
58 static SPIBoolean use_festival = FALSE;
59 static SPIBoolean festival_chatty = FALSE;
60 static SPIBoolean name_changed = FALSE;
61
62 static AccessibleEventListener *focus_listener;
63 static AccessibleEventListener *property_listener;
64 static AccessibleEventListener *generic_listener;
65 static AccessibleEventListener *window_listener;
66 static AccessibleEventListener *button_listener;
67 static AccessibleEventListener *text_listener;
68 static AccessibleKeystrokeListener *command_key_listener;
69 static AccessibleKeystrokeListener *ordinary_key_listener;
70 static AccessibleKeySet            *command_keyset;
71
72 int
73 main (int argc, char **argv)
74 {
75   int i, j;
76   int n_desktops;
77   int n_apps;
78   char *s;
79   Accessible *desktop;
80   Accessible *application;
81   const char *modules;
82
83   if ((argc > 1) && (!strncmp (argv[1], "-h", 2)))
84     {
85       printf ("Usage: simple-at\n");
86       printf ("\tEnvironment variables used:\n\t\tFESTIVAL\n\t\tMAGNIFIER\n\t\tFESTIVAL_CHATTY\n");
87       exit (0);
88     }
89
90   modules = g_getenv ("GTK_MODULES");
91   if (!modules || modules [0] == '\0')
92     {
93       putenv ("GTK_MODULES=");
94     }
95   modules = NULL;
96
97   SPI_init ();
98
99   focus_listener = SPI_createAccessibleEventListener (report_focus_event, NULL);
100   property_listener = SPI_createAccessibleEventListener (check_property_change, NULL); 
101   generic_listener = SPI_createAccessibleEventListener (report_generic_event, NULL); 
102   window_listener = SPI_createAccessibleEventListener (report_window_event, NULL); 
103   text_listener = SPI_createAccessibleEventListener (report_text_event, NULL); 
104   button_listener = SPI_createAccessibleEventListener (report_button_press, NULL);
105   SPI_registerGlobalEventListener (focus_listener, "focus:");
106   SPI_registerGlobalEventListener (property_listener, "object:property-change");
107 /* :accessible-selection"); */
108   SPI_registerGlobalEventListener (property_listener, "object:property-change:accessible-name");
109   SPI_registerGlobalEventListener (generic_listener, "object:selection-changed"); 
110   SPI_registerGlobalEventListener (generic_listener, "object:children-changed"); 
111   SPI_registerGlobalEventListener (generic_listener, "object:visible-data-changed"); 
112   SPI_registerGlobalEventListener (generic_listener, "object:text-selection-changed"); 
113   SPI_registerGlobalEventListener (text_listener, "object:text-caret-moved"); 
114   SPI_registerGlobalEventListener (text_listener, "object:text-changed"); 
115   SPI_registerGlobalEventListener (button_listener, "Gtk:GtkWidget:button-press-event");
116   SPI_registerGlobalEventListener (window_listener, "window:minimize");
117   n_desktops = SPI_getDesktopCount ();
118
119   for (i=0; i<n_desktops; ++i)
120     {
121       desktop = SPI_getDesktop (i);
122       s = Accessible_getName (desktop);
123       fprintf (stderr, "desktop %d name: %s\n", i, s);
124       SPI_freeString (s);
125       n_apps = Accessible_getChildCount (desktop);
126       for (j=0; j<n_apps; ++j)
127         {
128           application = Accessible_getChildAtIndex (desktop, j);
129           s = Accessible_getName (application);
130           fprintf (stderr, "app %d name: %s\n", j, s);
131 #ifdef PRINT_TREE
132           print_accessible_tree (application, "*");
133 #endif
134           SPI_freeString (s);
135           Accessible_unref (application);
136         }
137       Accessible_unref (desktop);
138     }
139
140   /* prepare the keyboard snoopers */
141   command_key_listener = SPI_createAccessibleKeystrokeListener (report_command_key_event, NULL);
142   ordinary_key_listener = SPI_createAccessibleKeystrokeListener (report_ordinary_key_event, NULL);
143
144   command_keyset = SPI_createAccessibleKeySet (11, "qmf23456789", NULL, NULL);
145   
146   /* will listen only to Control-Alt-q KeyPress events */
147   SPI_registerAccessibleKeystrokeListener(command_key_listener,
148                                           command_keyset,
149                                           SPI_KEYMASK_ALT | SPI_KEYMASK_CONTROL,
150                                           (unsigned long) ( SPI_KEY_PRESSED ),
151                                           SPI_KEYLISTENER_ALL_WINDOWS);
152
153   /* will listen only to CAPSLOCK key events, both press and release */
154   SPI_registerAccessibleKeystrokeListener(ordinary_key_listener,
155                                           (AccessibleKeySet *) SPI_KEYSET_ALL_KEYS,
156                                           SPI_KEYMASK_SHIFTLOCK,
157                                           (unsigned long) ( SPI_KEY_PRESSED | SPI_KEY_RELEASED ),
158                                           SPI_KEYLISTENER_NOSYNC);
159
160   get_environment_vars ();
161
162   SPI_event_main ();
163
164   putenv ("AT_BRIDGE_SHUTDOWN=1");
165
166   return SPI_exit ();
167 }
168
169 static void
170 get_environment_vars (void)
171 {
172   if (g_getenv ("FESTIVAL"))
173     {
174       fprintf (stderr, "Using festival\n");
175       use_festival = TRUE;
176       if (g_getenv ("FESTIVAL_CHATTY"))
177         {
178           festival_chatty = TRUE;
179         }
180     }
181 #ifdef MAGNIFIER_ENABLED
182   if (g_getenv ("MAGNIFIER"))
183     {
184       fprintf (stderr, "Using magnifier\n");
185       use_magnifier = TRUE;
186     }  
187   else
188     {
189       fprintf (stderr, "Not using magnifier\n");
190     }
191 #endif
192
193   if (!use_festival)
194     {
195       fprintf (stderr, "No speech output\n");
196     }
197 }
198
199 #ifdef PRINT_TREE
200 static void
201 print_accessible_tree (Accessible *accessible, char *prefix)
202 {
203         int n_children;
204         int i;
205         char *name;
206         char *role_name;
207         char *parent_name = NULL;
208         char *parent_role = NULL;
209         char child_prefix[100];
210         Accessible *child;
211         Accessible *parent;
212         
213         strncpy (child_prefix, prefix, 98);
214         strcat (child_prefix, "*");
215         parent = Accessible_getParent (accessible);
216         if (parent)
217           {
218                 parent_name = Accessible_getName (parent);
219                 parent_role = Accessible_getRoleName (parent);
220                 Accessible_unref (parent);
221           }
222         name = Accessible_getName (accessible);
223         role_name = Accessible_getRoleName (accessible);
224         fprintf (stdout, "%sAccessible [%s] \"%s\"; parent [%s] %s.\n",
225                  prefix, role_name, name, parent_role, parent_name);
226         SPI_freeString (name);
227         SPI_freeString (role_name);
228         SPI_freeString (parent_name);
229         SPI_freeString (parent_role);
230         n_children = Accessible_getChildCount (accessible);
231         for (i = 0; i < n_children; ++i)
232                 {
233                         child = Accessible_getChildAtIndex (accessible, i);
234                         print_accessible_tree (child, child_prefix);
235                         Accessible_unref (child);
236                 }
237 }
238 #endif
239
240 void
241 report_focussed_accessible (Accessible *obj, SPIBoolean shutup_previous_speech)
242 {
243   char *s;
244   int len;
245   long x, y, width, height;
246   /* hack for GUADEC demo, to make sure name changes are spoken */
247   shutup_previous_speech = (shutup_previous_speech && !name_changed);
248
249   if (use_festival)
250     {
251       if (festival_chatty)          
252         {
253           s = Accessible_getRoleName (obj);     
254           _festival_say (s, "voice_don_diphone", shutup_previous_speech);
255           SPI_freeString (s);
256         }
257       fprintf (stderr, "getting Name\n");
258       s = Accessible_getName (obj);
259       _festival_say (s, "voice_kal_diphone",
260                      shutup_previous_speech || festival_chatty);
261       SPI_freeString (s);
262     }
263   
264   if (Accessible_isComponent (obj))
265     {
266       AccessibleComponent *component = Accessible_getComponent (obj);
267       AccessibleComponent_getExtents (component, &x, &y, &width, &height,
268                                       SPI_COORD_TYPE_SCREEN);
269       fprintf (stderr, "Bounding box: (%ld, %ld) ; (%ld, %ld)\n",
270                x, y, x+width, y+height);
271       if (Accessible_isText (obj))
272         {
273           long x0, y0, xN, yN, w0, h0, wN, hN, nchars;
274           AccessibleText *text = Accessible_getText (obj);
275           nchars = AccessibleText_getCharacterCount (text);
276           if (nchars > 0) 
277             {
278               AccessibleText_getCharacterExtents (text, 0, &x0, &y0, &w0, &h0,
279                                               SPI_COORD_TYPE_SCREEN);
280               AccessibleText_getCharacterExtents (text, nchars-1, &xN, &yN, &wN, &hN, 
281                                                   SPI_COORD_TYPE_SCREEN);
282               x = MIN (x0, xN);
283               width = MAX (x0 + w0, xN + wN) - x;
284               fprintf (stderr, "Text bounding box: (%ld, %ld) ; (%ld, %ld)\n",
285                        x, y, x+width, y+height);
286             }
287         }
288 #ifdef MAGNIFIER_ENABLED
289       if (use_magnifier) {
290         magnifier_set_roi ((short) 0, x, y, width, height);
291       }
292 #endif
293     }
294
295
296   if (Accessible_isValue (obj))
297     {
298       AccessibleValue *value = Accessible_getValue (obj);
299       fprintf (stderr, "Current value = %f, min = %f; max = %f\n",
300                AccessibleValue_getCurrentValue (value),
301                AccessibleValue_getMinimumValue (value),
302                AccessibleValue_getMaximumValue (value));
303     }
304   /* if this is a text object, speak the first sentence. */
305
306   if (Accessible_isText(obj))
307
308   {
309      AccessibleText *text_interface;
310      long start_offset, end_offset;
311      char *first_sentence = "empty";
312      text_interface = Accessible_getText (obj);
313      first_sentence = AccessibleText_getTextAtOffset (
314                text_interface, (long) 0, SPI_TEXT_BOUNDARY_SENTENCE_START, &start_offset, &end_offset);
315      if (first_sentence && use_festival)
316        {
317          _festival_say(first_sentence, "voice_don_diphone", FALSE);
318          SPI_freeString (first_sentence);
319        }
320      len = AccessibleText_getCharacterCount (text_interface);
321      s = AccessibleText_getText (text_interface, 0, len);
322      fprintf (stderr, "done reporting on focussed object, text=%s\n", s);
323   }
324 }
325
326 void
327 report_focus_event (const AccessibleEvent *event, void *user_data)
328 {
329   char *s;
330
331   g_return_if_fail (event->source != NULL);
332   s = Accessible_getName (event->source);
333   if (s)
334     {
335       fprintf (stderr, "%s event from %s\n", event->type, s);
336       SPI_freeString (s);
337       report_focussed_accessible (event->source, TRUE);
338     }
339   Accessible_getParent (event->source);
340   name_changed = FALSE;
341 }
342
343 void
344 report_generic_event (const AccessibleEvent *event, void *user_data)
345 {
346   fprintf (stderr, "%s event received\n", event->type);
347 }
348
349 void
350 report_window_event (const AccessibleEvent *event, void *user_data)
351 {
352   fprintf (stderr, "%s event received\n", event->type);
353 }
354
355 void
356 report_text_event (const AccessibleEvent *event, void *user_data)
357 {
358   AccessibleText *text = Accessible_getText (event->source);
359   fprintf (stderr, "%s event received\n", event->type);
360 #ifdef MAGNIFIER_ENABLED
361   if (use_magnifier && strcmp (event->type, "object:text-changed"))
362     {
363       long offset = AccessibleText_getCaretOffset (text);
364       long x, y, w, h;
365       fprintf (stderr, "offset %d\n", (int) offset);
366       AccessibleText_getCharacterExtents (text, offset, &x, &y, &w, &h, 
367                                           SPI_COORD_TYPE_SCREEN);
368       fprintf (stderr, "new roi %d %d %d %d\n", (int) x, (int) y, (int) w, (int) h);
369       magnifier_set_roi ((short) 0, x, y, w, h);
370     }
371 #endif
372   if (!strcmp (event->type, "object:text-changed"))
373     {
374       long start, end;
375       char *new_text = AccessibleText_getTextAtOffset (text, (long) event->detail1, SPI_TEXT_BOUNDARY_WORD_START, &start, &end);
376       _festival_say (new_text, "voice_kal_diphone", FALSE);
377       fprintf (stderr, "text changed: %s", new_text ? new_text : "");
378       SPI_freeString (new_text);
379     }
380   else
381     {
382       long start, end;
383       char *word_text = AccessibleText_getTextAtOffset (text, (long) event->detail1, SPI_TEXT_BOUNDARY_WORD_START, &start, &end);
384       char *sentence_text = AccessibleText_getTextAtOffset (text, (long) event->detail1, SPI_TEXT_BOUNDARY_SENTENCE_START, &start, &end);
385       fprintf (stderr, "text changed: word %s; sentence %s at %d",
386                (word_text ? word_text : ""),
387                (sentence_text ? sentence_text : ""),
388                event->detail1);
389       if (word_text) SPI_freeString (word_text);
390       if (sentence_text) SPI_freeString (sentence_text);
391     }
392 }
393
394 void
395 report_button_press (const AccessibleEvent *event, void *user_data)
396 {
397   char *s;
398
399   g_return_if_fail (event->source != NULL);
400
401   s = Accessible_getName (event->source);
402
403   fprintf (stderr, "%s event from %s\n", event->type, s);
404   SPI_freeString (s);
405   s = Accessible_getDescription (event->source);
406   fprintf (stderr, "Object description %s\n", s);
407   SPI_freeString (s);
408 }
409
410 void
411 check_property_change (const AccessibleEvent *event, void *user_data)
412 {
413   AccessibleSelection *selection = Accessible_getSelection (event->source);
414   int n_selections;
415   int i;
416   char *s;
417   fprintf (stderr, "property change event!\n");
418   if (selection)
419   {
420     n_selections = (int) AccessibleSelection_getNSelectedChildren (selection);
421     s = Accessible_getName (event->source);
422     fprintf (stderr, "(Property) %s event from %s, %d selected children\n",
423              event->type, s, n_selections);
424     SPI_freeString (s);
425   /* for now, speak entire selection set */
426     for (i=0; i<n_selections; ++i)
427       {
428         Accessible *obj = AccessibleSelection_getSelectedChild (selection, (long) i);
429         g_return_if_fail (obj);
430         s = Accessible_getName (obj);
431         fprintf (stderr, "Child %d, name=%s\n", i, s);
432         SPI_freeString (s);
433         report_focussed_accessible (obj, i==0);
434     }
435   }
436   else if (!strcmp (event->type, "object:property-change:accessible-name"))
437     {
438       name_changed = TRUE;          
439       report_focussed_accessible (event->source, TRUE);
440     }
441   else
442     {
443       fprintf (stderr, "Property change %s received\n", event->type);
444     }
445 }
446
447 static void
448 simple_at_exit ()
449 {
450   SPI_deregisterGlobalEventListenerAll (focus_listener);
451   AccessibleEventListener_unref        (focus_listener);
452
453   SPI_deregisterGlobalEventListenerAll (property_listener);
454   AccessibleEventListener_unref        (property_listener);
455
456   SPI_deregisterGlobalEventListenerAll (generic_listener);
457   AccessibleEventListener_unref        (generic_listener);
458
459   SPI_deregisterGlobalEventListenerAll (text_listener);
460   AccessibleEventListener_unref        (text_listener);
461
462   SPI_deregisterGlobalEventListenerAll (button_listener);
463   AccessibleEventListener_unref        (button_listener);
464
465   SPI_deregisterAccessibleKeystrokeListener (command_key_listener, SPI_KEYMASK_ALT | SPI_KEYMASK_CONTROL);
466   AccessibleKeystrokeListener_unref         (command_key_listener);
467   SPI_freeAccessibleKeySet                  (command_keyset);
468
469   SPI_deregisterAccessibleKeystrokeListener (ordinary_key_listener, SPI_KEYMASK_SHIFTLOCK);
470   AccessibleKeystrokeListener_unref         (ordinary_key_listener);
471
472   SPI_event_quit ();
473 }
474
475 static SPIBoolean
476 is_command_key (const AccessibleKeystroke *key)
477 {
478   switch (key->keyID)
479     {
480     case 'Q':
481     case 'q':
482             simple_at_exit(); 
483             return TRUE; /* not reached */
484 #ifdef MAGNIFIER_ENABLED
485     case 'M':
486     case 'm':
487             use_magnifier = ! use_magnifier;
488             fprintf (stderr, "%ssing magnifier\n", use_magnifier ? "U" : "Not u");
489             return TRUE;
490 #endif
491     case 'F':
492     case 'f':
493             use_festival = ! use_festival;
494             fprintf (stderr, "%speech output\n", use_festival ? "S" : "No s");
495             return TRUE;
496     default:
497             return FALSE;
498     }
499 }
500
501 static SPIBoolean
502 report_command_key_event (const AccessibleKeystroke *key, void *user_data)
503 {
504   fprintf (stderr, "Command KeyEvent %s%c (keycode %d); string=%s; time=%lx\n",
505           (key->modifiers & SPI_KEYMASK_ALT)?"Alt-":"",
506           ((key->modifiers & SPI_KEYMASK_SHIFT)^(key->modifiers & SPI_KEYMASK_SHIFTLOCK))?
507           (char) toupper((int) key->keyID) : (char) tolower((int) key->keyID),
508           (int) key->keycode,
509           key->keystring,
510           (long int) key->timestamp);
511   return is_command_key (key);
512 }
513
514
515 static SPIBoolean
516 report_ordinary_key_event (const AccessibleKeystroke *key, void *user_data)
517 {
518   fprintf (stderr, "Received key event:\tsym %ld\n\tmods %x\n\tcode %d\n\tstring=\'%s\'\n\ttime %lx\n",
519            (long) key->keyID,
520            (unsigned int) key->modifiers,
521            (int) key->keycode,
522            key->keystring,
523            (long int) key->timestamp);
524   return FALSE;
525 }
526
527 static int
528 _festival_init ()
529 {
530   int fd;
531   struct sockaddr_in name;
532   int tries = 2;
533
534   name.sin_family = AF_INET;
535   name.sin_port = htons (1314);
536   name.sin_addr.s_addr = htonl(INADDR_ANY);
537   fd = socket (PF_INET, SOCK_STREAM, 0);
538
539   while (connect(fd, (struct sockaddr *) &name, sizeof (name)) < 0) {
540     if (!tries--) {
541       perror ("connect");
542       return -1;
543     }
544   }
545
546   _festival_write ("(audio_mode'async)\n", fd);
547   _festival_write ("(Parameter.set 'Duration_Model 'Tree_ZScore)\n", fd);
548   _festival_write ("(Parameter.set 'Duration_Stretch 0.75)\n", fd);
549   return fd;
550 }
551
552 static void 
553 _festival_say (const char *text, const char *voice, SPIBoolean shutup)
554 {
555   static int fd = 0;
556   gchar *quoted;
557   gchar *p;
558   gchar prefix[50];
559   static gchar voice_spec[32];
560   
561   if (!fd)
562     {
563       fd = _festival_init ();
564     }
565
566   fprintf (stderr, "saying text: %s\n", text);
567   
568   quoted = g_malloc(64+strlen(text)*2);
569
570   sprintf (prefix, "(SayText \"");
571
572   strncpy(quoted, prefix, 10);
573   p = quoted+strlen(prefix);
574   while (*text) {
575     if ( *text == '\\' || *text == '"' )
576       *p = '\\';
577     *p++ = *text++;
578   }
579   *p++ = '"';
580   *p++ = ')';
581   *p++ = '\n';
582   *p = 0;
583
584   if (shutup) _festival_write ("(audio_mode'shutup)\n", fd);
585   if (voice && (strncmp (voice, (char *) (voice_spec+1), strlen(voice))))
586     {
587       snprintf (voice_spec, 32, "(%s)\n", voice); 
588       _festival_write (voice_spec, fd);
589       _festival_write ("(Parameter.set 'Duration_Model 'Tree_ZScore)\n", fd);
590       _festival_write ("(Parameter.set 'Duration_Stretch 0.75)\n", fd);
591     }
592
593   _festival_write (quoted, fd);
594
595   g_free(quoted);
596 }
597
598 static void
599 _festival_write (const gchar *command_string, int fd)
600 {
601   fprintf(stderr, command_string);
602   if (fd < 0) {
603     perror("socket");
604     return;
605   }
606   write(fd, command_string, strlen(command_string));
607 }
608