summaryrefslogtreecommitdiff
path: root/clutter/clutter-main.c
blob: 10fcc2085475a122375f424d184621a7c778cba2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
/*
 * 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
 * License along with this library. If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * SECTION:clutter-main
 * @short_description: Various 'global' Clutter functions.
 *
 * Functions to retrieve various global Clutter resources and other utility
 * functions for mainloops, events and threads
 *
 * ## The Clutter Threading Model
 *
 * 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.
 *
 * 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().
 *
 * 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.
 *
 * 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)
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <stdlib.h>
#include <glib/gi18n-lib.h>
#include <locale.h>

#include "clutter-actor-private.h"
#include "clutter-backend-private.h"
#include "clutter-config.h"
#include "clutter-debug.h"
#include "clutter-device-manager-private.h"
#include "clutter-event-private.h"
#include "clutter-feature.h"
#include "clutter-main.h"
#include "clutter-master-clock.h"
#include "clutter-private.h"
#include "clutter-settings-private.h"
#include "clutter-stage-manager.h"
#include "clutter-stage-private.h"
#include "clutter-version.h" 	/* For flavour define */

#ifdef CLUTTER_WINDOWING_OSX
#include "osx/clutter-backend-osx.h"
#endif
#ifdef CLUTTER_WINDOWING_WIN32
#include "win32/clutter-backend-win32.h"
#endif
#ifdef CLUTTER_WINDOWING_GDK
#include "gdk/clutter-backend-gdk.h"
#endif
#ifdef CLUTTER_WINDOWING_X11
#include "x11/clutter-backend-x11.h"
#endif
#ifdef CLUTTER_WINDOWING_EGL
#include "egl/clutter-backend-eglnative.h"
#endif
#ifdef CLUTTER_WINDOWING_WAYLAND
#include "wayland/clutter-backend-wayland.h"
#endif
#ifdef CLUTTER_WINDOWING_MIR
#include "mir/clutter-backend-mir.h"
#endif

#include <cogl/cogl.h>
#include <cogl-pango/cogl-pango.h>

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

/* main context */
static ClutterMainContext *ClutterCntx       = NULL;
G_LOCK_DEFINE_STATIC (ClutterCntx);

/* main lock and locking/unlocking functions */
static GMutex clutter_threads_mutex;
static GCallback clutter_threads_lock        = NULL;
static GCallback clutter_threads_unlock      = NULL;

/* command line options */
static gboolean clutter_is_initialized       = FALSE;
static gboolean clutter_show_fps             = FALSE;
static gboolean clutter_fatal_warnings       = FALSE;
static gboolean clutter_disable_mipmap_text  = FALSE;
static gboolean clutter_use_fuzzy_picking    = FALSE;
static gboolean clutter_enable_accessibility = TRUE;
static gboolean clutter_sync_to_vblank       = TRUE;

static guint clutter_default_fps             = 60;

static ClutterTextDirection clutter_text_direction = CLUTTER_TEXT_DIRECTION_LTR;

static guint clutter_main_loop_level         = 0;
static GSList *main_loops                    = NULL;

/* debug flags */
guint clutter_debug_flags       = 0;
guint clutter_paint_debug_flags = 0;
guint clutter_pick_debug_flags  = 0;

const guint clutter_major_version = CLUTTER_MAJOR_VERSION;
const guint clutter_minor_version = CLUTTER_MINOR_VERSION;
const guint clutter_micro_version = CLUTTER_MICRO_VERSION;

#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 },
  { "pick", CLUTTER_DEBUG_PICK },
  { "pango", CLUTTER_DEBUG_PANGO },
  { "backend", CLUTTER_DEBUG_BACKEND },
  { "scheduler", CLUTTER_DEBUG_SCHEDULER },
  { "script", CLUTTER_DEBUG_SCRIPT },
  { "shader", CLUTTER_DEBUG_SHADER },
  { "animation", CLUTTER_DEBUG_ANIMATION },
  { "layout", CLUTTER_DEBUG_LAYOUT },
  { "clipping", CLUTTER_DEBUG_CLIPPING },
  { "oob-transforms", CLUTTER_DEBUG_OOB_TRANSFORMS },
};
#endif /* CLUTTER_ENABLE_DEBUG */

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

static const GDebugKey clutter_paint_debug_keys[] = {
  { "disable-swap-events", CLUTTER_DEBUG_DISABLE_SWAP_EVENTS },
  { "disable-clipped-redraws", CLUTTER_DEBUG_DISABLE_CLIPPED_REDRAWS },
  { "redraws", CLUTTER_DEBUG_REDRAWS },
  { "paint-volumes", CLUTTER_DEBUG_PAINT_VOLUMES },
  { "disable-culling", CLUTTER_DEBUG_DISABLE_CULLING },
  { "disable-offscreen-redirect", CLUTTER_DEBUG_DISABLE_OFFSCREEN_REDIRECT },
  { "continuous-redraw", CLUTTER_DEBUG_CONTINUOUS_REDRAW },
  { "paint-deform-tiles", CLUTTER_DEBUG_PAINT_DEFORM_TILES },
};

static void
clutter_threads_impl_lock (void)
{
  g_mutex_lock (&clutter_threads_mutex);
}

static void
clutter_threads_impl_unlock (void)
{
  /* 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);
  g_mutex_unlock (&clutter_threads_mutex);
}

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

#ifndef CLUTTER_WINDOWING_WIN32
  /* we don't need nor want locking functions on Windows.here
  * as Windows GUI system assumes multithreadedness
  * see bug: https://bugzilla.gnome.org/show_bug.cgi?id=662071
  */
  if (clutter_threads_lock == NULL)
    clutter_threads_lock = clutter_threads_impl_lock;

  if (clutter_threads_unlock == NULL)
    clutter_threads_unlock = clutter_threads_impl_unlock;
#endif /* CLUTTER_WINDOWING_WIN32 */
}

#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;
  gchar *str_value;

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

  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);

  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);

  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;

  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;

  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;
    }

  g_free (str_value);
}

#ifdef CLUTTER_ENABLE_DEBUG
static void
clutter_debug_read_from_key_file (GKeyFile *keyfile)
{
  GError *key_error = NULL;
  gchar *value;

  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);

  g_free (value);

  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);

  g_free (value);

  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);

  g_free (value);
}
#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)
    {
      CLUTTER_NOTE (MISC, "Reading configuration from '%s'", config_path);

      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);
}

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))
    clutter_config_read_from_file (config_path);

  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))
    clutter_config_read_from_file (config_path);

  g_free (config_path);
}

/**
 * clutter_get_show_fps:
 *
 * 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. *
 *
 * Return value: %TRUE if Clutter should show the FPS.
 *
 * Since: 0.4
 *
 * 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.
 */
gboolean
clutter_get_show_fps (void)
{
  return FALSE;
}

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

  return context->show_fps;
}

/**
 * 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 ();
}

/**
 * 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;
}

/**
 * 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.
 *
 * Deprecated: 1.10: Use clutter_stage_ensure_redraw() instead.
 */
void
clutter_redraw (ClutterStage *stage)
{
  g_return_if_fail (CLUTTER_IS_STAGE (stage));

  clutter_stage_ensure_redraw (stage);
}

/**
 * clutter_set_motion_events_enabled:
 * @enable: %TRUE to enable per-actor motion events
 *
 * Sets whether per-actor motion events should be enabled or not on
 * all #ClutterStage<!-- -->s managed by Clutter.
 *
 * If @enable is %FALSE the following events will not work:
 *
 *  - ClutterActor::motion-event, except on the #ClutterStage
 *  - ClutterActor::enter-event
 *  - ClutterActor::leave-event
 *
 * Since: 0.6
 *
 * Deprecated: 1.8: Use clutter_stage_set_motion_events_enabled() instead.
 */
void
clutter_set_motion_events_enabled (gboolean enable)
{
  ClutterStageManager *stage_manager;
  ClutterMainContext *context;
  const GSList *l;

  enable = !!enable;

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

  /* store the flag for later query and for newly created stages */
  context->motion_events_per_actor = enable;

  /* 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)
    {
      clutter_stage_set_motion_events_enabled (l->data, enable);
    }
}

/**
 * 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
 *
 * Deprecated: 1.8: Use clutter_stage_get_motion_events_enabled() instead.
 */
gboolean
clutter_get_motion_events_enabled (void)
{
  return _clutter_context_get_motion_events_enabled ();
}

void
_clutter_id_to_color (guint         id_,
                      ClutterColor *col)
{
  ClutterMainContext *ctx;
  gint red, green, blue;

  ctx = _clutter_context_get_default ();

  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--;
	}
    }

  /* compute the numbers we'll store in the components */
  red   = (id_ >> (ctx->fb_g_mask_used+ctx->fb_b_mask_used))
        & (0xff >> (8-ctx->fb_r_mask_used));
  green = (id_ >> ctx->fb_b_mask_used)
        & (0xff >> (8-ctx->fb_g_mask_used));
  blue  = (id_)
        & (0xff >> (8-ctx->fb_b_mask_used));

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

  /* shift up to be full 8bit values */
  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));

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

  /* 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.
   */
  if (G_UNLIKELY (clutter_pick_debug_flags & CLUTTER_DEBUG_DUMP_PICK_BUFFERS))
    {
      col->red   = (col->red << 4)   | (col->red >> 4);
      col->green = (col->green << 4) | (col->green >> 4);
      col->blue  = (col->blue << 4)  | (col->blue >> 4);
    }
}

guint
_clutter_pixel_to_id (guchar pixel[4])
{
  ClutterMainContext *ctx;
  gint red, green, blue;
  guint retval;

  ctx = _clutter_context_get_default ();

  /* reduce the pixel components to the number of bits actually used of the
   * 8bits.
   */
  if (G_UNLIKELY (clutter_pick_debug_flags & CLUTTER_DEBUG_DUMP_PICK_BUFFERS))
    {
      guchar tmp;

      /* 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.
       */
      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);
    }

  /* 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);
  blue  = blue  >> (ctx->fb_b_mask - ctx->fb_b_mask_used);

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

  return retval;
}

static CoglPangoFontMap *
clutter_context_get_pango_fontmap (void)
{
  ClutterMainContext *self;
  CoglPangoFontMap *font_map;
  gdouble resolution;
  gboolean use_mipmapping;

  self = _clutter_context_get_default ();
  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;
}

static ClutterTextDirection
clutter_get_text_direction (void)
{
  ClutterTextDirection dir = CLUTTER_TEXT_DIRECTION_LTR;
  const gchar *direction;

  direction = g_getenv ("CLUTTER_TEXT_DIRECTION");
  if (direction && *direction != '\0')
    {
      if (strcmp (direction, "rtl") == 0)
        dir = CLUTTER_TEXT_DIRECTION_RTL;
      else if (strcmp (direction, "ltr") == 0)
        dir = CLUTTER_TEXT_DIRECTION_LTR;
    }
  else
    {
      /* Translators: Leave this UNTRANSLATED if your language is
       * left-to-right.  If your language is right-to-left
       * (e.g. Hebrew, Arabic), translate it to "default:RTL".
       *
       * Do NOT translate it to non-English e.g. "predefinito:LTR"! If
       * it isn't default:LTR or default:RTL it will not work.
       */
      char *e = _("default:LTR");

      if (strcmp (e, "default:RTL") == 0)
        dir = CLUTTER_TEXT_DIRECTION_RTL;
      else if (strcmp (e, "default:LTR") == 0)
        dir = CLUTTER_TEXT_DIRECTION_LTR;
      else
        g_warning ("Whoever translated default:LTR did so wrongly.");
    }

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

  return dir;
}

/**
 * clutter_main_quit:
 *
 * Terminates the Clutter mainloop.
 */
void
clutter_main_quit (void)
{
  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);

  g_main_loop_quit (main_loops->data);
}

/**
 * clutter_main_level:
 *
 * Retrieves the depth of the Clutter mainloop.
 *
 * Return value: The level of the mainloop.
 */
gint
clutter_main_level (void)
{
  return clutter_main_loop_level;
}

/**
 * clutter_main:
 *
 * Starts the Clutter mainloop.
 */
void
clutter_main (void)
{
  GMainLoop *loop;

  if (!_clutter_context_is_initialized ())
    {
      g_warning ("Called clutter_main() but Clutter wasn't initialised. "
		 "You must call clutter_init() first.");
      return;
    }

  clutter_main_loop_level++;

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

  loop = g_main_loop_new (NULL, TRUE);
  main_loops = g_slist_prepend (main_loops, loop);

  if (g_main_loop_is_running (main_loops->data))
    {
      _clutter_threads_release_lock ();
      g_main_loop_run (loop);
      _clutter_threads_acquire_lock ();
    }

  main_loops = g_slist_remove (main_loops, loop);

  g_main_loop_unref (loop);

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

  clutter_main_loop_level--;
}

/**
 * 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().
 *
 * It is safe to call this function multiple times.
 *
 * Since: 0.4
 *
 * Deprecated: 1.10: This function does not do anything. Threading support
 *   is initialized when Clutter is initialized.
 */
void
clutter_threads_init (void)
{
}

/**
 * clutter_threads_set_lock_functions: (skip)
 * @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.
 *
 * This method must be called before clutter_init(), and cannot
 * be called multiple times.
 *
 * Since: 0.4
 */
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;
}

gboolean
_clutter_threads_dispatch (gpointer data)
{
  ClutterThreadsDispatch *dispatch = data;
  gboolean ret = FALSE;

  _clutter_threads_acquire_lock ();

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

  _clutter_threads_release_lock ();

  return ret;
}

void
_clutter_threads_dispatch_free (gpointer data)
{
  ClutterThreadsDispatch *dispatch = data;

  /* 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
   */
  if (dispatch->notify)
    dispatch->notify (dispatch->data);

  g_slice_free (ClutterThreadsDispatch, dispatch);
}

/**
 * clutter_threads_add_idle_full: (rename-to clutter_threads_add_idle)
 * @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
 * events pending. If the function returns %FALSE it is automatically
 * removed from the list of event sources and will not be called again.
 *
 * 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:
 *
 * |[
 * static gboolean
 * idle_safe_callback (gpointer data)
 * {
 *    SafeClosure *closure = data;
 *    gboolean res = FALSE;
 *
 *    // mark the critical section //
 *
 *    clutter_threads_enter();
 *
 *    // the callback does not need to acquire the Clutter
 *     / lock itself, as it is held by the this proxy handler
 *     //
 *    res = closure->callback (closure->data);
 *
 *    clutter_threads_leave();
 *
 *    return res;
 * }
 * static gulong
 * add_safe_idle (GSourceFunc callback,
 *                gpointer    data)
 * {
 *   SafeClosure *closure = g_new0 (SafeClosure, 1);
 *
 *   closure->callback = callback;
 *   closure->data = data;
 *
 *   return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE,
 *                           idle_safe_callback,
 *                           closure,
 *                           g_free)
 * }
 *]|
 *
 * 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)
 * {
 *   SomeClosure *closure = data;
 *
 *   // 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);
 *
 *   g_object_unref (closure->label);
 *   g_free (closure);
 *
 *   return FALSE;
 * }
 *
 *   // within another thread //
 *   closure = g_new0 (SomeClosure, 1);
 *   // 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);
 *
 *   clutter_threads_add_idle_full (G_PRIORITY_HIGH_IDLE,
 *                                  update_ui,
 *                                  closure,
 *                                  NULL);
 * ]|
 *
 * Return value: the ID (greater than 0) of the event source.
 *
 * Since: 0.4
 */
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,
                          _clutter_threads_dispatch, dispatch,
                          _clutter_threads_dispatch_free);
}

/**
 * clutter_threads_add_idle: (skip)
 * @func: function to call
 * @data: data to pass to the function
 *
 * Simple wrapper around clutter_threads_add_idle_full() using the
 * default priority.
 *
 * Return value: the ID (greater than 0) of the event source.
 *
 * Since: 0.4
 */
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);
}

/**
 * clutter_threads_add_timeout_full: (rename-to clutter_threads_add_timeout)
 * @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
 *
 * 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.
 *
 * The first call to the function will be at the end of the first @interval.
 *
 * 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
 * "keep up" with the interval.
 *
 * See also clutter_threads_add_idle_full().
 *
 * Return value: the ID (greater than 0) of the event source.
 *
 * Since: 0.4
 */
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,
                             _clutter_threads_dispatch, dispatch,
                             _clutter_threads_dispatch_free);
}

/**
 * clutter_threads_add_timeout: (skip)
 * @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.
 *
 * Since: 0.4
 */
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);
}

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) ();
}

/**
 * clutter_threads_enter:
 *
 * Locks the Clutter thread lock.
 *
 * Since: 0.4
 *
 * 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().
 */
void
clutter_threads_enter (void)
{
  _clutter_threads_acquire_lock ();
}

/**
 * clutter_threads_leave:
 *
 * Unlocks the Clutter thread lock.
 *
 * Since: 0.4
 *
 * 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().
 */
void
clutter_threads_leave (void)
{
  _clutter_threads_release_lock ();
}


/**
 * clutter_get_debug_enabled:
 *
 * Check if Clutter has debugging enabled.
 *
 * Return value: %FALSE
 *
 * Deprecated: 1.10: This function does not do anything.
 */
gboolean
clutter_get_debug_enabled (void)
{
  return FALSE;
}

void
_clutter_context_lock (void)
{
  G_LOCK (ClutterCntx);
}

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

gboolean
_clutter_context_is_initialized (void)
{
  if (ClutterCntx == NULL)
    return FALSE;

  return ClutterCntx->is_initialized;
}

static ClutterMainContext *
clutter_context_get_default_unlocked (void)
{
  if (G_UNLIKELY (ClutterCntx == NULL))
    {
      ClutterMainContext *ctx;

      /* 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 ();

      ClutterCntx = ctx = g_new0 (ClutterMainContext, 1);

      ctx->is_initialized = FALSE;

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

      /* 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);

      ctx->motion_events_per_actor = TRUE;
      ctx->last_repaint_id = 1;
    }

  return ClutterCntx;
}

ClutterMainContext *
_clutter_context_get_default (void)
{
  ClutterMainContext *retval;

  _clutter_context_lock ();

  retval = clutter_context_get_default_unlocked ();

  _clutter_context_unlock ();

  return retval;
}

/**
 * clutter_get_timestamp:
 *
 * Returns the approximate number of microseconds passed since Clutter was
 * intialised.
 *
 * 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
 */
gulong
clutter_get_timestamp (void)
{
#ifdef CLUTTER_ENABLE_DEBUG
  return (gulong) g_get_monotonic_time ();
#else
  return 0L;
#endif
}

static gboolean
clutter_arg_direction_cb (const char *key,
                          const char *value,
                          gpointer    user_data)
{
  clutter_text_direction =
    (strcmp (value, "rtl") == 0) ? CLUTTER_TEXT_DIRECTION_RTL
                                 : CLUTTER_TEXT_DIRECTION_LTR;

  return TRUE;
}

#ifdef CLUTTER_ENABLE_DEBUG
static gboolean
clutter_arg_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;
}

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 */

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;
  ClutterBackend *backend;

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

  if (!ctx->options_parsed)
    {
      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()");

      return CLUTTER_INIT_ERROR_INTERNAL;
    }

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

  /* 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;

  /* The same is true when drawing the outlines of paint volumes... */
  if (clutter_paint_debug_flags & CLUTTER_DEBUG_PAINT_VOLUMES)
    {
      clutter_paint_debug_flags |=
        CLUTTER_DEBUG_DISABLE_CLIPPED_REDRAWS | CLUTTER_DEBUG_DISABLE_CULLING;
    }

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

  clutter_text_direction = clutter_get_text_direction ();

  /* Initiate event collection */
  _clutter_backend_init_events (ctx->backend);

  clutter_is_initialized = TRUE;
  ctx->is_initialized = TRUE;

  /* Initialize a11y */
  if (clutter_enable_accessibility)
    cally_accessibility_init ();

  return CLUTTER_INIT_SUCCESS;
}

static GOptionEntry clutter_args[] = {
  { "clutter-show-fps", 0, 0, G_OPTION_ARG_NONE, &clutter_show_fps,
    N_("Show frames per second"), NULL },
  { "clutter-default-fps", 0, 0, G_OPTION_ARG_INT, &clutter_default_fps,
    N_("Default frame rate"), "FPS" },
  { "g-fatal-warnings", 0, 0, G_OPTION_ARG_NONE, &clutter_fatal_warnings,
    N_("Make all warnings fatal"), NULL },
  { "clutter-text-direction", 0, 0, G_OPTION_ARG_CALLBACK,
    clutter_arg_direction_cb,
    N_("Direction for the text"), "DIRECTION" },
  { "clutter-disable-mipmapped-text", 0, 0, G_OPTION_ARG_NONE,
    &clutter_disable_mipmap_text,
    N_("Disable mipmapping on text"), NULL },
  { "clutter-use-fuzzy-picking", 0, 0, G_OPTION_ARG_NONE,
    &clutter_use_fuzzy_picking,
    N_("Use 'fuzzy' picking"), NULL },
#ifdef CLUTTER_ENABLE_DEBUG
  { "clutter-debug", 0, 0, G_OPTION_ARG_CALLBACK, clutter_arg_debug_cb,
    N_("Clutter debugging flags to set"), "FLAGS" },
  { "clutter-no-debug", 0, 0, G_OPTION_ARG_CALLBACK, clutter_arg_no_debug_cb,
    N_("Clutter debugging flags to unset"), "FLAGS" },
#endif /* CLUTTER_ENABLE_DEBUG */
  { "clutter-enable-accessibility", 0, 0, G_OPTION_ARG_NONE, &clutter_enable_accessibility,
    N_("Enable accessibility"), NULL },
  { NULL, },
};

/* 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)
{
  ClutterMainContext *clutter_context;
  ClutterBackend *backend;
  const char *env_string;

  if (clutter_is_initialized)
    return TRUE;

  if (setlocale (LC_ALL, "") == NULL)
    g_warning ("Locale not supported by C library.\n"
               "Using the fallback 'C' locale.");

  clutter_context = _clutter_context_get_default ();

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

#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 */

  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;
    }

  env_string = g_getenv ("CLUTTER_SHOW_FPS");
  if (env_string)
    clutter_show_fps = TRUE;

  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);
    }

  env_string = g_getenv ("CLUTTER_DISABLE_MIPMAPPED_TEXT");
  if (env_string)
    clutter_disable_mipmap_text = TRUE;

  env_string = g_getenv ("CLUTTER_FUZZY_PICK");
  if (env_string)
    clutter_use_fuzzy_picking = TRUE;

  env_string = g_getenv ("CLUTTER_VBLANK");
  if (g_strcmp0 (env_string, "none") == 0)
    clutter_sync_to_vblank = FALSE;

  return _clutter_backend_pre_parse (backend, error);
}

/* 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;
  ClutterBackend *backend;

  if (clutter_is_initialized)
    return TRUE;

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

  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);
    }

  clutter_context->frame_rate = clutter_default_fps;
  clutter_context->show_fps = clutter_show_fps;
  clutter_context->options_parsed = TRUE;

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

  return TRUE;
}

/**
 * clutter_get_option_group: (skip)
 *
 * Returns a #GOptionGroup for the command line arguments recognized
 * by Clutter. You should add this group to your #GOptionContext with
 * g_option_context_add_group(), if you are using g_option_context_parse()
 * to parse your commandline arguments.
 *
 * Calling g_option_context_parse() with Clutter's #GOptionGroup will result
 * in Clutter's initialization. That is, the following code:
 *
 * |[
 *   g_option_context_set_main_group (context, clutter_get_option_group ());
 *   res = g_option_context_parse (context, &argc, &argc, NULL);
 * ]|
 *
 * is functionally equivalent to:
 *
 * |[
 *   clutter_init (&argc, &argv);
 * ]|
 *
 * After g_option_context_parse() on a #GOptionContext containing the
 * Clutter #GOptionGroup has returned %TRUE, Clutter is guaranteed to be
 * initialized.
 *
 * Return value: (transfer full): a #GOptionGroup for the commandline arguments
 *   recognized by Clutter
 *
 * Since: 0.2
 */
GOptionGroup *
clutter_get_option_group (void)
{
  ClutterMainContext *context;
  GOptionGroup *group;

  clutter_base_init ();

  context = _clutter_context_get_default ();

  group = g_option_group_new ("clutter",
                              _("Clutter Options"),
                              _("Show Clutter Options"),
                              NULL,
                              NULL);

  g_option_group_set_parse_hooks (group, pre_parse_hook, post_parse_hook);
  g_option_group_add_entries (group, clutter_args);
  g_option_group_set_translation_domain (group, GETTEXT_PACKAGE);

  /* add backend-specific options */
  _clutter_backend_add_options (context->backend, group);

  return group;
}

/**
 * clutter_get_option_group_without_init: (skip)
 *
 * Returns a #GOptionGroup for the command line arguments recognized
 * by Clutter. You should add this group to your #GOptionContext with
 * g_option_context_add_group(), if you are using g_option_context_parse()
 * to parse your commandline arguments.
 *
 * Unlike clutter_get_option_group(), calling g_option_context_parse() with
 * the #GOptionGroup returned by this function requires a subsequent explicit
 * call to clutter_init(); use this function when needing to set foreign
 * display connection with clutter_x11_set_display(), or with
 * `gtk_clutter_init()`.
 *
 * Return value: (transfer full): a #GOptionGroup for the commandline arguments
 *   recognized by Clutter
 *
 * Since: 0.8
 */
GOptionGroup *
clutter_get_option_group_without_init (void)
{
  ClutterMainContext *context;
  GOptionGroup *group;

  clutter_base_init ();

  context = _clutter_context_get_default ();
  context->defer_display_setup = TRUE;

  group = clutter_get_option_group ();

  return group;
}

/* Note that the gobject-introspection annotations for the argc/argv
 * parameters do not produce the right result; however, they do
 * allow the common case of argc=NULL, argv=NULL to work.
 */

/**
 * clutter_init_with_args:
 * @argc: (inout): a pointer to the number of command line arguments
 * @argv: (array length=argc) (inout) (allow-none): a pointer to the array
 *   of command line arguments
 * @parameter_string: (allow-none): a string which is displayed in the
 *   first line of <option>--help</option> output, after
 *   <literal><replaceable>programname</replaceable> [OPTION...]</literal>
 * @entries: (array) (allow-none): a %NULL terminated array of
 *   #GOptionEntry<!-- -->s describing the options of your program
 * @translation_domain: (allow-none): a translation domain to use for
 *   translating the <option>--help</option> output for the options in
 *   @entries with gettext(), or %NULL
 * @error: (allow-none): a return location for a #GError
 *
 * This function does the same work as clutter_init(). Additionally,
 * it allows you to add your own command line options, and it
 * automatically generates nicely formatted <option>--help</option>
 * output. Note that your program will be terminated after writing
 * out the help output. Also note that, in case of error, the
 * error message will be placed inside @error instead of being
 * printed on the display.
 *
 * Just like clutter_init(), if this function returns an error code then
 * any subsequent call to any other Clutter API will result in undefined
 * behaviour - including segmentation faults.
 *
 * Return value: %CLUTTER_INIT_SUCCESS if Clutter has been successfully
 *   initialised, or other values or #ClutterInitError in case of
 *   error.
 *
 * Since: 0.2
 */
ClutterInitError
clutter_init_with_args (int            *argc,
                        char         ***argv,
                        const char     *parameter_string,
                        GOptionEntry   *entries,
                        const char     *translation_domain,
                        GError        **error)
{
  GOptionContext *context;
  GOptionGroup *group;
  gboolean res;
  ClutterMainContext *ctx;

  if (clutter_is_initialized)
    return CLUTTER_INIT_SUCCESS;

  clutter_base_init ();

  ctx = _clutter_context_get_default ();

  if (!ctx->defer_display_setup)
    {
#if 0
      if (argc && *argc > 0 && *argv)
	g_set_prgname ((*argv)[0]);
#endif

      context = g_option_context_new (parameter_string);

      group = clutter_get_option_group ();
      g_option_context_add_group (context, group);

      group = cogl_get_option_group ();
      g_option_context_add_group (context, group);

      if (entries)
	g_option_context_add_main_entries (context, entries, translation_domain);

      res = g_option_context_parse (context, argc, argv, error);
      g_option_context_free (context);

      /* if res is FALSE, the error is filled for
       * us by g_option_context_parse()
       */
      if (!res)
	{
	  /* if there has been an error in the initialization, the
	   * error id will be preserved inside the GError code
	   */
	  if (error && *error)
	    return (*error)->code;
	  else
	    return CLUTTER_INIT_ERROR_INTERNAL;
	}

      return CLUTTER_INIT_SUCCESS;
    }
  else
    return clutter_init_real (error);
}

static gboolean
clutter_parse_args (int      *argc,
                    char   ***argv,
                    GError  **error)
{
  GOptionContext *option_context;
  GOptionGroup *clutter_group, *cogl_group;
  GError *internal_error = NULL;
  gboolean ret = TRUE;

  if (clutter_is_initialized)
    return TRUE;

  option_context = g_option_context_new (NULL);
  g_option_context_set_ignore_unknown_options (option_context, TRUE);
  g_option_context_set_help_enabled (option_context, FALSE);

  /* Initiate any command line options from the backend */
  clutter_group = clutter_get_option_group ();
  g_option_context_set_main_group (option_context, clutter_group);

  cogl_group = cogl_get_option_group ();
  g_option_context_add_group (option_context, cogl_group);

  if (!g_option_context_parse (option_context, argc, argv, &internal_error))
    {
      g_propagate_error (error, internal_error);
      ret = FALSE;
    }

  g_option_context_free (option_context);

  return ret;
}

/**
 * clutter_init:
 * @argc: (inout): The number of arguments in @argv
 * @argv: (array length=argc) (inout) (allow-none): A pointer to an array
 *   of arguments.
 *
 * Initialises everything needed to operate with Clutter and parses some
 * standard command line options; @argc and @argv are adjusted accordingly
 * so your own code will never see those standard arguments.
 *
 * It is safe to call this function multiple times.
 *
 * This function will not abort in case of errors during
 * initialization; clutter_init() will print out the error message on
 * stderr, and will return an error code. It is up to the application
 * code to handle this case. If you need to display the error message
 * yourself, you can use clutter_init_with_args(), which takes a #GError
 * pointer.
 *
 * If this function fails, and returns an error code, any subsequent
 * Clutter API will have undefined behaviour - including segmentation
 * faults and assertion failures. Make sure to handle the returned
 * #ClutterInitError enumeration value.
 *
 * Return value: a #ClutterInitError value
 */
ClutterInitError
clutter_init (int    *argc,
              char ***argv)
{
  ClutterMainContext *ctx;
  GError *error = NULL;
  ClutterInitError res;

  if (clutter_is_initialized)
    return CLUTTER_INIT_SUCCESS;

  clutter_base_init ();

  ctx = _clutter_context_get_default ();

  if (!ctx->defer_display_setup)
    {
#if 0
      if (argc && *argc > 0 && *argv)
	g_set_prgname ((*argv)[0]);
#endif

      /* parse_args will trigger backend creation and things like
       * DISPLAY connection etc.
       */
      if (!clutter_parse_args (argc, argv, &error))
	{
          g_critical ("Unable to initialize Clutter: %s", error->message);
          g_error_free (error);

          res = CLUTTER_INIT_ERROR_INTERNAL;
	}
      else
        res = CLUTTER_INIT_SUCCESS;
    }
  else
    {
      res = clutter_init_real (&error);
      if (error != NULL)
        {
          g_critical ("Unable to initialize Clutter: %s", error->message);
          g_error_free (error);
        }
    }

  return res;
}

gboolean
_clutter_boolean_handled_accumulator (GSignalInvocationHint *ihint,
                                      GValue                *return_accu,
                                      const GValue          *handler_return,
                                      gpointer               dummy)
{
  gboolean continue_emission;
  gboolean signal_handled;

  signal_handled = g_value_get_boolean (handler_return);
  g_value_set_boolean (return_accu, signal_handled);
  continue_emission = !signal_handled;

  return continue_emission;
}

gboolean
_clutter_boolean_continue_accumulator (GSignalInvocationHint *ihint,
                                       GValue                *return_accu,
                                       const GValue          *handler_return,
                                       gpointer               dummy)
{
  gboolean continue_emission;

  continue_emission = g_value_get_boolean (handler_return);
  g_value_set_boolean (return_accu, continue_emission);

  return continue_emission;
}

static void
event_click_count_generate (ClutterEvent *event)
{
  /* multiple button click detection */
  static gint    click_count            = 0;
  static gint    previous_x             = -1;
  static gint    previous_y             = -1;
  static guint32 previous_time          = 0;
  static gint    previous_button_number = -1;

  ClutterInputDevice *device = NULL;
  ClutterSettings *settings;
  guint double_click_time;
  guint double_click_distance;

  settings = clutter_settings_get_default ();

  g_object_get (settings,
                "double-click-distance", &double_click_distance,
                "double-click-time", &double_click_time,
                NULL);

  device = clutter_event_get_device (event);
  if (device != NULL)
    {
      click_count = device->click_count;
      previous_x = device->previous_x;
      previous_y = device->previous_y;
      previous_time = device->previous_time;
      previous_button_number = device->previous_button_number;

      CLUTTER_NOTE (EVENT,
                    "Restoring previous click count:%d (device:%d, time:%u)",
                    click_count,
                    clutter_input_device_get_device_id (device),
                    previous_time);
    }
  else
    {
      CLUTTER_NOTE (EVENT,
                    "Restoring previous click count:%d (time:%u)",
                    click_count,
                    previous_time);
    }

  switch (clutter_event_type (event))
    {
      case CLUTTER_BUTTON_PRESS:
        /* check if we are in time and within distance to increment an
         * existing click count
         */
        if (event->button.button == previous_button_number &&
            event->button.time < (previous_time + double_click_time) &&
            (ABS (event->button.x - previous_x) <= double_click_distance) &&
            (ABS (event->button.y - previous_y) <= double_click_distance))
          {
            CLUTTER_NOTE (EVENT, "Increase click count (button: %d, time: %u)",
                          event->button.button,
                          event->button.time);

            click_count += 1;
          }
        else /* start a new click count*/
          {
            CLUTTER_NOTE (EVENT, "Reset click count (button: %d, time: %u)",
                          event->button.button,
                          event->button.time);

            click_count = 1;
            previous_button_number = event->button.button;
          }

        previous_x = event->button.x;
        previous_y = event->button.y;
        previous_time = event->button.time;

        /* fallthrough */
      case CLUTTER_BUTTON_RELEASE:
        event->button.click_count = click_count;
        break;

      default:
        g_assert_not_reached ();
        break;
    }

  if (event->type == CLUTTER_BUTTON_PRESS && device != NULL)
    {
      CLUTTER_NOTE (EVENT, "Storing click count: %d (device:%d, time:%u)",
                    click_count,
                    clutter_input_device_get_device_id (device),
                    previous_time);

      device->click_count = click_count;
      device->previous_x = previous_x;
      device->previous_y = previous_y;
      device->previous_time = previous_time;
      device->previous_button_number = previous_button_number;
    }
}

static inline void
emit_event_chain (ClutterEvent *event)
{
  static gboolean lock = FALSE;

  if (event->any.source == NULL)
    {
      CLUTTER_NOTE (EVENT, "No source set, discarding event");
      return;
    }

  /* reentrancy check */
  if (lock != FALSE)
    {
      g_warning ("Tried emitting event during event delivery, bailing out.");
      return;
    }

  lock = TRUE;

  _clutter_actor_handle_event (event->any.source, event);

  lock = FALSE;
}

/*
 * Emits a pointer event after having prepared the event for delivery (setting
 * source, computing click_count, generating enter/leave etc.).
 */

static inline void
emit_pointer_event (ClutterEvent       *event,
                    ClutterInputDevice *device)
{
  ClutterMainContext *context = _clutter_context_get_default ();

  if (_clutter_event_process_filters (event))
    return;

  if (context->pointer_grab_actor == NULL &&
      (device == NULL || device->pointer_grab_actor == NULL))
    {
      /* no grab, time to capture and bubble */
      emit_event_chain (event);
    }
  else
    {
      if (context->pointer_grab_actor != NULL)
        {
          /* global grab */
          clutter_actor_event (context->pointer_grab_actor, event, FALSE);
        }
      else if (device != NULL && device->pointer_grab_actor != NULL)
        {
          /* per device grab */
          clutter_actor_event (device->pointer_grab_actor, event, FALSE);
        }
    }
}

static inline void
emit_touch_event (ClutterEvent       *event,
                  ClutterInputDevice *device)
{
  ClutterActor *grab_actor = NULL;

  if (_clutter_event_process_filters (event))
    return;

  if (device->sequence_grab_actors != NULL)
    {
      grab_actor = g_hash_table_lookup (device->sequence_grab_actors,
                                        event->touch.sequence);
    }

  if (grab_actor != NULL)
    {
      /* per-device sequence grab */
      clutter_actor_event (grab_actor, event, FALSE);
    }
  else
    {
      /* no grab, time to capture and bubble */
      emit_event_chain (event);
    }
}

static inline void
emit_keyboard_event (ClutterEvent       *event,
                     ClutterInputDevice *device)
{
  ClutterMainContext *context = _clutter_context_get_default ();

  if (_clutter_event_process_filters (event))
    return;

  if (context->keyboard_grab_actor == NULL &&
      (device == NULL || device->keyboard_grab_actor == NULL))
    {
      /* no grab, time to capture and bubble */
      emit_event_chain (event);
    }
  else
    {
      if (context->keyboard_grab_actor != NULL)
        {
          /* global key grab */
          clutter_actor_event (context->keyboard_grab_actor, event, FALSE);
        }
      else if (device != NULL && device->keyboard_grab_actor != NULL)
        {
          /* per-device key grab */
          clutter_actor_event (context->keyboard_grab_actor, event, FALSE);
        }
    }
}

static gboolean
is_off_stage (ClutterActor *stage,
              gfloat        x,
              gfloat        y)
{
  gfloat width, height;

  clutter_actor_get_size (stage, &width, &height);

  return (x < 0 ||
          y < 0 ||
          x >= width ||
          y >= height);
}

/**
 * clutter_do_event:
 * @event: a #ClutterEvent.
 *
 * Processes an event.
 *
 * The @event must be a valid #ClutterEvent and have a #ClutterStage
 * associated to it.
 *
 * This function is only useful when embedding Clutter inside another
 * toolkit, and it should never be called by applications.
 *
 * Since: 0.4
 */
void
clutter_do_event (ClutterEvent *event)
{
  /* we need the stage for the event */
  if (event->any.stage == NULL)
    {
      g_warning ("%s: Event does not have a stage: discarding.", G_STRFUNC);
      return;
    }

  /* stages in destruction do not process events */
  if (CLUTTER_ACTOR_IN_DESTRUCTION (event->any.stage))
    return;

  /* Instead of processing events when received, we queue them up to
   * handle per-frame before animations, layout, and drawing.
   *
   * This gives us the chance to reliably compress motion events
   * because we've "looked ahead" and know all motion events that
   * will occur before drawing the frame.
   */
  _clutter_stage_queue_event (event->any.stage, event, TRUE);
}

static void
_clutter_process_event_details (ClutterActor        *stage,
                                ClutterMainContext  *context,
                                ClutterEvent        *event)
{
  ClutterInputDevice *device = clutter_event_get_device (event);

  switch (event->type)
    {
      case CLUTTER_NOTHING:
        event->any.source = stage;
        break;

      case CLUTTER_KEY_PRESS:
      case CLUTTER_KEY_RELEASE:
        {
          ClutterActor *actor = NULL;

          /* check that we're not a synthetic event with source set */
          if (event->any.source == NULL)
            {
              actor = clutter_stage_get_key_focus (CLUTTER_STAGE (stage));
              event->any.source = actor;
              if (G_UNLIKELY (actor == NULL))
                {
                  g_warning ("No key focus set, discarding");
                  return;
                }
            }

          emit_keyboard_event (event, device);
        }
        break;

      case CLUTTER_ENTER:
        /* if we're entering from outside the stage we need
         * to check whether the pointer is actually on another
         * actor, and emit an additional pointer event
         */
        if (event->any.source == stage &&
            event->crossing.related == NULL)
          {
            ClutterActor *actor = NULL;

            emit_pointer_event (event, device);

            actor = _clutter_input_device_update (device, NULL, FALSE);
            if (actor != stage)
              {
                ClutterEvent *crossing;

                /* we emit the exact same event on the actor */
                crossing = clutter_event_copy (event);
                crossing->crossing.related = stage;
                crossing->crossing.source = actor;

                emit_pointer_event (crossing, device);
                clutter_event_free (crossing);
              }
          }
        else
          emit_pointer_event (event, device);
        break;

      case CLUTTER_LEAVE:
        /* same as CLUTTER_ENTER above: when leaving the stage
         * we need to also emit a CLUTTER_LEAVE event on the
         * actor currently underneath the device, unless it's the
         * stage
         */
        if (event->any.source == stage &&
            event->crossing.related == NULL &&
            device->cursor_actor != stage)
          {
            ClutterEvent *crossing;

            crossing = clutter_event_copy (event);
            crossing->crossing.related = stage;
            crossing->crossing.source = device->cursor_actor;

            emit_pointer_event (crossing, device);
            clutter_event_free (crossing);
          }
        emit_pointer_event (event, device);
        break;

      case CLUTTER_DESTROY_NOTIFY:
      case CLUTTER_DELETE:
        event->any.source = stage;

        if (_clutter_event_process_filters (event))
          break;

        /* the stage did not handle the event, so we just quit */
        clutter_stage_event (CLUTTER_STAGE (stage), event);
        break;

      case CLUTTER_MOTION:
        /* only the stage gets motion events if they are enabled */
        if (!clutter_stage_get_motion_events_enabled (CLUTTER_STAGE (stage)) &&
            event->any.source == NULL)
          {
            /* Only stage gets motion events */
            event->any.source = stage;

            if (_clutter_event_process_filters (event))
              break;

            /* global grabs */
            if (context->pointer_grab_actor != NULL)
              {
                clutter_actor_event (context->pointer_grab_actor,
                                     event,
                                     FALSE);
                break;
              }
            else if (device != NULL && device->pointer_grab_actor != NULL)
              {
                clutter_actor_event (device->pointer_grab_actor,
                                     event,
                                     FALSE);
                break;
              }

            /* Trigger handlers on stage in both capture .. */
            if (!clutter_actor_event (stage, event, TRUE))
              {
                /* and bubbling phase */
                clutter_actor_event (stage, event, FALSE);
              }
            break;
          }

      /* fallthrough from motion */
      case CLUTTER_BUTTON_PRESS:
      case CLUTTER_BUTTON_RELEASE:
      case CLUTTER_SCROLL:
      case CLUTTER_TOUCHPAD_PINCH:
      case CLUTTER_TOUCHPAD_SWIPE:
        {
          ClutterActor *actor;
          gfloat x, y;

          clutter_event_get_coords (event, &x, &y);

          /* Only do a pick to find the source if source is not already set
           * (as it could be in a synthetic event)
           */
          if (event->any.source == NULL)
            {
              /* emulate X11 the implicit soft grab; the implicit soft grab
               * keeps relaying motion events when the stage is left with a
               * pointer button pressed. since this is what happens when we
               * disable per-actor motion events we need to maintain the same
               * behaviour when the per-actor motion events are enabled as
               * well
               */
              if (is_off_stage (stage, x, y))
                {
                  if (event->type == CLUTTER_BUTTON_RELEASE)
                    {
                      CLUTTER_NOTE (EVENT,
                                    "Release off stage received at %.2f, %.2f",
                                    x, y);

                      event->button.source = stage;
                      event->button.click_count = 1;

                      emit_pointer_event (event, device);
                    }
                  else if (event->type == CLUTTER_MOTION)
                    {
                      CLUTTER_NOTE (EVENT,
                                    "Motion off stage received at %.2f, %2.f",
                                    x, y);

                      event->motion.source = stage;

                      emit_pointer_event (event, device);
                    }

                  break;
                }

              /* if the backend provides a device then we should
               * already have everything we need to update it and
               * get the actor underneath
               */
              if (device != NULL)
                actor = _clutter_input_device_update (device, NULL, TRUE);
              else
                {
                  CLUTTER_NOTE (EVENT, "No device found: picking");

                  actor = _clutter_stage_do_pick (CLUTTER_STAGE (stage),
                                                  x, y,
                                                  CLUTTER_PICK_REACTIVE);
                }

              if (actor == NULL)
                break;

              event->any.source = actor;
            }
          else
            {
              /* use the source already set in the synthetic event */
              actor = event->any.source;
            }

          CLUTTER_NOTE (EVENT,
                        "Reactive event received at %.2f, %.2f - actor: %p",
                        x, y,
                        actor);

          /* button presses and releases need a click count */
          if (event->type == CLUTTER_BUTTON_PRESS ||
              event->type == CLUTTER_BUTTON_RELEASE)
            {
              /* Generate click count */
              event_click_count_generate (event);
            }

          emit_pointer_event (event, device);
          break;
        }

      case CLUTTER_TOUCH_UPDATE:
        /* only the stage gets motion events if they are enabled */
        if (!clutter_stage_get_motion_events_enabled (CLUTTER_STAGE (stage)) &&
            event->any.source == NULL)
          {
            ClutterActor *grab_actor = NULL;

            /* Only stage gets motion events */
            event->any.source = stage;

            if (_clutter_event_process_filters (event))
              break;

            /* global grabs */
            if (device->sequence_grab_actors != NULL)
              {
                grab_actor = g_hash_table_lookup (device->sequence_grab_actors,
                                                  event->touch.sequence);
              }

            if (grab_actor != NULL)
              {
                clutter_actor_event (grab_actor, event, FALSE);
                break;
              }

            /* Trigger handlers on stage in both capture .. */
            if (!clutter_actor_event (stage, event, TRUE))
              {
                /* and bubbling phase */
                clutter_actor_event (stage, event, FALSE);
              }
            break;
          }

      /* fallthrough from motion */
      case CLUTTER_TOUCH_BEGIN:
      case CLUTTER_TOUCH_CANCEL:
      case CLUTTER_TOUCH_END:
        {
          ClutterActor *actor;
          ClutterEventSequence *sequence;
          gfloat x, y;

          sequence =
            clutter_event_get_event_sequence (event);

          if (event->type == CLUTTER_TOUCH_BEGIN)
            _clutter_input_device_add_event_sequence (device, event);

          clutter_event_get_coords (event, &x, &y);

          /* Only do a pick to find the source if source is not already set
           * (as it could be in a synthetic event)
           */
          if (event->any.source == NULL)
            {
              /* same as the mouse events above, emulate the X11 implicit
               * soft grab */
              if (is_off_stage (stage, x, y))
                {
                  CLUTTER_NOTE (EVENT,
                                "Touch %s off stage received at %.2f, %.2f",
                                event->type == CLUTTER_TOUCH_UPDATE ? "update" :
                                event->type == CLUTTER_TOUCH_END ? "end" :
                                event->type == CLUTTER_TOUCH_CANCEL ? "cancel" :
                                "?", x, y);

                  event->touch.source = stage;

                  emit_touch_event (event, device);

                  if (event->type == CLUTTER_TOUCH_END)
                    _clutter_input_device_remove_event_sequence (device, event);

                  break;
                }

              if (device != NULL)
                actor = _clutter_input_device_update (device, sequence, TRUE);
              else
                {
                  CLUTTER_NOTE (EVENT, "No device found: picking");

                  actor = _clutter_stage_do_pick (CLUTTER_STAGE (stage),
                                                  x, y,
                                                  CLUTTER_PICK_REACTIVE);
                }

              if (actor == NULL)
                break;

              event->any.source = actor;
            }
          else
            {
              /* use the source already set in the synthetic event */
              actor = event->any.source;
            }

          CLUTTER_NOTE (EVENT,
                        "Reactive event received at %.2f, %.2f - actor: %p",
                        x, y,
                        actor);

          emit_touch_event (event, device);

          if (event->type == CLUTTER_TOUCH_END)
            _clutter_input_device_remove_event_sequence (device, event);

          break;
        }

      case CLUTTER_STAGE_STATE:
        /* fullscreen / focus - forward to stage */
        event->any.source = stage;
        if (!_clutter_event_process_filters (event))
          clutter_stage_event (CLUTTER_STAGE (stage), event);
        break;

      case CLUTTER_CLIENT_MESSAGE:
        break;

      case CLUTTER_EVENT_LAST:
        break;
    }
}

/*
 * _clutter_process_event
 * @event: a #ClutterEvent.
 *
 * Does the actual work of processing an event that was queued earlier
 * out of clutter_do_event().
 */
void
_clutter_process_event (ClutterEvent *event)
{
  ClutterMainContext *context;
  ClutterActor *stage;

  context = _clutter_context_get_default ();

  stage = CLUTTER_ACTOR (event->any.stage);
  if (stage == NULL)
    {
      CLUTTER_NOTE (EVENT, "Discarding event without a stage set");
      return;
    }

  /* push events on a stack, so that we don't need to
   * add an event parameter to all signals that can be emitted within
   * an event chain
   */
  context->current_event = g_slist_prepend (context->current_event, event);

  _clutter_process_event_details (stage, context, event);

  context->current_event = g_slist_delete_link (context->current_event, context->current_event);
}

/**
 * clutter_get_actor_by_gid:
 * @id_: a #ClutterActor unique id.
 *
 * Retrieves the #ClutterActor with @id_.
 *
 * Return value: (transfer none): the actor with the passed id or %NULL.
 *   The returned actor does not have its reference count increased.
 *
 * Since: 0.6
 *
 * Deprecated: 1.8: The id is deprecated, and this function always returns
 *   %NULL. Use the proper scene graph API in #ClutterActor to find a child
 *   of the stage.
 */
ClutterActor *
clutter_get_actor_by_gid (guint32 id_)
{
  return NULL;
}

void
clutter_base_init (void)
{
  static gboolean initialised = FALSE;

  if (!initialised)
    {
      initialised = TRUE;

      bindtextdomain (GETTEXT_PACKAGE, CLUTTER_LOCALEDIR);
      bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");

#if !GLIB_CHECK_VERSION (2, 35, 1)
      /* initialise GLib type system */
      g_type_init ();
#endif

      /* initialise the Big Clutter Lockā„¢ if necessary */
      clutter_threads_init_default ();
    }
}

/**
 * clutter_get_default_frame_rate:
 *
 * Retrieves the default frame rate. See clutter_set_default_frame_rate().
 *
 * Return value: the default frame rate
 *
 * Since: 0.6
 */
guint
clutter_get_default_frame_rate (void)
{
  ClutterMainContext *context;

  context = _clutter_context_get_default ();

  return context->frame_rate;
}

/**
 * clutter_set_default_frame_rate:
 * @frames_per_sec: the new default frame rate
 *
 * Sets the default frame rate. This frame rate will be used to limit
 * the number of frames drawn if Clutter is not able to synchronize
 * with the vertical refresh rate of the display. When synchronization
 * is possible, this value is ignored.
 *
 * Since: 0.6
 *
 * Deprecated: 1.10: This function does not do anything any more.
 */
void
clutter_set_default_frame_rate (guint frames_per_sec)
{
}

static void
on_grab_actor_destroy (ClutterActor       *actor,
                       ClutterInputDevice *device)
{
  if (device == NULL)
    {
      ClutterMainContext *context = _clutter_context_get_default ();

      if (context->pointer_grab_actor == actor)
        clutter_ungrab_pointer ();

      if (context->keyboard_grab_actor == actor)
        clutter_ungrab_keyboard ();

      return;
    }

  switch (device->device_type)
    {
    case CLUTTER_POINTER_DEVICE:
      device->pointer_grab_actor = NULL;
      break;

    case CLUTTER_KEYBOARD_DEVICE:
      device->keyboard_grab_actor = NULL;
      break;

    default:
      g_assert_not_reached ();
    }
}

/**
 * clutter_grab_pointer:
 * @actor: a #ClutterActor
 *
 * Grabs pointer events, after the grab is done all pointer related events
 * (press, motion, release, enter, leave and scroll) are delivered to this
 * actor directly without passing through both capture and bubble phases of
 * the event delivery chain. The source set in the event will be the actor
 * that would have received the event if the pointer grab was not in effect.
 *
 * Grabs completely override the entire event delivery chain
 * done by Clutter. Pointer grabs should only be used as a last resource;
 * using the #ClutterActor::captured-event signal should always be the
 * preferred way to intercept event delivery to reactive actors.
 *
 * This function should rarely be used.
 *
 * If a grab is required, you are strongly encouraged to use a specific
 * input device by calling clutter_input_device_grab().
 *
 * Since: 0.6
 */
void
clutter_grab_pointer (ClutterActor *actor)
{
  ClutterMainContext *context;

  g_return_if_fail (actor == NULL || CLUTTER_IS_ACTOR (actor));

  context = _clutter_context_get_default ();

  if (context->pointer_grab_actor == actor)
    return;

  if (context->pointer_grab_actor != NULL)
    {
      g_signal_handlers_disconnect_by_func (context->pointer_grab_actor,
                                            G_CALLBACK (on_grab_actor_destroy),
                                            NULL);
      context->pointer_grab_actor = NULL;
    }

  if (actor != NULL)
    {
      context->pointer_grab_actor = actor;

      g_signal_connect (context->pointer_grab_actor, "destroy",
                        G_CALLBACK (on_grab_actor_destroy),
                        NULL);
    }
}

/**
 * clutter_input_device_grab:
 * @device: a #ClutterInputDevice
 * @actor: a #ClutterActor
 *
 * Acquires a grab on @actor for the given @device.
 *
 * Any event coming from @device will be delivered to @actor, bypassing
 * the usual event delivery mechanism, until the grab is released by
 * calling clutter_input_device_ungrab().
 *
 * The grab is client-side: even if the windowing system used by the Clutter
 * backend has the concept of "device grabs", Clutter will not use them.
 *
 * Only #ClutterInputDevice of types %CLUTTER_POINTER_DEVICE and
 * %CLUTTER_KEYBOARD_DEVICE can hold a grab.
 *
 * Since: 1.10
 */
void
clutter_input_device_grab (ClutterInputDevice *device,
                           ClutterActor       *actor)
{
  ClutterActor **grab_actor;

  g_return_if_fail (CLUTTER_IS_INPUT_DEVICE (device));
  g_return_if_fail (CLUTTER_IS_ACTOR (actor));

  switch (device->device_type)
    {
    case CLUTTER_POINTER_DEVICE:
      grab_actor = &(device->pointer_grab_actor);
      break;

    case CLUTTER_KEYBOARD_DEVICE:
      grab_actor = &(device->keyboard_grab_actor);
      break;

    default:
      g_critical ("Only pointer and keyboard devices can grab an actor");
      return;
    }

  if (*grab_actor != NULL)
    {
      g_signal_handlers_disconnect_by_func (*grab_actor,
                                            G_CALLBACK (on_grab_actor_destroy),
                                            device);
    }

  *grab_actor = actor;

  g_signal_connect (*grab_actor,
                    "destroy",
                    G_CALLBACK (on_grab_actor_destroy),
                    device);
}

/**
 * clutter_input_device_ungrab:
 * @device: a #ClutterInputDevice
 *
 * Releases the grab on the @device, if one is in place.
 *
 * Since: 1.10
 */
void
clutter_input_device_ungrab (ClutterInputDevice *device)
{
  ClutterActor **grab_actor;

  g_return_if_fail (CLUTTER_IS_INPUT_DEVICE (device));

  switch (device->device_type)
    {
    case CLUTTER_POINTER_DEVICE:
      grab_actor = &(device->pointer_grab_actor);
      break;

    case CLUTTER_KEYBOARD_DEVICE:
      grab_actor = &(device->keyboard_grab_actor);
      break;

    default:
      return;
    }

  if (*grab_actor == NULL)
    return;

  g_signal_handlers_disconnect_by_func (*grab_actor,
                                        G_CALLBACK (on_grab_actor_destroy),
                                        device);

  *grab_actor = NULL;
}

/**
 * clutter_input_device_get_grabbed_actor:
 * @device: a #ClutterInputDevice
 *
 * Retrieves a pointer to the #ClutterActor currently grabbing all
 * the events coming from @device.
 *
 * Return value: (transfer none): a #ClutterActor, or %NULL
 *
 * Since: 1.10
 */
ClutterActor *
clutter_input_device_get_grabbed_actor (ClutterInputDevice *device)
{
  g_return_val_if_fail (CLUTTER_IS_INPUT_DEVICE (device), NULL);

  switch (device->device_type)
    {
    case CLUTTER_POINTER_DEVICE:
      return device->pointer_grab_actor;

    case CLUTTER_KEYBOARD_DEVICE:
      return device->keyboard_grab_actor;

    default:
      g_critical ("Only pointer and keyboard devices can grab an actor");
    }

  return NULL;
}

/**
 * clutter_grab_pointer_for_device:
 * @actor: a #ClutterActor
 * @id_: a device id, or -1
 *
 * Grabs all the pointer events coming from the device @id for @actor.
 *
 * If @id is -1 then this function is equivalent to clutter_grab_pointer().
 *
 * Since: 0.8
 *
 * Deprecated: 1.10: Use clutter_input_device_grab() instead.
 */
void
clutter_grab_pointer_for_device (ClutterActor *actor,
                                 gint          id_)
{
  ClutterDeviceManager *manager;
  ClutterInputDevice *dev;

  g_return_if_fail (actor == NULL || CLUTTER_IS_ACTOR (actor));

  /* essentially a global grab */
  if (id_ == -1)
    {
      if (actor == NULL)
        clutter_ungrab_pointer ();
      else
        clutter_grab_pointer (actor);

      return;
    }

  manager = clutter_device_manager_get_default ();
  if (manager == NULL)
    return;

  dev = clutter_device_manager_get_device (manager, id_);
  if (dev == NULL)
    return;

  if (dev->device_type != CLUTTER_POINTER_DEVICE)
    return;

  if (actor == NULL)
    clutter_input_device_ungrab (dev);
  else
    clutter_input_device_grab (dev, actor);
}


/**
 * clutter_ungrab_pointer:
 *
 * Removes an existing grab of the pointer.
 *
 * Since: 0.6
 */
void
clutter_ungrab_pointer (void)
{
  clutter_grab_pointer (NULL);
}

/**
 * clutter_ungrab_pointer_for_device:
 * @id_: a device id
 *
 * Removes an existing grab of the pointer events for device @id_.
 *
 * Since: 0.8
 *
 * Deprecated: 1.10: Use clutter_input_device_ungrab() instead.
 */
void
clutter_ungrab_pointer_for_device (gint id_)
{
  ClutterDeviceManager *manager;
  ClutterInputDevice *device;

  manager = clutter_device_manager_get_default ();
  if (manager == NULL)
    return;

  device = clutter_device_manager_get_device (manager, id_);
  if (device != NULL)
    clutter_input_device_ungrab (device);
}


/**
 * clutter_get_pointer_grab:
 *
 * Queries the current pointer grab of clutter.
 *
 * Return value: (transfer none): the actor currently holding the pointer grab, or NULL if there is no grab.
 *
 * Since: 0.6
 */
ClutterActor *
clutter_get_pointer_grab (void)
{
  ClutterMainContext *context;
  context = _clutter_context_get_default ();

  return context->pointer_grab_actor;
}


/**
 * clutter_grab_keyboard:
 * @actor: a #ClutterActor
 *
 * Grabs keyboard events, after the grab is done keyboard
 * events (#ClutterActor::key-press-event and #ClutterActor::key-release-event)
 * are delivered to this actor directly. The source set in the event will be
 * the actor that would have received the event if the keyboard grab was not
 * in effect.
 *
 * Like pointer grabs, keyboard grabs should only be used as a last
 * resource.
 *
 * See also clutter_stage_set_key_focus() and clutter_actor_grab_key_focus()
 * to perform a "soft" key grab and assign key focus to a specific actor.
 *
 * Since: 0.6
 */
void
clutter_grab_keyboard (ClutterActor *actor)
{
  ClutterMainContext *context;

  g_return_if_fail (actor == NULL || CLUTTER_IS_ACTOR (actor));

  context = _clutter_context_get_default ();

  if (context->keyboard_grab_actor == actor)
    return;

  if (context->keyboard_grab_actor != NULL)
    {
      g_signal_handlers_disconnect_by_func (context->keyboard_grab_actor,
                                            G_CALLBACK (on_grab_actor_destroy),
                                            NULL);
      context->keyboard_grab_actor = NULL;
    }

  if (actor != NULL)
    {
      context->keyboard_grab_actor = actor;

      g_signal_connect (context->keyboard_grab_actor, "destroy",
                        G_CALLBACK (on_grab_actor_destroy),
                        NULL);
    }
}

/**
 * clutter_ungrab_keyboard:
 *
 * Removes an existing grab of the keyboard.
 *
 * Since: 0.6
 */
void
clutter_ungrab_keyboard (void)
{
  clutter_grab_keyboard (NULL);
}

/**
 * clutter_get_keyboard_grab:
 *
 * Queries the current keyboard grab of clutter.
 *
 * Return value: (transfer none): the actor currently holding the keyboard grab, or NULL if there is no grab.
 *
 * Since: 0.6
 */
ClutterActor *
clutter_get_keyboard_grab (void)
{
  ClutterMainContext *context;

  context = _clutter_context_get_default ();

  return context->keyboard_grab_actor;
}

/**
 * clutter_clear_glyph_cache:
 *
 * Clears the internal cache of glyphs used by the Pango
 * renderer. This will free up some memory and GL texture
 * resources. The cache will be automatically refilled as more text is
 * drawn.
 *
 * Since: 0.8
 *
 * Deprecated: 1.10: Use clutter_get_font_map() and
 *   cogl_pango_font_map_clear_glyph_cache() instead.
 */
void
clutter_clear_glyph_cache (void)
{
  CoglPangoFontMap *font_map;

  font_map = clutter_context_get_pango_fontmap ();
  cogl_pango_font_map_clear_glyph_cache (font_map);
}

/**
 * clutter_set_font_flags:
 * @flags: The new flags
 *
 * Sets the font quality options for subsequent text rendering
 * operations.
 *
 * Using mipmapped textures will improve the quality for scaled down
 * text but will use more texture memory.
 *
 * Enabling hinting improves text quality for static text but may
 * introduce some artifacts if the text is animated.
 *
 * Since: 1.0
 *
 * Deprecated: 1.10: Use clutter_backend_set_font_options() and the
 *   #cairo_font_option_t API.
 */
void
clutter_set_font_flags (ClutterFontFlags flags)
{
  CoglPangoFontMap *font_map;
  ClutterFontFlags old_flags, changed_flags;
  const cairo_font_options_t *font_options;
  cairo_font_options_t *new_font_options;
  cairo_hint_style_t hint_style;
  gboolean use_mipmapping;
  ClutterBackend *backend;

  backend = clutter_get_default_backend ();
  font_map = clutter_context_get_pango_fontmap ();
  font_options = clutter_backend_get_font_options (backend);
  old_flags = 0;

  if (cogl_pango_font_map_get_use_mipmapping (font_map))
    old_flags |= CLUTTER_FONT_MIPMAPPING;

  hint_style = cairo_font_options_get_hint_style (font_options);
  if (hint_style != CAIRO_HINT_STYLE_DEFAULT &&
      hint_style != CAIRO_HINT_STYLE_NONE)
    old_flags |= CLUTTER_FONT_HINTING;

  if (old_flags == flags)
    return;

  new_font_options = cairo_font_options_copy (font_options);

  /* Only set the font options that have actually changed so we don't
     override a detailed setting from the backend */
  changed_flags = old_flags ^ flags;

  if ((changed_flags & CLUTTER_FONT_MIPMAPPING))
    {
      use_mipmapping = (changed_flags & CLUTTER_FONT_MIPMAPPING) != 0;

      cogl_pango_font_map_set_use_mipmapping (font_map, use_mipmapping);
    }

  if ((changed_flags & CLUTTER_FONT_HINTING))
    {
      hint_style = (flags & CLUTTER_FONT_HINTING)
                 ? CAIRO_HINT_STYLE_FULL
                 : CAIRO_HINT_STYLE_NONE;

      cairo_font_options_set_hint_style (new_font_options, hint_style);
    }

  clutter_backend_set_font_options (backend, new_font_options);

  cairo_font_options_destroy (new_font_options);
}

/**
 * clutter_get_font_flags:
 *
 * Gets the current font flags for rendering text. See
 * clutter_set_font_flags().
 *
 * Return value: The font flags
 *
 * Since: 1.0
 *
 * Deprecated: 1.10: Use clutter_backend_get_font_options() and the
 *   #cairo_font_options_t API.
 */
ClutterFontFlags
clutter_get_font_flags (void)
{
  CoglPangoFontMap *font_map = NULL;
  const cairo_font_options_t *font_options;
  ClutterFontFlags flags = 0;
  cairo_hint_style_t hint_style;

  font_map = clutter_context_get_pango_fontmap ();
  if (cogl_pango_font_map_get_use_mipmapping (font_map))
    flags |= CLUTTER_FONT_MIPMAPPING;

  font_options =
    clutter_backend_get_font_options (clutter_get_default_backend ());

  hint_style = cairo_font_options_get_hint_style (font_options);
  if (hint_style != CAIRO_HINT_STYLE_DEFAULT &&
      hint_style != CAIRO_HINT_STYLE_NONE)
    flags |= CLUTTER_FONT_HINTING;

  return flags;
}

/**
 * clutter_get_input_device_for_id:
 * @id_: the unique id for a device
 *
 * Retrieves the #ClutterInputDevice from its @id_. This is a convenience
 * wrapper for clutter_device_manager_get_device() and it is functionally
 * equivalent to:
 *
 * |[
 *   ClutterDeviceManager *manager;
 *   ClutterInputDevice *device;
 *
 *   manager = clutter_device_manager_get_default ();
 *   device = clutter_device_manager_get_device (manager, id);
 * ]|
 *
 * Return value: (transfer none): a #ClutterInputDevice, or %NULL
 *
 * Since: 0.8
 *
 * Deprecated: 1.10: Use clutter_device_manager_get_device() instead.
 */
ClutterInputDevice *
clutter_get_input_device_for_id (gint id_)
{
  ClutterDeviceManager *manager;

  manager = clutter_device_manager_get_default ();
  if (manager == NULL)
    return NULL;

  return clutter_device_manager_get_device (manager, id_);
}

/**
 * clutter_get_font_map:
 *
 * Retrieves the #PangoFontMap instance used by Clutter.
 * You can use the global font map object with the COGL
 * Pango API.
 *
 * Return value: (transfer none): the #PangoFontMap instance. The returned
 *   value is owned by Clutter and it should never be unreferenced.
 *
 * Since: 1.0
 */
PangoFontMap *
clutter_get_font_map (void)
{
  return PANGO_FONT_MAP (clutter_context_get_pango_fontmap ());
}

typedef struct _ClutterRepaintFunction
{
  guint id;
  ClutterRepaintFlags flags;
  GSourceFunc func;
  gpointer data;
  GDestroyNotify notify;
} ClutterRepaintFunction;

/**
 * clutter_threads_remove_repaint_func:
 * @handle_id: an unsigned integer greater than zero
 *
 * Removes the repaint function with @handle_id as its id
 *
 * Since: 1.0
 */
void
clutter_threads_remove_repaint_func (guint handle_id)
{
  ClutterRepaintFunction *repaint_func;
  ClutterMainContext *context;
  GList *l;

  g_return_if_fail (handle_id > 0);

  _clutter_context_lock ();

  context = clutter_context_get_default_unlocked ();
  l = context->repaint_funcs;
  while (l != NULL)
    {
      repaint_func = l->data;

      if (repaint_func->id == handle_id)
        {
          context->repaint_funcs =
            g_list_remove_link (context->repaint_funcs, l);

          g_list_free (l);

          if (repaint_func->notify)
            repaint_func->notify (repaint_func->data);

          g_slice_free (ClutterRepaintFunction, repaint_func);

          break;
        }

      l = l->next;
    }

  _clutter_context_unlock ();
}

/**
 * clutter_threads_add_repaint_func:
 * @func: the function to be called within the paint cycle
 * @data: data to be passed to the function, or %NULL
 * @notify: function to be called when removing the repaint
 *    function, or %NULL
 *
 * Adds a function to be called whenever Clutter is processing a new
 * frame.
 *
 * If the function returns %FALSE it is automatically removed from the
 * list of repaint functions and will not be called again.
 *
 * This function is guaranteed to be called from within the same thread
 * that called clutter_main(), and while the Clutter lock is being held;
 * the function will be called within the main loop, so it is imperative
 * that it does not block, otherwise the frame time budget may be lost.
 *
 * A repaint function is useful to ensure that an update of the scenegraph
 * is performed before the scenegraph is repainted; for instance, uploading
 * a frame from a video into a #ClutterTexture. By default, a repaint
 * function added using this function will be invoked prior to the frame
 * being processed.
 *
 * Adding a repaint function does not automatically ensure that a new
 * frame will be queued.
 *
 * When the repaint function is removed (either because it returned %FALSE
 * or because clutter_threads_remove_repaint_func() has been called) the
 * @notify function will be called, if any is set.
 *
 * See also: clutter_threads_add_repaint_func_full()
 *
 * Return value: the ID (greater than 0) of the repaint function. You
 *   can use the returned integer to remove the repaint function by
 *   calling clutter_threads_remove_repaint_func().
 *
 * Since: 1.0
 */
guint
clutter_threads_add_repaint_func (GSourceFunc    func,
                                  gpointer       data,
                                  GDestroyNotify notify)
{
  return clutter_threads_add_repaint_func_full (CLUTTER_REPAINT_FLAGS_PRE_PAINT,
                                                func,
                                                data, notify);
}

/**
 * clutter_threads_add_repaint_func_full:
 * @flags: flags for the repaint function
 * @func: the function to be called within the paint cycle
 * @data: data to be passed to the function, or %NULL
 * @notify: function to be called when removing the repaint
 *    function, or %NULL
 *
 * Adds a function to be called whenever Clutter is processing a new
 * frame.
 *
 * If the function returns %FALSE it is automatically removed from the
 * list of repaint functions and will not be called again.
 *
 * This function is guaranteed to be called from within the same thread
 * that called clutter_main(), and while the Clutter lock is being held;
 * the function will be called within the main loop, so it is imperative
 * that it does not block, otherwise the frame time budget may be lost.
 *
 * A repaint function is useful to ensure that an update of the scenegraph
 * is performed before the scenegraph is repainted; for instance, uploading
 * a frame from a video into a #ClutterTexture. The @flags passed to this
 * function will determine the section of the frame processing that will
 * result in @func being called.
 *
 * Adding a repaint function does not automatically ensure that a new
 * frame will be queued.
 *
 * When the repaint function is removed (either because it returned %FALSE
 * or because clutter_threads_remove_repaint_func() has been called) the
 * @notify function will be called, if any is set.
 *
 * Return value: the ID (greater than 0) of the repaint function. You
 *   can use the returned integer to remove the repaint function by
 *   calling clutter_threads_remove_repaint_func().
 *
 * Since: 1.10
 */
guint
clutter_threads_add_repaint_func_full (ClutterRepaintFlags flags,
                                       GSourceFunc         func,
                                       gpointer            data,
                                       GDestroyNotify      notify)
{
  ClutterMainContext *context;
  ClutterRepaintFunction *repaint_func;

  g_return_val_if_fail (func != NULL, 0);

  _clutter_context_lock ();

  context = clutter_context_get_default_unlocked ();

  repaint_func = g_slice_new (ClutterRepaintFunction);

  repaint_func->id = context->last_repaint_id++;

  /* mask out QUEUE_REDRAW_ON_ADD, since we're going to consume it */
  repaint_func->flags = flags & ~CLUTTER_REPAINT_FLAGS_QUEUE_REDRAW_ON_ADD;
  repaint_func->func = func;
  repaint_func->data = data;
  repaint_func->notify = notify;

  context->repaint_funcs = g_list_prepend (context->repaint_funcs,
                                           repaint_func);

  _clutter_context_unlock ();

  if ((flags & CLUTTER_REPAINT_FLAGS_QUEUE_REDRAW_ON_ADD) != 0)
    {
      ClutterMasterClock *master_clock = _clutter_master_clock_get_default ();

      _clutter_master_clock_ensure_next_iteration (master_clock);
    }

  return repaint_func->id;
}

/*
 * _clutter_run_repaint_functions:
 * @flags: only run the repaint functions matching the passed flags
 *
 * Executes the repaint functions added using the
 * clutter_threads_add_repaint_func() function.
 *
 * Must be called with the Clutter thread lock held.
 */
void
_clutter_run_repaint_functions (ClutterRepaintFlags flags)
{
  ClutterMainContext *context = _clutter_context_get_default ();
  ClutterRepaintFunction *repaint_func;
  GList *invoke_list, *reinvoke_list, *l;

  if (context->repaint_funcs == NULL)
    return;

  /* steal the list */
  invoke_list = context->repaint_funcs;
  context->repaint_funcs = NULL;

  reinvoke_list = NULL;

  /* consume the whole list while we execute the functions */
  while (invoke_list != NULL)
    {
      gboolean res = FALSE;

      repaint_func = invoke_list->data;

      l = invoke_list;
      invoke_list = g_list_remove_link (invoke_list, invoke_list);

      g_list_free (l);

      if ((repaint_func->flags & flags) != 0)
        res = repaint_func->func (repaint_func->data);
      else
        res = TRUE;

      if (res)
        reinvoke_list = g_list_prepend (reinvoke_list, repaint_func);
      else
        {
          if (repaint_func->notify != NULL)
            repaint_func->notify (repaint_func->data);

          g_slice_free (ClutterRepaintFunction, repaint_func);
        }
    }

  if (context->repaint_funcs != NULL)
    {
      context->repaint_funcs = g_list_concat (context->repaint_funcs,
                                              g_list_reverse (reinvoke_list));
    }
  else
    context->repaint_funcs = g_list_reverse (reinvoke_list);
}

/**
 * clutter_check_version:
 * @major: major version, like 1 in 1.2.3
 * @minor: minor version, like 2 in 1.2.3
 * @micro: micro version, like 3 in 1.2.3
 *
 * Run-time version check, to check the version the Clutter library
 * that an application is currently linked against
 *
 * This is the run-time equivalent of the compile-time %CLUTTER_CHECK_VERSION
 * pre-processor macro
 *
 * Return value: %TRUE if the version of the Clutter library is
 *   greater than (@major, @minor, @micro), and %FALSE otherwise
 *
 * Since: 1.2
 */
gboolean
clutter_check_version (guint major,
                       guint minor,
                       guint micro)
{
  return (clutter_major_version > major ||
          (clutter_major_version == major &&
           clutter_minor_version > minor) ||
          (clutter_major_version == major &&
           clutter_minor_version == minor &&
           clutter_micro_version >= micro));
}

/**
 * clutter_get_default_text_direction:
 *
 * Retrieves the default direction for the text. The text direction is
 * determined by the locale and/or by the `CLUTTER_TEXT_DIRECTION`
 * environment variable.
 *
 * The default text direction can be overridden on a per-actor basis by using
 * clutter_actor_set_text_direction().
 *
 * Return value: the default text direction
 *
 * Since: 1.2
 */
ClutterTextDirection
clutter_get_default_text_direction (void)
{
  return clutter_text_direction;
}

/*< private >
 * clutter_clear_events_queue:
 *
 * Clears the events queue stored in the main context.
 */
void
_clutter_clear_events_queue (void)
{
  ClutterMainContext *context = _clutter_context_get_default ();

  if (context->events_queue != NULL)
    {
      g_queue_foreach (context->events_queue,
                       (GFunc) clutter_event_free,
                       NULL);
      g_queue_free (context->events_queue);
      context->events_queue = NULL;
    }
}

void
_clutter_clear_events_queue_for_stage (ClutterStage *stage)
{
  ClutterMainContext *context = _clutter_context_get_default ();
  GList *l, *next;

  if (context->events_queue == NULL)
    return;

  /* Remove any pending events for this stage from the event queue */
  for (l = context->events_queue->head; l; l = next)
    {
      ClutterEvent *event = l->data;

      next = l->next;

      if (event->any.stage == stage)
        {
          g_queue_delete_link (context->events_queue, l);
          clutter_event_free (event);
        }
    }
}

ClutterPickMode
_clutter_context_get_pick_mode (void)
{
  ClutterMainContext *context = _clutter_context_get_default ();

  return context->pick_mode;
}

void
_clutter_context_push_shader_stack (ClutterActor *actor)
{
  ClutterMainContext *context = _clutter_context_get_default ();

  context->shaders = g_slist_prepend (context->shaders, actor);
}

ClutterActor *
_clutter_context_peek_shader_stack (void)
{
  ClutterMainContext *context = _clutter_context_get_default ();

  if (context->shaders != NULL)
    return context->shaders->data;

  return NULL;
}

ClutterActor *
_clutter_context_pop_shader_stack (ClutterActor *actor)
{
  ClutterMainContext *context = _clutter_context_get_default ();

  context->shaders = g_slist_remove (context->shaders, actor);

  return _clutter_context_peek_shader_stack ();
}

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

  return context->motion_events_per_actor;
}

/**
 * clutter_check_windowing_backend:
 * @backend_type: the name of the backend to check
 *
 * Checks the run-time name of the Clutter windowing system backend, using
 * the symbolic macros like %CLUTTER_WINDOWING_WIN32 or
 * %CLUTTER_WINDOWING_X11.
 *
 * This function should be used in conjuction with the compile-time macros
 * inside applications and libraries that are using the platform-specific
 * windowing system API, to ensure that they are running on the correct
 * windowing system; for instance:
 *
 * |[
 * #ifdef CLUTTER_WINDOWING_X11
 *   if (clutter_check_windowing_backend (CLUTTER_WINDOWING_X11))
 *     {
 *       // it is safe to use the clutter_x11_* API
 *     }
 *   else
 * #endif
 * #ifdef CLUTTER_WINDOWING_WIN32
 *   if (clutter_check_windowing_backend (CLUTTER_WINDOWING_WIN32))
 *     {
 *       // it is safe to use the clutter_win32_* API
 *     }
 *   else
 * #endif
 *     g_error ("Unknown Clutter backend.");
 * ]|
 *
 * Return value: %TRUE if the current Clutter windowing system backend is
 *   the one checked, and %FALSE otherwise
 *
 * Since: 1.10
 */
gboolean
clutter_check_windowing_backend (const char *backend_type)
{
  ClutterMainContext *context = _clutter_context_get_default ();

  g_return_val_if_fail (backend_type != NULL, FALSE);

  backend_type = g_intern_string (backend_type);

#ifdef CLUTTER_WINDOWING_OSX
  if (backend_type == I_(CLUTTER_WINDOWING_OSX) &&
      CLUTTER_IS_BACKEND_OSX (context->backend))
    return TRUE;
  else
#endif
#ifdef CLUTTER_WINDOWING_WIN32
  if (backend_type == I_(CLUTTER_WINDOWING_WIN32) &&
      CLUTTER_IS_BACKEND_WIN32 (context->backend))
    return TRUE;
  else
#endif
#ifdef CLUTTER_WINDOWING_WAYLAND
  if (backend_type == I_(CLUTTER_WINDOWING_WAYLAND) &&
      CLUTTER_IS_BACKEND_WAYLAND (context->backend))
    return TRUE;
  else
#endif
#ifdef CLUTTER_WINDOWING_EGL
  if (backend_type == I_(CLUTTER_WINDOWING_EGL) &&
      CLUTTER_IS_BACKEND_EGL_NATIVE (context->backend))
    return TRUE;
  else
#endif
#ifdef CLUTTER_WINDOWING_MIR
  if (backend_type == I_(CLUTTER_WINDOWING_MIR) &&
      CLUTTER_IS_BACKEND_MIR (context->backend))
    return TRUE;
  else
#endif
#ifdef CLUTTER_WINDOWING_GDK
  if (backend_type == I_(CLUTTER_WINDOWING_GDK) &&
      CLUTTER_IS_BACKEND_GDK (context->backend))
    return TRUE;
  else
#endif
#ifdef CLUTTER_WINDOWING_X11
  if (backend_type == I_(CLUTTER_WINDOWING_X11) &&
      CLUTTER_IS_BACKEND_X11 (context->backend))
    return TRUE;
  else
#endif
  return FALSE;
}

void
_clutter_set_sync_to_vblank (gboolean sync_to_vblank)
{
  clutter_sync_to_vblank = !!sync_to_vblank;
}

gboolean
_clutter_get_sync_to_vblank (void)
{
  return clutter_sync_to_vblank;
}

void
_clutter_debug_messagev (const char *format,
                         va_list     var_args)
{
  static gint64 last_debug_stamp;
  gchar *stamp, *fmt;
  gint64 cur_time, debug_stamp;

  cur_time = g_get_monotonic_time ();

  /* if the last debug message happened less than a second ago, just
   * show the increments instead of the full timestamp
   */
  if (last_debug_stamp == 0 ||
      cur_time - last_debug_stamp >= G_USEC_PER_SEC)
    {
      debug_stamp = cur_time;
      last_debug_stamp = debug_stamp;

      stamp = g_strdup_printf ("[%16" G_GINT64_FORMAT "]", debug_stamp);
    }
  else
    {
      debug_stamp = cur_time - last_debug_stamp;

      stamp = g_strdup_printf ("[%+16" G_GINT64_FORMAT "]", debug_stamp);
    }

  fmt = g_strconcat (stamp, ":", format, NULL);
  g_free (stamp);

  g_logv (G_LOG_DOMAIN, G_LOG_LEVEL_MESSAGE, fmt, var_args);

  g_free (fmt);
}

void
_clutter_debug_message (const char *format, ...)
{
  va_list args;

  va_start (args, format);
  _clutter_debug_messagev (format, args);
  va_end (args);
}

gboolean
_clutter_diagnostic_enabled (void)
{
  static const char *clutter_enable_diagnostic = NULL;

  if (G_UNLIKELY (clutter_enable_diagnostic == NULL))
    {
      clutter_enable_diagnostic = g_getenv ("CLUTTER_ENABLE_DIAGNOSTIC");

      if (clutter_enable_diagnostic == NULL)
        clutter_enable_diagnostic = "0";
    }

  return *clutter_enable_diagnostic != '0';
}

void
_clutter_diagnostic_message (const char *format, ...)
{
  va_list args;
  char *fmt;

  fmt = g_strconcat ("[DIAGNOSTIC]: ", format, NULL);

  va_start (args, format);
  g_logv (G_LOG_DOMAIN, G_LOG_LEVEL_MESSAGE, fmt, args);
  va_end (args);

  g_free (fmt);
}