clutter-main.c 103 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/*
 * Clutter.
 *
 * An OpenGL based 'interactive canvas' library.
 *
 * Authored By Matthew Allum  <mallum@openedhand.com>
 *
 * Copyright (C) 2006 OpenedHand
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
21
 * License along with this library. If not, see <http://www.gnu.org/licenses/>.
22
 */
23

24 25
/**
 * SECTION:clutter-main
Emmanuele Bassi's avatar
Emmanuele Bassi committed
26
 * @short_description: Various 'global' Clutter functions.
27
 *
Iain Holmes's avatar
Iain Holmes committed
28 29
 * Functions to retrieve various global Clutter resources and other utility
 * functions for mainloops, events and threads
30
 *
Emmanuele Bassi's avatar
Emmanuele Bassi committed
31
 * ## The Clutter Threading Model
32
 *
Emmanuele Bassi's avatar
Emmanuele Bassi committed
33 34 35 36
 * Clutter is *thread-aware*: all operations performed by Clutter are assumed
 * to be under the Big Clutter Lock, which is created when the threading is
 * initialized through clutter_init(), and entered when calling user-related
 * code during event handling and actor drawing.
37
 *
Emmanuele Bassi's avatar
Emmanuele Bassi committed
38 39 40
 * The only safe and portable way to use the Clutter API in a multi-threaded
 * environment is to only access the Clutter API from a thread that did called
 * clutter_init() and clutter_main().
41
 *
Emmanuele Bassi's avatar
Emmanuele Bassi committed
42 43 44
 * The common pattern for using threads with Clutter is to use worker threads
 * to perform blocking operations and then install idle or timeout sources with
 * the result when the thread finishes, and update the UI from those callbacks.
45
 *
Emmanuele Bassi's avatar
Emmanuele Bassi committed
46 47
 * For a working example of how to use a worker thread to update the UI, see
 * [threads.c](https://git.gnome.org/browse/clutter/tree/examples/threads.c?h=clutter-1.18)
48 49
 */

50
#ifdef HAVE_CONFIG_H
51
#include "clutter-build-config.h"
52
#endif
53 54 55

#include <stdlib.h>

56
#include "clutter-actor-private.h"
57
#include "clutter-backend-private.h"
58
#include "clutter-config.h"
59 60
#include "clutter-debug.h"
#include "clutter-device-manager-private.h"
61
#include "clutter-event-private.h"
62
#include "clutter-feature.h"
63
#include "clutter-main.h"
64
#include "clutter-master-clock.h"
65
#include "clutter-mutter.h"
66
#include "clutter-private.h"
67
#include "clutter-settings-private.h"
68
#include "clutter-stage-manager.h"
69 70
#include "clutter-stage-private.h"
#include "clutter-version.h" 	/* For flavour define */
71

72 73 74 75 76 77 78
#ifdef CLUTTER_WINDOWING_X11
#include "x11/clutter-backend-x11.h"
#endif
#ifdef CLUTTER_WINDOWING_EGL
#include "egl/clutter-backend-eglnative.h"
#endif

79
#include <cogl/cogl.h>
80
#include <cogl-pango/cogl-pango.h>
81

82 83
#include "cally.h" /* For accessibility support */

84
/* main context */
85
static ClutterMainContext *ClutterCntx       = NULL;
86
G_LOCK_DEFINE_STATIC (ClutterCntx);
87

88
/* main lock and locking/unlocking functions */
89
static GMutex clutter_threads_mutex;
90 91
static GCallback clutter_threads_lock        = NULL;
static GCallback clutter_threads_unlock      = NULL;
92

93
/* command line options */
94 95 96
static gboolean clutter_is_initialized       = FALSE;
static gboolean clutter_show_fps             = FALSE;
static gboolean clutter_fatal_warnings       = FALSE;
97
static gboolean clutter_disable_mipmap_text  = FALSE;
98
static gboolean clutter_use_fuzzy_picking    = FALSE;
99
static gboolean clutter_enable_accessibility = TRUE;
100
static gboolean clutter_sync_to_vblank       = TRUE;
101

102
static guint clutter_default_fps             = 60;
103

104
static ClutterTextDirection clutter_text_direction = CLUTTER_TEXT_DIRECTION_LTR;
105

106 107 108
static guint clutter_main_loop_level         = 0;
static GSList *main_loops                    = NULL;

Emmanuele Bassi's avatar
Emmanuele Bassi committed
109 110
/* debug flags */
guint clutter_debug_flags       = 0;
111
guint clutter_paint_debug_flags = 0;
Emmanuele Bassi's avatar
Emmanuele Bassi committed
112
guint clutter_pick_debug_flags  = 0;
113

114 115 116 117
const guint clutter_major_version = CLUTTER_MAJOR_VERSION;
const guint clutter_minor_version = CLUTTER_MINOR_VERSION;
const guint clutter_micro_version = CLUTTER_MICRO_VERSION;

118 119 120 121 122 123 124
#ifdef CLUTTER_ENABLE_DEBUG
static const GDebugKey clutter_debug_keys[] = {
  { "misc", CLUTTER_DEBUG_MISC },
  { "actor", CLUTTER_DEBUG_ACTOR },
  { "texture", CLUTTER_DEBUG_TEXTURE },
  { "event", CLUTTER_DEBUG_EVENT },
  { "paint", CLUTTER_DEBUG_PAINT },
125
  { "pick", CLUTTER_DEBUG_PICK },
126
  { "pango", CLUTTER_DEBUG_PANGO },
127
  { "backend", CLUTTER_DEBUG_BACKEND },
128
  { "scheduler", CLUTTER_DEBUG_SCHEDULER },
129
  { "script", CLUTTER_DEBUG_SCRIPT },
130
  { "shader", CLUTTER_DEBUG_SHADER },
131
  { "animation", CLUTTER_DEBUG_ANIMATION },
132
  { "layout", CLUTTER_DEBUG_LAYOUT },
133
  { "clipping", CLUTTER_DEBUG_CLIPPING },
134
  { "oob-transforms", CLUTTER_DEBUG_OOB_TRANSFORMS },
135 136 137 138
};
#endif /* CLUTTER_ENABLE_DEBUG */

static const GDebugKey clutter_pick_debug_keys[] = {
139
  { "nop-picking", CLUTTER_DEBUG_NOP_PICKING },
140
  { "dump-pick-buffers", CLUTTER_DEBUG_DUMP_PICK_BUFFERS },
141 142 143
};

static const GDebugKey clutter_paint_debug_keys[] = {
144 145
  { "disable-swap-events", CLUTTER_DEBUG_DISABLE_SWAP_EVENTS },
  { "disable-clipped-redraws", CLUTTER_DEBUG_DISABLE_CLIPPED_REDRAWS },
146 147
  { "redraws", CLUTTER_DEBUG_REDRAWS },
  { "paint-volumes", CLUTTER_DEBUG_PAINT_VOLUMES },
148
  { "disable-culling", CLUTTER_DEBUG_DISABLE_CULLING },
149
  { "disable-offscreen-redirect", CLUTTER_DEBUG_DISABLE_OFFSCREEN_REDIRECT },
150 151
  { "continuous-redraw", CLUTTER_DEBUG_CONTINUOUS_REDRAW },
  { "paint-deform-tiles", CLUTTER_DEBUG_PAINT_DEFORM_TILES },
152
};
153

154 155 156 157 158 159 160 161 162
static void
clutter_threads_impl_lock (void)
{
  g_mutex_lock (&clutter_threads_mutex);
}

static void
clutter_threads_impl_unlock (void)
{
163 164 165 166 167 168 169 170 171 172
  /* we need to trylock here, in case the lock hasn't been acquired; on
   * various systems trying to release a mutex that hasn't been acquired
   * will cause a run-time error. trylock() will either fail, in which
   * case we can release the lock we own; or it will succeeds, in which
   * case we need to release the lock we just acquired. so we ignore the
   * returned value.
   *
   * see: https://bugs.gnome.org/679439
   */
  g_mutex_trylock (&clutter_threads_mutex);
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
  g_mutex_unlock (&clutter_threads_mutex);
}

static inline void
clutter_threads_init_default (void)
{
  g_mutex_init (&clutter_threads_mutex);

  if (clutter_threads_lock == NULL)
    clutter_threads_lock = clutter_threads_impl_lock;

  if (clutter_threads_unlock == NULL)
    clutter_threads_unlock = clutter_threads_impl_unlock;
}

188 189 190 191 192 193 194 195 196
#define ENVIRONMENT_GROUP       "Environment"
#define DEBUG_GROUP             "Debug"

static void
clutter_config_read_from_key_file (GKeyFile *keyfile)
{
  GError *key_error = NULL;
  gboolean bool_value;
  gint int_value;
197
  gchar *str_value;
198 199 200 201

  if (!g_key_file_has_group (keyfile, ENVIRONMENT_GROUP))
    return;

202 203 204 205 206 207 208 209 210 211 212
  str_value =
    g_key_file_get_string (keyfile, ENVIRONMENT_GROUP,
                           "Backends",
                           &key_error);
  if (key_error != NULL)
    g_clear_error (&key_error);
  else
    clutter_try_set_windowing_backend (str_value);

  g_free (str_value);

213 214 215 216 217 218 219 220 221 222 223
  str_value =
    g_key_file_get_string (keyfile, ENVIRONMENT_GROUP,
                           "Drivers",
                           &key_error);
  if (key_error != NULL)
    g_clear_error (&key_error);
  else
    clutter_set_allowed_drivers (str_value);

  g_free (str_value);

224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
  bool_value =
    g_key_file_get_boolean (keyfile, ENVIRONMENT_GROUP,
                            "ShowFps",
                            &key_error);

  if (key_error != NULL)
    g_clear_error (&key_error);
  else
    clutter_show_fps = bool_value;

  bool_value =
    g_key_file_get_boolean (keyfile, ENVIRONMENT_GROUP,
                            "DisableMipmappedText",
                            &key_error);

  if (key_error != NULL)
    g_clear_error (&key_error);
  else
    clutter_disable_mipmap_text = bool_value;

  bool_value =
    g_key_file_get_boolean (keyfile, ENVIRONMENT_GROUP,
                            "UseFuzzyPicking",
                            &key_error);

  if (key_error != NULL)
    g_clear_error (&key_error);
  else
    clutter_use_fuzzy_picking = bool_value;

  bool_value =
    g_key_file_get_boolean (keyfile, ENVIRONMENT_GROUP,
                            "EnableAccessibility",
                            &key_error);

  if (key_error != NULL)
    g_clear_error (&key_error);
  else
    clutter_enable_accessibility = bool_value;

264 265 266 267 268 269 270 271 272 273
  bool_value =
    g_key_file_get_boolean (keyfile, ENVIRONMENT_GROUP,
                            "SyncToVblank",
                            &key_error);

  if (key_error != NULL)
    g_clear_error (&key_error);
  else
    clutter_sync_to_vblank = bool_value;

274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
  int_value =
    g_key_file_get_integer (keyfile, ENVIRONMENT_GROUP,
                            "DefaultFps",
                            &key_error);

  if (key_error != NULL)
    g_clear_error (&key_error);
  else
    clutter_default_fps = int_value;

  str_value =
    g_key_file_get_string (keyfile, ENVIRONMENT_GROUP,
                           "TextDirection",
                           &key_error);

  if (key_error != NULL)
    g_clear_error (&key_error);
  else
    {
      if (g_strcmp0 (str_value, "rtl") == 0)
        clutter_text_direction = CLUTTER_TEXT_DIRECTION_RTL;
      else
        clutter_text_direction = CLUTTER_TEXT_DIRECTION_LTR;
    }
298 299

  g_free (str_value);
300 301 302 303 304 305 306
}

#ifdef CLUTTER_ENABLE_DEBUG
static void
clutter_debug_read_from_key_file (GKeyFile *keyfile)
{
  GError *key_error = NULL;
307
  gchar *value;
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324

  if (!g_key_file_has_group (keyfile, DEBUG_GROUP))
    return;

  value = g_key_file_get_value (keyfile, DEBUG_GROUP,
                                "Debug",
                                &key_error);
  if (key_error == NULL)
    {
      clutter_debug_flags |=
        g_parse_debug_string (value,
                              clutter_debug_keys,
                              G_N_ELEMENTS (clutter_debug_keys));
    }
  else
    g_clear_error (&key_error);

325 326
  g_free (value);

327 328 329 330 331 332 333 334 335 336 337 338 339
  value = g_key_file_get_value (keyfile, DEBUG_GROUP,
                                "PaintDebug",
                                &key_error);
  if (key_error == NULL)
    {
      clutter_paint_debug_flags |=
        g_parse_debug_string (value,
                              clutter_paint_debug_keys,
                              G_N_ELEMENTS (clutter_paint_debug_keys));
    }
  else
    g_clear_error (&key_error);

340 341
  g_free (value);

342 343 344 345 346 347 348 349 350 351 352 353
  value = g_key_file_get_value (keyfile, DEBUG_GROUP,
                                "PickDebug",
                                &key_error);
  if (key_error == NULL)
    {
      clutter_pick_debug_flags |=
        g_parse_debug_string (value,
                              clutter_pick_debug_keys,
                              G_N_ELEMENTS (clutter_pick_debug_keys));
    }
  else
    g_clear_error (&key_error);
354 355

  g_free (value);
356 357 358 359 360 361 362 363 364 365 366 367 368
}
#endif

static void
clutter_config_read_from_file (const gchar *config_path)
{
  ClutterSettings *settings = clutter_settings_get_default ();
  GKeyFile *key_file = g_key_file_new ();
  GError *error = NULL;

  g_key_file_load_from_file (key_file, config_path, G_KEY_FILE_NONE, &error);
  if (error == NULL)
    {
369 370
      CLUTTER_NOTE (MISC, "Reading configuration from '%s'", config_path);

371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
      clutter_config_read_from_key_file (key_file);
#ifdef CLUTTER_ENABLE_DEBUG
      clutter_debug_read_from_key_file (key_file);
#endif
      _clutter_settings_read_from_key_file (settings, key_file);
    }
  else
    {
      g_warning ("Unable to read configuration settings from '%s': %s",
                 config_path,
                 error->message);
      g_error_free (error);
    }

  g_key_file_free (key_file);
}
387 388 389 390 391 392 393 394 395 396 397

static void
clutter_config_read (void)
{
  gchar *config_path;

  config_path = g_build_filename (CLUTTER_SYSCONFDIR,
                                  "clutter-1.0",
                                  "settings.ini",
                                  NULL);
  if (g_file_test (config_path, G_FILE_TEST_EXISTS))
398
    clutter_config_read_from_file (config_path);
399 400 401 402 403 404 405 406

  g_free (config_path);

  config_path = g_build_filename (g_get_user_config_dir (),
                                  "clutter-1.0",
                                  "settings.ini",
                                  NULL);
  if (g_file_test (config_path, G_FILE_TEST_EXISTS))
407
    clutter_config_read_from_file (config_path);
408 409 410 411

  g_free (config_path);
}

412 413 414
/**
 * clutter_get_show_fps:
 *
415 416 417 418
 * Returns whether Clutter should print out the frames per second on the
 * console. You can enable this setting either using the
 * <literal>CLUTTER_SHOW_FPS</literal> environment variable or passing
 * the <literal>--clutter-show-fps</literal> command line argument. *
419
 *
420
 * Return value: %TRUE if Clutter should show the FPS.
421 422
 *
 * Since: 0.4
423 424 425 426
 *
 * Deprecated: 1.10: This function does not do anything. Use the environment
 *   variable or the configuration file to determine whether Clutter should
 *   print out the FPS counter on the console.
427
 */
428
gboolean
429
clutter_get_show_fps (void)
430
{
431 432 433 434 435 436 437 438 439
  return FALSE;
}

gboolean
_clutter_context_get_show_fps (void)
{
  ClutterMainContext *context = _clutter_context_get_default ();

  return context->show_fps;
440 441
}

442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
/**
 * clutter_get_accessibility_enabled:
 *
 * Returns whether Clutter has accessibility support enabled.  As
 * least, a value of TRUE means that there are a proper AtkUtil
 * implementation available
 *
 * Return value: %TRUE if Clutter has accessibility support enabled
 *
 * Since: 1.4
 */
gboolean
clutter_get_accessibility_enabled (void)
{
  return cally_get_cally_initialized ();
}

459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
/**
 * clutter_disable_accessibility:
 *
 * Disable loading the accessibility support. It has the same effect
 * as setting the environment variable
 * CLUTTER_DISABLE_ACCESSIBILITY. For the same reason, this method
 * should be called before clutter_init().
 *
 * Since: 1.14
 */
void
clutter_disable_accessibility (void)
{
  if (clutter_is_initialized)
    {
      g_warning ("clutter_disable_accessibility() can only be called before "
                 "initializing Clutter.");
      return;
    }

  clutter_enable_accessibility = FALSE;
}

482 483 484 485 486 487 488 489
/**
 * clutter_redraw:
 *
 * Forces a redraw of the entire stage. Applications should never use this
 * function, but queue a redraw using clutter_actor_queue_redraw().
 *
 * This function should only be used by libraries integrating Clutter from
 * within another toolkit.
490 491
 *
 * Deprecated: 1.10: Use clutter_stage_ensure_redraw() instead.
492 493 494 495
 */
void
clutter_redraw (ClutterStage *stage)
{
496
  g_return_if_fail (CLUTTER_IS_STAGE (stage));
497

498
  clutter_stage_ensure_redraw (stage);
499 500
}

501 502 503 504
/**
 * clutter_set_motion_events_enabled:
 * @enable: %TRUE to enable per-actor motion events
 *
505 506
 * Sets whether per-actor motion events should be enabled or not on
 * all #ClutterStage<!-- -->s managed by Clutter.
507 508
 *
 * If @enable is %FALSE the following events will not work:
Emmanuele Bassi's avatar
Emmanuele Bassi committed
509 510 511 512
 *
 *  - ClutterActor::motion-event, except on the #ClutterStage
 *  - ClutterActor::enter-event
 *  - ClutterActor::leave-event
513 514
 *
 * Since: 0.6
515 516
 *
 * Deprecated: 1.8: Use clutter_stage_set_motion_events_enabled() instead.
517
 */
518
void
519
clutter_set_motion_events_enabled (gboolean enable)
520
{
521 522 523 524 525 526 527 528 529
  ClutterStageManager *stage_manager;
  ClutterMainContext *context;
  const GSList *l;

  enable = !!enable;

  context = _clutter_context_get_default ();
  if (context->motion_events_per_actor == enable)
    return;
530

531
  /* store the flag for later query and for newly created stages */
532
  context->motion_events_per_actor = enable;
533 534 535 536 537 538 539 540

  /* propagate the change to all stages */
  stage_manager = clutter_stage_manager_get_default ();

  for (l = clutter_stage_manager_peek_stages (stage_manager);
       l != NULL;
       l = l->next)
    {
541
      clutter_stage_set_motion_events_enabled (l->data, enable);
542
    }
543 544
}

545 546 547 548 549 550 551 552
/**
 * clutter_get_motion_events_enabled:
 *
 * Gets whether the per-actor motion events are enabled.
 *
 * Return value: %TRUE if the motion events are enabled
 *
 * Since: 0.6
553 554
 *
 * Deprecated: 1.8: Use clutter_stage_get_motion_events_enabled() instead.
555
 */
556 557 558
gboolean
clutter_get_motion_events_enabled (void)
{
559
  return _clutter_context_get_motion_events_enabled ();
560 561
}

562
void
563 564
_clutter_id_to_color (guint         id_,
                      ClutterColor *col)
565 566
{
  ClutterMainContext *ctx;
567 568 569
  gint red, green, blue;

  ctx = _clutter_context_get_default ();
570

571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
  if (ctx->fb_g_mask == 0)
    {
      /* Figure out framebuffer masks used for pick */
      cogl_get_bitmasks (&ctx->fb_r_mask,
			 &ctx->fb_g_mask,
			 &ctx->fb_b_mask, NULL);

      ctx->fb_r_mask_used = ctx->fb_r_mask;
      ctx->fb_g_mask_used = ctx->fb_g_mask;
      ctx->fb_b_mask_used = ctx->fb_b_mask;

      /* XXX - describe what "fuzzy picking" is */
      if (clutter_use_fuzzy_picking)
	{
	  ctx->fb_r_mask_used--;
	  ctx->fb_g_mask_used--;
	  ctx->fb_b_mask_used--;
	}
    }

591
  /* compute the numbers we'll store in the components */
592
  red   = (id_ >> (ctx->fb_g_mask_used+ctx->fb_b_mask_used))
593
        & (0xff >> (8-ctx->fb_r_mask_used));
594
  green = (id_ >> ctx->fb_b_mask_used)
595
        & (0xff >> (8-ctx->fb_g_mask_used));
596
  blue  = (id_)
597
        & (0xff >> (8-ctx->fb_b_mask_used));
598 599 600

  /* shift left bits a bit and add one, this circumvents
   * at least some potential rounding errors in GL/GLES
601
   * driver / hw implementation.
602 603
   */
  if (ctx->fb_r_mask_used != ctx->fb_r_mask)
604
    red = red * 2;
605
  if (ctx->fb_g_mask_used != ctx->fb_g_mask)
606
    green = green * 2;
607
  if (ctx->fb_b_mask_used != ctx->fb_b_mask)
608
    blue  = blue  * 2;
609

610
  /* shift up to be full 8bit values */
611 612 613
  red   = (red   << (8 - ctx->fb_r_mask)) | (0x7f >> (ctx->fb_r_mask_used));
  green = (green << (8 - ctx->fb_g_mask)) | (0x7f >> (ctx->fb_g_mask_used));
  blue  = (blue  << (8 - ctx->fb_b_mask)) | (0x7f >> (ctx->fb_b_mask_used));
614 615 616 617 618

  col->red   = red;
  col->green = green;
  col->blue  = blue;
  col->alpha = 0xff;
619

620 621 622 623 624
  /* XXX: We rotate the nibbles of the colors here so that there is a
   * visible variation between colors of sequential actor identifiers;
   * otherwise pick buffers dumped to an image will pretty much just look
   * black.
   */
625
  if (G_UNLIKELY (clutter_pick_debug_flags & CLUTTER_DEBUG_DUMP_PICK_BUFFERS))
626
    {
627
      col->red   = (col->red << 4)   | (col->red >> 4);
628
      col->green = (col->green << 4) | (col->green >> 4);
629
      col->blue  = (col->blue << 4)  | (col->blue >> 4);
630
    }
631 632
}

633
guint
634
_clutter_pixel_to_id (guchar pixel[4])
635 636
{
  ClutterMainContext *ctx;
637 638
  gint red, green, blue;
  guint retval;
639

640
  ctx = _clutter_context_get_default ();
641 642 643 644

  /* reduce the pixel components to the number of bits actually used of the
   * 8bits.
   */
645
  if (G_UNLIKELY (clutter_pick_debug_flags & CLUTTER_DEBUG_DUMP_PICK_BUFFERS))
646 647
    {
      guchar tmp;
648 649 650 651 652 653

      /* XXX: In _clutter_id_to_color we rotated the nibbles of the colors so
       * that there is a visible variation between colors of sequential actor
       * identifiers (otherwise pick buffers dumped to an image will pretty
       * much just look black.) Here we reverse that rotation.
       */
654 655 656 657 658 659 660 661 662 663 664 665 666
      tmp = ((pixel[0] << 4) | (pixel[0] >> 4));
      red = tmp >> (8 - ctx->fb_r_mask);
      tmp = ((pixel[1] << 4) | (pixel[1] >> 4));
      green = tmp >> (8 - ctx->fb_g_mask);
      tmp = ((pixel[2] << 4) | (pixel[2] >> 4));
      blue = tmp >> (8 - ctx->fb_b_mask);
    }
  else
    {
      red   = pixel[0] >> (8 - ctx->fb_r_mask);
      green = pixel[1] >> (8 - ctx->fb_g_mask);
      blue  = pixel[2] >> (8 - ctx->fb_b_mask);
    }
667 668 669 670

  /* divide potentially by two if 'fuzzy' */
  red   = red   >> (ctx->fb_r_mask - ctx->fb_r_mask_used);
  green = green >> (ctx->fb_g_mask - ctx->fb_g_mask_used);
671
  blue  = blue  >> (ctx->fb_b_mask - ctx->fb_b_mask_used);
672 673

  /* combine the correct per component values into the final id */
674 675 676
  retval = blue
         + (green <<  ctx->fb_b_mask_used)
         + (red << (ctx->fb_b_mask_used + ctx->fb_g_mask_used));
677

678
  return retval;
679 680
}

681 682
static CoglPangoFontMap *
clutter_context_get_pango_fontmap (void)
683
{
684
  ClutterMainContext *self;
685 686 687 688
  CoglPangoFontMap *font_map;
  gdouble resolution;
  gboolean use_mipmapping;

689
  self = _clutter_context_get_default ();
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
  if (G_LIKELY (self->font_map != NULL))
    return self->font_map;

  font_map = COGL_PANGO_FONT_MAP (cogl_pango_font_map_new ());

  resolution = clutter_backend_get_resolution (self->backend);
  cogl_pango_font_map_set_resolution (font_map, resolution);

  use_mipmapping = !clutter_disable_mipmap_text;
  cogl_pango_font_map_set_use_mipmapping (font_map, use_mipmapping);

  self->font_map = font_map;

  return self->font_map;
}

706
static ClutterTextDirection
707
clutter_get_text_direction (void)
708
{
709
  ClutterTextDirection dir = CLUTTER_TEXT_DIRECTION_LTR;
710
  const gchar *direction;
711 712 713 714 715

  direction = g_getenv ("CLUTTER_TEXT_DIRECTION");
  if (direction && *direction != '\0')
    {
      if (strcmp (direction, "rtl") == 0)
716
        dir = CLUTTER_TEXT_DIRECTION_RTL;
717
      else if (strcmp (direction, "ltr") == 0)
718
        dir = CLUTTER_TEXT_DIRECTION_LTR;
719 720
    }
  else
721
    {
722 723
      /* Re-use GTK+'s LTR/RTL handling */
      const char *e = g_dgettext ("gtk30", "default:LTR");
724 725

      if (strcmp (e, "default:RTL") == 0)
726
        dir = CLUTTER_TEXT_DIRECTION_RTL;
727
      else if (strcmp (e, "default:LTR") == 0)
728
        dir = CLUTTER_TEXT_DIRECTION_LTR;
729 730 731
      else
        g_warning ("Whoever translated default:LTR did so wrongly.");
    }
732

733 734 735
  CLUTTER_NOTE (MISC, "Text direction: %s",
                dir == CLUTTER_TEXT_DIRECTION_RTL ? "rtl" : "ltr");

736 737 738
  return dir;
}

739 740 741
/**
 * clutter_main_quit:
 *
Iain Holmes's avatar
Iain Holmes committed
742
 * Terminates the Clutter mainloop.
743
 */
744
void
745
clutter_main_quit (void)
746
{
747 748 749 750 751 752 753 754 755
  if (main_loops == NULL)
    {
      g_critical ("Calling clutter_main_quit() without calling clutter_main() "
                  "is not allowed. If you are using another main loop, use the "
                  "appropriate API to terminate it.");
      return;
    }

  CLUTTER_NOTE (MISC, "Terminating main loop level %d", clutter_main_loop_level);
756

757
  g_main_loop_quit (main_loops->data);
758 759
}

760 761 762
/**
 * clutter_main_level:
 *
Iain Holmes's avatar
Iain Holmes committed
763 764 765
 * Retrieves the depth of the Clutter mainloop.
 *
 * Return value: The level of the mainloop.
766 767 768 769
 */
gint
clutter_main_level (void)
{
770
  return clutter_main_loop_level;
771 772 773 774 775
}

/**
 * clutter_main:
 *
Iain Holmes's avatar
Iain Holmes committed
776
 * Starts the Clutter mainloop.
777
 */
778
void
779
clutter_main (void)
780
{
781 782
  GMainLoop *loop;

783
  if (!_clutter_context_is_initialized ())
784
    {
785
      g_warning ("Called clutter_main() but Clutter wasn't initialised. "
786 787 788 789
		 "You must call clutter_init() first.");
      return;
    }

790 791 792 793
  clutter_main_loop_level++;

  CLUTTER_NOTE (MISC, "Entering main loop level %d", clutter_main_loop_level);

794
  loop = g_main_loop_new (NULL, TRUE);
795
  main_loops = g_slist_prepend (main_loops, loop);
796

797
  if (g_main_loop_is_running (main_loops->data))
798
    {
799
      _clutter_threads_release_lock ();
800
      g_main_loop_run (loop);
801
      _clutter_threads_acquire_lock ();
802 803
    }

804
  main_loops = g_slist_remove (main_loops, loop);
805 806 807

  g_main_loop_unref (loop);

808 809
  CLUTTER_NOTE (MISC, "Leaving main loop level %d", clutter_main_loop_level);

810
  clutter_main_loop_level--;
811 812
}

813 814 815 816 817 818 819 820 821 822 823
/**
 * clutter_threads_init:
 *
 * Initialises the Clutter threading mechanism, so that Clutter API can be
 * called by multiple threads, using clutter_threads_enter() and
 * clutter_threads_leave() to mark the critical sections.
 *
 * You must call g_thread_init() before this function.
 *
 * This function must be called before clutter_init().
 *
824 825
 * It is safe to call this function multiple times.
 *
826
 * Since: 0.4
827 828 829
 *
 * Deprecated: 1.10: This function does not do anything. Threading support
 *   is initialized when Clutter is initialized.
830 831 832 833 834 835 836
 */
void
clutter_threads_init (void)
{
}

/**
837
 * clutter_threads_set_lock_functions: (skip)
838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
 * @enter_fn: function called when aquiring the Clutter main lock
 * @leave_fn: function called when releasing the Clutter main lock
 *
 * Allows the application to replace the standard method that
 * Clutter uses to protect its data structures. Normally, Clutter
 * creates a single #GMutex that is locked by clutter_threads_enter(),
 * and released by clutter_threads_leave(); using this function an
 * application provides, instead, a function @enter_fn that is
 * called by clutter_threads_enter() and a function @leave_fn that is
 * called by clutter_threads_leave().
 *
 * The functions must provide at least same locking functionality
 * as the default implementation, but can also do extra application
 * specific processing.
 *
 * As an example, consider an application that has its own recursive
 * lock that when held, holds the Clutter lock as well. When Clutter
 * unlocks the Clutter lock when entering a recursive main loop, the
 * application must temporarily release its lock as well.
 *
 * Most threaded Clutter apps won't need to use this method.
 *
Emmanuele Bassi's avatar
Emmanuele Bassi committed
860
 * This method must be called before clutter_init(), and cannot
861 862
 * be called multiple times.
 *
863
 * Since: 0.4
864 865 866 867 868 869 870 871 872 873 874 875
 */
void
clutter_threads_set_lock_functions (GCallback enter_fn,
                                    GCallback leave_fn)
{
  g_return_if_fail (clutter_threads_lock == NULL &&
                    clutter_threads_unlock == NULL);

  clutter_threads_lock = enter_fn;
  clutter_threads_unlock = leave_fn;
}

876 877
gboolean
_clutter_threads_dispatch (gpointer data)
878 879 880 881
{
  ClutterThreadsDispatch *dispatch = data;
  gboolean ret = FALSE;

882
  _clutter_threads_acquire_lock ();
883 884 885 886

  if (!g_source_is_destroyed (g_main_current_source ()))
    ret = dispatch->func (dispatch->data);

887
  _clutter_threads_release_lock ();
888 889 890 891

  return ret;
}

892 893
void
_clutter_threads_dispatch_free (gpointer data)
894 895 896
{
  ClutterThreadsDispatch *dispatch = data;

897 898 899 900 901 902
  /* XXX - we cannot hold the thread lock here because the main loop
   * might destroy a source while still in the dispatcher function; so
   * knowing whether the lock is being held or not is not known a priori.
   *
   * see bug: http://bugzilla.gnome.org/show_bug.cgi?id=459555
   */
903 904 905 906 907 908 909
  if (dispatch->notify)
    dispatch->notify (dispatch->data);

  g_slice_free (ClutterThreadsDispatch, dispatch);
}

/**
910
 * clutter_threads_add_idle_full: (rename-to clutter_threads_add_idle)
911 912 913 914 915 916 917
 * @priority: the priority of the timeout source. Typically this will be in the
 *    range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE
 * @func: function to call
 * @data: data to pass to the function
 * @notify: functio to call when the idle source is removed
 *
 * Adds a function to be called whenever there are no higher priority
918
 * events pending. If the function returns %FALSE it is automatically
919 920
 * removed from the list of event sources and will not be called again.
 *
921 922 923
 * This function can be considered a thread-safe variant of g_idle_add_full():
 * it will call @function while holding the Clutter lock. It is logically
 * equivalent to the following implementation:
924
 *
925
 * |[
926
 * static gboolean
927
 * idle_safe_callback (gpointer data)
928
 * {
929 930
 *    SafeClosure *closure = data;
 *    gboolean res = FALSE;
931
 *
Emmanuele Bassi's avatar
Emmanuele Bassi committed
932
 *    // mark the critical section //
933
 *
934
 *    clutter_threads_enter();
935
 *
Emmanuele Bassi's avatar
Emmanuele Bassi committed
936 937 938
 *    // the callback does not need to acquire the Clutter
 *     / lock itself, as it is held by the this proxy handler
 *     //
939 940 941 942 943
 *    res = closure->callback (closure->data);
 *
 *    clutter_threads_leave();
 *
 *    return res;
944
 * }
945 946 947
 * static gulong
 * add_safe_idle (GSourceFunc callback,
 *                gpointer    data)
948
 * {
949 950
 *   SafeClosure *closure = g_new0 (SafeClosure, 1);
 *
Emmanuele Bassi's avatar
Emmanuele Bassi committed
951 952
 *   closure->callback = callback;
 *   closure->data = data;
953
 *
Emmanuele Bassi's avatar
Emmanuele Bassi committed
954
 *   return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE,
955 956 957
 *                           idle_safe_callback,
 *                           closure,
 *                           g_free)
958
 * }
959
 *]|
960
 *
961 962 963 964 965 966 967 968 969
 * This function should be used by threaded applications to make sure
 * that @func is emitted under the Clutter threads lock and invoked
 * from the same thread that started the Clutter main loop. For instance,
 * it can be used to update the UI using the results from a worker
 * thread:
 *
 * |[
 * static gboolean
 * update_ui (gpointer data)
970
 * {
971 972
 *   SomeClosure *closure = data;
 *
Emmanuele Bassi's avatar
Emmanuele Bassi committed
973 974 975 976 977 978
 *   // it is safe to call Clutter API from this function because
 *    / it is invoked from the same thread that started the main
 *    / loop and under the Clutter thread lock
 *    //
 *   clutter_label_set_text (CLUTTER_LABEL (closure->label),
 *                           closure->text);
979
 *
Emmanuele Bassi's avatar
Emmanuele Bassi committed
980
 *   g_object_unref (closure->label);
981 982 983
 *   g_free (closure);
 *
 *   return FALSE;
984
 * }
985
 *
Emmanuele Bassi's avatar
Emmanuele Bassi committed
986
 *   // within another thread //
987
 *   closure = g_new0 (SomeClosure, 1);
Emmanuele Bassi's avatar
Emmanuele Bassi committed
988 989 990
 *   // always take a reference on GObject instances //
 *   closure->label = g_object_ref (my_application->label);
 *   closure->text = g_strdup (processed_text_to_update_the_label);
991 992 993 994 995 996
 *
 *   clutter_threads_add_idle_full (G_PRIORITY_HIGH_IDLE,
 *                                  update_ui,
 *                                  closure,
 *                                  NULL);
 * ]|
997 998 999
 *
 * Return value: the ID (greater than 0) of the event source.
 *
1000
 * Since: 0.4
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
 */
guint
clutter_threads_add_idle_full (gint           priority,
                               GSourceFunc    func,
                               gpointer       data,
                               GDestroyNotify notify)
{
  ClutterThreadsDispatch *dispatch;

  g_return_val_if_fail (func != NULL, 0);

  dispatch = g_slice_new (ClutterThreadsDispatch);
  dispatch->func = func;
  dispatch->data = data;
  dispatch->notify = notify;

  return g_idle_add_full (priority,
1018 1019
                          _clutter_threads_dispatch, dispatch,
                          _clutter_threads_dispatch_free);
1020 1021 1022
}

/**
1023
 * clutter_threads_add_idle: (skip)
1024 1025 1026
 * @func: function to call
 * @data: data to pass to the function
 *
1027 1028
 * Simple wrapper around clutter_threads_add_idle_full() using the
 * default priority.
1029 1030 1031
 *
 * Return value: the ID (greater than 0) of the event source.
 *
1032
 * Since: 0.4
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
 */
guint
clutter_threads_add_idle (GSourceFunc func,
                          gpointer    data)
{
  g_return_val_if_fail (func != NULL, 0);

  return clutter_threads_add_idle_full (G_PRIORITY_DEFAULT_IDLE,
                                        func, data,
                                        NULL);
}

/**
1046
 * clutter_threads_add_timeout_full: (rename-to clutter_threads_add_timeout)
1047 1048 1049 1050 1051 1052 1053
 * @priority: the priority of the timeout source. Typically this will be in the
 *            range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
 * @interval: the time between calls to the function, in milliseconds
 * @func: function to call
 * @data: data to pass to the function
 * @notify: function to call when the timeout source is removed
 *
1054 1055 1056 1057 1058
 * Sets a function to be called at regular intervals holding the Clutter
 * threads lock, with the given priority. The function is called repeatedly
 * until it returns %FALSE, at which point the timeout is automatically
 * removed and the function will not be called again. The @notify function
 * is called when the timeout is removed.
1059
 *
1060
 * The first call to the function will be at the end of the first @interval.
1061
 *
1062 1063
 * It is important to note that, due to how the Clutter main loop is
 * implemented, the timing will not be accurate and it will not try to
Emmanuele Bassi's avatar
Emmanuele Bassi committed
1064
 * "keep up" with the interval.
1065 1066
 *
 * See also clutter_threads_add_idle_full().
1067 1068 1069
 *
 * Return value: the ID (greater than 0) of the event source.
 *
1070
 * Since: 0.4
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
 */
guint
clutter_threads_add_timeout_full (gint           priority,
                                  guint          interval,
                                  GSourceFunc    func,
                                  gpointer       data,
                                  GDestroyNotify notify)
{
  ClutterThreadsDispatch *dispatch;

  g_return_val_if_fail (func != NULL, 0);

  dispatch = g_slice_new (ClutterThreadsDispatch);
  dispatch->func = func;
  dispatch->data = data;
  dispatch->notify = notify;

  return g_timeout_add_full (priority,
                             interval,
1090 1091
                             _clutter_threads_dispatch, dispatch,
                             _clutter_threads_dispatch_free);
1092 1093 1094
}

/**
1095
 * clutter_threads_add_timeout: (skip)
1096 1097 1098 1099 1100 1101 1102 1103
 * @interval: the time between calls to the function, in milliseconds
 * @func: function to call
 * @data: data to pass to the function
 *
 * Simple wrapper around clutter_threads_add_timeout_full().
 *
 * Return value: the ID (greater than 0) of the event source.
 *
1104
 * Since: 0.4
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
 */
guint
clutter_threads_add_timeout (guint       interval,
                             GSourceFunc func,
                             gpointer    data)
{
  g_return_val_if_fail (func != NULL, 0);

  return clutter_threads_add_timeout_full (G_PRIORITY_DEFAULT,
                                           interval,
                                           func, data,
                                           NULL);
}

1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
void
_clutter_threads_acquire_lock (void)
{
  if (clutter_threads_lock != NULL)
    (* clutter_threads_lock) ();
}

void
_clutter_threads_release_lock (void)
{
  if (clutter_threads_unlock != NULL)
    (* clutter_threads_unlock) ();
}

1133 1134 1135 1136 1137
/**
 * clutter_threads_enter:
 *
 * Locks the Clutter thread lock.
 *
1138
 * Since: 0.4
1139 1140 1141 1142 1143 1144
 *
 * Deprecated: 1.12: This function should not be used by application
 *   code; marking critical sections is not portable on various
 *   platforms. Instead of acquiring the Clutter lock, schedule UI
 *   updates from the main loop using clutter_threads_add_idle() or
 *   clutter_threads_add_timeout().
1145 1146 1147 1148
 */
void
clutter_threads_enter (void)
{
1149
  _clutter_threads_acquire_lock ();
1150 1151 1152 1153 1154 1155 1156
}

/**
 * clutter_threads_leave:
 *
 * Unlocks the Clutter thread lock.
 *
1157
 * Since: 0.4
1158 1159 1160 1161 1162 1163
 *
 * Deprecated: 1.12: This function should not be used by application
 *   code; marking critical sections is not portable on various
 *   platforms. Instead of acquiring the Clutter lock, schedule UI
 *   updates from the main loop using clutter_threads_add_idle() or
 *   clutter_threads_add_timeout().
1164 1165 1166 1167
 */
void
clutter_threads_leave (void)
{
1168
  _clutter_threads_release_lock ();
1169 1170 1171
}


1172
/**
1173
 * clutter_get_debug_enabled:
1174
 *
1175 1176 1177
 * Check if Clutter has debugging enabled.
 *
 * Return value: %FALSE
1178
 *
1179
 * Deprecated: 1.10: This function does not do anything.
1180
 */
1181
gboolean
1182
clutter_get_debug_enabled (void)
1183
{
1184
  return FALSE;
1185 1186
}

1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
void
_clutter_context_lock (void)
{
  G_LOCK (ClutterCntx);
}

void
_clutter_context_unlock (void)
{
  G_UNLOCK (ClutterCntx);
}

1199 1200 1201 1202 1203 1204 1205 1206 1207
gboolean
_clutter_context_is_initialized (void)
{
  if (ClutterCntx == NULL)
    return FALSE;

  return ClutterCntx->is_initialized;
}

1208 1209 1210 1211 1212 1213 1214
static ClutterMainContext *
clutter_context_get_default_unlocked (void)
{
  if (G_UNLIKELY (ClutterCntx == NULL))
    {
      ClutterMainContext *ctx;

1215 1216 1217 1218 1219 1220
      /* Read the configuration file, if any, before we set up the
       * whole thing, so that we can override things like the backend
       * and the driver
       */
      clutter_config_read ();

1221
      ClutterCntx = ctx = g_new0 (ClutterMainContext, 1);
1222

1223
      ctx->is_initialized = FALSE;
1224 1225

      /* create the windowing system backend */
1226
      ctx->backend = _clutter_create_backend ();
1227

1228 1229 1230 1231 1232 1233
      /* create the default settings object, and store a back pointer to
       * the backend singleton
       */
      ctx->settings = clutter_settings_get_default ();
      _clutter_settings_set_backend (ctx->settings, ctx->backend);

1234
      ctx->motion_events_per_actor = TRUE;
1235
      ctx->last_repaint_id = 1;
1236 1237 1238 1239 1240
    }

  return ClutterCntx;
}

1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
ClutterMainContext *
_clutter_context_get_default (void)
{
  ClutterMainContext *retval;

  _clutter_context_lock ();

  retval = clutter_context_get_default_unlocked ();

  _clutter_context_unlock ();

  return retval;
}

1255 1256 1257
/**
 * clutter_get_timestamp:
 *
1258
 * Returns the approximate number of microseconds passed since Clutter was
1259 1260
 * intialised.
 *
1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
 * This function shdould not be used by application code.
 *
 * The output of this function depends on whether Clutter was configured to
 * enable its debugging code paths, so it's less useful than intended.
 *
 * Since Clutter 1.10, this function is an alias to g_get_monotonic_time()
 * if Clutter was configured to enable the debugging code paths.
 *
 * Return value: Number of microseconds since clutter_init() was called, or
 *   zero if Clutter was not configured with debugging code paths.
 *
 * Deprecated: 1.10: Use #GTimer or g_get_monotonic_time() for a proper
 *   timing source
1274 1275 1276 1277 1278
 */
gulong
clutter_get_timestamp (void)
{
#ifdef CLUTTER_ENABLE_DEBUG
1279
  return (gulong) g_get_monotonic_time ();
1280
#else
1281
  return 0L;
1282 1283 1284
#endif
}

1285 1286 1287 1288 1289 1290
static gboolean
clutter_arg_direction_cb (const char *key,
                          const char *value,
                          gpointer    user_data)
{
  clutter_text_direction =
1291 1292
    (strcmp (value, "rtl") == 0) ? CLUTTER_TEXT_DIRECTION_RTL
                                 : CLUTTER_TEXT_DIRECTION_LTR;
1293 1294 1295

  return TRUE;
}
1296

1297 1298 1299 1300 1301
#ifdef CLUTTER_ENABLE_DEBUG
static gboolean
clutter_arg_debug_cb (const char *key,
                      const char *value,
                      gpointer    user_data)
1302
{
1303 1304 1305 1306 1307 1308
  clutter_debug_flags |=
    g_parse_debug_string (value,
                          clutter_debug_keys,
                          G_N_ELEMENTS (clutter_debug_keys));
  return TRUE;
}
1309

1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
static gboolean
clutter_arg_no_debug_cb (const char *key,
                         const char *value,
                         gpointer    user_data)
{
  clutter_debug_flags &=
    ~g_parse_debug_string (value,
                           clutter_debug_keys,
                           G_N_ELEMENTS (clutter_debug_keys));
  return TRUE;
}
#endif /* CLUTTER_ENABLE_DEBUG */

1323 1324 1325 1326 1327 1328 1329 1330 1331 1332
GQuark
clutter_init_error_quark (void)
{
  return g_quark_from_static_string ("clutter-init-error-quark");
}

static ClutterInitError
clutter_init_real (GError **error)
{
  ClutterMainContext *ctx;
1333
  ClutterBackend *backend;
1334 1335 1336 1337

  /* Note, creates backend if not already existing, though parse args will
   * have likely created it
   */
1338
  ctx = _clutter_context_get_default ();
1339 1340 1341 1342
  backend = ctx->backend;

  if (!ctx->options_parsed)
    {
1343 1344 1345 1346 1347 1348 1349 1350
      if (error)
        g_set_error (error, CLUTTER_INIT_ERROR,
                     CLUTTER_INIT_ERROR_INTERNAL,
                     "When using clutter_get_option_group_without_init() "
		     "you must parse options before calling clutter_init()");
      else
        g_critical ("When using clutter_get_option_group_without_init() "
		    "you must parse options before calling clutter_init()");
1351 1352 1353 1354 1355 1356 1357

      return CLUTTER_INIT_ERROR_INTERNAL;
    }

  /*
   * Call backend post parse hooks.
   */
1358 1359
  if (!_clutter_backend_post_parse (backend, error))
    return CLUTTER_INIT_ERROR_BACKEND;
1360

1361 1362 1363 1364 1365 1366 1367
  /* If we are displaying the regions that would get redrawn with clipped
   * redraws enabled we actually have to disable the clipped redrawing
   * because otherwise we end up with nasty trails of rectangles everywhere.
   */
  if (clutter_paint_debug_flags & CLUTTER_DEBUG_REDRAWS)
    clutter_paint_debug_flags |= CLUTTER_DEBUG_DISABLE_CLIPPED_REDRAWS;

1368 1369
  /* The same is true when drawing the outlines of paint volumes... */
  if (clutter_paint_debug_flags & CLUTTER_DEBUG_PAINT_VOLUMES)
1370 1371 1372 1373
    {
      clutter_paint_debug_flags |=
        CLUTTER_DEBUG_DISABLE_CLIPPED_REDRAWS | CLUTTER_DEBUG_DISABLE_CULLING;
    }
1374

1375 1376
  /* this will take care of initializing Cogl's state and
   * query the GL machinery for features
1377
   */
1378 1379
  if (!_clutter_feature_init (error))
    return CLUTTER_INIT_ERROR_BACKEND;
1380

1381 1382
  clutter_text_direction = clutter_get_text_direction ();

1383 1384 1385 1386
  /* Initiate event collection */
  _clutter_backend_init_events (ctx->backend);

  clutter_is_initialized = TRUE;
1387
  ctx->is_initialized = TRUE;
1388

1389 1390 1391 1392
  /* Initialize a11y */
  if (clutter_enable_accessibility)
    cally_accessibility_init ();

1393 1394 1395
  return CLUTTER_INIT_SUCCESS;
}

1396 1397
static GOptionEntry clutter_args[] = {
  { "clutter-show-fps", 0, 0, G_OPTION_ARG_NONE, &clutter_show_fps,
1398
    N_("Show frames per second"), NULL },
1399
  { "clutter-default-fps", 0, 0, G_OPTION_ARG_INT, &clutter_default_fps,
1400
    N_("Default frame rate"), "FPS" },
1401
  { "g-fatal-warnings", 0, 0, G_OPTION_ARG_NONE, &clutter_fatal_warnings,
1402
    N_("Make all warnings fatal"), NULL },
1403 1404
  { "clutter-text-direction", 0, 0, G_OPTION_ARG_CALLBACK,
    clutter_arg_direction_cb,
1405
    N_("Direction for the text"), "DIRECTION" },
1406 1407 1408
  { "clutter-disable-mipmapped-text", 0, 0, G_OPTION_ARG_NONE,
    &clutter_disable_mipmap_text,
    N_("Disable mipmapping on text"), NULL },
1409 1410 1411
  { "clutter-use-fuzzy-picking", 0, 0, G_OPTION_ARG_NONE,
    &clutter_use_fuzzy_picking,
    N_("Use 'fuzzy' picking"), NULL },
1412 1413
#ifdef CLUTTER_ENABLE_DEBUG
  { "clutter-debug", 0, 0, G_OPTION_ARG_CALLBACK, clutter_arg_debug_cb,
1414
    N_("Clutter debugging flags to set"), "FLAGS" },
1415
  { "clutter-no-debug", 0, 0, G_OPTION_ARG_CALLBACK, clutter_arg_no_debug_cb,
1416
    N_("Clutter debugging flags to unset"), "FLAGS" },
1417
#endif /* CLUTTER_ENABLE_DEBUG */
1418 1419
  { "clutter-enable-accessibility", 0, 0, G_OPTION_ARG_NONE, &clutter_enable_accessibility,
    N_("Enable accessibility"), NULL },
1420 1421
  { NULL, },
};
1422

1423 1424 1425 1426 1427 1428 1429 1430 1431 1432
/* pre_parse_hook: initialise variables depending on environment
 * variables; these variables might be overridden by the command
 * line arguments that are going to be parsed after.
 */
static gboolean
pre_parse_hook (GOptionContext  *context,
                GOptionGroup    *group,
                gpointer         data,
                GError         **error)
{
1433 1434
  ClutterMainContext *clutter_context;
  ClutterBackend *backend;
1435
  const char *env_string;
1436

1437 1438
  if (clutter_is_initialized)
    return TRUE;
1439

1440
  clutter_context = _clutter_context_get_default ();
1441 1442 1443 1444

  backend = clutter_context->backend;
  g_assert (CLUTTER_IS_BACKEND (backend));

1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455
#ifdef CLUTTER_ENABLE_DEBUG
  env_string = g_getenv ("CLUTTER_DEBUG");
  if (env_string != NULL)
    {
      clutter_debug_flags =
        g_parse_debug_string (env_string,
                              clutter_debug_keys,
                              G_N_ELEMENTS (clutter_debug_keys));
      env_string = NULL;
    }
#endif /* CLUTTER_ENABLE_DEBUG */
1456

1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476
  env_string = g_getenv ("CLUTTER_PICK");
  if (env_string != NULL)
    {
      clutter_pick_debug_flags =
        g_parse_debug_string (env_string,
                              clutter_pick_debug_keys,
                              G_N_ELEMENTS (clutter_pick_debug_keys));
      env_string = NULL;
    }

  env_string = g_getenv ("CLUTTER_PAINT");
  if (env_string != NULL)
    {
      clutter_paint_debug_flags =
        g_parse_debug_string (env_string,
                              clutter_paint_debug_keys,
                              G_N_ELEMENTS (clutter_paint_debug_keys));
      env_string = NULL;
    }

1477 1478 1479
  env_string = g_getenv ("CLUTTER_SHOW_FPS");
  if (env_string)
    clutter_show_fps = TRUE;
1480

1481 1482 1483 1484 1485 1486 1487 1488
  env_string = g_getenv ("CLUTTER_DEFAULT_FPS");
  if (env_string)
    {
      gint default_fps = g_ascii_strtoll (env_string, NULL, 10);

      clutter_default_fps = CLAMP (default_fps, 1, 1000);
    }

1489 1490 1491 1492
  env_string = g_getenv ("CLUTTER_DISABLE_MIPMAPPED_TEXT");
  if (env_string)
    clutter_disable_mipmap_text = TRUE;

1493 1494 1495 1496
  env_string = g_getenv ("CLUTTER_FUZZY_PICK");
  if (env_string)
    clutter_use_fuzzy_picking = TRUE;

1497 1498 1499 1500
  env_string = g_getenv ("CLUTTER_VBLANK");
  if (g_strcmp0 (env_string, "none") == 0)
    clutter_sync_to_vblank = FALSE;

1501
  return _clutter_backend_pre_parse (backend, error);
1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513
}

/* post_parse_hook: initialise the context and data structures
 * and opens the X display
 */
static gboolean
post_parse_hook (GOptionContext  *context,
                 GOptionGroup    *group,
                 gpointer         data,
                 GError         **error)
{
  ClutterMainContext *clutter_context;
1514
  ClutterBackend *backend;
1515

1516 1517 1518
  if (clutter_is_initialized)
    return TRUE;

1519
  clutter_context = _clutter_context_get_default ();
1520 1521 1522
  backend = clutter_context->backend;
  g_assert (CLUTTER_IS_BACKEND (backend));

1523 1524 1525 1526 1527 1528 1529 1530 1531
  if (clutter_fatal_warnings)
    {
      GLogLevelFlags fatal_mask;

      fatal_mask = g_log_set_always_fatal (G_LOG_FATAL_MASK);
      fatal_mask |= G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL;
      g_log_set_always_fatal (fatal_mask);
    }

1532
  clutter_context->frame_rate = clutter_default_fps;
1533
  clutter_context->show_fps = clutter_show_fps;
1534
  clutter_context->options_parsed = TRUE;
1535

1536
  /* If not asked to defer display setup, call clutter_init_real(),
1537 1538 1539
   * which in turn calls the backend post parse hooks.
   */
  if (!clutter_context->defer_display_setup)
1540
    return clutter_init_real (error) == CLUTTER_INIT_SUCCESS;