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