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