482180be34ad7ce3dc647a9341c1dd7b1aa20c45
[platform/core/uifw/at-spi2-atk.git] / test / screen-review-test.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
24 #include <stdio.h>
25 #include <string.h>
26 #include <stdlib.h>
27 #include "../cspi/spi-private.h"
28
29 #undef CLIP_DEBUG
30
31 /*
32  * Screen Review Algorithm Demonstration, Benchmark, and Test-bed.
33  *
34  * Issues:
35  *
36  * * there are bugs in the compositing code.
37  *
38  * * brute-force algorithm uses no client-side cache; performance mediocre.
39  *
40  * * we don't have good ordering information for the toplevel windows,
41  *          and our current heuristic is not guaranteed if
42  *          the active window is not always on top (i.e. autoraise is
43  *          not enabled).
44  *
45  * * can't know about "inaccessible" objects that may be obscuring the
46  *          accessible windows (inherent to API-based approach).
47  *
48  * * text column alignment is crude since it relies on a hard-coded
49  *          (and arbitrary) ratio of horizontal pixels to character columns.
50  *          For small proportional fonts, overruns are likely to result in
51  *          occasional review lines that exceed the standard length.
52  *
53  * * (others).
54  */
55
56 #undef CHUNK_LIST_DEBUG /* define to get list of text chunks before clip */
57
58 #define BOUNDS_CONTAIN_X_BOUNDS(b, p)  ( ((p).x>=(b).x) &&\
59                                          (((p).x + (p).width) <= \
60                                          ((b).x + (b).width)) && \
61                                         ((b).width > 0) && ((b).height > 0))
62
63 #define BOUNDS_CONTAIN_Y(b, p)  (((p)>=(b)->y) && ((p)<=((b)->y + (b)->height))\
64             && ((b)->width > 0) && ((b)->height > 0))
65
66 #define CHUNK_BOUNDS_BEFORE_START(c, i) ((i) && ((c)->clip_bounds.x < \
67                                          (i)->clip_bounds.x)) 
68
69 #define CHUNK_BOUNDS_END_BEFORE_START(c, i) ((i) && \
70                                          (((c)->clip_bounds.x + \
71                                          (c)->clip_bounds.width) < \
72                                          (i)->clip_bounds.x))
73
74 #define CHUNK_BOUNDS_AFTER_END(c, i) ((i) && ((c)->clip_bounds.x >= \
75                                        ((i)->clip_bounds.x + \
76                                         (i)->clip_bounds.width)))
77
78 #define CHUNK_BOUNDS_SPANS_END(c, i) ((i) && (((c)->clip_bounds.x + \
79                                               (c)->clip_bounds.width) >= \
80                                        ((i)->clip_bounds.x + \
81                                         (i)->clip_bounds.width)))
82 /*
83  * #define CHUNK_BOUNDS_WITHIN(c, i)  ((i) && ((c)->clip_bounds.x >= \
84  *                               (i)->text_bounds.x) && \
85  *                               (((c)->clip_bounds.x + (c)->clip_bounds.width) \
86  *                             <= ((i)->text_bounds.x + (i)->text_bounds.width)))
87  */
88
89 #define IS_CLIPPING_CONTAINER(a) ((a) != SPI_ROLE_PAGE_TAB)
90
91 static void report_screen_review_line  (const AccessibleEvent *event, void *user_data);
92
93 static gint n_elements_traversed = 0;
94 static AccessibleEventListener *mouseclick_listener;
95
96 typedef struct _BoundaryRect {
97         long int x;
98         long int y;
99         long int width;
100         long int height;
101         AccessibleRole role; /* role of last clipping element */
102         gboolean isClipped;
103         gboolean isEmpty;
104 } BoundaryRect;
105
106 typedef struct _TextChunk {
107         char           *string;
108         Accessible     *source;
109         int             start_offset;
110         int             end_offset;
111         BoundaryRect    clip_bounds;
112         BoundaryRect    text_bounds;
113         BoundaryRect    start_char_bounds;
114         BoundaryRect    end_char_bounds;
115 } TextChunk;
116
117 typedef struct _ScreenReviewBuffer { 
118         GList *text_chunks;
119 } ScreenReviewBuffer;
120
121 static gboolean isJava = FALSE;
122
123 int
124 main (int argc, char **argv)
125 {
126   int i, j;
127   int n_desktops;
128   int n_apps;
129   char *s;
130   GTimer *timer;
131   gdouble elapsed_time;
132   Accessible *desktop;
133   Accessible *application;
134   const char *modules;
135
136   SPI_init ();
137
138   mouseclick_listener = SPI_createAccessibleEventListener (
139           report_screen_review_line, NULL); 
140
141   SPI_registerGlobalEventListener (mouseclick_listener,
142                                    "Gtk:GtkWidget:button-press-event");
143 #undef JAVA_TEST_HACK
144 #ifdef JAVA_TEST_HACK /* Only use this to test Java apps */
145   SPI_registerGlobalEventListener (mouseclick_listener,
146                                    "object:text-caret-moved");
147   isJava = TRUE;
148 #endif
149   SPI_event_main ();
150
151   putenv ("AT_BRIDGE_SHUTDOWN=1");
152
153   /*
154    * TODO: Add a key event listener that calls test_exit, to
155    * deregister and cleanup appropriately.
156    */
157
158   return SPI_exit ();
159 }
160
161 static inline gboolean
162 chunk_bounds_within (TextChunk *chunk, TextChunk *test_chunk)
163 {
164         int x1, tx1;
165         gboolean gtx1, ltx2;
166
167         x1 = chunk->clip_bounds.x;
168         tx1 = test_chunk->clip_bounds.x;
169         gtx1 = (chunk->clip_bounds.x >= test_chunk->clip_bounds.x);
170         ltx2 = (chunk->clip_bounds.x + chunk->clip_bounds.width
171                 <= test_chunk->clip_bounds.x + test_chunk->clip_bounds.width);
172         return gtx1 && ltx2;
173 }
174
175 #define CHUNK_BOUNDS_WITHIN(a, b) chunk_bounds_within(a, b)
176
177 static BoundaryRect **
178 clip_bounds_clone (BoundaryRect *bounds[])
179 {
180         int i;
181         BoundaryRect **bounds_clone;
182         bounds_clone = (BoundaryRect **)
183                 g_new0 (gpointer, SPI_LAYER_LAST_DEFINED);
184         for (i = 1; i < SPI_LAYER_LAST_DEFINED; ++i) {
185                 bounds_clone[i] = g_new0 (BoundaryRect, 1);
186                 *bounds_clone[i] = *bounds[i];
187         }
188         return bounds_clone;
189 }
190
191 static void
192 boundary_clip (BoundaryRect *bounds, BoundaryRect *clipBounds)
193 {
194         int x2 = bounds->x + bounds->width;
195         int y2 = bounds->y + bounds->height;
196 #ifdef CLIP_DEBUG
197         fprintf (stderr, "bclip %d-%d, %d-%d; ",
198                  bounds->x, x2,
199                  clipBounds->x, clipBounds->x+clipBounds->width);
200 #endif           
201         bounds->x = MAX (bounds->x, clipBounds->x);
202         bounds->y = MAX (bounds->y, clipBounds->y);
203         x2 =  MIN (x2,  clipBounds->x + clipBounds->width);
204         y2 =  MIN (y2, clipBounds->y + clipBounds->height);
205         bounds->width = MAX (x2 - bounds->x, 0);
206         bounds->height = MAX (y2 - bounds->y, 0);
207         if (!bounds->width || !bounds->height)
208                 bounds->isEmpty = TRUE;
209         if (IS_CLIPPING_CONTAINER (bounds->role)) {
210                 *clipBounds = *bounds;
211         }
212 #ifdef CLIP_DEBUG
213         fprintf (stderr, "%d-%d\n",
214                  bounds->x, bounds->x+bounds->width);
215 #endif
216 }
217
218 static void
219 boundary_xclip_head (BoundaryRect *bounds, BoundaryRect *clipBounds)
220 {
221         int x2;
222         int cx2 = clipBounds->x + clipBounds->width;
223         if (cx2 < bounds->x) return;
224         x2 = bounds->x + bounds->width;
225         if (cx2 <= x2) bounds->x = cx2;
226         bounds->width = MAX (0, x2 - cx2);
227 }
228
229 static void
230 boundary_xclip_tail (BoundaryRect *bounds, BoundaryRect *clipBounds)
231 {
232         int x2 = bounds->x + bounds->width;
233         if (clipBounds->x > x2) return;
234         bounds->width = MAX (0, clipBounds->x - bounds->x);
235 }
236
237 static TextChunk*
238 text_chunk_copy (TextChunk *chunk)
239 {
240         TextChunk *copy = g_new0 (TextChunk, 1);
241         *copy = *chunk;
242         if (chunk->string) copy->string = g_strdup (chunk->string);
243         if (copy->source) Accessible_ref (copy->source);
244         return copy;
245 }
246
247 static void
248 text_chunk_tail_clip (TextChunk *bottom, TextChunk *top)
249 {
250 #ifdef CLIP_DEBUG
251         fprintf (stderr, "bottom %d-%d, top %d-%d;",
252                  bottom->clip_bounds.x,
253                  bottom->clip_bounds.x + bottom->clip_bounds.width,
254                  top->clip_bounds.x,
255                  top->clip_bounds.x + top->clip_bounds.width);
256 #endif
257         boundary_xclip_tail (&bottom->text_bounds, &top->clip_bounds);
258         boundary_xclip_tail (&bottom->clip_bounds, &top->clip_bounds);
259         bottom->text_bounds.isClipped = TRUE;
260         bottom->clip_bounds.isClipped = TRUE;
261 #ifdef CLIP_DEBUG
262         fprintf (stderr, "result %d-%d\n",
263                  bottom->clip_bounds.x,
264                  bottom->clip_bounds.x + bottom->clip_bounds.width);
265 #endif
266 }
267
268 static void
269 text_chunk_head_clip (TextChunk *bottom, TextChunk *top)
270 {
271 #ifdef CLIP_DEBUG
272         fprintf (stderr, "bottom %d-%d, top %d-%d;",
273                  bottom->clip_bounds.x,
274                  bottom->clip_bounds.x + bottom->clip_bounds.width,
275                  top->clip_bounds.x,
276                  top->clip_bounds.x + top->clip_bounds.width);
277 #endif  
278         boundary_xclip_head (&bottom->text_bounds, &top->clip_bounds);
279         boundary_xclip_head (&bottom->clip_bounds, &top->clip_bounds);
280         bottom->text_bounds.isClipped = TRUE;
281         bottom->clip_bounds.isClipped = TRUE;
282 #ifdef CLIP_DEBUG       
283         fprintf (stderr, "result %d-%d\n",
284                  bottom->clip_bounds.x,
285                  bottom->clip_bounds.x + bottom->clip_bounds.width);
286 #endif  
287 }
288
289 static GList *
290 text_chunk_split_insert (GList *chunk_list, GList *iter, TextChunk *chunk)
291 {
292         TextChunk *iter_chunk = iter->data;
293         TextChunk *iter_copy = text_chunk_copy (iter_chunk);
294         /* TODO: FIXME something is wrong here */
295 #ifdef CLIP_DEBUG
296         fprintf (stderr, "***clip insert of %s into %s\n", 
297                  chunk->string ? chunk->string : "<null>",
298                  iter_chunk->string ? iter_chunk->string : "<null>");
299 #endif  
300         chunk_list = g_list_insert_before (chunk_list, iter, iter_copy);
301         text_chunk_tail_clip (iter_copy, chunk);
302         chunk_list = g_list_insert_before (chunk_list, iter, chunk);
303         text_chunk_head_clip (iter_chunk, chunk);
304         return chunk_list;
305 }
306
307 /* #define PRINT_CHUNK_DEBUG(a, b, c, d) print_chunk_debug(a, b, c, d) */
308
309 #define PRINT_CHUNK_DEBUG(a, b, c, d)
310
311 #ifdef PRINT_CHUNK_DEBUG
312 static void
313 print_chunk_debug (TextChunk *chunk, char *opname, GList *prev, GList *next)
314 {
315         fprintf (stderr, "%sing chunk %s between %s and %s; %d-%d\n",
316                  opname,
317                  chunk->string,
318                  (prev ? ((TextChunk *) prev->data)->string : "<null>"),
319                  (next ? ((TextChunk *) next->data)->string : "<null>"),
320                  chunk->clip_bounds.x,
321                  chunk->text_bounds.x + chunk->text_bounds.width);
322 }
323 #endif
324
325 static GList *
326 text_chunk_list_head_clip (GList *text_chunk_list,
327                            TextChunk *chunk,
328                            GList *next)
329 {
330         GList *target, *iter = next, *prev;
331         prev = iter->prev;
332 /*      if (chunk->string && strlen (chunk->string)) { */
333                 text_chunk_list =
334                         g_list_insert_before (text_chunk_list, next, chunk);
335 /*      }*/
336         while (iter && CHUNK_BOUNDS_SPANS_END (chunk, (TextChunk *)iter->data)) {
337 #ifdef CLIP_DEBUG                       
338                         fprintf (stderr, "deleting %s\n",
339                                  ((TextChunk *)iter->data)->string);
340 #endif                  
341                         target = iter;
342                         iter = iter->next;
343                         text_chunk_list =
344                                 g_list_delete_link (text_chunk_list, target);
345         }
346         if (iter && !CHUNK_BOUNDS_END_BEFORE_START (chunk,
347                                                     (TextChunk *)iter->data)) {
348                 text_chunk_head_clip ((TextChunk *)iter->data,
349                                       chunk);
350         }
351         if (prev &&
352             !CHUNK_BOUNDS_AFTER_END (
353                     chunk,
354                     (TextChunk *)prev->data)) {
355                 text_chunk_tail_clip (
356                         (TextChunk *)prev->data,
357                         chunk);
358         }
359         
360         return text_chunk_list;
361 }
362
363 static GList *
364 text_chunk_list_clip_and_insert (GList *text_chunk_list,
365                                  TextChunk *chunk,
366                                  GList *prev,
367                                  GList *next)
368 {
369 #ifdef CLIP_DEBUG
370 /*      if (chunk->string) */
371                 fprintf (stderr, "clip-and-insert for %s, between %s (%d) and %s (%d)\n",
372                          chunk->string,
373                          (prev && ((TextChunk *)prev->data)->string ? ((TextChunk *)prev->data)->string : "<null>"),
374                          (prev ? ((TextChunk *)prev->data)->text_bounds.x : -1),
375                          (next && ((TextChunk *)next->data)->string ? ((TextChunk *)next->data)->string : "<null>"),
376                          (next ? ((TextChunk *)next->data)->text_bounds.x : -1));
377 #endif
378         /* cases: */
379         if (!prev && !next) { /* first element in, no clip needed */
380                 text_chunk_list =
381                         g_list_append (text_chunk_list, chunk);
382                 PRINT_CHUNK_DEBUG (chunk, "append",
383                                    prev,
384                                    NULL);
385         } else { /* check for clip with prev */
386                 /* if we split the prev */
387                 if (prev &&
388                     CHUNK_BOUNDS_WITHIN (chunk, (TextChunk *) prev->data)) {
389                         text_chunk_list =
390                                 text_chunk_split_insert (
391                                         text_chunk_list,
392                                         prev, chunk);
393                 } else if (next) { 
394                     /* we split the 'next' element */
395                     if (CHUNK_BOUNDS_WITHIN (chunk, (TextChunk *)next->data)) {
396                             text_chunk_list =
397                                     text_chunk_split_insert (text_chunk_list,
398                                                              next, chunk);
399                     } else {
400                             /* do an insert +  head clip */
401                             text_chunk_list =
402                                     text_chunk_list_head_clip (
403                                             text_chunk_list,
404                                             chunk,
405                                             next);
406                     }
407                 } else {
408                         if (!CHUNK_BOUNDS_AFTER_END (chunk,
409                                                      (TextChunk *) prev->data)) {
410                                 text_chunk_tail_clip (prev->data, chunk);
411                         }
412                         text_chunk_list =
413                                 g_list_append (text_chunk_list, chunk);
414                 }
415         }
416         return text_chunk_list;
417 }
418
419 static GList *
420 text_chunk_list_insert_chunk (GList *text_chunk_list, TextChunk *chunk)
421 {
422         GList *iter = g_list_first (text_chunk_list);
423         TextChunk *iter_chunk = NULL;
424         do {
425                 if (iter) iter_chunk = (TextChunk *) iter->data;
426                 /* if we're ahead of the current element */
427                 if (!iter) {
428                         text_chunk_list =
429                                 text_chunk_list_clip_and_insert (text_chunk_list,
430                                                                  chunk,
431                                                                  iter,
432                                                                  NULL);
433                         break;
434                 } else if (CHUNK_BOUNDS_BEFORE_START (chunk, iter_chunk)) {
435                         text_chunk_list =
436                                 text_chunk_list_clip_and_insert (text_chunk_list,
437                                                                  chunk,
438                                                                  iter->prev,
439                                                                  iter);
440                         break;
441                 } else if (!iter->next ) {
442                         text_chunk_list =
443                                 text_chunk_list_clip_and_insert (text_chunk_list,
444                                                                  chunk,
445                                                                  iter,
446                                                                  NULL);
447                         break;
448                 }
449                 if (iter) iter = iter->next;
450         } while (iter);
451         return text_chunk_list;
452 }
453
454 static TextChunk *
455 review_buffer_get_text_chunk (ScreenReviewBuffer *reviewBuffer,
456                               Accessible *accessible, BoundaryRect *bounds,
457                               int screen_x, int screen_y)
458 {
459         AccessibleText *text = NULL;
460         AccessibleRole role;
461         TextChunk *text_chunk;
462         BoundaryRect start_char_bounds, end_char_bounds;
463         char *s = NULL;
464         int offset;
465         long start, end;
466         long x2, y2;
467
468         role = Accessible_getRole (accessible);
469         text_chunk = g_new0 (TextChunk, 1);
470         text_chunk->clip_bounds = *bounds;
471         text_chunk->source = accessible;
472         Accessible_ref (accessible);
473         if (Accessible_isText (accessible)) {
474                 text = Accessible_getText (accessible);
475                 offset = AccessibleText_getOffsetAtPoint (text,
476                                                           screen_x,
477                                                           screen_y,
478                                                           SPI_COORD_TYPE_SCREEN);
479                 s = AccessibleText_getTextAtOffset (text, offset,
480                                                     SPI_TEXT_BOUNDARY_LINE_START,
481                                                     &start, &end);
482                 if (end > start) {
483                         AccessibleText_getCharacterExtents (
484                                 text, start,
485                                 &text_chunk->start_char_bounds.x,
486                                 &text_chunk->start_char_bounds.y,
487                                 &text_chunk->start_char_bounds.width,
488                                 &text_chunk->start_char_bounds.height,
489                                 SPI_COORD_TYPE_SCREEN);
490 #ifdef CLIP_DEBUG
491                         fprintf (stderr, "%s: start char (%d) x, width %d %d; ",
492                                  s,
493                                  start,
494                                  text_chunk->start_char_bounds.x,
495                                  text_chunk->start_char_bounds.width);
496 #endif
497                         if (s && strlen (s) && s[strlen (s) - 1] == '\n')
498                                 end--;
499                         AccessibleText_getCharacterExtents (
500                                 text, end - 1,
501                                 &text_chunk->end_char_bounds.x,
502                                 &text_chunk->end_char_bounds.y,
503                                 &text_chunk->end_char_bounds.width,
504                                 &text_chunk->end_char_bounds.height,
505                                 SPI_COORD_TYPE_SCREEN);
506 #ifdef CLIP_DEBUG                       
507                         fprintf (stderr, "end char (%d) x, width %d %d\n",
508                                  end - 1,
509                                  text_chunk->end_char_bounds.x,
510                                  text_chunk->end_char_bounds.width);
511 #endif
512                 }
513                 text_chunk->text_bounds.x = MIN (text_chunk->start_char_bounds.x,
514                                                  text_chunk->end_char_bounds.x);
515                 text_chunk->text_bounds.y = MIN (text_chunk->start_char_bounds.y,
516                                                  text_chunk->end_char_bounds.y);
517                 x2 = MAX (text_chunk->start_char_bounds.x +
518                           text_chunk->start_char_bounds.width,
519                           text_chunk->end_char_bounds.x +
520                           text_chunk->end_char_bounds.width);
521                 text_chunk->text_bounds.width = x2 - text_chunk->text_bounds.x;
522                 y2 = MAX (text_chunk->start_char_bounds.y +
523                           text_chunk->start_char_bounds.height,
524                           text_chunk->end_char_bounds.y + 
525                           text_chunk->end_char_bounds.height);
526                 text_chunk->text_bounds.height = y2 - text_chunk->text_bounds.y;
527                 text_chunk->start_offset = start;
528                 text_chunk->end_offset = end;
529                 AccessibleText_unref (text);
530         } else {
531                 if (role == SPI_ROLE_PUSH_BUTTON ||
532                     role == SPI_ROLE_CHECK_BOX ||
533                     role == SPI_ROLE_LABEL ||
534                     role == SPI_ROLE_MENU ||
535                     role == SPI_ROLE_MENU_ITEM) { /* don't like this
536                                                      special casing :-( */
537                         s = Accessible_getName (accessible);
538                         /* use name instead */
539                         text_chunk->text_bounds = text_chunk->clip_bounds;
540                         text_chunk->start_offset = 0;
541                         text_chunk->end_offset = strlen (s);
542                 }
543         }
544         if (text_chunk->text_bounds.x < text_chunk->clip_bounds.x) {
545                 text_chunk->text_bounds.x = text_chunk->clip_bounds.x;
546                 text_chunk->text_bounds.isClipped = TRUE;
547         } 
548         if ((text_chunk->text_bounds.x +
549              text_chunk->text_bounds.width)
550             > (text_chunk->clip_bounds.x +
551                text_chunk->clip_bounds.width)) {
552                 text_chunk->text_bounds.width =
553                         MAX (0, (text_chunk->clip_bounds.x +
554                                  text_chunk->clip_bounds.width) -
555                              text_chunk->text_bounds.x);
556                 text_chunk->text_bounds.isClipped = TRUE;
557         }
558         if (!BOUNDS_CONTAIN_Y (&text_chunk->text_bounds,
559                                screen_y)) {
560 #ifdef CLIP_DEBUG                       
561                 fprintf (stderr, "%s out of bounds (%d-%d)\n", s,
562                          text_chunk->text_bounds.y,
563                          text_chunk->text_bounds.y +
564                          text_chunk->text_bounds.height);
565 #endif                  
566                 s = NULL;
567                 text_chunk->start_offset = offset;
568                 text_chunk->end_offset = offset;
569         }
570         if (s && strlen (s)) {
571                 if (s[strlen(s)-1] == '\n') s[strlen(s)-1] = ' ';
572                 /* XXX: if last char is newline, aren't its bounds wrong now? */
573                 text_chunk->string = s;
574 #ifdef CLIP_DEBUG
575                 fprintf (stderr, "%s, bounds %d-%d; clip %d-%d\n",
576                          s,
577                          text_chunk->text_bounds.x,
578                          text_chunk->text_bounds.x+text_chunk->text_bounds.width,
579                          text_chunk->clip_bounds.x,
580                          text_chunk->clip_bounds.x+text_chunk->clip_bounds.width);
581 #endif          
582         } else {
583                 text_chunk->string = NULL;
584         }
585         return text_chunk;
586 }
587
588 static void
589 debug_chunk_list (GList *iter)
590 {
591         TextChunk *chunk;
592         while (iter) {
593                 chunk = (TextChunk *)iter->data;
594                 fprintf (stderr, "Chunk %s, clip %d-%d, text %d-%d\n",
595                          chunk->string,
596                          chunk->clip_bounds.x,
597                          chunk->clip_bounds.x + chunk->clip_bounds.width,
598                          chunk->text_bounds.x,
599                          chunk->text_bounds.x + chunk->text_bounds.width);
600                 iter = iter->next;
601         }
602 }
603
604 static void
605 clip_into_buffers (Accessible *accessible,  BoundaryRect* parentClipBounds[],
606                    ScreenReviewBuffer *reviewBuffers[],
607                    int screen_x, int screen_y)
608 {
609         int n_children, child_n;
610         Accessible *child;
611         BoundaryRect bounds;
612         BoundaryRect** clip_bounds;
613         TextChunk *text_chunk;
614         AccessibleComponent *component;
615         AccessibleRole role;
616         int layer;
617
618         clip_bounds = clip_bounds_clone (parentClipBounds);
619         if (Accessible_isComponent (accessible)) {
620                 role = Accessible_getRole (accessible);
621                 component = Accessible_getComponent (accessible);
622                 layer = AccessibleComponent_getLayer (component);
623                 bounds = *clip_bounds[layer];
624                 if (!bounds.isEmpty) {
625                         AccessibleComponent_getExtents (component,
626                                                         &bounds.x,
627                                                         &bounds.y,
628                                                         &bounds.width,
629                                                         &bounds.height,
630                                                         SPI_COORD_TYPE_SCREEN);
631                         bounds.role = role;
632                         if (clip_bounds[layer])
633                                 boundary_clip (&bounds, clip_bounds[layer]);
634                         if (BOUNDS_CONTAIN_Y (&bounds, screen_y)) {
635                                 text_chunk = review_buffer_get_text_chunk (
636                                         reviewBuffers[layer], accessible, &bounds,
637                                         screen_x, screen_y);
638                                 reviewBuffers[layer]->text_chunks = 
639                                         text_chunk_list_insert_chunk (
640                                                 reviewBuffers[layer]->text_chunks,
641                                                 text_chunk);
642                         } else {
643                                 bounds.isEmpty =
644                                         IS_CLIPPING_CONTAINER (bounds.role);
645                         }
646                 } 
647                 Accessible_unref (component);
648         }
649         /*
650          * we always descend into children in case they are in a higher layer
651          * this can of course be optimized for the topmost layer...
652          * but nobody uses that one! (SPI_LAYER_OVERLAY)
653          */
654         n_children = Accessible_getChildCount (accessible);
655         for (child_n = 0; child_n < n_children; ++child_n) {
656                 child = Accessible_getChildAtIndex (accessible, child_n);
657                 clip_into_buffers (child, clip_bounds, reviewBuffers, screen_x, screen_y);
658                 Accessible_unref (child);
659         }
660         /* TODO: free the parent clip bounds */
661 }
662
663 #undef CHARACTER_CLIP_DEBUG
664
665 static char*
666 text_chunk_get_clipped_substring_by_char (TextChunk *chunk, int start, int end)
667 {
668         BoundaryRect char_bounds;
669         int i;
670         char *s;
671         GString *string = g_string_new ("");
672         gunichar c;
673         AccessibleText *text = Accessible_getText (chunk->source);
674         for (i = start; i < end; ++i) {
675                 AccessibleText_getCharacterExtents (text,
676                                                     i,
677                                                     &char_bounds.x,
678                                                     &char_bounds.y,
679                                                     &char_bounds.width,
680                                                     &char_bounds.height,
681                                                     SPI_COORD_TYPE_SCREEN);
682 #ifdef CHARACTER_CLIP_DEBUG
683                 fprintf (stderr, "testing %d-%d against %d-%d\n",
684                          char_bounds.x, char_bounds.x+char_bounds.width,
685                          chunk->text_bounds.x,
686                          chunk->text_bounds.x + chunk->text_bounds.width);
687 #endif
688                 if (BOUNDS_CONTAIN_X_BOUNDS (chunk->text_bounds,
689                                              char_bounds)) {
690                         c = AccessibleText_getCharacterAtOffset (
691                                 text, i);
692 #ifdef CLIP_DEBUG                               
693                         fprintf (stderr, "[%c]", c);
694 #endif                          
695                         g_string_append_unichar (string, c);
696                 }
697         }
698         AccessibleText_unref (text);
699         s = string->str;
700         g_string_free (string, FALSE);
701         return s;
702 }
703
704
705 /*
706  * Note: this routine shouldn't have to do as much as it currently does,
707  *       but at the moment it works around another bug (probably one in this
708  *       code).
709  */
710 static char *
711 string_strip_newlines (char *s, long offset, long *start_offset, long *end_offset)
712 {
713         int i;
714         char *word_start = s;
715         /* FIXME: potential memory leak here */
716         for (i=0; s && s[i]; ++i)
717         {
718                 if (s [i] == '\n' && i > (offset - *start_offset) ) {
719                         s [i] = '\0';
720                         *end_offset = *start_offset + i;
721                         return word_start;
722                 } else if (s [i] == '\n') {
723                         word_start = &s[i + 1];
724                 }
725         }
726         return word_start;
727 }
728
729 static char *
730 string_guess_clip (TextChunk *chunk)
731 {
732         BoundaryRect b;
733         char *s = NULL, *sp = chunk->string, *ep;
734         long start_offset, end_offset, len;
735         if (sp) {
736                 AccessibleComponent *component =
737                         Accessible_getComponent (chunk->source);
738                 ep = sp + (strlen (sp));
739                 len = g_utf8_strlen (chunk->string, -1);
740                 if (component) {
741                         AccessibleComponent_getExtents (component,
742                                                         &b.x, &b.y,
743                                                         &b.width, &b.height,
744                                                         SPI_COORD_TYPE_SCREEN);
745                         start_offset = len * (chunk->text_bounds.x - b.x) / b.width;
746                         end_offset = len * (chunk->text_bounds.x +
747                                             chunk->text_bounds.width - b.x) / b.width;
748                         fprintf (stderr, "String len %d, clipped to %d-%d\n",
749                                  len, start_offset, end_offset);
750                         len = end_offset - start_offset;
751                         sp = g_utf8_offset_to_pointer (chunk->string, start_offset);
752                         ep = g_utf8_offset_to_pointer (chunk->string, end_offset);
753                 }
754                 s = g_new0 (char, ep - sp + 1);
755                 s = g_utf8_strncpy (s, sp, len);
756                 s [sp - ep] = '\0';
757                 g_assert (g_utf8_validate (s, -1, NULL));
758         }
759         return s;
760 }
761
762 static char*
763 text_chunk_get_clipped_string (TextChunk *chunk)
764 {
765         char *s, *string = "";
766         int i;
767         long start = chunk->start_offset, end = chunk->end_offset;
768         long word_start, word_end, range_end;
769         BoundaryRect start_bounds, end_bounds;
770         gboolean start_inside, end_inside;
771         if (!chunk->text_bounds.isClipped || !chunk->string)
772                 string = chunk->string;
773         else if (chunk->source && Accessible_isText (chunk->source)) {
774                 /* while words at offset lie within the bounds, add them */
775                 AccessibleText *text = Accessible_getText (chunk->source);
776 #ifdef CLIP_DEBUG               
777                 fprintf (stderr, "clipping %s\n", chunk->string);
778 #endif
779                 do {
780                     s = AccessibleText_getTextAtOffset (text,
781                                                         start,
782                                                 SPI_TEXT_BOUNDARY_WORD_END,
783                                                         &word_start,
784                                                         &word_end);
785                     range_end = word_end;
786                     s = string_strip_newlines (s, start, &word_start, &word_end);
787                     AccessibleText_getCharacterExtents (text,
788                                                         word_start,
789                                                         &start_bounds.x,
790                                                         &start_bounds.y,
791                                                         &start_bounds.width,
792                                                         &start_bounds.height,
793                                                         SPI_COORD_TYPE_SCREEN);
794                     AccessibleText_getCharacterExtents (text,
795                                                         word_end - 1,
796                                                         &end_bounds.x,
797                                                         &end_bounds.y,
798                                                         &end_bounds.width,
799                                                         &end_bounds.height,
800                                                         SPI_COORD_TYPE_SCREEN);
801                     start_inside = BOUNDS_CONTAIN_X_BOUNDS (chunk->text_bounds,
802                                                             start_bounds);
803                     end_inside = BOUNDS_CONTAIN_X_BOUNDS (chunk->text_bounds,
804                                                           end_bounds);
805                     if (start_inside && end_inside) {
806                             /* word is contained in bounds */
807                             string = g_strconcat (string, s, NULL);
808                     } else if (start_inside || end_inside) {
809                             /* one end of word is in */
810                             if (word_end > end) word_end = end;
811                             s = text_chunk_get_clipped_substring_by_char (
812                                     chunk,
813                                     MAX (word_start, chunk->start_offset),
814                                     MIN (word_end, chunk->end_offset));
815                             string = g_strconcat (string, s, NULL);
816                     } else {
817                     }
818                     start = range_end;
819                 } while (start < chunk->end_offset);
820         } else { /* we're clipped, but don't implement AccessibleText :-( */
821                 /* guess for now, maybe we can do better someday */
822                 string = string_guess_clip (chunk);
823         }
824         return string;
825 }
826
827
828 static char*
829 text_chunk_pad_string (TextChunk *chunk, char *string, glong offset, const char *pad_chars)
830 {
831         char *s = "";
832         char *cp;
833         char startbuf[6], padbuf[6], endbuf[6];
834         int pixels_per_column = 6;
835         /* this is an arbitrary pixel-to-textcolumn mapping at present */
836         glong end_padding;
837         gint howmany;
838         howmany = g_unichar_to_utf8 (g_utf8_get_char (pad_chars), startbuf);
839         startbuf[howmany] = '\0';
840         g_assert (howmany < 7 && howmany > 0);
841         cp = g_utf8_find_next_char (pad_chars, NULL);
842         howmany = g_unichar_to_utf8 (g_utf8_get_char (cp), padbuf);
843         padbuf[howmany] = '\0';
844         g_assert (howmany < 7 && howmany > 0);
845         cp = g_utf8_find_next_char (cp, NULL);
846         howmany = g_unichar_to_utf8 (g_utf8_get_char (cp), endbuf);
847         endbuf[howmany] = '\0';
848         g_assert (howmany < 7 && howmany > 0);
849         end_padding = chunk->clip_bounds.x / pixels_per_column; 
850         while (offset < end_padding - 1) {
851                 s = g_strconcat (s, padbuf, NULL); /* could be more efficient */
852                 ++offset;
853         }
854         s = g_strconcat (s, startbuf, string, NULL);
855         offset += g_utf8_strlen (string, -1) + 1;
856         end_padding = chunk->text_bounds.x / pixels_per_column; 
857         while (offset < end_padding) {
858                 s = g_strconcat (s, padbuf, NULL); /* could be more efficient */
859                 ++offset;
860         }
861         end_padding = (chunk->clip_bounds.x + chunk->clip_bounds.width) /
862                 pixels_per_column;
863         while (offset < end_padding - 1) {
864                 s = g_strconcat (s, padbuf, NULL); /* could be more efficient */
865                 ++offset;
866         }
867         s = g_strconcat (s, endbuf, NULL);
868         return s;
869 }
870
871 static char*
872 text_chunk_to_string (TextChunk *chunk, glong offset)
873 {
874         char *s = NULL;
875         if (chunk->string) {
876                 s = text_chunk_get_clipped_string (chunk);
877                 if (chunk->clip_bounds.role == SPI_ROLE_PUSH_BUTTON) {
878                         s = text_chunk_pad_string (chunk, s, offset, "[ ]");
879                 } else if (chunk->clip_bounds.role == SPI_ROLE_FRAME) {
880                         s = text_chunk_pad_string (chunk, s, offset, "| |");
881                 } else if (chunk->clip_bounds.role == SPI_ROLE_TEXT) {
882                         s = text_chunk_pad_string (chunk, s, offset, "\" \"");
883                 } else {
884                         s = text_chunk_pad_string (chunk, s, offset, "   ");
885                 }
886         }
887         return s;
888 }
889
890 static char*
891 text_chunk_list_to_string (GList *iter)
892 {
893         char *s = "";
894         char *string;
895         TextChunk *chunk = NULL;
896         int offset = 0;
897         while (iter) {
898                 chunk = (TextChunk *)iter->data;
899                 if (chunk) {
900                         string = text_chunk_to_string (chunk, g_utf8_strlen (s, -1));
901                         if (string)
902                                 s = g_strconcat (s, string, NULL);
903                 }
904                 iter = iter->next;
905         }
906         s = g_strconcat (s, "|", NULL);
907         return s;
908 }
909
910 #define COMPOSITE_DEBUG
911
912 static void
913 toplevel_composite (ScreenReviewBuffer *buffers[])
914 {
915         int i;
916         GList *chunk_list, *iter;
917         TextChunk *chunk;
918
919         chunk_list = buffers[SPI_LAYER_CANVAS]->text_chunks;
920         for (i = SPI_LAYER_MDI; i < SPI_LAYER_OVERLAY; ++i) {
921                 iter = buffers[i]->text_chunks;
922 #ifdef COMPOSITE_DEBUG
923                 fprintf (stderr, "layer %d has %d chunks\n",
924                          i, g_list_length (iter));
925 #endif          
926                 while (iter) {
927                         chunk = (TextChunk *) iter->data;
928                         if (chunk) {
929 #ifdef COMPOSITE_DEBUG
930                                 fprintf (stderr, "inserting chunk <%s>\n",
931                                          chunk->string ? chunk->string : "<null>");
932 #endif
933                                 chunk_list =
934                                         text_chunk_list_insert_chunk (chunk_list,
935                                                                       chunk);
936                         }
937                         iter = iter->next;
938                 }
939         }
940 }
941
942 static char*
943 review_buffer_composite (ScreenReviewBuffer *buffers[])
944 {
945         /* TODO: FIXME: something is wrong here, compositing fails */
946         int i;
947         GList *chunk_list, *iter;
948         TextChunk *chunk;
949         chunk_list = buffers[SPI_LAYER_BACKGROUND]->text_chunks;
950         for (i = 2; i < SPI_LAYER_LAST_DEFINED; ++i) {
951                 if (i == SPI_LAYER_WIDGET) i = SPI_LAYER_OVERLAY;
952                 /*
953                  * Q: why skip these layers ?
954                  * A: since layers WIDGET, MDI, and POPUP have already been
955                  *  composited into layer CANVAS for each toplevel before this
956                  *  routine is called.
957                  */
958                 iter = buffers[i]->text_chunks;
959 #ifdef CLIP_DEBUG
960                 fprintf (stderr, "layer %d has %d chunks\n",
961                          i, g_list_length (iter));
962 #endif          
963                 while (iter) {
964                         chunk = (TextChunk *) iter->data;
965                         if (chunk) {
966 #ifdef CLIP_DEBUG
967                                 fprintf (stderr, "inserting chunk <%s>\n",
968                                          chunk->string ? chunk->string : "<null>");
969 #endif
970                                 chunk_list =
971                                         text_chunk_list_insert_chunk (chunk_list,
972                                                                       chunk);
973                         }
974                         iter = iter->next;
975                 }
976         }
977         
978         chunk_list = buffers[SPI_LAYER_WIDGET]->text_chunks;
979         return text_chunk_list_to_string (chunk_list);
980 }
981
982 static char *
983 get_screen_review_line_at (int x, int y)
984 {
985   char *string;
986   Accessible *desktop, *app, *toplevel, *child;
987   AccessibleComponent *component;
988   AccessibleStateSet *states;
989   GList *toplevels = NULL, *actives = NULL, *iter;
990   ScreenReviewBuffer* reviewBuffers[SPI_LAYER_LAST_DEFINED];
991   BoundaryRect* clip_bounds[SPI_LAYER_LAST_DEFINED];
992   BoundaryRect toplevel_bounds;
993   int n_apps, n_toplevels, n_children, app_n, toplevel_n, child_n;
994   GTimer *timer = g_timer_new ();
995   int i;
996
997   for (i = 1; i < SPI_LAYER_LAST_DEFINED; ++i) {
998           reviewBuffers[i] = g_new0 (ScreenReviewBuffer, 1);
999           clip_bounds[i] = g_new0 (BoundaryRect, 1);
1000           clip_bounds[i]->isClipped = FALSE;
1001           clip_bounds[i]->isEmpty = FALSE;
1002   }
1003   
1004   /* how do we decide which desktop ? */
1005   desktop = SPI_getDesktop (0);
1006   
1007   /* for each app */
1008   n_apps = Accessible_getChildCount (desktop);
1009   for (app_n = 0; app_n < n_apps; ++app_n) {
1010           /* for each toplevel in app */
1011           app =  Accessible_getChildAtIndex (desktop, app_n);
1012           n_toplevels = Accessible_getChildCount (app);
1013           for (toplevel_n = 0; toplevel_n < n_toplevels; ++toplevel_n) {
1014                   Accessible *toplevel = Accessible_getChildAtIndex (app, toplevel_n);
1015                   if (Accessible_isComponent (toplevel))
1016                           toplevels = g_list_prepend (toplevels, toplevel);
1017                   else {
1018                           Accessible_unref (toplevel);
1019                           fprintf (stderr, "warning, app toplevel not a component.\n");
1020                   }
1021           }
1022   }
1023   
1024   /* sort: at the moment we don't have a good way to sort except to put actives on top */
1025   for (iter = g_list_first (toplevels); iter; iter = iter->next) {
1026           Accessible *toplevel =
1027                   (Accessible *) iter->data;
1028           if (AccessibleStateSet_contains (Accessible_getStateSet (toplevel),
1029                                            SPI_STATE_ACTIVE)) {
1030                   actives = g_list_prepend (actives, toplevel);
1031           }
1032   }
1033
1034   for (iter = g_list_first (actives); iter; iter = actives->next) {
1035           toplevels = g_list_remove (toplevels, iter->data); /* place at end */
1036           toplevels = g_list_append (toplevels, iter->data);
1037   }
1038   g_list_free (actives);
1039
1040   /* for each toplevel, ending with the active one(s),
1041    * clip against children, putting results into appropriate charBuffer.
1042    */
1043   for (iter = g_list_first (toplevels); iter; iter = iter->next) {
1044           toplevel = (Accessible *) iter->data;
1045           if (Accessible_isComponent (toplevel)) {
1046               /* make sure toplevel is visible and not iconified or shaded */
1047               states = Accessible_getStateSet (toplevel);
1048               if (AccessibleStateSet_contains (states, SPI_STATE_VISIBLE)
1049                   && !AccessibleStateSet_contains (states, SPI_STATE_ICONIFIED)
1050                   || isJava) { /* isJava hack! */
1051                       component = Accessible_getComponent (toplevel);
1052                       AccessibleComponent_getExtents (component,
1053                                                       &toplevel_bounds.x,
1054                                                       &toplevel_bounds.y,
1055                                                       &toplevel_bounds.width,
1056                                                       &toplevel_bounds.height,
1057                                                       SPI_COORD_TYPE_SCREEN);
1058                       toplevel_bounds.isEmpty = FALSE;
1059                       for (i = 1; i < SPI_LAYER_LAST_DEFINED; ++i) {
1060                               *clip_bounds[i] = toplevel_bounds;
1061                       }
1062                       clip_into_buffers (toplevel, clip_bounds,
1063                                      reviewBuffers, x, y);
1064
1065                       toplevel_composite (reviewBuffers);
1066 #ifdef CHUNK_LIST_DEBUG
1067                       fprintf (stderr, "toplevel clip done\n");
1068                       debug_chunk_list (reviewBuffers[SPI_LAYER_WIDGET]->text_chunks);
1069 #endif                
1070               }
1071           }
1072           Accessible_unref (toplevel);
1073   }
1074
1075   string = review_buffer_composite (reviewBuffers);
1076
1077   /* SIMPLE SINGLE-PASS ALGORITHM:*/
1078   /* traverse the tree:
1079    *   keep a pointer to outermost instance of each layer
1080    *   clip against outermost in same layer
1081    *   when this clip occurs, store outermost clipped string in 2d string buffer.
1082    *   string buffer may have attributes to mark component bounds, line art,
1083    *      or attributes of text being reviewed.
1084    *   composite the layers, ignoring NULL chars in the string buffers.
1085    *
1086    * Limitations:
1087    *   sibling clip not correct, text may overwrite if siblings intersect onscreen
1088    *   length of resulting text buffer may vary!
1089    *
1090    * Technical issues:
1091    *   no API for ordering toplevels yet, other than knowing which is ACTIVE.
1092    *   not much implementation for the LAYER API yet, other than menus.
1093    */
1094   g_timer_stop (timer);
1095   fprintf (stderr, "elapsed time = %f s\n", g_timer_elapsed (timer, NULL));
1096   
1097   return string;
1098 }
1099
1100 void
1101 report_screen_review_line (const AccessibleEvent *event, void *user_data)
1102 {
1103   static Display *display = NULL;
1104   int x, y, win_x, win_y;
1105   Window root_return, child_return;
1106   unsigned int mask_return;
1107   
1108   if (!display) display = XOpenDisplay (getenv ("DISPLAY"));
1109   /*
1110    *  we would prefer to get the x,y info in the above event.
1111    *  At the moment we don't get detail params for "toolkit" events,
1112    *  so for testing purposes we use XQueryPointer.  Actual apps
1113    *  probably shouldn't do this.
1114    */
1115   XQueryPointer (display,
1116                  DefaultRootWindow (display),
1117                  &root_return, &child_return,
1118                  &x, &y,
1119                  &win_x, &win_y,
1120                  &mask_return);
1121
1122   fprintf (stderr, "screen review event %s at %d, %d\n", event->type,
1123            x, y);
1124   fprintf (stderr, "[%s]\n", 
1125            get_screen_review_line_at (x, y));
1126 }
1127
1128 void
1129 test_exit (void)
1130 {
1131   SPI_deregisterGlobalEventListenerAll (mouseclick_listener);
1132   AccessibleEventListener_unref (mouseclick_listener);
1133 }