]> Pileus Git - ~andy/gtk/blob - gtk/gtktestutils.c
Moved Gdk test functions from Gtk+ to Gdk test utils.
[~andy/gtk] / gtk / gtktestutils.c
1 /* Gtk+ testing utilities
2  * Copyright (C) 2007 Tim Janik
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19 #include "gtktestutils.h"
20 #include <gtk/gtk.h>
21 #include <gdk/gdktestutils.h>
22 #include "gtkalias.h"
23
24 #include <locale.h>
25 #include <string.h>
26 #include <math.h>
27
28
29 /* --- test utilities --- */
30 /**
31  * gtk_test_init:
32  * @argc: Address of the <parameter>argc</parameter> parameter of the
33  *        main() function. Changed if any arguments were handled.
34  * @argv: Address of the <parameter>argv</parameter> parameter of main().
35  *        Any parameters understood by g_test_init() or gtk_init() are
36  *        stripped before return.
37  *
38  * This function is used to initialize a Gtk+ test program.
39  * It will in turn call g_test_init() and gtk_init() to properly
40  * initialize the testing framework and graphical toolkit.
41  * It'll also set the program's locale to "C" and prevent loading of
42  * rc files and Gtk+ modules. This is done to make tets program
43  * environments as deterministic as possible.
44  * Like gtk_init() and g_test_init(), any known arguments will be
45  * processed and stripped from @argc and @argv.
46  **/
47 void
48 gtk_test_init (int    *argcp,
49                char ***argvp,
50                ...)
51 {
52   /* - enter C locale
53    * - call g_test_init();
54    * - call gtk_init();
55    * - prevent RC files from loading;
56    * - prevent Gtk modules from loading;
57    * - supply mock object for GtkSettings
58    * FUTURE TODO:
59    * - this function could install a mock object around GtkSettings
60    */
61   // FIXME: g_test_init (argcp, argvp, NULL);
62   g_setenv ("GTK_MODULES", "", TRUE);
63   g_setenv ("GTK2_RC_FILES", "/dev/null", TRUE);
64   gtk_disable_setlocale();
65   setlocale (LC_ALL, "C");
66   gtk_init (argcp, argvp);
67 }
68
69 static GSList*
70 test_find_widget_input_windows (GtkWidget *widget,
71                                 gboolean   input_only)
72 {
73   GList *node, *children;
74   GSList *matches = NULL;
75   gpointer udata;
76   gdk_window_get_user_data (widget->window, &udata);
77   if (udata == widget && (!input_only || (GDK_IS_WINDOW (widget->window) && GDK_WINDOW_OBJECT (widget->window)->input_only)))
78     matches = g_slist_prepend (matches, widget->window);
79   children = gdk_window_get_children (gtk_widget_get_parent_window (widget));
80   for (node = children; node; node = node->next)
81     {
82       gdk_window_get_user_data (node->data, &udata);
83       if (udata == widget && (!input_only || (GDK_IS_WINDOW (node->data) && GDK_WINDOW_OBJECT (node->data)->input_only)))
84         matches = g_slist_prepend (matches, node->data);
85     }
86   return g_slist_reverse (matches);
87 }
88
89 /**
90  * gtk_test_widget_send_key
91  * @widget: Widget to generate a key press and release on.
92  * @keyval: A Gdk keyboard value.
93  * @modifiers: Keyboard modifiers the event is setup with.
94  *
95  * This function will generate keyboard press and release events in
96  * the middle of the first GdkWindow found that belongs to @widget.
97  * For %GTK_NO_WINDOW widgets like GtkButton, this will often be an
98  * input-only event window. For other widgets, this is usually widget->window.
99  * Certain caveats should be considered when using this function, in
100  * particular because the mouse pointer is warped to the key press
101  * location, see gdk_test_simulate_key() for details.
102  *
103  * Returns: wether all actions neccessary for the key event simulation were carried out successfully.
104  **/
105 gboolean
106 gtk_test_widget_send_key (GtkWidget      *widget,
107                           guint           keyval,
108                           GdkModifierType modifiers)
109 {
110   gboolean k1res, k2res;
111   GSList *iwindows = test_find_widget_input_windows (widget, FALSE);
112   if (!iwindows)
113     iwindows = test_find_widget_input_windows (widget, TRUE);
114   if (!iwindows)
115     return FALSE;
116   k1res = gdk_test_simulate_key (iwindows->data, -1, -1, keyval, modifiers, GDK_KEY_PRESS);
117   k2res = gdk_test_simulate_key (iwindows->data, -1, -1, keyval, modifiers, GDK_KEY_RELEASE);
118   g_slist_free (iwindows);
119   return k1res && k2res;
120 }
121
122 /**
123  * gtk_test_widget_click
124  * @widget: Widget to generate a button click on.
125  * @button: Number of the pointer button for the event, usually 1, 2 or 3.
126  * @modifiers: Keyboard modifiers the event is setup with.
127  *
128  * This function will generate a @button click (button press and button
129  * release event) in the middle of the first GdkWindow found that belongs
130  * to @widget.
131  * For %GTK_NO_WINDOW widgets like GtkButton, this will often be an
132  * input-only event window. For other widgets, this is usually widget->window.
133  * Certain caveats should be considered when using this function, in
134  * particular because the mouse pointer is warped to the button click
135  * location, see gdk_test_simulate_button() for details.
136  *
137  * Returns: wether all actions neccessary for the button click simulation were carried out successfully.
138  **/
139 gboolean
140 gtk_test_widget_click (GtkWidget      *widget,
141                        guint           button,
142                        GdkModifierType modifiers)
143 {
144   gboolean b1res, b2res;
145   GSList *iwindows = test_find_widget_input_windows (widget, FALSE);
146   if (!iwindows)
147     iwindows = test_find_widget_input_windows (widget, TRUE);
148   if (!iwindows)
149     return FALSE;
150   b1res = gdk_test_simulate_button (iwindows->data, -1, -1, button, modifiers, GDK_BUTTON_PRESS);
151   b2res = gdk_test_simulate_button (iwindows->data, -1, -1, button, modifiers, GDK_BUTTON_RELEASE);
152   g_slist_free (iwindows);
153   return b1res && b2res;
154 }
155
156 /**
157  * gtk_test_spin_button_click
158  * @spinner: valid GtkSpinButton widget.
159  * @button:  Number of the pointer button for the event, usually 1, 2 or 3.
160  * @upwards: %TRUE for upwards arrow click, %FALSE for downwards arrow click.
161  *
162  * This function will generate a @button click in the upwards or downwards
163  * spin button arrow areas, usually leading to an increase or decrease of
164  * spin button's value.
165  *
166  * Returns: wether all actions neccessary for the button click simulation were carried out successfully.
167  **/
168 gboolean
169 gtk_test_spin_button_click (GtkSpinButton  *spinner,
170                             guint           button,
171                             gboolean        upwards)
172 {
173   gboolean b1res = FALSE, b2res = FALSE;
174   if (spinner->panel)
175     {
176       gint width, height, pos;
177       gdk_drawable_get_size (spinner->panel, &width, &height);
178       pos = upwards ? 0 : height - 1;
179       b1res = gdk_test_simulate_button (spinner->panel, width - 1, pos, button, 0, GDK_BUTTON_PRESS);
180       b2res = gdk_test_simulate_button (spinner->panel, width - 1, pos, button, 0, GDK_BUTTON_RELEASE);
181     }
182   return b1res && b2res;
183 }
184
185 /**
186  * gtk_test_find_label
187  * @widget:        Valid label or container widget.
188  * @label_pattern: Shell-glob pattern to match a label string.
189  *
190  * This function will search @widget and all its descendants for a GtkLabel
191  * widget with a text string matching @label_pattern.
192  * The @label_pattern may contain asterisks '*' and question marks '?' as
193  * placeholders, g_pattern_match() is used for the matching.
194  * Note that locales other than "C" tend to alter (translate" label strings,
195  * so this function is genrally only useful in test programs with
196  * predetermined locales, see gtk_test_init() for more details.
197  *
198  * Returns: a GtkLabel widget if any is found.
199  **/
200 GtkWidget*
201 gtk_test_find_label (GtkWidget    *widget,
202                      const gchar  *label_pattern)
203 {
204   if (GTK_IS_LABEL (widget))
205     {
206       const gchar *text = gtk_label_get_text (GTK_LABEL (widget));
207       if (g_pattern_match_simple (label_pattern, text))
208         return widget;
209     }
210   if (GTK_IS_CONTAINER (widget))
211     {
212       GList *node, *list = gtk_container_get_children (GTK_CONTAINER (widget));
213       for (node = list; node; node = node->next)
214         {
215           GtkWidget *label = gtk_test_find_label (node->data, label_pattern);
216           if (label)
217             return label;
218         }
219       g_list_free (list);
220     }
221   return NULL;
222 }
223
224 static GList*
225 test_list_descendants (GtkWidget *widget,
226                        GType      widget_type)
227 {
228   GList *results = NULL;
229   if (GTK_IS_CONTAINER (widget))
230     {
231       GList *node, *list = gtk_container_get_children (GTK_CONTAINER (widget));
232       for (node = list; node; node = node->next)
233         {
234           if (!widget_type || g_type_is_a (G_OBJECT_TYPE (node->data), widget_type))
235             results = g_list_prepend (results, node->data);
236           else
237             results = g_list_concat (results, test_list_descendants (node->data, widget_type));
238         }
239       g_list_free (list);
240     }
241   return results;
242 }
243
244 static int
245 widget_geo_dist (GtkWidget *a,
246                  GtkWidget *b,
247                  GtkWidget *base)
248 {
249   int ax0, ay0, ax1, ay1, bx0, by0, bx1, by1, xdist = 0, ydist = 0;
250   if (!gtk_widget_translate_coordinates (a, base, 0, 0, &ax0, &ay0) ||
251       !gtk_widget_translate_coordinates (a, base, a->allocation.width, a->allocation.height, &ax1, &ay1))
252     return -G_MAXINT;
253   if (!gtk_widget_translate_coordinates (b, base, 0, 0, &bx0, &by0) ||
254       !gtk_widget_translate_coordinates (b, base, b->allocation.width, b->allocation.height, &bx1, &by1))
255     return +G_MAXINT;
256   if (bx0 >= ax1)
257     xdist = bx0 - ax1;
258   else if (ax0 >= bx1)
259     xdist = ax0 - bx1;
260   if (by0 >= ay1)
261     ydist = by0 - ay1;
262   else if (ay0 >= by1)
263     ydist = ay0 - by1;
264   return xdist + ydist;
265 }
266
267 static int
268 widget_geo_cmp (gconstpointer a,
269                 gconstpointer b,
270                 gpointer      user_data)
271 {
272   gpointer *data = user_data;
273   GtkWidget *wa = (void*) a, *wb = (void*) b, *toplevel = data[0], *base_widget = data[1];
274   int adist = widget_geo_dist (wa, base_widget, toplevel);
275   int bdist = widget_geo_dist (wb, base_widget, toplevel);
276   return adist > bdist ? +1 : adist == bdist ? 0 : -1;
277 }
278
279 /**
280  * gtk_test_find_sibling
281  * @base_widget:        Valid widget, part of a widget hierarchy
282  * @widget_type:        Type of a aearched for sibling widget
283  *
284  * This function will search siblings of @base_widget and siblings of its
285  * ancestors for all widgets matching @widget_type.
286  * Of the matching widgets, the one that is geometrically closest to
287  * @base_widget will be returned.
288  * The general purpose of this function is to find the most likely "action"
289  * widget, relative to another labeling widget. Such as finding a
290  * button or text entry widget, given it's corresponding label widget.
291  *
292  * Returns: a widget of type @widget_type if any is found.
293  **/
294 GtkWidget*
295 gtk_test_find_sibling (GtkWidget *base_widget,
296                        GType      widget_type)
297 {
298   GList *siblings = NULL;
299   GtkWidget *tmpwidget = base_widget;
300   gpointer data[2];
301   /* find all sibling candidates */
302   while (tmpwidget)
303     {
304       tmpwidget = tmpwidget->parent;
305       siblings = g_list_concat (siblings, test_list_descendants (tmpwidget, widget_type));
306     }
307   /* sort them by distance to base_widget */
308   data[0] = gtk_widget_get_toplevel (base_widget);
309   data[1] = base_widget;
310   siblings = g_list_sort_with_data (siblings, widget_geo_cmp, data);
311   /* pick nearest != base_widget */
312   siblings = g_list_remove (siblings, base_widget);
313   tmpwidget = siblings ? siblings->data : NULL;
314   g_list_free (siblings);
315   return tmpwidget;
316 }
317
318 /**
319  * gtk_test_find_widget
320  * @widget:        Container widget, usually a GtkWindow.
321  * @label_pattern: Shell-glob pattern to match a label string.
322  * @widget_type:   Type of a aearched for label sibling widget.
323  *
324  * This function will search the descendants of @widget for a widget
325  * of type @widget_type that has a label matching @label_pattern next
326  * to it. This is most useful for automated GUI testing, e.g. to find
327  * the "OK" button in a dialog and synthesize clicks on it.
328  * However see gtk_test_find_label(), gtk_test_find_sibling() and
329  * gtk_test_widget_click() for possible caveats involving the search of
330  * such widgets and synthesizing widget events.
331  *
332  * Returns: a valid widget if any is found or %NULL.
333  **/
334 GtkWidget*
335 gtk_test_find_widget (GtkWidget    *widget,
336                       const gchar  *label_pattern,
337                       GType         widget_type)
338 {
339   GtkWidget *label = gtk_test_find_label (widget, label_pattern);
340   if (!label)
341     label = gtk_test_find_label (gtk_widget_get_toplevel (widget), label_pattern);
342   if (label)
343     return gtk_test_find_sibling (label, widget_type);
344   return NULL;
345 }
346
347 /**
348  * gtk_test_slider_set_perc
349  * @widget:     valid widget pointer.
350  * @percentage: value between 0 and 100.
351  *
352  * This function will adjust theslider position of all GtkRange
353  * based widgets, such as scrollbars or scales, it'll also adjust
354  * spin buttons. The adjustment value of tehse widgets is set to
355  * a value between the lower and upper limits, according to the
356  * @percentage argument.
357  **/
358 void
359 gtk_test_slider_set_perc (GtkWidget      *widget,
360                           double          percentage)
361 {
362   GtkAdjustment *adjustment = NULL;
363   if (GTK_IS_RANGE (widget))
364     adjustment = gtk_range_get_adjustment (GTK_RANGE (widget));
365   else if (GTK_IS_SPIN_BUTTON (widget))
366     adjustment = gtk_spin_button_get_adjustment (GTK_SPIN_BUTTON (widget));
367   if (adjustment)
368     gtk_adjustment_set_value (adjustment, adjustment->lower + (adjustment->upper - adjustment->lower - adjustment->page_size) * percentage * 0.01);
369 }
370
371 /**
372  * gtk_test_slider_get_value
373  * @widget:     valid widget pointer.
374  *
375  * Retrive the literal adjustment value for GtkRange based
376  * widgets and spin buttons. Note that the value returned by
377  * this function is anything between the lower and upper bounds
378  * of the adjustment belonging to @widget, and is not a percentage
379  * as passed in to gtk_test_slider_set_perc().
380  *
381  * Returns: adjustment->value for an adjustment belonging to @widget.
382  **/
383 double
384 gtk_test_slider_get_value (GtkWidget *widget)
385 {
386   GtkAdjustment *adjustment = NULL;
387   if (GTK_IS_RANGE (widget))
388     adjustment = gtk_range_get_adjustment (GTK_RANGE (widget));
389   else if (GTK_IS_SPIN_BUTTON (widget))
390     adjustment = gtk_spin_button_get_adjustment (GTK_SPIN_BUTTON (widget));
391   return adjustment ? adjustment->value : 0;
392 }
393
394 /**
395  * gtk_test_text_set
396  * @widget:     valid widget pointer.
397  * @string:     a 0-terminated C string
398  *
399  * Set the text string of @widget to @string if it is a GtkLabel,
400  * GtkEditable (entry and text widgets) or GtkTextView.
401  **/
402 void
403 gtk_test_text_set (GtkWidget   *widget,
404                    const gchar *string)
405 {
406   if (GTK_IS_LABEL (widget))
407     gtk_label_set_text (GTK_LABEL (widget), string);
408   else if (GTK_IS_EDITABLE (widget))
409     {
410       int pos = 0;
411       gtk_editable_delete_text (GTK_EDITABLE (widget), 0, -1);
412       gtk_editable_insert_text (GTK_EDITABLE (widget), string, -1, &pos);
413     }
414   else if (GTK_IS_TEXT_VIEW (widget))
415     {
416       GtkTextBuffer *tbuffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (widget));
417       gtk_text_buffer_set_text (tbuffer, string, -1);
418     }
419 }
420
421 /**
422  * gtk_test_text_get
423  * @widget:     valid widget pointer.
424  *
425  * Retrive the text string of @widget if it is a GtkLabel,
426  * GtkEditable (entry and text widgets) or GtkTextView.
427  *
428  * Returns: new 0-terminated C string, needs to be releaed with g_free().
429  **/
430 gchar*
431 gtk_test_text_get (GtkWidget *widget)
432 {
433   if (GTK_IS_LABEL (widget))
434     return g_strdup (gtk_label_get_text (GTK_LABEL (widget)));
435   else if (GTK_IS_EDITABLE (widget))
436     {
437       return g_strdup (gtk_editable_get_chars (GTK_EDITABLE (widget), 0, -1));
438     }
439   else if (GTK_IS_TEXT_VIEW (widget))
440     {
441       GtkTextBuffer *tbuffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (widget));
442       GtkTextIter start, end;
443       gtk_text_buffer_get_start_iter (tbuffer, &start);
444       gtk_text_buffer_get_end_iter (tbuffer, &end);
445       return gtk_text_buffer_get_text (tbuffer, &start, &end, FALSE);
446     }
447   return NULL;
448 }
449
450 /**
451  * gtk_test_create_widget
452  * @widget_type:        valid widget type.
453  * @first_property_name: Name of first property to set or %NULL
454  *
455  * This function wraps g_object_new() for widget types.
456  * It'll automatically show all created non window widgets, also
457  * g_object_ref_sink() them (to keep them alive across a running test)
458  * and set them up for destruction during test teardown phase.
459  *
460  * Returns: a newly created widget.
461  */
462 GtkWidget*
463 gtk_test_create_widget (GType        widget_type,
464                         const gchar *first_property_name,
465                         ...)
466 {
467   GtkWidget *widget;
468   va_list var_args;
469   g_return_val_if_fail (g_type_is_a (widget_type, GTK_TYPE_WIDGET), NULL);
470   va_start (var_args, first_property_name);
471   widget = (GtkWidget*) g_object_new_valist (widget_type, first_property_name, var_args);
472   va_end (var_args);
473   if (widget)
474     {
475       if (!GTK_IS_WINDOW (widget))
476         gtk_widget_show (widget);
477       g_object_ref_sink (widget);
478 #ifdef __G_TESTFRAMEWORK_H__ /* FIXME */
479       g_test_queue_unref (widget);
480       g_test_queue_destroy ((GDestroyNotify) gtk_widget_destroy, widget);
481 #endif
482     }
483   return widget;
484 }
485
486 static void
487 try_main_quit (void)
488 {
489   if (gtk_main_level())
490     gtk_main_quit();
491 }
492
493 static int
494 test_increment_intp (int *intp)
495 {
496   *intp += 1;
497   return 1; /* TRUE in case we're connected to event signals */
498 }
499
500 /**
501  * gtk_test_display_button_window
502  * @window_title:       Title of the window to be displayed.
503  * @dialog_text:        Text inside the window to be displayed.
504  * @...:                %NULL terminated list of (const char *label, int *nump) pairs.
505  *
506  * Create a window with window title @window_title, text contents @dialog_text,
507  * and a number of buttons, according to the paired argument list given
508  * as @... parameters.
509  * Each button is created with a @label and a ::clicked signal handler that
510  * incremrents the integer stored in @nump.
511  * The window will be automatically shown with gtk_widget_show_now() after
512  * creation, so when this function returns it has already been mapped,
513  * resized and positioned on screen.
514  * The window will quit any running gtk_main()-loop when destroyed, and it
515  * will automatically be destroyed upon test function teardown.
516  *
517  * Returns: a widget pointer to the newly created GtkWindow.
518  **/
519 GtkWidget*
520 gtk_test_display_button_window (const gchar *window_title,
521                                 const gchar *dialog_text,
522                                 ...) /* NULL terminated list of (label, &int) pairs */
523 {
524   va_list var_args;
525   GtkWidget *window = gtk_test_create_widget (GTK_TYPE_WINDOW, "title", window_title, NULL);
526   GtkWidget *vbox = gtk_test_create_widget (GTK_TYPE_VBOX, "parent", window, NULL);
527   const char *arg1;
528   gtk_test_create_widget (GTK_TYPE_LABEL, "label", dialog_text, "parent", vbox, NULL);
529   g_signal_connect (window, "destroy", G_CALLBACK (try_main_quit), NULL);
530   va_start (var_args, dialog_text);
531   arg1 = va_arg (var_args, const char*);
532   while (arg1)
533     {
534       int *arg2 = va_arg (var_args, int*);
535       GtkWidget *button = gtk_test_create_widget (GTK_TYPE_BUTTON, "label", arg1, "parent", vbox, NULL);
536       g_signal_connect_swapped (button, "clicked", G_CALLBACK (test_increment_intp), arg2);
537       arg1 = va_arg (var_args, const char*);
538     }
539   va_end (var_args);
540   gtk_widget_show_all (vbox);
541   gtk_widget_show_now (window);
542   while (gtk_events_pending ())
543     gtk_main_iteration ();
544   return window;
545 }
546
547 /**
548  * gtk_test_create_simple_window
549  * @window_title:       Title of the window to be displayed.
550  * @dialog_text:        Text inside the window to be displayed.
551  *
552  * Create a simple window with window title @window_title and
553  * text contents @dialog_text.
554  * The window will quit any running gtk_main()-loop when destroyed, and it
555  * will automatically be destroyed upon test function teardown.
556  *
557  * Returns: a widget pointer to the newly created GtkWindow.
558  **/
559 GtkWidget*
560 gtk_test_create_simple_window (const gchar *window_title,
561                                const gchar *dialog_text)
562 {
563   GtkWidget *window = gtk_test_create_widget (GTK_TYPE_WINDOW, "title", window_title, NULL);
564   GtkWidget *vbox = gtk_test_create_widget (GTK_TYPE_VBOX, "parent", window, NULL);
565   gtk_test_create_widget (GTK_TYPE_LABEL, "label", dialog_text, "parent", vbox, NULL);
566   g_signal_connect (window, "destroy", G_CALLBACK (try_main_quit), NULL);
567   gtk_widget_show_all (vbox);
568   return window;
569 }
570
571 /**
572  * gtk_test_register_all_types
573  *
574  * Force registration of all core Gtk+ and Gdk object types.
575  * This allowes to refer to any of those object types via
576  * g_type_from_name() after calling this function.
577  **/
578 void
579 gtk_test_register_all_types (void)
580 {
581   volatile GType vgt;
582 #include "gtktypefuncs.c"
583 }
584
585 #define __GTK_TEST_UTILS_C__
586 #include "gtkaliasdef.c"