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