Make fuzzy picking a command line switch
[profile/ivi/clutter.git] / clutter / clutter-main.c
1 /*
2  * Clutter.
3  *
4  * An OpenGL based 'interactive canvas' library.
5  *
6  * Authored By Matthew Allum  <mallum@openedhand.com>
7  *
8  * Copyright (C) 2006 OpenedHand
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with this library; if not, write to the
22  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23  * Boston, MA 02111-1307, USA.
24  */
25 /**
26  * SECTION:clutter-main
27  * @short_description: Various 'global' clutter functions.
28  *
29  * Functions to retrieve various global Clutter resources and other utility
30  * functions for mainloops, events and threads
31  */
32
33 #ifdef HAVE_CONFIG_H
34 #include "config.h"
35 #endif
36
37 #include <stdlib.h>
38 #include <glib/gi18n-lib.h>
39 #include <locale.h>
40
41 #include "clutter-event.h"
42 #include "clutter-backend.h"
43 #include "clutter-main.h"
44 #include "clutter-feature.h"
45 #include "clutter-actor.h"
46 #include "clutter-stage.h"
47 #include "clutter-private.h"
48 #include "clutter-debug.h"
49 #include "clutter-version.h"    /* For flavour define */
50 #include "clutter-frame-source.h"
51
52 #include "cogl/cogl.h"
53 #include "pango/cogl-pango.h"
54
55 /* main context */
56 static ClutterMainContext *ClutterCntx       = NULL;
57
58 /* main lock and locking/unlocking functions */
59 static GMutex *clutter_threads_mutex         = NULL;
60 static GCallback clutter_threads_lock        = NULL;
61 static GCallback clutter_threads_unlock      = NULL;
62
63 /* command line options */
64 static gboolean clutter_is_initialized       = FALSE;
65 static gboolean clutter_show_fps             = FALSE;
66 static gboolean clutter_fatal_warnings       = FALSE;
67 static gboolean clutter_disable_mipmap_text  = FALSE;
68 static gboolean clutter_use_fuzzy_picking    = FALSE;
69
70 static guint clutter_default_fps             = 60;
71
72 static PangoDirection clutter_text_direction = PANGO_DIRECTION_LTR;
73
74 static guint clutter_main_loop_level         = 0;
75 static GSList *main_loops                    = NULL;
76
77 guint clutter_debug_flags = 0;  /* global clutter debug flag */
78
79 #ifdef CLUTTER_ENABLE_DEBUG
80 static const GDebugKey clutter_debug_keys[] = {
81   { "misc", CLUTTER_DEBUG_MISC },
82   { "actor", CLUTTER_DEBUG_ACTOR },
83   { "texture", CLUTTER_DEBUG_TEXTURE },
84   { "event", CLUTTER_DEBUG_EVENT },
85   { "paint", CLUTTER_DEBUG_PAINT },
86   { "gl", CLUTTER_DEBUG_GL },
87   { "alpha", CLUTTER_DEBUG_ALPHA },
88   { "behaviour", CLUTTER_DEBUG_BEHAVIOUR },
89   { "pango", CLUTTER_DEBUG_PANGO },
90   { "backend", CLUTTER_DEBUG_BACKEND },
91   { "scheduler", CLUTTER_DEBUG_SCHEDULER },
92   { "script", CLUTTER_DEBUG_SCRIPT },
93   { "shader", CLUTTER_DEBUG_SHADER },
94   { "multistage", CLUTTER_DEBUG_MULTISTAGE },
95   { "animation", CLUTTER_DEBUG_ANIMATION }
96 };
97 #endif /* CLUTTER_ENABLE_DEBUG */
98
99 /**
100  * clutter_get_show_fps:
101  *
102  * Returns whether Clutter should print out the frames per second on the
103  * console. You can enable this setting either using the
104  * <literal>CLUTTER_SHOW_FPS</literal> environment variable or passing
105  * the <literal>--clutter-show-fps</literal> command line argument. *
106  *
107  * Return value: %TRUE if Clutter should show the FPS.
108  *
109  * Since: 0.4
110  */
111 gboolean
112 clutter_get_show_fps (void)
113 {
114   return clutter_show_fps;
115 }
116
117 void
118 _clutter_stage_maybe_relayout (ClutterActor *stage)
119 {
120   ClutterUnit natural_width, natural_height;
121   ClutterActorBox box = { 0, };
122
123   /* avoid reentrancy */
124   if (!(CLUTTER_PRIVATE_FLAGS (stage) & CLUTTER_ACTOR_IN_RELAYOUT))
125     {
126       CLUTTER_NOTE (ACTOR, "Recomputing layout");
127
128       CLUTTER_SET_PRIVATE_FLAGS (stage, CLUTTER_ACTOR_IN_RELAYOUT);
129
130       natural_width = natural_height = 0;
131       clutter_actor_get_preferred_size (stage,
132                                         NULL, NULL,
133                                         &natural_width, &natural_height);
134
135       box.x1 = 0;
136       box.y1 = 0;
137       box.x2 = natural_width;
138       box.y2 = natural_height;
139
140       CLUTTER_NOTE (ACTOR, "Allocating (0, 0 - %d, %d) for the stage",
141                     CLUTTER_UNITS_TO_DEVICE (natural_width),
142                     CLUTTER_UNITS_TO_DEVICE (natural_height));
143
144       clutter_actor_allocate (stage, &box, FALSE);
145
146       CLUTTER_UNSET_PRIVATE_FLAGS (stage, CLUTTER_ACTOR_IN_RELAYOUT);
147     }
148 }
149
150 void
151 _clutter_stage_maybe_setup_viewport (ClutterStage *stage)
152 {
153   if (CLUTTER_PRIVATE_FLAGS (stage) & CLUTTER_ACTOR_SYNC_MATRICES)
154     {
155       ClutterPerspective perspective;
156       guint width, height;
157
158       clutter_actor_get_size (CLUTTER_ACTOR (stage), &width, &height);
159       clutter_stage_get_perspectivex (stage, &perspective);
160
161       CLUTTER_NOTE (PAINT, "Setting up the viewport");
162
163       cogl_setup_viewport (width, height,
164                            perspective.fovy,
165                            perspective.aspect,
166                            perspective.z_near,
167                            perspective.z_far);
168
169       CLUTTER_UNSET_PRIVATE_FLAGS (stage, CLUTTER_ACTOR_SYNC_MATRICES);
170     }
171 }
172
173 /**
174  * clutter_redraw:
175  *
176  * Forces a redraw of the entire stage. Applications should never use this
177  * function, but queue a redraw using clutter_actor_queue_redraw().
178  */
179 void
180 clutter_redraw (ClutterStage *stage)
181 {
182   ClutterMainContext *ctx;
183   static GTimer      *timer = NULL;
184   static guint        timer_n_frames = 0;
185
186   ctx  = clutter_context_get_default ();
187
188   CLUTTER_TIMESTAMP (SCHEDULER, "Redraw start for stage:%p", stage);
189   CLUTTER_NOTE (PAINT, " Redraw enter for stage:%p", stage);
190   CLUTTER_NOTE (MULTISTAGE, "Redraw called for stage:%p", stage);
191
192   /* Before we can paint, we have to be sure we have the latest layout */
193   _clutter_stage_maybe_relayout (CLUTTER_ACTOR (stage));
194
195   _clutter_backend_ensure_context (ctx->backend, stage);
196
197   /* Setup FPS count - not currently across *all* stages rather than per */
198   if (G_UNLIKELY (clutter_get_show_fps ()))
199     {
200       if (!timer)
201         timer = g_timer_new ();
202     }
203
204   /* The code below can't go in stage paint as base actor_paint
205    * will get called before it (and break picking, etc)
206    */
207   _clutter_stage_maybe_setup_viewport (stage);
208
209   /* Call through to the actual backend to do the painting down from
210    * the stage. It will likely need to swap buffers, vblank sync etc
211    * which will be windowing system dependant.
212   */
213   _clutter_backend_redraw (ctx->backend, stage);
214
215   /* Complete FPS info */
216   if (G_UNLIKELY (clutter_get_show_fps ()))
217     {
218       timer_n_frames++;
219
220       if (g_timer_elapsed (timer, NULL) >= 1.0)
221         {
222           g_print ("*** FPS: %i ***\n", timer_n_frames);
223           timer_n_frames = 0;
224           g_timer_start (timer);
225         }
226     }
227
228   CLUTTER_NOTE (PAINT, " Redraw leave for stage:%p", stage);
229   CLUTTER_TIMESTAMP (SCHEDULER, "Redraw finish for stage:%p", stage);
230 }
231
232 /**
233  * clutter_set_motion_events_enabled:
234  * @enable: %TRUE to enable per-actor motion events
235  *
236  * Sets whether per-actor motion events should be enabled or not (the
237  * default is to enable them).
238  *
239  * If @enable is %FALSE the following events will not work:
240  * <itemizedlist>
241  *   <listitem><para>ClutterActor::motion-event, unless on the
242  *     #ClutterStage</para></listitem>
243  *   <listitem><para>ClutterActor::enter-event</para></listitem>
244  *   <listitem><para>ClutterActor::leave-event</para></listitem>
245  * </itemizedlist>
246  *
247  * Since: 0.6
248  */
249 void
250 clutter_set_motion_events_enabled (gboolean enable)
251 {
252   ClutterMainContext *context = clutter_context_get_default ();
253
254   context->motion_events_per_actor = enable;
255 }
256
257 /**
258  * clutter_get_motion_events_enabled:
259  *
260  * Gets whether the per-actor motion events are enabled.
261  *
262  * Return value: %TRUE if the motion events are enabled
263  *
264  * Since: 0.6
265  */
266 gboolean
267 clutter_get_motion_events_enabled (void)
268 {
269   ClutterMainContext *context = clutter_context_get_default ();
270
271   return context->motion_events_per_actor;
272 }
273
274 guint _clutter_pix_to_id (guchar pixel[4]);
275
276 static inline void init_bits (void)
277 {
278   ClutterMainContext *ctx;
279
280   static gboolean done = FALSE;
281   if (G_LIKELY (done))
282     return;
283
284   ctx = clutter_context_get_default ();
285
286   done = TRUE;
287 }
288
289 void
290 _clutter_id_to_color (guint id, ClutterColor *col)
291 {
292   ClutterMainContext *ctx;
293   gint                red, green, blue;
294   ctx = clutter_context_get_default ();
295
296   /* compute the numbers we'll store in the components */
297   red   = (id >> (ctx->fb_g_mask_used+ctx->fb_b_mask_used))
298                 & (0xff >> (8-ctx->fb_r_mask_used));
299   green = (id >> ctx->fb_b_mask_used) & (0xff >> (8-ctx->fb_g_mask_used));
300   blue  = (id)  & (0xff >> (8-ctx->fb_b_mask_used));
301
302   /* shift left bits a bit and add one, this circumvents
303    * at least some potential rounding errors in GL/GLES
304    * driver / hw implementation.
305    */
306   if (ctx->fb_r_mask_used != ctx->fb_r_mask)
307     red = red * 2;
308   if (ctx->fb_g_mask_used != ctx->fb_g_mask)
309     green = green * 2;
310   if (ctx->fb_b_mask_used != ctx->fb_b_mask)
311     blue  = blue  * 2;
312
313   /* shift up to be full 8bit values */
314   red   = (red   << (8 - ctx->fb_r_mask)) | (0x7f >> (ctx->fb_r_mask_used));
315   green = (green << (8 - ctx->fb_g_mask)) | (0x7f >> (ctx->fb_g_mask_used));
316   blue  = (blue  << (8 - ctx->fb_b_mask)) | (0x7f >> (ctx->fb_b_mask_used));
317
318   col->red   = red;
319   col->green = green;
320   col->blue  = blue;
321   col->alpha = 0xff;
322 }
323
324 guint
325 _clutter_pixel_to_id (guchar pixel[4])
326 {
327   ClutterMainContext *ctx;
328   gint  red, green, blue;
329   guint id;
330
331   ctx = clutter_context_get_default ();
332
333   /* reduce the pixel components to the number of bits actually used of the
334    * 8bits.
335    */
336   red   = pixel[0] >> (8 - ctx->fb_r_mask);
337   green = pixel[1] >> (8 - ctx->fb_g_mask);
338   blue  = pixel[2] >> (8 - ctx->fb_b_mask);
339
340   /* divide potentially by two if 'fuzzy' */
341   red   = red   >> (ctx->fb_r_mask - ctx->fb_r_mask_used);
342   green = green >> (ctx->fb_g_mask - ctx->fb_g_mask_used);
343   blue  = blue  >> (ctx->fb_b_mask - ctx->fb_b_mask_used);
344
345   /* combine the correct per component values into the final id */
346   id =  blue + (green <<  ctx->fb_b_mask_used)
347           + (red << (ctx->fb_b_mask_used + ctx->fb_g_mask_used));
348
349   return id;
350 }
351
352 ClutterActor *
353 _clutter_do_pick (ClutterStage   *stage,
354                   gint            x,
355                   gint            y,
356                   ClutterPickMode mode)
357 {
358   ClutterMainContext *context;
359   guchar              pixel[4];
360   GLint               viewport[4];
361   CoglColor           white;
362   guint32             id;
363   GLboolean           dither_was_on;
364
365   context = clutter_context_get_default ();
366
367   _clutter_backend_ensure_context (context->backend, stage);
368
369   /* needed for when a context switch happens */
370   _clutter_stage_maybe_setup_viewport (stage);
371
372   cogl_color_set_from_4ub (&white, 255, 255, 255, 255);
373   cogl_disable_fog ();
374   cogl_clear (&white);
375
376   /* Disable dithering (if any) when doing the painting in pick mode */
377   dither_was_on = glIsEnabled (GL_DITHER);
378   glDisable (GL_DITHER);
379
380   /* Render the entire scence in pick mode - just single colored silhouette's
381    * are drawn offscreen (as we never swap buffers)
382   */
383   context->pick_mode = mode;
384   clutter_actor_paint (CLUTTER_ACTOR (stage));
385   context->pick_mode = CLUTTER_PICK_NONE;
386
387   /* Calls should work under both GL and GLES, note GLES needs RGBA */
388   glGetIntegerv(GL_VIEWPORT, viewport);
389
390   /* Below to be safe, particularly on GL ES. an EGL wait call or full
391    * could be nicer.
392   */
393   glFinish();
394
395   /* Read the color of the screen co-ords pixel */
396   glReadPixels (x, viewport[3] - y -1, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, pixel);
397
398   /* Restore whether GL_DITHER was enabled */
399   if (dither_was_on)
400     glEnable (GL_DITHER);
401
402   if (pixel[0] == 0xff && pixel[1] == 0xff && pixel[2] == 0xff)
403     return CLUTTER_ACTOR (stage);
404
405   id = _clutter_pixel_to_id (pixel);
406
407   return clutter_get_actor_by_gid (id);
408 }
409
410 static PangoDirection
411 clutter_get_text_direction (void)
412 {
413   PangoDirection dir = PANGO_DIRECTION_LTR;
414   const gchar *direction;
415
416   direction = g_getenv ("CLUTTER_TEXT_DIRECTION");
417   if (direction && *direction != '\0')
418     {
419       if (strcmp (direction, "rtl") == 0)
420         dir = PANGO_DIRECTION_RTL;
421       else if (strcmp (direction, "ltr") == 0)
422         dir = PANGO_DIRECTION_LTR;
423     }
424   else
425     {
426       /* Translate to default:RTL if you want your widgets
427        * to be RTL, otherwise translate to default:LTR.
428        *
429        * Do *not* translate it to "predefinito:LTR": if it
430        * it isn't default:LTR or default:RTL it will not work
431        */
432       char *e = _("default:LTR");
433
434       if (strcmp (e, "default:RTL") == 0)
435         dir = PANGO_DIRECTION_RTL;
436       else if (strcmp (e, "default:LTR") == 0)
437         dir = PANGO_DIRECTION_LTR;
438       else
439         g_warning ("Whoever translated default:LTR did so wrongly.");
440     }
441
442   return dir;
443 }
444
445 static void
446 update_pango_context (ClutterBackend *backend,
447                       PangoContext   *context)
448 {
449   PangoFontDescription *font_desc;
450   cairo_font_options_t *font_options;
451   const gchar *font_name;
452   gdouble resolution;
453
454   /* update the text direction */
455   pango_context_set_base_dir (context, clutter_text_direction);
456
457   /* get the configuration for the PangoContext from the backend */
458   font_name = clutter_backend_get_font_name (backend);
459   font_options = clutter_backend_get_font_options (backend);
460   resolution = clutter_backend_get_resolution (backend);
461
462   font_desc = pango_font_description_from_string (font_name);
463
464   if (resolution < 0)
465     resolution = 96.0; /* fall back */
466
467   pango_context_set_font_description (context, font_desc);
468   pango_cairo_context_set_font_options (context, font_options);
469   pango_cairo_context_set_resolution (context, resolution);
470
471   pango_font_description_free (font_desc);
472 }
473
474 PangoContext *
475 _clutter_context_get_pango_context (ClutterMainContext *self)
476 {
477   if (G_UNLIKELY (self->pango_context == NULL))
478     {
479       PangoContext *context;
480
481       context = cogl_pango_font_map_create_context (self->font_map);
482       self->pango_context = context;
483
484       g_signal_connect (self->backend, "resolution-changed",
485                         G_CALLBACK (update_pango_context),
486                         self->pango_context);
487       g_signal_connect (self->backend, "font-changed",
488                         G_CALLBACK (update_pango_context),
489                         self->pango_context);
490     }
491
492   update_pango_context (self->backend, self->pango_context);
493
494   return self->pango_context;
495 }
496
497 PangoContext *
498 _clutter_context_create_pango_context (ClutterMainContext *self)
499 {
500   PangoContext *context;
501
502   context = cogl_pango_font_map_create_context (self->font_map);
503   update_pango_context (self->backend, context);
504
505   return context;
506 }
507
508 /**
509  * clutter_main_quit:
510  *
511  * Terminates the Clutter mainloop.
512  */
513 void
514 clutter_main_quit (void)
515 {
516   g_return_if_fail (main_loops != NULL);
517
518   g_main_loop_quit (main_loops->data);
519 }
520
521 /**
522  * clutter_main_level:
523  *
524  * Retrieves the depth of the Clutter mainloop.
525  *
526  * Return value: The level of the mainloop.
527  */
528 gint
529 clutter_main_level (void)
530 {
531   return clutter_main_loop_level;
532 }
533
534 /**
535  * clutter_main:
536  *
537  * Starts the Clutter mainloop.
538  */
539 void
540 clutter_main (void)
541 {
542   GMainLoop *loop;
543
544   /* Make sure there is a context */
545   CLUTTER_CONTEXT ();
546
547   if (!clutter_is_initialized)
548     {
549       g_warning ("Called clutter_main() but Clutter wasn't initialised.  "
550                  "You must call clutter_init() first.");
551       return;
552     }
553
554   CLUTTER_MARK ();
555
556   clutter_main_loop_level++;
557
558   loop = g_main_loop_new (NULL, TRUE);
559   main_loops = g_slist_prepend (main_loops, loop);
560
561 #ifdef HAVE_CLUTTER_FRUITY
562   /* clutter fruity creates an application that forwards events and manually
563    * spins the mainloop
564    */
565   clutter_fruity_main ();
566 #else
567   if (g_main_loop_is_running (main_loops->data))
568     {
569       clutter_threads_leave ();
570       g_main_loop_run (loop);
571       clutter_threads_enter ();
572     }
573 #endif
574
575   main_loops = g_slist_remove (main_loops, loop);
576
577   g_main_loop_unref (loop);
578
579   clutter_main_loop_level--;
580
581   CLUTTER_MARK ();
582 }
583
584 static void
585 clutter_threads_impl_lock (void)
586 {
587   if (clutter_threads_mutex)
588     g_mutex_lock (clutter_threads_mutex);
589 }
590
591 static void
592 clutter_threads_impl_unlock (void)
593 {
594   if (clutter_threads_mutex)
595     g_mutex_unlock (clutter_threads_mutex);
596 }
597
598 /**
599  * clutter_threads_init:
600  *
601  * Initialises the Clutter threading mechanism, so that Clutter API can be
602  * called by multiple threads, using clutter_threads_enter() and
603  * clutter_threads_leave() to mark the critical sections.
604  *
605  * You must call g_thread_init() before this function.
606  *
607  * This function must be called before clutter_init().
608  *
609  * Since: 0.4
610  */
611 void
612 clutter_threads_init (void)
613 {
614   if (!g_thread_supported ())
615     g_error ("g_thread_init() must be called before clutter_threads_init()");
616
617   clutter_threads_mutex = g_mutex_new ();
618
619   if (!clutter_threads_lock)
620     clutter_threads_lock = clutter_threads_impl_lock;
621
622   if (!clutter_threads_unlock)
623     clutter_threads_unlock = clutter_threads_impl_unlock;
624 }
625
626 /**
627  * clutter_threads_set_lock_functions:
628  * @enter_fn: function called when aquiring the Clutter main lock
629  * @leave_fn: function called when releasing the Clutter main lock
630  *
631  * Allows the application to replace the standard method that
632  * Clutter uses to protect its data structures. Normally, Clutter
633  * creates a single #GMutex that is locked by clutter_threads_enter(),
634  * and released by clutter_threads_leave(); using this function an
635  * application provides, instead, a function @enter_fn that is
636  * called by clutter_threads_enter() and a function @leave_fn that is
637  * called by clutter_threads_leave().
638  *
639  * The functions must provide at least same locking functionality
640  * as the default implementation, but can also do extra application
641  * specific processing.
642  *
643  * As an example, consider an application that has its own recursive
644  * lock that when held, holds the Clutter lock as well. When Clutter
645  * unlocks the Clutter lock when entering a recursive main loop, the
646  * application must temporarily release its lock as well.
647  *
648  * Most threaded Clutter apps won't need to use this method.
649  *
650  * This method must be called before clutter_threads_init(), and cannot
651  * be called multiple times.
652  *
653  * Since: 0.4
654  */
655 void
656 clutter_threads_set_lock_functions (GCallback enter_fn,
657                                     GCallback leave_fn)
658 {
659   g_return_if_fail (clutter_threads_lock == NULL &&
660                     clutter_threads_unlock == NULL);
661
662   clutter_threads_lock = enter_fn;
663   clutter_threads_unlock = leave_fn;
664 }
665
666 typedef struct
667 {
668   GSourceFunc func;
669   gpointer data;
670   GDestroyNotify notify;
671 } ClutterThreadsDispatch;
672
673 static gboolean
674 clutter_threads_dispatch (gpointer data)
675 {
676   ClutterThreadsDispatch *dispatch = data;
677   gboolean ret = FALSE;
678
679   clutter_threads_enter ();
680
681   if (!g_source_is_destroyed (g_main_current_source ()))
682     ret = dispatch->func (dispatch->data);
683
684   clutter_threads_leave ();
685
686   return ret;
687 }
688
689 static void
690 clutter_threads_dispatch_free (gpointer data)
691 {
692   ClutterThreadsDispatch *dispatch = data;
693
694   /* XXX - we cannot hold the thread lock here because the main loop
695    * might destroy a source while still in the dispatcher function; so
696    * knowing whether the lock is being held or not is not known a priori.
697    *
698    * see bug: http://bugzilla.gnome.org/show_bug.cgi?id=459555
699    */
700   if (dispatch->notify)
701     dispatch->notify (dispatch->data);
702
703   g_slice_free (ClutterThreadsDispatch, dispatch);
704 }
705
706 /**
707  * clutter_threads_add_idle_full:
708  * @priority: the priority of the timeout source. Typically this will be in the
709  *    range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE
710  * @func: function to call
711  * @data: data to pass to the function
712  * @notify: functio to call when the idle source is removed
713  *
714  * Adds a function to be called whenever there are no higher priority
715  * events pending. If the function returns %FALSE it is automatically
716  * removed from the list of event sources and will not be called again.
717  *
718  * This function can be considered a thread-safe variant of g_idle_add_full():
719  * it will call @function while holding the Clutter lock. It is logically
720  * equivalent to the following implementation:
721  *
722  * |[
723  * static gboolean
724  * idle_safe_callback (gpointer data)
725  * {
726  *    SafeClosure *closure = data;
727  *    gboolean res = FALSE;
728  *
729  *    /&ast; mark the critical section &ast;/
730  *
731  *    clutter_threads_enter();
732  *
733  *    /&ast; the callback does not need to acquire the Clutter
734  *     &ast; lock itself, as it is held by the this proxy handler
735  *     &ast;/
736  *    res = closure->callback (closure->data);
737  *
738  *    clutter_threads_leave();
739  *
740  *    return res;
741  * }
742  * static gulong
743  * add_safe_idle (GSourceFunc callback,
744  *                gpointer    data)
745  * {
746  *   SafeClosure *closure = g_new0 (SafeClosure, 1);
747  *
748  *   closure-&gt;callback = callback;
749  *   closure-&gt;data = data;
750  *
751  *   return g_add_idle_full (G_PRIORITY_DEFAULT_IDLE,
752  *                           idle_safe_callback,
753  *                           closure,
754  *                           g_free)
755  * }
756  *]|
757  *
758  * This function should be used by threaded applications to make sure
759  * that @func is emitted under the Clutter threads lock and invoked
760  * from the same thread that started the Clutter main loop. For instance,
761  * it can be used to update the UI using the results from a worker
762  * thread:
763  *
764  * |[
765  * static gboolean
766  * update_ui (gpointer data)
767  * {
768  *   SomeClosure *closure = data;
769  *
770  *   /&ast; it is safe to call Clutter API from this function because
771  *    &ast; it is invoked from the same thread that started the main
772  *    &ast; loop and under the Clutter thread lock
773  *    &ast;/
774  *   clutter_label_set_text (CLUTTER_LABEL (closure-&gt;label),
775  *                           closure-&gt;text);
776  *
777  *   g_object_unref (closure-&gt;label);
778  *   g_free (closure);
779  *
780  *   return FALSE;
781  * }
782  *
783  *   /&ast; within another thread &ast;/
784  *   closure = g_new0 (SomeClosure, 1);
785  *   /&ast; always take a reference on GObject instances &ast;/
786  *   closure-&gt;label = g_object_ref (my_application-&gt;label);
787  *   closure-&gt;text = g_strdup (processed_text_to_update_the_label);
788  *
789  *   clutter_threads_add_idle_full (G_PRIORITY_HIGH_IDLE,
790  *                                  update_ui,
791  *                                  closure,
792  *                                  NULL);
793  * ]|
794  *
795  * Return value: the ID (greater than 0) of the event source.
796  *
797  * Since: 0.4
798  */
799 guint
800 clutter_threads_add_idle_full (gint           priority,
801                                GSourceFunc    func,
802                                gpointer       data,
803                                GDestroyNotify notify)
804 {
805   ClutterThreadsDispatch *dispatch;
806
807   g_return_val_if_fail (func != NULL, 0);
808
809   dispatch = g_slice_new (ClutterThreadsDispatch);
810   dispatch->func = func;
811   dispatch->data = data;
812   dispatch->notify = notify;
813
814   return g_idle_add_full (priority,
815                           clutter_threads_dispatch, dispatch,
816                           clutter_threads_dispatch_free);
817 }
818
819 /**
820  * clutter_threads_add_idle:
821  * @func: function to call
822  * @data: data to pass to the function
823  *
824  * Simple wrapper around clutter_threads_add_idle_full() using the
825  * default priority.
826  *
827  * Return value: the ID (greater than 0) of the event source.
828  *
829  * Since: 0.4
830  */
831 guint
832 clutter_threads_add_idle (GSourceFunc func,
833                           gpointer    data)
834 {
835   g_return_val_if_fail (func != NULL, 0);
836
837   return clutter_threads_add_idle_full (G_PRIORITY_DEFAULT_IDLE,
838                                         func, data,
839                                         NULL);
840 }
841
842 /**
843  * clutter_threads_add_timeout_full:
844  * @priority: the priority of the timeout source. Typically this will be in the
845  *            range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
846  * @interval: the time between calls to the function, in milliseconds
847  * @func: function to call
848  * @data: data to pass to the function
849  * @notify: function to call when the timeout source is removed
850  *
851  * Sets a function to be called at regular intervals holding the Clutter
852  * threads lock, with the given priority. The function is called repeatedly
853  * until it returns %FALSE, at which point the timeout is automatically
854  * removed and the function will not be called again. The @notify function
855  * is called when the timeout is removed.
856  *
857  * The first call to the function will be at the end of the first @interval.
858  *
859  * It is important to note that, due to how the Clutter main loop is
860  * implemented, the timing will not be accurate and it will not try to
861  * "keep up" with the interval. A more reliable source is available
862  * using clutter_threads_add_frame_source_full(), which is also internally
863  * used by #ClutterTimeline.
864  *
865  * See also clutter_threads_add_idle_full().
866  *
867  * Return value: the ID (greater than 0) of the event source.
868  *
869  * Since: 0.4
870  */
871 guint
872 clutter_threads_add_timeout_full (gint           priority,
873                                   guint          interval,
874                                   GSourceFunc    func,
875                                   gpointer       data,
876                                   GDestroyNotify notify)
877 {
878   ClutterThreadsDispatch *dispatch;
879
880   g_return_val_if_fail (func != NULL, 0);
881
882   dispatch = g_slice_new (ClutterThreadsDispatch);
883   dispatch->func = func;
884   dispatch->data = data;
885   dispatch->notify = notify;
886
887   return g_timeout_add_full (priority,
888                              interval,
889                              clutter_threads_dispatch, dispatch,
890                              clutter_threads_dispatch_free);
891 }
892
893 /**
894  * clutter_threads_add_timeout:
895  * @interval: the time between calls to the function, in milliseconds
896  * @func: function to call
897  * @data: data to pass to the function
898  *
899  * Simple wrapper around clutter_threads_add_timeout_full().
900  *
901  * Return value: the ID (greater than 0) of the event source.
902  *
903  * Since: 0.4
904  */
905 guint
906 clutter_threads_add_timeout (guint       interval,
907                              GSourceFunc func,
908                              gpointer    data)
909 {
910   g_return_val_if_fail (func != NULL, 0);
911
912   return clutter_threads_add_timeout_full (G_PRIORITY_DEFAULT,
913                                            interval,
914                                            func, data,
915                                            NULL);
916 }
917
918 /**
919  * clutter_threads_add_frame_source_full:
920  * @priority: the priority of the frame source. Typically this will be in the
921  *            range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
922  * @interval: the time between calls to the function, in milliseconds
923  * @func: function to call
924  * @data: data to pass to the function
925  * @notify: function to call when the timeout source is removed
926  *
927  * Sets a function to be called at regular intervals holding the Clutter
928  * threads lock, with the given priority. The function is called repeatedly
929  * until it returns %FALSE, at which point the timeout is automatically
930  * removed and the function will not be called again. The @notify function
931  * is called when the timeout is removed.
932  *
933  * This function is similar to clutter_threads_add_timeout_full()
934  * except that it will try to compensate for delays. For example, if
935  * @func takes half the interval time to execute then the function
936  * will be called again half the interval time after it finished. In
937  * contrast clutter_threads_add_timeout_full() would not fire until a
938  * full interval after the function completes so the delay between
939  * calls would be @interval * 1.5. This function does not however try
940  * to invoke the function multiple times to catch up missing frames if
941  * @func takes more than @interval ms to execute.
942  *
943  * See also clutter_threads_add_idle_full().
944  *
945  * Return value: the ID (greater than 0) of the event source.
946  *
947  * Since: 0.8
948  */
949 guint
950 clutter_threads_add_frame_source_full (gint           priority,
951                                        guint          interval,
952                                        GSourceFunc    func,
953                                        gpointer       data,
954                                        GDestroyNotify notify)
955 {
956   ClutterThreadsDispatch *dispatch;
957
958   g_return_val_if_fail (func != NULL, 0);
959
960   dispatch = g_slice_new (ClutterThreadsDispatch);
961   dispatch->func = func;
962   dispatch->data = data;
963   dispatch->notify = notify;
964
965   return clutter_frame_source_add_full (priority,
966                                         interval,
967                                         clutter_threads_dispatch, dispatch,
968                                         clutter_threads_dispatch_free);
969 }
970
971 /**
972  * clutter_threads_add_frame_source:
973  * @interval: the time between calls to the function, in milliseconds
974  * @func: function to call
975  * @data: data to pass to the function
976  *
977  * Simple wrapper around clutter_threads_add_frame_source_full().
978  *
979  * Return value: the ID (greater than 0) of the event source.
980  *
981  * Since: 0.8
982  */
983 guint
984 clutter_threads_add_frame_source (guint       interval,
985                                   GSourceFunc func,
986                                   gpointer    data)
987 {
988   g_return_val_if_fail (func != NULL, 0);
989
990   return clutter_threads_add_frame_source_full (G_PRIORITY_DEFAULT,
991                                                 interval,
992                                                 func, data,
993                                                 NULL);
994 }
995
996 /**
997  * clutter_threads_enter:
998  *
999  * Locks the Clutter thread lock.
1000  *
1001  * Since: 0.4
1002  */
1003 void
1004 clutter_threads_enter (void)
1005 {
1006   if (clutter_threads_lock)
1007     (* clutter_threads_lock) ();
1008 }
1009
1010 /**
1011  * clutter_threads_leave:
1012  *
1013  * Unlocks the Clutter thread lock.
1014  *
1015  * Since: 0.4
1016  */
1017 void
1018 clutter_threads_leave (void)
1019 {
1020   if (clutter_threads_unlock)
1021     (* clutter_threads_unlock) ();
1022 }
1023
1024
1025 /**
1026  * clutter_get_debug_enabled:
1027  *
1028  * Check if clutter has debugging turned on.
1029  *
1030  * Return value: TRUE if debugging is turned on, FALSE otherwise.
1031  */
1032 gboolean
1033 clutter_get_debug_enabled (void)
1034 {
1035 #ifdef CLUTTER_ENABLE_DEBUG
1036   return clutter_debug_flags != 0;
1037 #else
1038   return FALSE;
1039 #endif
1040 }
1041
1042 ClutterMainContext *
1043 clutter_context_get_default (void)
1044 {
1045   if (G_UNLIKELY(!ClutterCntx))
1046     {
1047       ClutterMainContext *ctx;
1048
1049       ClutterCntx = ctx = g_new0 (ClutterMainContext, 1);
1050       ctx->backend = g_object_new (_clutter_backend_impl_get_type (), NULL);
1051
1052       ctx->is_initialized = FALSE;
1053       ctx->motion_events_per_actor = TRUE;
1054
1055 #ifdef CLUTTER_ENABLE_DEBUG
1056       ctx->timer          =  g_timer_new ();
1057       g_timer_start (ctx->timer);
1058 #endif
1059     }
1060
1061   return ClutterCntx;
1062 }
1063
1064 /**
1065  * clutter_get_timestamp:
1066  *
1067  * Returns the approximate number of microseconds passed since clutter was
1068  * intialised.
1069  *
1070  * Return value: Number of microseconds since clutter_init() was called.
1071  */
1072 gulong
1073 clutter_get_timestamp (void)
1074 {
1075 #ifdef CLUTTER_ENABLE_DEBUG
1076   ClutterMainContext *ctx;
1077   gdouble seconds;
1078
1079   ctx = clutter_context_get_default ();
1080
1081   /* FIXME: may need a custom timer for embedded setups */
1082   seconds = g_timer_elapsed (ctx->timer, NULL);
1083
1084   return (gulong)(seconds / 1.0e-6);
1085 #else
1086   return 0;
1087 #endif
1088 }
1089
1090 static gboolean
1091 clutter_arg_direction_cb (const char *key,
1092                           const char *value,
1093                           gpointer    user_data)
1094 {
1095   clutter_text_direction =
1096     (strcmp (value, "rtl") == 0) ? PANGO_DIRECTION_RTL
1097                                  : PANGO_DIRECTION_LTR;
1098
1099   return TRUE;
1100 }
1101
1102 #ifdef CLUTTER_ENABLE_DEBUG
1103 static gboolean
1104 clutter_arg_debug_cb (const char *key,
1105                       const char *value,
1106                       gpointer    user_data)
1107 {
1108   clutter_debug_flags |=
1109     g_parse_debug_string (value,
1110                           clutter_debug_keys,
1111                           G_N_ELEMENTS (clutter_debug_keys));
1112   return TRUE;
1113 }
1114
1115 static gboolean
1116 clutter_arg_no_debug_cb (const char *key,
1117                          const char *value,
1118                          gpointer    user_data)
1119 {
1120   clutter_debug_flags &=
1121     ~g_parse_debug_string (value,
1122                            clutter_debug_keys,
1123                            G_N_ELEMENTS (clutter_debug_keys));
1124   return TRUE;
1125 }
1126 #endif /* CLUTTER_ENABLE_DEBUG */
1127
1128 GQuark
1129 clutter_init_error_quark (void)
1130 {
1131   return g_quark_from_static_string ("clutter-init-error-quark");
1132 }
1133
1134 static ClutterInitError
1135 clutter_init_real (GError **error)
1136 {
1137   ClutterMainContext *ctx;
1138   ClutterActor *stage;
1139   gdouble resolution;
1140   ClutterBackend *backend;
1141
1142   /* Note, creates backend if not already existing, though parse args will
1143    * have likely created it
1144    */
1145   ctx = clutter_context_get_default ();
1146   backend = ctx->backend;
1147
1148   if (!ctx->options_parsed)
1149     {
1150       g_set_error (error, CLUTTER_INIT_ERROR,
1151                    CLUTTER_INIT_ERROR_INTERNAL,
1152                    "When using clutter_get_option_group_without_init() "
1153                    "you must parse options before calling clutter_init()");
1154
1155       return CLUTTER_INIT_ERROR_INTERNAL;
1156     }
1157
1158   /*
1159    * Call backend post parse hooks.
1160    */
1161   if (!_clutter_backend_post_parse (backend, error))
1162     return CLUTTER_INIT_ERROR_BACKEND;
1163
1164   /* Stage will give us a GL Context etc */
1165   stage = clutter_stage_get_default ();
1166   if (!stage)
1167     {
1168       if (error)
1169         g_set_error (error, CLUTTER_INIT_ERROR,
1170                      CLUTTER_INIT_ERROR_INTERNAL,
1171                      "Unable to create the default stage");
1172       else
1173         g_critical ("Unable to create the default stage");
1174
1175       return CLUTTER_INIT_ERROR_INTERNAL;
1176     }
1177
1178   clutter_stage_set_title (CLUTTER_STAGE (stage), g_get_prgname ());
1179
1180   clutter_actor_realize (stage);
1181
1182   if (!CLUTTER_ACTOR_IS_REALIZED (stage))
1183     {
1184       if (error)
1185         g_set_error (error, CLUTTER_INIT_ERROR,
1186                      CLUTTER_INIT_ERROR_INTERNAL,
1187                      "Unable to realize the default stage");
1188       else
1189         g_critical ("Unable to realize the default stage");
1190
1191       return CLUTTER_INIT_ERROR_INTERNAL;
1192     }
1193
1194   /* Now we can safely assume we have a valid GL context and can
1195    * start issueing cogl commands
1196   */
1197
1198   /*
1199    * Resolution requires display to be open, so can only be queried after
1200    * the post_parse hooks run.
1201    *
1202    * NB: cogl_pango requires a Cogl context.
1203    */
1204   ctx->font_map = COGL_PANGO_FONT_MAP (cogl_pango_font_map_new ());
1205
1206   resolution = clutter_backend_get_resolution (ctx->backend);
1207   cogl_pango_font_map_set_resolution (ctx->font_map, resolution);
1208
1209   if (G_LIKELY (!clutter_disable_mipmap_text))
1210     cogl_pango_font_map_set_use_mipmapping (ctx->font_map, TRUE);
1211
1212   clutter_text_direction = clutter_get_text_direction ();
1213
1214
1215   /* Figure out framebuffer masks used for pick */
1216   cogl_get_bitmasks (&ctx->fb_r_mask, &ctx->fb_g_mask, &ctx->fb_b_mask, NULL);
1217
1218   ctx->fb_r_mask_used = ctx->fb_r_mask;
1219   ctx->fb_g_mask_used = ctx->fb_g_mask;
1220   ctx->fb_b_mask_used = ctx->fb_b_mask;
1221
1222   /* XXX - describe what "fuzzy picking" is */
1223   if (clutter_use_fuzzy_picking)
1224     {
1225       ctx->fb_r_mask_used--;
1226       ctx->fb_g_mask_used--;
1227       ctx->fb_b_mask_used--;
1228     }
1229
1230   /* Initiate event collection */
1231   _clutter_backend_init_events (ctx->backend);
1232
1233   /* finally features - will call to backend and cogl */
1234   _clutter_feature_init ();
1235
1236   clutter_is_initialized = TRUE;
1237   ctx->is_initialized = TRUE;
1238
1239   return CLUTTER_INIT_SUCCESS;
1240 }
1241
1242 static GOptionEntry clutter_args[] = {
1243   { "clutter-show-fps", 0, 0, G_OPTION_ARG_NONE, &clutter_show_fps,
1244     N_("Show frames per second"), NULL },
1245   { "clutter-default-fps", 0, 0, G_OPTION_ARG_INT, &clutter_default_fps,
1246     N_("Default frame rate"), "FPS" },
1247   { "g-fatal-warnings", 0, 0, G_OPTION_ARG_NONE, &clutter_fatal_warnings,
1248     N_("Make all warnings fatal"), NULL },
1249   { "clutter-text-direction", 0, 0, G_OPTION_ARG_CALLBACK,
1250     clutter_arg_direction_cb,
1251     N_("Direction for the text"), "DIRECTION" },
1252   { "clutter-disable-mipmapped-text", 0, 0, G_OPTION_ARG_NONE,
1253     &clutter_disable_mipmap_text,
1254     N_("Disable mipmapping on text"), NULL },
1255   { "clutter-use-fuzzy-picking", 0, 0, G_OPTION_ARG_NONE,
1256     &clutter_use_fuzzy_picking,
1257     N_("Use 'fuzzy' picking"), NULL },
1258 #ifdef CLUTTER_ENABLE_DEBUG
1259   { "clutter-debug", 0, 0, G_OPTION_ARG_CALLBACK, clutter_arg_debug_cb,
1260     N_("Clutter debugging flags to set"), "FLAGS" },
1261   { "clutter-no-debug", 0, 0, G_OPTION_ARG_CALLBACK, clutter_arg_no_debug_cb,
1262     N_("Clutter debugging flags to unset"), "FLAGS" },
1263 #endif /* CLUTTER_ENABLE_DEBUG */
1264   { NULL, },
1265 };
1266
1267 /* pre_parse_hook: initialise variables depending on environment
1268  * variables; these variables might be overridden by the command
1269  * line arguments that are going to be parsed after.
1270  */
1271 static gboolean
1272 pre_parse_hook (GOptionContext  *context,
1273                 GOptionGroup    *group,
1274                 gpointer         data,
1275                 GError         **error)
1276 {
1277   ClutterMainContext *clutter_context;
1278   ClutterBackend *backend;
1279   const char *env_string;
1280
1281   if (clutter_is_initialized)
1282     return TRUE;
1283
1284   if (setlocale (LC_ALL, "") == NULL)
1285     g_warning ("Locale not supported by C library.\n"
1286                "Using the fallback 'C' locale.");
1287
1288   clutter_context = clutter_context_get_default ();
1289
1290   clutter_context->id_pool = clutter_id_pool_new (256);
1291
1292   backend = clutter_context->backend;
1293   g_assert (CLUTTER_IS_BACKEND (backend));
1294
1295 #ifdef CLUTTER_ENABLE_DEBUG
1296   env_string = g_getenv ("CLUTTER_DEBUG");
1297   if (env_string != NULL)
1298     {
1299       clutter_debug_flags =
1300         g_parse_debug_string (env_string,
1301                               clutter_debug_keys,
1302                               G_N_ELEMENTS (clutter_debug_keys));
1303       env_string = NULL;
1304     }
1305 #endif /* CLUTTER_ENABLE_DEBUG */
1306
1307   env_string = g_getenv ("CLUTTER_SHOW_FPS");
1308   if (env_string)
1309     clutter_show_fps = TRUE;
1310
1311   env_string = g_getenv ("CLUTTER_DEFAULT_FPS");
1312   if (env_string)
1313     {
1314       gint default_fps = g_ascii_strtoll (env_string, NULL, 10);
1315
1316       clutter_default_fps = CLAMP (default_fps, 1, 1000);
1317     }
1318
1319   env_string = g_getenv ("CLUTTER_DISABLE_MIPMAPPED_TEXT");
1320   if (env_string)
1321     clutter_disable_mipmap_text = TRUE;
1322
1323 #ifdef HAVE_CLUTTER_FRUITY
1324   /* we always enable fuzzy picking in the "fruity" backend */
1325   clutter_use_fuzzy_picking = TRUE;
1326 #else
1327   env_string = g_getenv ("CLUTTER_FUZZY_PICK");
1328   if (env_string)
1329     clutter_use_fuzzy_picking = TRUE;
1330 #endif /* HAVE_CLUTTER_FRUITY */
1331
1332   return _clutter_backend_pre_parse (backend, error);
1333 }
1334
1335 /* post_parse_hook: initialise the context and data structures
1336  * and opens the X display
1337  */
1338 static gboolean
1339 post_parse_hook (GOptionContext  *context,
1340                  GOptionGroup    *group,
1341                  gpointer         data,
1342                  GError         **error)
1343 {
1344   ClutterMainContext *clutter_context;
1345   ClutterBackend *backend;
1346
1347   if (clutter_is_initialized)
1348     return TRUE;
1349
1350   clutter_context = clutter_context_get_default ();
1351   backend = clutter_context->backend;
1352   g_assert (CLUTTER_IS_BACKEND (backend));
1353
1354   if (clutter_fatal_warnings)
1355     {
1356       GLogLevelFlags fatal_mask;
1357
1358       fatal_mask = g_log_set_always_fatal (G_LOG_FATAL_MASK);
1359       fatal_mask |= G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL;
1360       g_log_set_always_fatal (fatal_mask);
1361     }
1362
1363   clutter_context->frame_rate = clutter_default_fps;
1364   clutter_context->options_parsed = TRUE;
1365
1366   /*
1367    * If not asked to defer display setup, call clutter_init_real(),
1368    * which in turn calls the backend post parse hooks.
1369    */
1370   if (!clutter_context->defer_display_setup)
1371     return clutter_init_real (error);
1372
1373   return TRUE;
1374 }
1375
1376 /**
1377  * clutter_get_option_group:
1378  *
1379  * Returns a #GOptionGroup for the command line arguments recognized
1380  * by Clutter. You should add this group to your #GOptionContext with
1381  * g_option_context_add_group(), if you are using g_option_context_parse()
1382  * to parse your commandline arguments.
1383  *
1384  * Calling g_option_context_parse() with Clutter's #GOptionGroup will result
1385  * in Clutter's initialization. That is, the following code:
1386  *
1387  * |[
1388  *   g_option_context_set_main_group (context, clutter_get_option_group ());
1389  *   res = g_option_context_parse (context, &amp;argc, &amp;argc, NULL);
1390  * ]|
1391  *
1392  * is functionally equivalent to:
1393  *
1394  * |[
1395  *   clutter_init (&amp;argc, &amp;argv);
1396  * ]|
1397  *
1398  * After g_option_context_parse() on a #GOptionContext containing the
1399  * Clutter #GOptionGroup has returned %TRUE, Clutter is guaranteed to be
1400  * initialized.
1401  *
1402  * Return value: (transfer full): a #GOptionGroup for the commandline arguments
1403  *   recognized by Clutter
1404  *
1405  * Since: 0.2
1406  */
1407 GOptionGroup *
1408 clutter_get_option_group (void)
1409 {
1410   ClutterMainContext *context;
1411   GOptionGroup *group;
1412
1413   clutter_base_init ();
1414
1415   context = clutter_context_get_default ();
1416
1417   group = g_option_group_new ("clutter",
1418                               _("Clutter Options"),
1419                               _("Show Clutter Options"),
1420                               NULL,
1421                               NULL);
1422
1423   g_option_group_set_parse_hooks (group, pre_parse_hook, post_parse_hook);
1424   g_option_group_add_entries (group, clutter_args);
1425   g_option_group_set_translation_domain (group, GETTEXT_PACKAGE);
1426
1427   /* add backend-specific options */
1428   _clutter_backend_add_options (context->backend, group);
1429
1430   return group;
1431 }
1432
1433 /**
1434  * clutter_get_option_group_without_init:
1435  *
1436  * Returns a #GOptionGroup for the command line arguments recognized
1437  * by Clutter. You should add this group to your #GOptionContext with
1438  * g_option_context_add_group(), if you are using g_option_context_parse()
1439  * to parse your commandline arguments. Unlike clutter_get_option_group(),
1440  * calling g_option_context_parse() with the #GOptionGroup returned by this
1441  * function requires a subsequent explicit call to clutter_init(); use this
1442  * function when needing to set foreign display connection with
1443  * clutter_x11_set_display(), or with gtk_clutter_init().
1444  *
1445  * Return value: (transfer full): a #GOptionGroup for the commandline arguments
1446  *   recognized by Clutter
1447  *
1448  * Since: 0.8.2
1449  */
1450 GOptionGroup *
1451 clutter_get_option_group_without_init (void)
1452 {
1453   ClutterMainContext *context;
1454   GOptionGroup *group;
1455
1456   clutter_base_init ();
1457
1458   context = clutter_context_get_default ();
1459   context->defer_display_setup = TRUE;
1460
1461   group = clutter_get_option_group ();
1462
1463   return group;
1464 }
1465
1466 /* Note that the gobject-introspection annotations for the argc/argv
1467  * parameters do not produce the right result; however, they do
1468  * allow the common case of argc=NULL, argv=NULL to work.
1469  */
1470
1471 /**
1472  * clutter_init_with_args:
1473  * @argc: (inout): a pointer to the number of command line arguments
1474  * @argv: (array length=argc) (inout): a pointer to the array of command line arguments
1475  * @parameter_string: a string which is displayed in the
1476  *   first line of <option>--help</option> output, after
1477  *   <literal><replaceable>programname</replaceable> [OPTION...]</literal>
1478  * @entries: a %NULL terminated array of #GOptionEntry<!-- -->s
1479  *   describing the options of your program
1480  * @translation_domain: a translation domain to use for translating
1481  *   the <option>--help</option> output for the options in @entries
1482  *   with gettext(), or %NULL
1483  * @error: a return location for a #GError
1484  *
1485  * This function does the same work as clutter_init(). Additionally,
1486  * it allows you to add your own command line options, and it
1487  * automatically generates nicely formatted <option>--help</option>
1488  * output. Note that your program will be terminated after writing
1489  * out the help output. Also note that, in case of error, the
1490  * error message will be placed inside @error instead of being
1491  * printed on the display.
1492  *
1493  * Return value: %CLUTTER_INIT_SUCCESS if Clutter has been successfully
1494  *   initialised, or other values or #ClutterInitError in case of
1495  *   error.
1496  *
1497  * Since: 0.2
1498  */
1499 ClutterInitError
1500 clutter_init_with_args (int            *argc,
1501                         char         ***argv,
1502                         const char     *parameter_string,
1503                         GOptionEntry   *entries,
1504                         const char     *translation_domain,
1505                         GError        **error)
1506 {
1507   GOptionContext *context;
1508   GOptionGroup *group;
1509   gboolean res;
1510   ClutterMainContext *ctx;
1511
1512   if (clutter_is_initialized)
1513     return CLUTTER_INIT_SUCCESS;
1514
1515   clutter_base_init ();
1516
1517   ctx = clutter_context_get_default ();
1518
1519   if (!ctx->defer_display_setup)
1520     {
1521       if (argc && *argc > 0 && *argv)
1522         g_set_prgname ((*argv)[0]);
1523
1524       context = g_option_context_new (parameter_string);
1525
1526       group = clutter_get_option_group ();
1527       g_option_context_add_group (context, group);
1528
1529       group = cogl_get_option_group ();
1530       g_option_context_add_group (context, group);
1531
1532       if (entries)
1533         g_option_context_add_main_entries (context, entries, translation_domain);
1534
1535       res = g_option_context_parse (context, argc, argv, error);
1536       g_option_context_free (context);
1537
1538       /* if res is FALSE, the error is filled for
1539        * us by g_option_context_parse()
1540        */
1541       if (!res)
1542         {
1543           /* if there has been an error in the initialization, the
1544            * error id will be preserved inside the GError code
1545            */
1546           if (error && *error)
1547             return (*error)->code;
1548           else
1549             return CLUTTER_INIT_ERROR_INTERNAL;
1550         }
1551
1552       return CLUTTER_INIT_SUCCESS;
1553     }
1554   else
1555     return clutter_init_real (error);
1556 }
1557
1558 static gboolean
1559 clutter_parse_args (int    *argc,
1560                     char ***argv)
1561 {
1562   GOptionContext *option_context;
1563   GOptionGroup   *clutter_group, *cogl_group;
1564   GError         *error = NULL;
1565   gboolean        ret = TRUE;
1566
1567   if (clutter_is_initialized)
1568     return TRUE;
1569
1570   option_context = g_option_context_new (NULL);
1571   g_option_context_set_ignore_unknown_options (option_context, TRUE);
1572   g_option_context_set_help_enabled (option_context, FALSE);
1573
1574   /* Initiate any command line options from the backend */
1575
1576   clutter_group = clutter_get_option_group ();
1577   g_option_context_set_main_group (option_context, clutter_group);
1578
1579   cogl_group = cogl_get_option_group ();
1580   g_option_context_add_group (option_context, cogl_group);
1581
1582   if (!g_option_context_parse (option_context, argc, argv, &error))
1583     {
1584       if (error)
1585         {
1586           g_warning ("%s", error->message);
1587           g_error_free (error);
1588         }
1589
1590       ret = FALSE;
1591     }
1592
1593   g_option_context_free (option_context);
1594
1595   return ret;
1596 }
1597
1598 /**
1599  * clutter_init:
1600  * @argc: (inout): The number of arguments in @argv
1601  * @argv: (array length=argc) (inout): A pointer to an array of arguments.
1602  *
1603  * It will initialise everything needed to operate with Clutter and
1604  * parses some standard command line options. @argc and @argv are
1605  * adjusted accordingly so your own code will never see those standard
1606  * arguments.
1607  *
1608  * Return value: 1 on success, < 0 on failure.
1609  */
1610 ClutterInitError
1611 clutter_init (int    *argc,
1612               char ***argv)
1613 {
1614   ClutterMainContext *ctx;
1615   GError *error = NULL;
1616
1617   if (clutter_is_initialized)
1618     return CLUTTER_INIT_SUCCESS;
1619
1620   clutter_base_init ();
1621
1622   ctx = clutter_context_get_default ();
1623
1624   if (!ctx->defer_display_setup)
1625     {
1626       if (argc && *argc > 0 && *argv)
1627         g_set_prgname ((*argv)[0]);
1628
1629       /* parse_args will trigger backend creation and things like
1630        * DISPLAY connection etc.
1631        */
1632       if (clutter_parse_args (argc, argv) == FALSE)
1633         {
1634           CLUTTER_NOTE (MISC, "failed to parse arguments.");
1635           return CLUTTER_INIT_ERROR_INTERNAL;
1636         }
1637
1638       return CLUTTER_INIT_SUCCESS;
1639     }
1640   else
1641     return clutter_init_real (&error);
1642 }
1643
1644 gboolean
1645 _clutter_boolean_handled_accumulator (GSignalInvocationHint *ihint,
1646                                       GValue                *return_accu,
1647                                       const GValue          *handler_return,
1648                                       gpointer               dummy)
1649 {
1650   gboolean continue_emission;
1651   gboolean signal_handled;
1652
1653   signal_handled = g_value_get_boolean (handler_return);
1654   g_value_set_boolean (return_accu, signal_handled);
1655   continue_emission = !signal_handled;
1656
1657   return continue_emission;
1658 }
1659
1660 static void
1661 event_click_count_generate (ClutterEvent *event)
1662 {
1663   /* multiple button click detection */
1664   static gint    click_count            = 0;
1665   static gint    previous_x             = -1;
1666   static gint    previous_y             = -1;
1667   static guint32 previous_time          = 0;
1668   static gint    previous_button_number = -1;
1669
1670   ClutterBackend *backend;
1671   guint           double_click_time;
1672   guint           double_click_distance;
1673
1674   backend = clutter_context_get_default ()->backend;
1675   double_click_distance = clutter_backend_get_double_click_distance (backend);
1676   double_click_time = clutter_backend_get_double_click_time (backend);
1677
1678   if (event->button.device != NULL)
1679     {
1680       click_count = event->button.device->click_count;
1681       previous_x = event->button.device->previous_x;
1682       previous_y = event->button.device->previous_y;
1683       previous_time = event->button.device->previous_time;
1684       previous_button_number = event->button.device->previous_button_number;
1685     }
1686
1687   switch (event->type)
1688     {
1689       case CLUTTER_BUTTON_PRESS:
1690       case CLUTTER_SCROLL:
1691         /* check if we are in time and within distance to increment an
1692          * existing click count
1693          */
1694         if (event->button.time < previous_time + double_click_time &&
1695             (ABS (event->button.x - previous_x) <= double_click_distance) &&
1696             (ABS (event->button.y - previous_y) <= double_click_distance)
1697             && event->button.button == previous_button_number)
1698           {
1699             click_count ++;
1700           }
1701         else /* start a new click count*/
1702           {
1703             click_count=1;
1704             previous_button_number = event->button.button;
1705           }
1706
1707         /* store time and position for this click for comparison with
1708          * next event
1709          */
1710         previous_time = event->button.time;
1711         previous_x    = event->button.x;
1712         previous_y    = event->button.y;
1713
1714         /* fallthrough */
1715       case CLUTTER_BUTTON_RELEASE:
1716         event->button.click_count=click_count;
1717         break;
1718       default:
1719         g_assert (NULL);
1720     }
1721
1722   if (event->button.device != NULL)
1723     {
1724       event->button.device->click_count = click_count;
1725       event->button.device->previous_x = previous_x;
1726       event->button.device->previous_y = previous_y;
1727       event->button.device->previous_time = previous_time;
1728       event->button.device->previous_button_number = previous_button_number;
1729     }
1730 }
1731
1732
1733 static inline void
1734 emit_event (ClutterEvent *event,
1735             gboolean      is_key_event)
1736 {
1737 #define MAX_EVENT_DEPTH 512
1738
1739   static ClutterActor **event_tree = NULL;
1740   static gboolean       lock = FALSE;
1741
1742   ClutterActor         *actor;
1743   gint                  i = 0, n_tree_events = 0;
1744
1745   if (!event->any.source)
1746     {
1747       g_warning ("No event source set, discarding event");
1748       return;
1749     }
1750
1751   /* reentrancy check */
1752   if (lock != FALSE)
1753     return;
1754
1755   lock = TRUE;
1756
1757   /* Sorry Mr Bassi. */
1758   if (G_UNLIKELY (event_tree == NULL))
1759     event_tree = g_new0 (ClutterActor *, MAX_EVENT_DEPTH);
1760
1761   actor = event->any.source;
1762
1763   /* Build 'tree' of emitters for the event */
1764   while (actor && n_tree_events < MAX_EVENT_DEPTH)
1765     {
1766       ClutterActor *parent;
1767
1768       parent = clutter_actor_get_parent (actor);
1769
1770       if (clutter_actor_get_reactive (actor) ||
1771           parent == NULL ||         /* stage gets all events */
1772           is_key_event)             /* keyboard events are always emitted */
1773         {
1774           event_tree[n_tree_events++] = g_object_ref (actor);
1775         }
1776
1777       actor = parent;
1778     }
1779
1780   /* Capture */
1781   for (i = n_tree_events-1; i >= 0; i--)
1782     if (clutter_actor_event (event_tree[i], event, TRUE))
1783       goto done;
1784
1785   /* Bubble */
1786   for (i = 0; i < n_tree_events; i++)
1787     if (clutter_actor_event (event_tree[i], event, FALSE))
1788       goto done;
1789
1790 done:
1791
1792   for (i = 0; i < n_tree_events; i++)
1793     g_object_unref (event_tree[i]);
1794
1795   lock = FALSE;
1796
1797 #undef MAX_EVENT_DEPTH
1798 }
1799
1800 /*
1801  * Emits a pointer event after having prepared the event for delivery (setting
1802  * source, computing click_count, generating enter/leave etc.).
1803  */
1804
1805 static inline void
1806 emit_pointer_event (ClutterEvent       *event,
1807                     ClutterInputDevice *device)
1808 {
1809   /* Using the global variable directly, since it has to be initialized
1810    * at this point
1811    */
1812   ClutterMainContext *context = ClutterCntx;
1813
1814   if (G_UNLIKELY (context->pointer_grab_actor != NULL &&
1815                   device == NULL))
1816     {
1817       /* global grab */
1818       clutter_actor_event (context->pointer_grab_actor, event, FALSE);
1819     }
1820   else if (G_UNLIKELY (device != NULL &&
1821                        device->pointer_grab_actor != NULL))
1822     {
1823       /* per device grab */
1824       clutter_actor_event (device->pointer_grab_actor, event, FALSE);
1825     }
1826   else
1827     {
1828       /* no grab, time to capture and bubble */
1829       emit_event (event, FALSE);
1830     }
1831 }
1832
1833 static inline void
1834 emit_keyboard_event (ClutterEvent *event)
1835 {
1836   ClutterMainContext *context = ClutterCntx;
1837
1838   if (G_UNLIKELY (context->keyboard_grab_actor != NULL))
1839     clutter_actor_event (context->keyboard_grab_actor, event, FALSE);
1840   else
1841     emit_event (event, TRUE);
1842 }
1843
1844 static void
1845 unset_motion_last_actor (ClutterActor *actor, ClutterInputDevice *dev)
1846 {
1847   ClutterMainContext *context = ClutterCntx;
1848
1849   if (dev == NULL)
1850     context->motion_last_actor = NULL;
1851   else
1852     dev->motion_last_actor = NULL;
1853 }
1854
1855 static ClutterInputDevice * clutter_event_get_device (ClutterEvent *event);
1856
1857 /* This function should perhaps be public and in clutter-event.c ?
1858  */
1859 static ClutterInputDevice *
1860 clutter_event_get_device (ClutterEvent *event)
1861 {
1862   g_return_val_if_fail (event != NULL, NULL);
1863
1864   switch (event->type)
1865     {
1866     case CLUTTER_NOTHING:
1867     case CLUTTER_STAGE_STATE:
1868     case CLUTTER_DESTROY_NOTIFY:
1869     case CLUTTER_CLIENT_MESSAGE:
1870     case CLUTTER_DELETE:
1871     case CLUTTER_ENTER:
1872     case CLUTTER_LEAVE:
1873       return NULL;
1874       break;
1875     case CLUTTER_BUTTON_PRESS:
1876     case CLUTTER_BUTTON_RELEASE:
1877       return event->button.device;
1878     case CLUTTER_MOTION:
1879       return event->motion.device;
1880     case CLUTTER_SCROLL:
1881       return event->scroll.device;
1882       break;
1883     case CLUTTER_KEY_PRESS:
1884     case CLUTTER_KEY_RELEASE:
1885       break;
1886     }
1887   return NULL;
1888 }
1889
1890 static void
1891 set_motion_last_actor (ClutterActor       *motion_current_actor,
1892                        ClutterInputDevice *device)
1893 {
1894   ClutterMainContext *context              = ClutterCntx;
1895   ClutterActor       *last_actor           = context->motion_last_actor;
1896
1897   if (device != NULL)
1898     last_actor = device->motion_last_actor;
1899
1900   if (last_actor && last_actor != motion_current_actor)
1901     {
1902       g_signal_handlers_disconnect_by_func
1903                        (last_actor,
1904                         G_CALLBACK (unset_motion_last_actor),
1905                         device);
1906     }
1907
1908   if (motion_current_actor && last_actor != motion_current_actor)
1909     {
1910       g_signal_connect (motion_current_actor, "destroy",
1911                         G_CALLBACK (unset_motion_last_actor),
1912                         device);
1913     }
1914
1915   if (device != NULL)
1916     device->motion_last_actor = motion_current_actor;
1917   else
1918     context->motion_last_actor = motion_current_actor;
1919 }
1920
1921 static inline void
1922 generate_enter_leave_events (ClutterEvent *event)
1923 {
1924   ClutterMainContext *context              = ClutterCntx;
1925   ClutterActor       *motion_current_actor = event->motion.source;
1926   ClutterActor       *last_actor           = context->motion_last_actor;
1927   ClutterInputDevice *device               = clutter_event_get_device (event);
1928
1929   if (device != NULL)
1930     last_actor = device->motion_last_actor;
1931
1932   if (last_actor != motion_current_actor)
1933     {
1934       if (motion_current_actor)
1935         {
1936           gint         x, y;
1937           ClutterEvent cev;
1938
1939           cev.crossing.device  = device;
1940           clutter_event_get_coords (event, &x, &y);
1941
1942           if (context->motion_last_actor)
1943             {
1944               cev.crossing.type    = CLUTTER_LEAVE;
1945               cev.crossing.time    = event->any.time;
1946               cev.crossing.flags   = 0;
1947               cev.crossing.x       = x;
1948               cev.crossing.y       = y;
1949               cev.crossing.source  = last_actor;
1950               cev.crossing.stage   = event->any.stage;
1951               cev.crossing.related = motion_current_actor;
1952
1953               emit_pointer_event (&cev, device);
1954             }
1955
1956           cev.crossing.type    = CLUTTER_ENTER;
1957           cev.crossing.time    = event->any.time;
1958           cev.crossing.flags   = 0;
1959           cev.crossing.x       = x;
1960           cev.crossing.y       = y;
1961           cev.crossing.source  = motion_current_actor;
1962           cev.crossing.stage   = event->any.stage;
1963
1964           if (context->motion_last_actor)
1965             cev.crossing.related = last_actor;
1966           else
1967             cev.crossing.related = NULL;
1968
1969           emit_pointer_event (&cev, device);
1970         }
1971     }
1972
1973   set_motion_last_actor (motion_current_actor, device);
1974 }
1975
1976 /**
1977  * clutter_do_event
1978  * @event: a #ClutterEvent.
1979  *
1980  * Processes an event. This function should never be called by applications.
1981  *
1982  * Since: 0.4
1983  */
1984 void
1985 clutter_do_event (ClutterEvent *event)
1986 {
1987   /* FIXME: This should probably be clutter_cook_event() - it would
1988    * take a raw event from the backend and 'cook' it so its more tasty.
1989    *
1990   */
1991   ClutterMainContext  *context;
1992   ClutterBackend      *backend;
1993   ClutterActor        *stage;
1994   ClutterInputDevice  *device = NULL;
1995   static gint32        motion_last_time = 0L;
1996   gint32               local_motion_time;
1997
1998   context = clutter_context_get_default ();
1999   backend = context->backend;
2000   stage   = CLUTTER_ACTOR(event->any.stage);
2001
2002   if (!stage)
2003     return;
2004
2005   CLUTTER_TIMESTAMP (EVENT, "Event received");
2006
2007   context->last_event_time = clutter_event_get_time (event);
2008
2009   switch (event->type)
2010     {
2011       case CLUTTER_NOTHING:
2012         event->any.source = stage;
2013         break;
2014
2015       case CLUTTER_LEAVE:
2016         /* The source is set for generated events, not for events
2017          * resulting from the cursor leaving the stage
2018          */
2019         if (event->any.source == NULL)
2020           {
2021             ClutterActor *last_actor = context->motion_last_actor;
2022
2023             if (event->crossing.device != NULL)
2024               last_actor = event->crossing.device->motion_last_actor;
2025
2026             event->any.source = last_actor;
2027
2028             set_motion_last_actor (NULL, event->crossing.device);
2029           }
2030         /* flow through */
2031       case CLUTTER_ENTER:
2032         emit_pointer_event (event, event->crossing.device);
2033         break;
2034
2035       case CLUTTER_DESTROY_NOTIFY:
2036       case CLUTTER_DELETE:
2037         event->any.source = stage;
2038         /* the stage did not handle the event, so we just quit */
2039         if (!clutter_stage_event (CLUTTER_STAGE (stage), event))
2040           {
2041             if (stage == clutter_stage_get_default())
2042               clutter_main_quit ();
2043             else
2044               clutter_actor_destroy (stage);
2045           }
2046
2047         break;
2048
2049       case CLUTTER_KEY_PRESS:
2050       case CLUTTER_KEY_RELEASE:
2051         {
2052           ClutterActor *actor = NULL;
2053
2054           /* check that we're not a synthetic event with source set */
2055           if (event->any.source == NULL)
2056             {
2057               actor = clutter_stage_get_key_focus (CLUTTER_STAGE (stage));
2058               event->any.source = actor;
2059               if (G_UNLIKELY (actor == NULL))
2060                 {
2061                   g_warning ("No key focus set, discarding");
2062                   return;
2063                 }
2064             }
2065
2066           emit_keyboard_event (event);
2067         }
2068         break;
2069
2070       case CLUTTER_MOTION:
2071         device = event->motion.device;
2072
2073         if (device)
2074           local_motion_time = device->motion_last_time;
2075         else
2076           local_motion_time = motion_last_time;
2077
2078         /* avoid rate throttling for synthetic motion events or if
2079          * the per-actor events are disabled
2080          */
2081         if (!(event->any.flags & CLUTTER_EVENT_FLAG_SYNTHETIC) ||
2082             !context->motion_events_per_actor)
2083           {
2084             gint32 frame_rate, delta;
2085
2086             /* avoid issuing too many motion events, which leads to many
2087              * redraws in pick mode (performance penalty)
2088              */
2089             frame_rate = clutter_get_motion_events_frequency ();
2090             delta = 1000 / frame_rate;
2091
2092             CLUTTER_NOTE (EVENT,
2093                   "skip motion event: %s (last:%d, delta:%d, time:%d)",
2094                   (event->any.time < (local_motion_time + delta) ? "yes" : "no"),
2095                   local_motion_time,
2096                   delta,
2097                   event->any.time);
2098
2099             /* we need to guard against roll-overs and the
2100              * case where the time is rolled backwards and
2101              * the backend is not ensuring a monotonic clock
2102              * for the events.
2103              *
2104              * see:
2105              *   http://bugzilla.openedhand.com/show_bug.cgi?id=1130
2106              */
2107             if (event->any.time >= local_motion_time &&
2108                 event->any.time < (local_motion_time + delta))
2109               break;
2110             else
2111               local_motion_time = event->any.time;
2112           }
2113
2114         if (device)
2115           device->motion_last_time = local_motion_time;
2116         else
2117           motion_last_time = local_motion_time;
2118
2119         /* Only stage gets motion events if clutter_set_motion_events is TRUE,
2120          * and the event is not a synthetic event with source set.
2121          */
2122         if (!context->motion_events_per_actor &&
2123             event->any.source == NULL)
2124           {
2125             /* Only stage gets motion events */
2126             event->any.source = stage;
2127
2128             /* global grabs */
2129             if (context->pointer_grab_actor != NULL)
2130               {
2131                 clutter_actor_event (context->pointer_grab_actor,
2132                                      event, FALSE);
2133                 break;
2134               }
2135             else if (device != NULL && device->pointer_grab_actor != NULL)
2136               {
2137                 clutter_actor_event (device->pointer_grab_actor,
2138                                      event, FALSE);
2139                 break;
2140               }
2141
2142             /* Trigger handlers on stage in both capture .. */
2143             if (!clutter_actor_event (stage, event, TRUE))
2144               {
2145                 /* and bubbling phase */
2146                 clutter_actor_event (stage, event, FALSE);
2147               }
2148             break;
2149           }
2150
2151         /* fallthrough */
2152
2153       case CLUTTER_BUTTON_PRESS:
2154       case CLUTTER_BUTTON_RELEASE:
2155       case CLUTTER_SCROLL:
2156         {
2157           ClutterActor *actor;
2158           gint          x,y;
2159
2160           clutter_event_get_coords (event, &x, &y);
2161
2162           /* Only do a pick to find the source if source is not already set
2163            * (as it could be in a synthetic event)
2164            */
2165           if (event->any.source == NULL)
2166             {
2167               /* Handle release off stage */
2168               if ((x >= clutter_actor_get_width (stage) ||
2169                    y >= clutter_actor_get_height (stage) ||
2170                    x < 0 || y < 0))
2171                 {
2172                   if (event->type == CLUTTER_BUTTON_RELEASE)
2173                     {
2174                       CLUTTER_NOTE (EVENT,
2175                                     "Release off stage received at %i, %i",
2176                                     x, y);
2177
2178                       event->button.source = stage;
2179                       emit_pointer_event (event, event->button.device);
2180                     }
2181                   break;
2182                 }
2183
2184               /* Map the event to a reactive actor */
2185               actor = _clutter_do_pick (CLUTTER_STAGE (stage),
2186                                         x, y,
2187                                         CLUTTER_PICK_REACTIVE);
2188
2189               event->any.source = actor;
2190               if (!actor)
2191                 break;
2192             }
2193           else
2194             {
2195               /* use the source already set in the synthetic event */
2196               actor = event->any.source;
2197             }
2198
2199
2200           /* FIXME: for an optimisation should check if there are
2201            * actually any reactive actors and avoid the pick all togeather
2202            * (signalling just the stage). Should be big help for gles.
2203            */
2204
2205           CLUTTER_NOTE (EVENT, "Reactive event received at %i, %i - actor: %p",
2206                         x, y, actor);
2207
2208           /* Create, enter/leave events if needed */
2209           generate_enter_leave_events (event);
2210
2211           if (event->type != CLUTTER_MOTION)
2212             {
2213               /* Generate click count */
2214               event_click_count_generate (event);
2215             }
2216
2217           if (device == NULL)
2218             {
2219               switch (event->type)
2220                 {
2221                   case CLUTTER_BUTTON_PRESS:
2222                   case CLUTTER_BUTTON_RELEASE:
2223                     device = event->button.device;
2224                     break;
2225                   case CLUTTER_SCROLL:
2226                     device = event->scroll.device;
2227                     break;
2228                   case CLUTTER_MOTION:
2229                     /* already handled in the MOTION case of the switch */
2230                   default:
2231                     break;
2232                 }
2233             }
2234
2235           emit_pointer_event (event, device);
2236           break;
2237         }
2238
2239       case CLUTTER_STAGE_STATE:
2240         /* fullscreen / focus - forward to stage */
2241         event->any.source = stage;
2242         clutter_stage_event (CLUTTER_STAGE (stage), event);
2243         break;
2244
2245       case CLUTTER_CLIENT_MESSAGE:
2246         break;
2247     }
2248 }
2249
2250 /**
2251  * clutter_get_actor_by_gid
2252  * @id: a #ClutterActor ID.
2253  *
2254  * Retrieves the #ClutterActor with @id.
2255  *
2256  * Return value: (transfer none): the actor with the passed id or %NULL.
2257  *   The returned actor does not have its reference count increased.
2258  *
2259  * Since: 0.6
2260  */
2261 ClutterActor*
2262 clutter_get_actor_by_gid (guint32 id)
2263 {
2264   ClutterMainContext *context;
2265
2266   context = clutter_context_get_default ();
2267
2268   g_return_val_if_fail (context != NULL, NULL);
2269
2270   return CLUTTER_ACTOR (clutter_id_pool_lookup (context->id_pool, id));
2271 }
2272
2273 void
2274 clutter_base_init (void)
2275 {
2276   static gboolean initialised = FALSE;
2277
2278   if (!initialised)
2279     {
2280       GType foo; /* Quiet gcc */
2281
2282       initialised = TRUE;
2283
2284       bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);
2285       bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
2286
2287       /* initialise GLib type system */
2288       g_type_init ();
2289
2290       /* CLUTTER_TYPE_ACTOR */
2291       foo = clutter_actor_get_type ();
2292     }
2293 }
2294
2295 /**
2296  * clutter_get_default_frame_rate:
2297  *
2298  * Retrieves the default frame rate used when creating #ClutterTimeline<!--
2299  * -->s.
2300  *
2301  * This value is also used to compute the default frequency of motion
2302  * events.
2303  *
2304  * Return value: the default frame rate
2305  *
2306  * Since: 0.6
2307  */
2308 guint
2309 clutter_get_default_frame_rate (void)
2310 {
2311   ClutterMainContext *context;
2312
2313   context = clutter_context_get_default ();
2314
2315   return context->frame_rate;
2316 }
2317
2318 /**
2319  * clutter_set_default_frame_rate:
2320  * @frames_per_sec: the new default frame rate
2321  *
2322  * Sets the default frame rate to be used when creating #ClutterTimeline<!--
2323  * -->s
2324  *
2325  * Since: 0.6
2326  */
2327 void
2328 clutter_set_default_frame_rate (guint frames_per_sec)
2329 {
2330   ClutterMainContext *context;
2331
2332   context = clutter_context_get_default ();
2333
2334   if (context->frame_rate != frames_per_sec)
2335     context->frame_rate = frames_per_sec;
2336 }
2337
2338
2339 static void
2340 on_pointer_grab_weak_notify (gpointer data,
2341                              GObject *where_the_object_was)
2342 {
2343   ClutterInputDevice *dev = (ClutterInputDevice *)data;
2344   ClutterMainContext *context;
2345
2346   context = clutter_context_get_default ();
2347
2348   if (dev)
2349     {
2350       dev->pointer_grab_actor = NULL;
2351       clutter_ungrab_pointer_for_device (dev->id);
2352     }
2353   else
2354     {
2355       context->pointer_grab_actor = NULL;
2356       clutter_ungrab_pointer ();
2357     }
2358 }
2359
2360 /**
2361  * clutter_grab_pointer:
2362  * @actor: a #ClutterActor
2363  *
2364  * Grabs pointer events, after the grab is done all pointer related events
2365  * (press, motion, release, enter, leave and scroll) are delivered to this
2366  * actor directly. The source set in the event will be the actor that would
2367  * have received the event if the pointer grab was not in effect.
2368  *
2369  * If you wish to grab all the pointer events for a specific input device,
2370  * you should use clutter_grab_pointer_for_device().
2371  *
2372  * Since: 0.6
2373  */
2374 void
2375 clutter_grab_pointer (ClutterActor *actor)
2376 {
2377   ClutterMainContext *context;
2378
2379   g_return_if_fail (actor == NULL || CLUTTER_IS_ACTOR (actor));
2380
2381   context = clutter_context_get_default ();
2382
2383   if (context->pointer_grab_actor == actor)
2384     return;
2385
2386   if (context->pointer_grab_actor)
2387     {
2388       g_object_weak_unref (G_OBJECT (context->pointer_grab_actor),
2389                            on_pointer_grab_weak_notify,
2390                            NULL);
2391       context->pointer_grab_actor = NULL;
2392     }
2393
2394   if (actor)
2395     {
2396       context->pointer_grab_actor = actor;
2397
2398       g_object_weak_ref (G_OBJECT (actor),
2399                          on_pointer_grab_weak_notify,
2400                          NULL);
2401     }
2402 }
2403
2404 /**
2405  * clutter_grab_pointer_for_device:
2406  * @actor: a #ClutterActor
2407  * @id: a device id, or -1
2408  *
2409  * Grabs all the pointer events coming from the device @id for @actor.
2410  *
2411  * If @id is -1 then this function is equivalent to clutter_grab_pointer().
2412  *
2413  * Since: 0.8
2414  */
2415 void
2416 clutter_grab_pointer_for_device (ClutterActor *actor,
2417                                  gint          id)
2418 {
2419   ClutterInputDevice *dev;
2420
2421   g_return_if_fail (actor == NULL || CLUTTER_IS_ACTOR (actor));
2422
2423   /* essentially a global grab */
2424   if (id == -1)
2425     {
2426       clutter_grab_pointer (actor);
2427       return;
2428     }
2429
2430   dev = clutter_get_input_device_for_id (id);
2431
2432   if (!dev)
2433     return;
2434
2435   if (dev->pointer_grab_actor == actor)
2436     return;
2437
2438   if (dev->pointer_grab_actor)
2439     {
2440       g_object_weak_unref (G_OBJECT (dev->pointer_grab_actor),
2441                           on_pointer_grab_weak_notify,
2442                           dev);
2443       dev->pointer_grab_actor = NULL;
2444     }
2445
2446   if (actor)
2447     {
2448       dev->pointer_grab_actor = actor;
2449
2450       g_object_weak_ref (G_OBJECT (actor),
2451                         on_pointer_grab_weak_notify,
2452                         dev);
2453     }
2454 }
2455
2456
2457 /**
2458  * clutter_ungrab_pointer:
2459  *
2460  * Removes an existing grab of the pointer.
2461  *
2462  * Since: 0.6
2463  */
2464 void
2465 clutter_ungrab_pointer (void)
2466 {
2467   clutter_grab_pointer (NULL);
2468 }
2469
2470 /**
2471  * clutter_ungrab_pointer_for_device:
2472  * @id: a device id
2473  *
2474  * Removes an existing grab of the pointer events for device @id.
2475  *
2476  * Since: 0.8
2477  */
2478 void
2479 clutter_ungrab_pointer_for_device (gint id)
2480 {
2481   clutter_grab_pointer_for_device (NULL, id);
2482 }
2483
2484
2485 /**
2486  * clutter_get_pointer_grab:
2487  *
2488  * Queries the current pointer grab of clutter.
2489  *
2490  * Return value: (transfer none): the actor currently holding the pointer grab, or NULL if there is no grab.
2491  *
2492  * Since: 0.6
2493  */
2494 ClutterActor *
2495 clutter_get_pointer_grab (void)
2496 {
2497   ClutterMainContext *context;
2498   context = clutter_context_get_default ();
2499
2500   return context->pointer_grab_actor;
2501 }
2502
2503
2504 static void
2505 on_keyboard_grab_weak_notify (gpointer data,
2506                               GObject *where_the_object_was)
2507 {
2508   ClutterMainContext *context;
2509
2510   context = clutter_context_get_default ();
2511   context->keyboard_grab_actor = NULL;
2512
2513   clutter_ungrab_keyboard ();
2514 }
2515
2516 /**
2517  * clutter_grab_keyboard:
2518  * @actor: a #ClutterActor
2519  *
2520  * Grabs keyboard events, after the grab is done keyboard events ("key-press-event"
2521  * and "key-release-event") are delivered to this actor directly. The source
2522  * set in the event will be the actor that would have received the event if the
2523  * keyboard grab was not in effect.
2524  *
2525  * Since: 0.6
2526  */
2527 void
2528 clutter_grab_keyboard (ClutterActor *actor)
2529 {
2530   ClutterMainContext *context;
2531
2532   g_return_if_fail (actor == NULL || CLUTTER_IS_ACTOR (actor));
2533
2534   context = clutter_context_get_default ();
2535
2536   if (context->keyboard_grab_actor == actor)
2537     return;
2538
2539   if (context->keyboard_grab_actor)
2540     {
2541       g_object_weak_unref (G_OBJECT (context->keyboard_grab_actor),
2542                            on_keyboard_grab_weak_notify,
2543                            NULL);
2544       context->keyboard_grab_actor = NULL;
2545     }
2546
2547   if (actor)
2548     {
2549       context->keyboard_grab_actor = actor;
2550
2551       g_object_weak_ref (G_OBJECT (actor),
2552                          on_keyboard_grab_weak_notify,
2553                          NULL);
2554     }
2555 }
2556
2557 /**
2558  * clutter_ungrab_keyboard:
2559  *
2560  * Removes an existing grab of the keyboard.
2561  *
2562  * Since: 0.6
2563  */
2564 void
2565 clutter_ungrab_keyboard (void)
2566 {
2567   clutter_grab_keyboard (NULL);
2568 }
2569
2570 /**
2571  * clutter_get_keyboard_grab:
2572  *
2573  * Queries the current keyboard grab of clutter.
2574  *
2575  * Return value: (transfer none): the actor currently holding the keyboard grab, or NULL if there is no grab.
2576  *
2577  * Since: 0.6
2578  */
2579 ClutterActor *
2580 clutter_get_keyboard_grab (void)
2581 {
2582   ClutterMainContext *context;
2583   context = clutter_context_get_default ();
2584
2585   return context->keyboard_grab_actor;
2586 }
2587
2588 /**
2589  * clutter_get_motion_events_frequency:
2590  *
2591  * Retrieves the number of motion events per second that are delivered
2592  * to the stage.
2593  *
2594  * See clutter_set_motion_events_frequency().
2595  *
2596  * Return value: the number of motion events per second
2597  *
2598  * Since: 0.6
2599  */
2600 guint
2601 clutter_get_motion_events_frequency (void)
2602 {
2603   ClutterMainContext *context = clutter_context_get_default ();
2604
2605   if (G_LIKELY (context->motion_frequency == 0))
2606     {
2607       guint frequency;
2608
2609       frequency = clutter_default_fps / 4;
2610       frequency = CLAMP (frequency, 20, 45);
2611
2612       return frequency;
2613     }
2614   else
2615     return context->motion_frequency;
2616 }
2617
2618 /**
2619  * clutter_set_motion_events_frequency:
2620  * @frequency: the number of motion events per second, or 0 for the
2621  *   default value
2622  *
2623  * Sets the motion events frequency. Setting this to a non-zero value
2624  * will override the default setting, so it should be rarely used.
2625  *
2626  * Motion events are delivered from the default backend to the stage
2627  * and are used to generate the enter/leave events pair. This might lead
2628  * to a performance penalty due to the way the actors are identified.
2629  * Using this function is possible to reduce the frequency of the motion
2630  * events delivery to the stage.
2631  *
2632  * Since: 0.6
2633  */
2634 void
2635 clutter_set_motion_events_frequency (guint frequency)
2636 {
2637   ClutterMainContext *context = clutter_context_get_default ();
2638
2639   /* never allow the motion events to exceed the default frame rate */
2640   context->motion_frequency = CLAMP (frequency, 1, clutter_default_fps);
2641 }
2642
2643 /**
2644  * clutter_clear_glyph_cache:
2645  *
2646  * Clears the internal cache of glyphs used by the Pango
2647  * renderer. This will free up some memory and GL texture
2648  * resources. The cache will be automatically refilled as more text is
2649  * drawn.
2650  *
2651  * Since: 0.8
2652  */
2653 void
2654 clutter_clear_glyph_cache (void)
2655 {
2656   if (CLUTTER_CONTEXT ()->font_map)
2657     cogl_pango_font_map_clear_glyph_cache (CLUTTER_CONTEXT ()->font_map);
2658 }
2659
2660 /**
2661  * clutter_set_font_flags:
2662  * @flags: The new flags
2663  *
2664  * Sets the font quality options for subsequent text rendering
2665  * operations.
2666  *
2667  * Using mipmapped textures will improve the quality for scaled down
2668  * text but will use more texture memory.
2669  *
2670  * Enabling hinting improves text quality for static text but may
2671  * introduce some artifacts if the text is animated.
2672  *
2673  * Since: 1.0
2674  */
2675 void
2676 clutter_set_font_flags (ClutterFontFlags flags)
2677 {
2678   ClutterFontFlags old_flags, changed_flags;
2679   cairo_font_options_t *font_options;
2680
2681   if (CLUTTER_CONTEXT ()->font_map)
2682     cogl_pango_font_map_set_use_mipmapping (CLUTTER_CONTEXT ()->font_map,
2683                                             (flags
2684                                              & CLUTTER_FONT_MIPMAPPING) != 0);
2685
2686   old_flags = clutter_get_font_flags ();
2687
2688   font_options = clutter_backend_get_font_options (CLUTTER_CONTEXT ()->backend);
2689   font_options = cairo_font_options_copy (font_options);
2690
2691   /* Only set the font options that have actually changed so we don't
2692      override a detailed setting from the backend */
2693   changed_flags = old_flags ^ flags;
2694
2695   if ((changed_flags & CLUTTER_FONT_HINTING))
2696     cairo_font_options_set_hint_style (font_options,
2697                                        (flags & CLUTTER_FONT_HINTING)
2698                                        ? CAIRO_HINT_STYLE_FULL
2699                                        : CAIRO_HINT_STYLE_NONE);
2700
2701   clutter_backend_set_font_options (CLUTTER_CONTEXT ()->backend, font_options);
2702
2703   cairo_font_options_destroy (font_options);
2704
2705   if (CLUTTER_CONTEXT ()->pango_context)
2706     update_pango_context (CLUTTER_CONTEXT ()->backend,
2707                           CLUTTER_CONTEXT ()->pango_context);
2708 }
2709
2710 /**
2711  * clutter_get_font_flags:
2712  *
2713  * Gets the current font flags for rendering text. See
2714  * clutter_set_font_flags().
2715  *
2716  * Return value: The font flags
2717  *
2718  * Since: 1.0
2719  */
2720 ClutterFontFlags
2721 clutter_get_font_flags (void)
2722 {
2723   ClutterMainContext *ctxt = CLUTTER_CONTEXT ();
2724   CoglPangoFontMap *font_map = NULL;
2725   cairo_font_options_t *font_options;
2726   ClutterFontFlags flags = 0;
2727
2728   font_map = CLUTTER_CONTEXT ()->font_map;
2729
2730   if (G_LIKELY (font_map)
2731       && cogl_pango_font_map_get_use_mipmapping (font_map))
2732     flags |= CLUTTER_FONT_MIPMAPPING;
2733
2734   font_options = clutter_backend_get_font_options (ctxt->backend);
2735
2736   if ((cairo_font_options_get_hint_style (font_options)
2737        != CAIRO_HINT_STYLE_DEFAULT)
2738       && (cairo_font_options_get_hint_style (font_options)
2739           != CAIRO_HINT_STYLE_NONE))
2740     flags |= CLUTTER_FONT_HINTING;
2741
2742   return flags;
2743 }
2744
2745 /**
2746  * clutter_get_input_device_for_id:
2747  * @id: a device id
2748  *
2749  * Retrieves the #ClutterInputDevice from its id.
2750  *
2751  * Return value: (transfer none): a #ClutterInputDevice, or %NULL
2752  *
2753  * Since: 0.8
2754  */
2755 ClutterInputDevice *
2756 clutter_get_input_device_for_id (gint id)
2757 {
2758   GSList *item;
2759   ClutterInputDevice *device = NULL;
2760   ClutterMainContext  *context;
2761
2762   context = clutter_context_get_default ();
2763
2764   for (item = context->input_devices;
2765        item != NULL;
2766        item = item->next)
2767   {
2768     device = item->data;
2769
2770     if (device->id == id)
2771       return device;
2772   }
2773
2774   return NULL;
2775 }
2776
2777 /**
2778  * clutter_get_font_map:
2779  *
2780  * Retrieves the #PangoFontMap instance used by Clutter.
2781  * You can use the global font map object with the COGL
2782  * Pango API.
2783  *
2784  * Return value: (transfer none): the #PangoFontMap instance. The returned
2785  *   value is owned by Clutter and it should never be unreferenced.
2786  *
2787  * Since: 1.0
2788  */
2789 PangoFontMap *
2790 clutter_get_font_map (void)
2791 {
2792   if (CLUTTER_CONTEXT ()->font_map)
2793     return PANGO_FONT_MAP (CLUTTER_CONTEXT ()->font_map);
2794
2795   return NULL;
2796 }