~unity-team/unity/trunk

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
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
// -*- Mode: C++; indent-tabs-mode: nil; tab-width: 2 -*-
/* Compiz unity plugin
 * unityshell.cpp
 *
 * Copyright (c) 2010-11 Canonical Ltd.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 3
 * of the License, or (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * Your own copyright notice would go above. You are free to choose whatever
 * licence you want, just take note that some compiz code is GPL and you will
 * not be able to re-use it if you want to use a different licence.
 */

#include <NuxCore/Logger.h>
#include <Nux/Nux.h>
#include <Nux/HLayout.h>
#include <Nux/BaseWindow.h>
#include <Nux/WindowCompositor.h>

#include <UnityCore/DBusIndicators.h>
#include <UnityCore/DesktopUtilities.h>
#include <UnityCore/GnomeSessionManager.h>
#include <UnityCore/ScopeProxyInterface.h>

#include "CompizUtils.h"
#include "BaseWindowRaiserImp.h"
#include "IconRenderer.h"
#include "Launcher.h"
#include "LauncherIcon.h"
#include "LauncherController.h"
#include "SwitcherController.h"
#include "SwitcherView.h"
#include "PanelView.h"
#include "PluginAdapter.h"
#include "QuicklistManager.h"
#include "StartupNotifyService.h"
#include "Timer.h"
#include "XKeyboardUtil.h"
#include "unityshell.h"
#include "BackgroundEffectHelper.h"
#include "UnityGestureBroker.h"
#include "launcher/EdgeBarrierController.h"
#include "launcher/XdndCollectionWindowImp.h"
#include "launcher/XdndManagerImp.h"
#include "launcher/XdndStartStopNotifierImp.h"
#include "CompizShortcutModeller.h"
#include "GnomeKeyGrabber.h"
#include "RawPixel.h"

#include "decorations/DecorationsDataPool.h"
#include "decorations/DecorationsManager.h"

#include <glib/gi18n-lib.h>
#include <glib/gstdio.h>
#include <gtk/gtk.h>
#include <gdk/gdk.h>
#include <gdk/gdkx.h>
#include <libnotify/notify.h>
#include <cairo-xlib-xrender.h>

#include <text/text.h>

#include <sstream>
#include <memory>

#include <core/atoms.h>

#include "unitya11y.h"

#include "UBusMessages.h"
#include "UBusWrapper.h"
#include "UScreen.h"

#include "config.h"

/* FIXME: once we get a better method to add the toplevel windows to
   the accessible root object, this include would not be required */
#include "unity-util-accessible.h"

/* Set up vtable symbols */
COMPIZ_PLUGIN_20090315(unityshell, unity::UnityPluginVTable);

namespace cgl = compiz::opengl;

namespace unity
{
using namespace launcher;
using launcher::AbstractLauncherIcon;
using launcher::Launcher;
using ui::LayoutWindow;
using util::Timer;

DECLARE_LOGGER(logger, "unity.shell.compiz");
namespace
{
UnityScreen* uScreen = nullptr;

void reset_glib_logging();
void configure_logging();
void capture_g_log_calls(const gchar* log_domain,
                         GLogLevelFlags log_level,
                         const gchar* message,
                         gpointer user_data);

#ifndef USE_GLES
gboolean is_extension_supported(const gchar* extensions, const gchar* extension);
gfloat get_opengl_version_f32(const gchar* version_string);
#endif

inline CompRegion CompRegionFromNuxGeo(nux::Geometry const& geo)
{
  return CompRegion(geo.x, geo.y, geo.width, geo.height);
}

inline CompRect CompRectFromNuxGeo(nux::Geometry const& geo)
{
  return CompRect(geo.x, geo.y, geo.width, geo.height);
}

inline nux::Geometry NuxGeometryFromCompRect(CompRect const& rect)
{
  return nux::Geometry(rect.x(), rect.y(), rect.width(), rect.height());
}

inline nux::Color NuxColorFromCompizColor(unsigned short* color)
{
  return nux::Color(color[0]/65535.0f, color[1]/65535.0f, color[2]/65535.0f, color[3]/65535.0f);
}

namespace local
{
// Tap duration in milliseconds.
const int ALT_TAP_DURATION = 250;
const unsigned int SCROLL_DOWN_BUTTON = 6;
const unsigned int SCROLL_UP_BUTTON = 7;
const int MAX_BUFFER_AGE = 11;
const int FRAMES_TO_REDRAW_ON_RESUME = 10;
const RawPixel SCALE_PADDING = 40_em;
const RawPixel SCALE_SPACING = 20_em;
const std::string RELAYOUT_TIMEOUT = "relayout-timeout";
const std::string HUD_UNGRAB_WAIT = "hud-ungrab-wait";
const std::string FIRST_RUN_STAMP = "first_run.stamp";
const std::string LOCKED_STAMP = "locked.stamp";
} // namespace local
} // anon namespace

UnityScreen::UnityScreen(CompScreen* screen)
  : BaseSwitchScreen(screen)
  , PluginClassHandler <UnityScreen, CompScreen>(screen)
  , screen(screen)
  , cScreen(CompositeScreen::get(screen))
  , gScreen(GLScreen::get(screen))
  , sScreen(ScaleScreen::get(screen))
  , menus_(std::make_shared<menu::Manager>(std::make_shared<indicator::DBusIndicators>(), std::make_shared<key::GnomeGrabber>()))
  , deco_manager_(std::make_shared<decoration::Manager>(menus_))
  , debugger_(this)
  , needsRelayout(false)
  , super_keypressed_(false)
  , newFocusedWindow(nullptr)
  , doShellRepaint(false)
  , didShellRepaint(false)
  , allowWindowPaint(false)
  , _key_nav_mode_requested(false)
  , _last_output(nullptr)
  , force_draw_countdown_(0)
  , firstWindowAboveShell(nullptr)
  , onboard_(nullptr)
  , grab_index_(0)
  , painting_tray_ (false)
  , last_scroll_event_(0)
  , hud_keypress_time_(0)
  , first_menu_keypress_time_(0)
  , paint_panel_under_dash_(false)
  , scale_just_activated_(false)
  , big_tick_(0)
  , screen_introspection_(screen)
  , ignore_redraw_request_(false)
  , dirty_helpers_on_this_frame_(false)
  , back_buffer_age_(0)
  , is_desktop_active_(false)
{
  Timer timer;
#ifndef USE_GLES
  gfloat version;
  gchar* extensions;
#endif
  bool  failed = false;
  configure_logging();
  LOG_DEBUG(logger) << __PRETTY_FUNCTION__;
  int (*old_handler)(Display*, XErrorEvent*);
  old_handler = XSetErrorHandler(NULL);

#ifndef USE_GLES
  /* Ensure OpenGL version is 1.4+. */
  version = get_opengl_version_f32((const gchar*) glGetString(GL_VERSION));
  if (version < 1.4f)
  {
    compLogMessage("unityshell", CompLogLevelError,
                   "OpenGL 1.4+ not supported\n");
    setFailed ();
    failed = true;
  }

  /* Ensure OpenGL extensions required by the Unity plugin are available. */
  extensions = (gchar*) glGetString(GL_EXTENSIONS);
  if (!is_extension_supported(extensions, "GL_ARB_vertex_program"))
  {
    compLogMessage("unityshell", CompLogLevelError,
                   "GL_ARB_vertex_program not supported\n");
    setFailed ();
    failed = true;
  }
  if (!is_extension_supported(extensions, "GL_ARB_fragment_program"))
  {
    compLogMessage("unityshell", CompLogLevelError,
                   "GL_ARB_fragment_program not supported\n");
    setFailed ();
    failed = true;
  }
  if (!is_extension_supported(extensions, "GL_ARB_vertex_buffer_object"))
  {
    compLogMessage("unityshell", CompLogLevelError,
                   "GL_ARB_vertex_buffer_object not supported\n");
    setFailed ();
    failed = true;
  }
  if (!is_extension_supported(extensions, "GL_ARB_framebuffer_object"))
  {
    if (!is_extension_supported(extensions, "GL_EXT_framebuffer_object"))
    {
      compLogMessage("unityshell", CompLogLevelError,
                     "GL_ARB_framebuffer_object or GL_EXT_framebuffer_object "
                     "not supported\n");
      setFailed();
      failed = true;
    }
  }
  if (!is_extension_supported(extensions, "GL_ARB_texture_non_power_of_two"))
  {
    if (!is_extension_supported(extensions, "GL_ARB_texture_rectangle"))
    {
      compLogMessage("unityshell", CompLogLevelError,
                     "GL_ARB_texture_non_power_of_two or "
                     "GL_ARB_texture_rectangle not supported\n");
      setFailed ();
      failed = true;
    }
  }

    //In case of software rendering then enable lowgfx mode.
  std::string renderer = ANSI_TO_TCHAR(NUX_REINTERPRET_CAST(const char *, glGetString(GL_RENDERER)));

  if (renderer.find("Software Rasterizer") != std::string::npos ||
      renderer.find("Mesa X11") != std::string::npos ||
      renderer.find("LLVM") != std::string::npos ||
      renderer.find("on softpipe") != std::string::npos ||
      (getenv("UNITY_LOW_GFX_MODE") != NULL && atoi(getenv("UNITY_LOW_GFX_MODE")) == 1))
    {
      unity_settings_.SetLowGfxMode(true);
    }
#endif

  if (!failed)
  {
     notify_init("unityshell");

     unity_a11y_preset_environment();

     XSetErrorHandler(old_handler);

     /* Wrap compiz interfaces */
     ScreenInterface::setHandler(screen);
     CompositeScreenInterface::setHandler(cScreen);
     GLScreenInterface::setHandler(gScreen);
     ScaleScreenInterface::setHandler(sScreen);
     screen->updateSupportedWmHints();

     PluginAdapter::Initialize(screen);
     AddChild(&WindowManager::Default());

     StartupNotifyService::Default()->SetSnDisplay(screen->snDisplay(), screen->screenNum());

     nux::NuxInitialize(0);
#ifndef USE_GLES
     wt.reset(nux::CreateFromForeignWindow(cScreen->output(),
                                           glXGetCurrentContext(),
                                           &UnityScreen::initUnity,
                                           this));
#else
     wt.reset(nux::CreateFromForeignWindow(cScreen->output(),
                                           eglGetCurrentContext(),
                                           &UnityScreen::initUnity,
                                           this));
#endif

    tick_source_.reset(new na::TickSource);
    animation_controller_.reset(new na::AnimationController(*tick_source_));

     wt->RedrawRequested.connect(sigc::mem_fun(this, &UnityScreen::onRedrawRequested));

     unity_a11y_init(wt.get());

     /* i18n init */
     bindtextdomain(GETTEXT_PACKAGE, LOCALE_DIR);
     bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8");

     wt->Run(NULL);
     uScreen = this;

     optionSetShowMenuBarInitiate(boost::bind(&UnityScreen::showMenuBarInitiate, this, _1, _2, _3));
     optionSetShowMenuBarTerminate(boost::bind(&UnityScreen::showMenuBarTerminate, this, _1, _2, _3));
     optionSetLockScreenInitiate(boost::bind(&UnityScreen::LockScreenInitiate, this, _1, _2, _3));
     optionSetOverrideDecorationThemeNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));
     optionSetShadowXOffsetNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));
     optionSetShadowYOffsetNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));
     optionSetActiveShadowRadiusNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));
     optionSetInactiveShadowRadiusNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));
     optionSetActiveShadowColorNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));
     optionSetInactiveShadowColorNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));
     optionSetShowHudInitiate(boost::bind(&UnityScreen::ShowHudInitiate, this, _1, _2, _3));
     optionSetShowHudTerminate(boost::bind(&UnityScreen::ShowHudTerminate, this, _1, _2, _3));
     optionSetBackgroundColorNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));
     optionSetLauncherHideModeNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));
     optionSetBacklightModeNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));
     optionSetRevealTriggerNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));
     optionSetLaunchAnimationNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));
     optionSetUrgentAnimationNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));
     optionSetPanelOpacityNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));
     optionSetPanelOpacityMaximizedToggleNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));
     optionSetMenusFadeinNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));
     optionSetMenusFadeoutNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));
     optionSetMenusDiscoveryDurationNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));
     optionSetMenusDiscoveryFadeinNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));
     optionSetMenusDiscoveryFadeoutNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));
     optionSetLauncherOpacityNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));
     optionSetIconSizeNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));
     optionSetAutohideAnimationNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));
     optionSetDashBlurExperimentalNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));
     optionSetShortcutOverlayNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));
     optionSetShowLauncherInitiate(boost::bind(&UnityScreen::showLauncherKeyInitiate, this, _1, _2, _3));
     optionSetShowLauncherTerminate(boost::bind(&UnityScreen::showLauncherKeyTerminate, this, _1, _2, _3));
     optionSetKeyboardFocusInitiate(boost::bind(&UnityScreen::setKeyboardFocusKeyInitiate, this, _1, _2, _3));
     //optionSetKeyboardFocusTerminate (boost::bind (&UnityScreen::setKeyboardFocusKeyTerminate, this, _1, _2, _3));
     optionSetExecuteCommandInitiate(boost::bind(&UnityScreen::executeCommand, this, _1, _2, _3));
     optionSetShowDesktopKeyInitiate(boost::bind(&UnityScreen::showDesktopKeyInitiate, this, _1, _2, _3));
     optionSetPanelFirstMenuInitiate(boost::bind(&UnityScreen::showPanelFirstMenuKeyInitiate, this, _1, _2, _3));
     optionSetPanelFirstMenuTerminate(boost::bind(&UnityScreen::showPanelFirstMenuKeyTerminate, this, _1, _2, _3));
     optionSetPanelFirstMenuNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));
     optionSetAutomaximizeValueNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));
     optionSetDashTapDurationNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));
     optionSetAltTabTimeoutNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));
     optionSetAltTabBiasViewportNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));
     optionSetDisableShowDesktopNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));
     optionSetDisableMouseNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));

     optionSetAltTabForwardAllInitiate(boost::bind(&UnityScreen::altTabForwardAllInitiate, this, _1, _2, _3));
     optionSetAltTabForwardInitiate(boost::bind(&UnityScreen::altTabForwardInitiate, this, _1, _2, _3));
     optionSetAltTabForwardTerminate(boost::bind(&UnityScreen::altTabTerminateCommon, this, _1, _2, _3));
     optionSetAltTabForwardAllTerminate(boost::bind(&UnityScreen::altTabTerminateCommon, this, _1, _2, _3));
     optionSetAltTabPrevAllInitiate(boost::bind(&UnityScreen::altTabPrevAllInitiate, this, _1, _2, _3));
     optionSetAltTabPrevInitiate(boost::bind(&UnityScreen::altTabPrevInitiate, this, _1, _2, _3));

     optionSetAltTabNextWindowInitiate(boost::bind(&UnityScreen::altTabNextWindowInitiate, this, _1, _2, _3));
     optionSetAltTabNextWindowTerminate(boost::bind(&UnityScreen::altTabTerminateCommon, this, _1, _2, _3));

     optionSetAltTabPrevWindowInitiate(boost::bind(&UnityScreen::altTabPrevWindowInitiate, this, _1, _2, _3));

     optionSetLauncherSwitcherForwardInitiate(boost::bind(&UnityScreen::launcherSwitcherForwardInitiate, this, _1, _2, _3));
     optionSetLauncherSwitcherPrevInitiate(boost::bind(&UnityScreen::launcherSwitcherPrevInitiate, this, _1, _2, _3));
     optionSetLauncherSwitcherForwardTerminate(boost::bind(&UnityScreen::launcherSwitcherTerminate, this, _1, _2, _3));

     optionSetStopVelocityNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));
     optionSetRevealPressureNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));
     optionSetEdgeResponsivenessNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));
     optionSetOvercomePressureNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));
     optionSetDecayRateNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));
     optionSetShowMinimizedWindowsNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));
     optionSetEdgePassedDisabledMsNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));

     optionSetNumLaunchersNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));
     optionSetLauncherCaptureMouseNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));

     optionSetScrollInactiveIconsNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));
     optionSetLauncherMinimizeWindowNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));

     ubus_manager_.RegisterInterest(UBUS_LAUNCHER_START_KEY_NAV,
                   sigc::mem_fun(this, &UnityScreen::OnLauncherStartKeyNav));

     ubus_manager_.RegisterInterest(UBUS_LAUNCHER_START_KEY_SWITCHER,
                   sigc::mem_fun(this, &UnityScreen::OnLauncherStartKeyNav));

     ubus_manager_.RegisterInterest(UBUS_LAUNCHER_END_KEY_NAV,
                   sigc::mem_fun(this, &UnityScreen::OnLauncherEndKeyNav));

     ubus_manager_.RegisterInterest(UBUS_LAUNCHER_END_KEY_SWITCHER,
                   sigc::mem_fun(this, &UnityScreen::OnLauncherEndKeyNav));

     auto init_plugins_cb = sigc::mem_fun(this, &UnityScreen::initPluginActions);
     sources_.Add(std::make_shared<glib::Idle>(init_plugins_cb, glib::Source::Priority::DEFAULT));

     InitGesturesSupport();

     CompString name(PKGDATADIR"/panel-shadow.png");
     CompString pname("unityshell");
     CompSize size(1, 20);
     _shadow_texture = GLTexture::readImageToTexture(name, pname, size);

     ubus_manager_.RegisterInterest(UBUS_OVERLAY_SHOWN, [this](GVariant * data)
     {
       unity::glib::String overlay_identity;
       gboolean can_maximise = FALSE;
       gint32 overlay_monitor = 0;
       int width, height;
       g_variant_get(data, UBUS_OVERLAY_FORMAT_STRING,
                    &overlay_identity, &can_maximise, &overlay_monitor, &width, &height);

       overlay_monitor_ = overlay_monitor;

       RaiseInputWindows();
     });

    Display* display = gdk_x11_display_get_xdisplay(gdk_display_get_default());;
    XSelectInput(display, GDK_ROOT_WINDOW(), PropertyChangeMask);
    LOG_INFO(logger) << "UnityScreen constructed: " << timer.ElapsedSeconds() << "s";

    UScreen::GetDefault()->resuming.connect([this] {
      /* Force paint local::FRAMES_TO_REDRAW_ON_RESUME frames on resume */
      force_draw_countdown_ += local::FRAMES_TO_REDRAW_ON_RESUME;
    });

    Introspectable::AddChild(deco_manager_.get());
    auto const& deco_style = decoration::Style::Get();
    auto deco_style_cb = sigc::hide(sigc::mem_fun(this, &UnityScreen::OnDecorationStyleChanged));
    deco_style->theme.changed.connect(deco_style_cb);
    deco_style->title_font.changed.connect(deco_style_cb);

    minimize_speed_controller_.DurationChanged.connect(
      sigc::mem_fun(this, &UnityScreen::OnMinimizeDurationChanged)
    );

    WindowManager& wm = WindowManager::Default();
    wm.initiate_spread.connect(sigc::mem_fun(this, &UnityScreen::OnInitiateSpread));
    wm.terminate_spread.connect(sigc::mem_fun(this, &UnityScreen::OnTerminateSpread));
    wm.initiate_expo.connect(sigc::mem_fun(this, &UnityScreen::DamagePanelShadow));
    wm.terminate_expo.connect(sigc::mem_fun(this, &UnityScreen::DamagePanelShadow));

    AddChild(&screen_introspection_);

    /* Create blur backup texture */
    auto gpu_device = nux::GetGraphicsDisplay()->GetGpuDevice();
    gpu_device->backup_texture0_ =
        gpu_device->CreateSystemCapableDeviceTexture(screen->width(), screen->height(),
                                                     1, nux::BITFMT_R8G8B8A8,
                                                     NUX_TRACKER_LOCATION);

    auto const& blur_update_cb = sigc::mem_fun(this, &UnityScreen::DamageBlurUpdateRegion);
    BackgroundEffectHelper::blur_region_needs_update_.connect(blur_update_cb);

    /* Track whole damage on the very first frame */
    cScreen->damageScreen();
  }
}

UnityScreen::~UnityScreen()
{
  notify_uninit();

  unity_a11y_finalize();
  QuicklistManager::Destroy();
  decoration::DataPool::Reset();
  SaveLockStamp(false);

  reset_glib_logging();
}

void UnityScreen::initAltTabNextWindow()
{
  Display* display = screen->dpy();
  KeySym tab_keysym = XStringToKeysym("Tab");
  KeySym above_tab_keysym = keyboard::get_key_above_key_symbol(display, tab_keysym);

  if (above_tab_keysym != NoSymbol)
  {
    {
      std::ostringstream sout;
      sout << "<Alt>" << XKeysymToString(above_tab_keysym);

      screen->removeAction(&optionGetAltTabNextWindow());

      CompAction action = CompAction();
      action.keyFromString(sout.str());
      action.setState (CompAction::StateInitKey | CompAction::StateAutoGrab);
      mOptions[UnityshellOptions::AltTabNextWindow].value().set (action);
      screen->addAction (&mOptions[UnityshellOptions::AltTabNextWindow].value ().action ());

      optionSetAltTabNextWindowInitiate(boost::bind(&UnityScreen::altTabNextWindowInitiate, this, _1, _2, _3));
      optionSetAltTabNextWindowTerminate(boost::bind(&UnityScreen::altTabTerminateCommon, this, _1, _2, _3));
    }
    {
      std::ostringstream sout;
      sout << "<Alt><Shift>" << XKeysymToString(above_tab_keysym);

      screen->removeAction(&optionGetAltTabPrevWindow());

      CompAction action = CompAction();
      action.keyFromString(sout.str());
      action.setState (CompAction::StateInitKey | CompAction::StateAutoGrab);
      mOptions[UnityshellOptions::AltTabPrevWindow].value().set (action);
      screen->addAction (&mOptions[UnityshellOptions::AltTabPrevWindow].value ().action ());

      optionSetAltTabPrevWindowInitiate(boost::bind(&UnityScreen::altTabPrevWindowInitiate, this, _1, _2, _3));
    }
  }
  else
  {
    LOG_WARN(logger) << "Could not find key above tab!";
  }

}

void UnityScreen::OnInitiateSpread()
{
  scale_just_activated_ = super_keypressed_;
  spread_filter_ = std::make_shared<spread::Filter>();
  spread_filter_->text.changed.connect([this] (std::string const& filter) {
    if (filter.empty())
    {
      sScreen->relayoutSlots(CompMatch::emptyMatch);
    }
    else
    {
      CompMatch windows_match;
      auto const& filtered_windows = spread_filter_->FilteredWindows();

      for (auto const& swin : sScreen->getWindows())
      {
        if (filtered_windows.find(swin->window->id()) != filtered_windows.end())
          continue;

        auto* uwin = UnityWindow::get(swin->window);
        uwin->OnTerminateSpread();
        fake_decorated_windows_.erase(uwin);
      }

      for (auto xid : filtered_windows)
        windows_match |= "xid="+std::to_string(xid);

      auto match = sScreen->getCustomMatch();
      match &= windows_match;
      sScreen->relayoutSlots(match);
    }
  });

  for (auto const& swin : sScreen->getWindows())
  {
    auto* uwin = UnityWindow::get(swin->window);
    fake_decorated_windows_.insert(uwin);
    uwin->OnInitiateSpread();
  }
}

void UnityScreen::OnTerminateSpread()
{
  spread_filter_.reset();

  for (auto const& swin : sScreen->getWindows())
    UnityWindow::get(swin->window)->OnTerminateSpread();

  fake_decorated_windows_.clear();
}

void UnityScreen::DamagePanelShadow()
{
  CompRect panelShadow;

  for (CompOutput const& output : screen->outputDevs())
  {
    FillShadowRectForOutput(panelShadow, output);
    cScreen->damageRegion(CompRegion(panelShadow));
  }
}

void UnityScreen::OnViewHidden(nux::BaseWindow *bw)
{
  /* Count this as regular damage */
  auto const& geo = bw->GetAbsoluteGeometry();
  cScreen->damageRegion(CompRegionFromNuxGeo(geo));
}

void UnityScreen::EnsureSuperKeybindings()
{
  for (auto action : _shortcut_actions)
    screen->removeAction(action.get());

  _shortcut_actions.clear ();

  for (auto shortcut : launcher_controller_->GetAllShortcuts())
  {
    CreateSuperNewAction(shortcut, impl::ActionModifiers::NONE);
    CreateSuperNewAction(shortcut, impl::ActionModifiers::USE_NUMPAD);
    CreateSuperNewAction(shortcut, impl::ActionModifiers::USE_SHIFT);
    CreateSuperNewAction(shortcut, impl::ActionModifiers::USE_SHIFT_NUMPAD);
  }

  for (auto shortcut : dash_controller_->GetAllShortcuts())
    CreateSuperNewAction(shortcut, impl::ActionModifiers::NONE);
}

void UnityScreen::CreateSuperNewAction(char shortcut, impl::ActionModifiers flag)
{
  CompActionPtr action(new CompAction());
  const std::string key(optionGetShowLauncher().keyToString());

  CompAction::KeyBinding binding;
  binding.fromString(impl::CreateActionString(key, shortcut, flag));

  action->setKey(binding);

  screen->addAction(action.get());
  _shortcut_actions.push_back(action);
}

void UnityScreen::nuxPrologue()
{
#ifndef USE_GLES
  /* Vertex lighting isn't used in Unity, we disable that state as it could have
   * been leaked by another plugin. That should theoretically be switched off
   * right after PushAttrib since ENABLE_BIT is meant to restore the LIGHTING
   * bit, but we do that here in order to workaround a bug (?) in the NVIDIA
   * drivers (lp:703140). */
  glDisable(GL_LIGHTING);
#endif

  glGetError();
}

void UnityScreen::nuxEpilogue()
{
#ifndef USE_GLES
  /* In some unknown place inside nux drawing we change the viewport without
   * setting it back to the default one, so we need to restore it before allowing
   * compiz to take the scene */
  auto* o = _last_output;
  glViewport(o->x(), screen->height() - o->y2(), o->width(), o->height());

  glDepthRange(0, 1);
#else
  glDepthRangef(0, 1);
#endif

  gScreen->resetRasterPos();
  glDisable(GL_SCISSOR_TEST);
}

void UnityScreen::setPanelShadowMatrix(GLMatrix const& matrix)
{
  panel_shadow_matrix_ = matrix;
}

void UnityScreen::FillShadowRectForOutput(CompRect& shadowRect, CompOutput const& output)
{
  if (_shadow_texture.empty ())
    return;

  int monitor = PluginAdapter::Default().MonitorGeometryIn(NuxGeometryFromCompRect(output));
  float panel_h = static_cast<float>(panel_style_.PanelHeight(monitor));
  float shadowX = output.x();
  float shadowY = output.y() + panel_h;
  float shadowWidth = output.width();
  float shadowHeight = _shadow_texture[0]->height();
  shadowRect.setGeometry(shadowX, shadowY, shadowWidth, shadowHeight);
}

void UnityScreen::paintPanelShadow(CompRegion const& clip)
{
  // You have no shadow texture. But how?
  if (_shadow_texture.empty() || !_shadow_texture[0])
    return;

  if (panel_controller_->opacity() == 0.0f)
    return;

  if (sources_.GetSource(local::RELAYOUT_TIMEOUT))
    return;

  if (WindowManager::Default().IsExpoActive())
    return;

  CompOutput* output = _last_output;

  if (fullscreenRegion.contains(*output))
    return;

  if (launcher_controller_->IsOverlayOpen())
  {
    auto const& uscreen = UScreen::GetDefault();
    if (uscreen->GetMonitorAtPosition(output->x(), output->y()) == overlay_monitor_)
      return;
  }

  CompRect shadowRect;
  FillShadowRectForOutput(shadowRect, *output);

  CompRegion redraw(clip);
  redraw &= shadowRect;
  redraw -= panelShadowPainted;

  if (redraw.isEmpty())
    return;

  panelShadowPainted |= redraw;

  for (auto const& r : redraw.rects())
  {
    for (GLTexture* tex : _shadow_texture)
    {
      std::vector<GLfloat>  vertexData;
      std::vector<GLfloat>  textureData;
      std::vector<GLushort> colorData;
      GLVertexBuffer       *streamingBuffer = GLVertexBuffer::streamingBuffer();
      bool                  wasBlend = glIsEnabled(GL_BLEND);

      if (!wasBlend)
        glEnable(GL_BLEND);

      GL::activeTexture(GL_TEXTURE0);
      tex->enable(GLTexture::Fast);

      glTexParameteri(tex->target(), GL_TEXTURE_WRAP_S, GL_REPEAT);

      colorData = { 0xFFFF, 0xFFFF, 0xFFFF,
                    (GLushort)(panel_controller_->opacity() * 0xFFFF)
                  };

      // Sub-rectangle of the shadow needing redrawing:
      float x1 = r.x1();
      float y1 = r.y1();
      float x2 = r.x2();
      float y2 = r.y2();

      // Texture coordinates of the above rectangle:
      float tx1 = (x1 - shadowRect.x()) / shadowRect.width();
      float ty1 = (y1 - shadowRect.y()) / shadowRect.height();
      float tx2 = (x2 - shadowRect.x()) / shadowRect.width();
      float ty2 = (y2 - shadowRect.y()) / shadowRect.height();

      vertexData = {
        x1, y1, 0,
        x1, y2, 0,
        x2, y1, 0,
        x2, y2, 0,
      };

      textureData = {
        tx1, ty1,
        tx1, ty2,
        tx2, ty1,
        tx2, ty2,
      };

      streamingBuffer->begin(GL_TRIANGLE_STRIP);

      streamingBuffer->addColors(1, &colorData[0]);
      streamingBuffer->addVertices(4, &vertexData[0]);
      streamingBuffer->addTexCoords(0, 4, &textureData[0]);

      streamingBuffer->end();
      streamingBuffer->render(panel_shadow_matrix_);

      tex->disable();
      if (!wasBlend)
        glDisable(GL_BLEND);
    }
  }
}

void
UnityWindow::updateIconPos(int &wx, int &wy, int x, int y, float width, float height)
{
  wx = x + (last_bound.width - width) / 2;
  wy = y + (last_bound.height - height) / 2;
}

void UnityScreen::OnDecorationStyleChanged()
{
  for (UnityWindow* uwin : fake_decorated_windows_)
    uwin->CleanupCachedTextures();

  auto const& style = decoration::Style::Get();
  deco_manager_->shadow_offset = style->ShadowOffset();
  deco_manager_->active_shadow_color = style->ActiveShadowColor();
  deco_manager_->active_shadow_radius = style->ActiveShadowRadius();
  deco_manager_->inactive_shadow_color = style->InactiveShadowColor();
  deco_manager_->inactive_shadow_radius = style->InactiveShadowRadius();
}

void UnityScreen::DamageBlurUpdateRegion(nux::Geometry const& blur_update)
{
  cScreen->damageRegion(CompRegionFromNuxGeo(blur_update));
}

void UnityScreen::paintDisplay()
{
  CompOutput *output = _last_output;

  DrawPanelUnderDash();

  /* Bind the currently bound draw framebuffer to the read framebuffer binding.
   * The reason being that we want to use the results of nux images being
   * drawn to this framebuffer in glCopyTexSubImage2D operations */
  GLint current_draw_binding = 0,
        old_read_binding = 0;
#ifndef USE_GLES
  glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING_EXT, &old_read_binding);
  glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING_EXT, &current_draw_binding);
  if (old_read_binding != current_draw_binding)
    (*GL::bindFramebuffer) (GL_READ_FRAMEBUFFER_BINDING_EXT, current_draw_binding);
#else
  glGetIntegerv(GL_FRAMEBUFFER_BINDING, &old_read_binding);
  current_draw_binding = old_read_binding;
#endif

  BackgroundEffectHelper::monitor_rect_.Set(0, 0, screen->width(), screen->height());

  // If we have dirty helpers re-copy the backbuffer into a texture
  if (dirty_helpers_on_this_frame_)
  {
    /* We are using a CompRegion here so that we can combine rectangles
     * where it might make sense to. Saves calls into OpenGL */
    CompRegion blur_region;

    for (auto const& blur_geometry : BackgroundEffectHelper::GetBlurGeometries())
    {
      auto blur_rect = CompRectFromNuxGeo(blur_geometry);
      blur_region += (blur_rect & *output);
    }

    /* Copy from the read buffer into the backup texture */
    auto gpu_device = nux::GetGraphicsDisplay()->GetGpuDevice();
    GLuint backup_texture_id = gpu_device->backup_texture0_->GetOpenGLID();
    GLuint surface_target = gpu_device->backup_texture0_->GetSurfaceLevel(0)->GetSurfaceTarget();

    CHECKGL(glEnable(surface_target));
    CHECKGL(glBindTexture(surface_target, backup_texture_id));

    for (CompRect const& rect : blur_region.rects())
    {
      int x = nux::Clamp<int>(rect.x(), 0, screen->width());
      int y = nux::Clamp<int>(screen->height() - rect.y2(), 0, screen->height());
      int width = std::min<int>(screen->width() - rect.x(), rect.width());
      int height = std::min<int>(screen->height() - y, rect.height());

      CHECKGL(glCopyTexSubImage2D(surface_target, 0, x, y, x, y, width, height));
    }

    CHECKGL(glDisable(surface_target));

    back_buffer_age_ = 0;
  }

  nux::Geometry const& outputGeo = NuxGeometryFromCompRect(*output);
  wt->GetWindowCompositor().SetReferenceFramebuffer(current_draw_binding, old_read_binding, outputGeo);

  nuxPrologue();
  wt->RenderInterfaceFromForeignCmd(outputGeo);
  nuxEpilogue();

  for (Window tray_xid : panel_controller_->GetTrayXids())
  {
    if (tray_xid && !allowWindowPaint)
    {
      CompWindow *tray = screen->findWindow (tray_xid);

      if (tray)
      {
        GLMatrix oTransform;
        UnityWindow  *uTrayWindow = UnityWindow::get (tray);
        GLWindowPaintAttrib attrib (uTrayWindow->gWindow->lastPaintAttrib());
        unsigned int oldGlAddGeometryIndex = uTrayWindow->gWindow->glAddGeometryGetCurrentIndex ();
        unsigned int oldGlDrawIndex = uTrayWindow->gWindow->glDrawGetCurrentIndex ();

        attrib.opacity = COMPIZ_COMPOSITE_OPAQUE;
        attrib.brightness = COMPIZ_COMPOSITE_BRIGHT;
        attrib.saturation = COMPIZ_COMPOSITE_COLOR;

        oTransform.toScreenSpace (output, -DEFAULT_Z_CAMERA);

        painting_tray_ = true;

        /* force the use of the core functions */
        uTrayWindow->gWindow->glDrawSetCurrentIndex (MAXSHORT);
        uTrayWindow->gWindow->glAddGeometrySetCurrentIndex ( MAXSHORT);
        uTrayWindow->gWindow->glDraw (oTransform, attrib, infiniteRegion,
               PAINT_WINDOW_TRANSFORMED_MASK |
               PAINT_WINDOW_BLEND_MASK |
               PAINT_WINDOW_ON_TRANSFORMED_SCREEN_MASK);
        uTrayWindow->gWindow->glAddGeometrySetCurrentIndex (oldGlAddGeometryIndex);
        uTrayWindow->gWindow->glDrawSetCurrentIndex (oldGlDrawIndex);
        painting_tray_ = false;
      }
    }
  }

  if (switcher_controller_->detail())
  {
    auto const& targets = switcher_controller_->ExternalRenderTargets();

    for (LayoutWindow::Ptr const& target : targets)
    {
      if (CompWindow* window = screen->findWindow(target->xid))
      {
        UnityWindow *unity_window = UnityWindow::get(window);
        double parent_alpha = switcher_controller_->Opacity();
        unity_window->paintThumbnail(target->result, target->alpha, parent_alpha, target->scale,
                                     target->decoration_height, target->selected);
      }
    }
  }

  doShellRepaint = false;
  didShellRepaint = true;
}

void UnityScreen::DrawPanelUnderDash()
{
  if (!paint_panel_under_dash_ || (!dash_controller_->IsVisible() && !hud_controller_->IsVisible()))
    return;

  auto const& output_dev = screen->currentOutputDev();

  if (_last_output->id() != output_dev.id())
    return;

  auto graphics_engine = nux::GetGraphicsDisplay()->GetGraphicsEngine();

  if (!graphics_engine->UsingGLSLCodePath())
    return;

  graphics_engine->ResetModelViewMatrixStack();
  graphics_engine->Push2DTranslationModelViewMatrix(0.0f, 0.0f, 0.0f);
  graphics_engine->ResetProjectionMatrix();
  graphics_engine->SetOrthographicProjectionMatrix(output_dev.width(), output_dev.height());

  nux::TexCoordXForm texxform;
  texxform.SetWrap(nux::TEXWRAP_REPEAT, nux::TEXWRAP_CLAMP);

  int monitor = WindowManager::Default().MonitorGeometryIn(NuxGeometryFromCompRect(output_dev));
  auto const& texture = panel_style_.GetBackground(monitor)->GetDeviceTexture();
  graphics_engine->QRP_GLSL_1Tex(0, 0, output_dev.width(), texture->GetHeight(), texture, texxform, nux::color::White);
}

bool UnityScreen::forcePaintOnTop()
{
  return !allowWindowPaint ||
         lockscreen_controller_->IsLocked() ||
         dash_controller_->IsVisible() ||
         hud_controller_->IsVisible() ||
          ((switcher_controller_->Visible() ||
            WindowManager::Default().IsExpoActive())
           && !fullscreen_windows_.empty () && (!(screen->grabbed () && !screen->otherGrabExist (NULL))));
}

void UnityScreen::EnableCancelAction(CancelActionTarget target, bool enabled, int modifiers)
{
  if (enabled)
  {
    /* Create a new keybinding for the Escape key and the current modifiers,
     * compiz will take of the ref-counting of the repeated actions */
    KeyCode escape = XKeysymToKeycode(screen->dpy(), XK_Escape);
    CompAction::KeyBinding binding(escape, modifiers);

    CompActionPtr &escape_action = _escape_actions[target];
    escape_action = CompActionPtr(new CompAction());
    escape_action->setKey(binding);

    screen->addAction(escape_action.get());
  }
  else if (!enabled && _escape_actions[target].get())
  {
    screen->removeAction(_escape_actions[target].get());
    _escape_actions.erase(target);
  }
}

void UnityScreen::enterShowDesktopMode ()
{
  for (CompWindow *w : screen->windows ())
  {
    CompPoint const& viewport = w->defaultViewport();
    UnityWindow *uw = UnityWindow::get (w);

    if (viewport == uScreen->screen->vp() &&
        ShowdesktopHandler::ShouldHide (static_cast <ShowdesktopHandlerWindowInterface *> (uw)))
    {
      UnityWindow::get (w)->enterShowDesktop ();
      // the animation plugin does strange things here ...
      // if this notification is sent
      // w->windowNotify (CompWindowNotifyEnterShowDesktopMode);
    }
    if (w->type() & CompWindowTypeDesktopMask)
      w->moveInputFocusTo();
  }

  if (dash_controller_->IsVisible())
    dash_controller_->HideDash();
    
  if (hud_controller_->IsVisible())
    hud_controller_->HideHud();

  PluginAdapter::Default().OnShowDesktop();

  /* Disable the focus handler as we will report that
   * minimized windows can be focused which will
   * allow them to enter showdesktop mode. That's
   * no good */
  for (CompWindow *w : screen->windows ())
  {
    UnityWindow *uw = UnityWindow::get (w);
    w->focusSetEnabled (uw, false);
  }

  screen->enterShowDesktopMode ();

  for (CompWindow *w : screen->windows ())
  {
    UnityWindow *uw = UnityWindow::get (w);
    w->focusSetEnabled (uw, true);
  }
}

void UnityScreen::leaveShowDesktopMode (CompWindow *w)
{
  /* Where a window is inhibiting, only allow the window
   * that is inhibiting the leave show desktop to actually
   * fade in again - all other windows should remain faded out */
  if (!ShowdesktopHandler::InhibitingXid ())
  {
    for (CompWindow *cw : screen->windows ())
    {
      CompPoint const& viewport = cw->defaultViewport();

      if (viewport == uScreen->screen->vp() &&
          cw->inShowDesktopMode ())
      {
        UnityWindow::get (cw)->leaveShowDesktop ();
        // the animation plugin does strange things here ...
        // if this notification is sent
        //cw->windowNotify (CompWindowNotifyLeaveShowDesktopMode);
      }
    }

    PluginAdapter::Default().OnLeaveDesktop();

    if (w)
    {
      CompPoint const& viewport = w->defaultViewport();

      if (viewport == uScreen->screen->vp())
        screen->leaveShowDesktopMode (w);
    }
    else
    {
      screen->focusDefaultWindow();
    }
  }
  else
  {
    CompWindow *cw = screen->findWindow (ShowdesktopHandler::InhibitingXid ());
    if (cw)
    {
      if (cw->inShowDesktopMode ())
      {
        UnityWindow::get (cw)->leaveShowDesktop ();
      }
    }
  }
}

bool UnityScreen::DoesPointIntersectUnityGeos(nux::Point const& pt)
{
  auto launchers = launcher_controller_->launchers();
  for (auto launcher : launchers)
  {
    nux::Geometry hud_geo = launcher->GetAbsoluteGeometry();

    if (launcher->Hidden())
      continue;

    if (hud_geo.IsInside(pt))
    {
      return true;
    }
  }

  for (nux::Geometry const& panel_geo : panel_controller_->GetGeometries ())
  {
    if (panel_geo.IsInside(pt))
    {
      return true;
    }
  }

  return false;
}

LayoutWindow::Ptr UnityScreen::GetSwitcherDetailLayoutWindow(Window window) const
{
  LayoutWindow::Vector const& targets = switcher_controller_->ExternalRenderTargets();

  for (LayoutWindow::Ptr const& target : targets)
  {
    if (target->xid == window)
      return target;
  }

  return nullptr;
}

void UnityWindow::enterShowDesktop ()
{
  if (!mShowdesktopHandler)
    mShowdesktopHandler.reset(new ShowdesktopHandler(static_cast <ShowdesktopHandlerWindowInterface *>(this),
                                                     static_cast <compiz::WindowInputRemoverLockAcquireInterface *>(this)));

  window->setShowDesktopMode (true);
  mShowdesktopHandler->FadeOut ();
}

void UnityWindow::leaveShowDesktop ()
{
  if (mShowdesktopHandler)
  {
    mShowdesktopHandler->FadeIn ();
    window->setShowDesktopMode (false);
  }
}

void UnityWindow::activate ()
{
  ShowdesktopHandler::InhibitLeaveShowdesktopMode (window->id ());
  window->activate ();
  ShowdesktopHandler::AllowLeaveShowdesktopMode (window->id ());

  PluginAdapter::Default().OnLeaveDesktop();
}

void UnityWindow::DoEnableFocus ()
{
  window->focusSetEnabled (this, true);
}

void UnityWindow::DoDisableFocus ()
{
  window->focusSetEnabled (this, false);
}

bool UnityWindow::IsOverrideRedirect ()
{
  return window->overrideRedirect ();
}

bool UnityWindow::IsManaged ()
{
  return window->managed ();
}

bool UnityWindow::IsGrabbed ()
{
  return window->grabbed ();
}

bool UnityWindow::IsDesktopOrDock ()
{
  return (window->type () & (CompWindowTypeDesktopMask | CompWindowTypeDockMask));
}

bool UnityWindow::IsSkipTaskbarOrPager ()
{
  return (window->state () & (CompWindowStateSkipTaskbarMask | CompWindowStateSkipPagerMask));
}

bool UnityWindow::IsInShowdesktopMode ()
{
  return window->inShowDesktopMode ();
}

bool UnityWindow::IsHidden ()
{
  return window->state () & CompWindowStateHiddenMask;
}

bool UnityWindow::IsShaded ()
{
  return window->shaded ();
}

bool UnityWindow::IsMinimized ()
{
  return window->minimized ();
}

bool UnityWindow::CanBypassLockScreen() const
{
  if (window->type() == CompWindowTypePopupMenuMask &&
      uScreen->lockscreen_controller_->HasOpenMenu())
  {
    return true;
  }

  if (window == uScreen->onboard_)
    return true;

  return false;
}

void UnityWindow::DoOverrideFrameRegion(CompRegion &region)
{
  unsigned int oldUpdateFrameRegionIndex = window->updateFrameRegionGetCurrentIndex();

  window->updateFrameRegionSetCurrentIndex(MAXSHORT);
  window->updateFrameRegion(region);
  deco_win_->UpdateFrameRegion(region);
  window->updateFrameRegionSetCurrentIndex(oldUpdateFrameRegionIndex);
}

void UnityWindow::DoHide ()
{
  window->changeState (window->state () | CompWindowStateHiddenMask);
}

void UnityWindow::DoNotifyHidden ()
{
  window->windowNotify (CompWindowNotifyHide);
}

void UnityWindow::DoShow ()
{
  window->changeState (window->state () & ~(CompWindowStateHiddenMask));
}

void UnityWindow::DoNotifyShown ()
{
  window->windowNotify (CompWindowNotifyShow);
}

void UnityWindow::DoMoveFocusAway ()
{
  window->moveInputFocusToOtherWindow ();
}

ShowdesktopHandlerWindowInterface::PostPaintAction UnityWindow::DoHandleAnimations (unsigned int ms)
{
  ShowdesktopHandlerWindowInterface::PostPaintAction action = ShowdesktopHandlerWindowInterface::PostPaintAction::Wait;

  if (mShowdesktopHandler)
    action = mShowdesktopHandler->Animate (ms);

  return action;
}

void UnityWindow::DoAddDamage()
{
  cWindow->addDamage();
}

void UnityWindow::DoDeleteHandler ()
{
  mShowdesktopHandler.reset();

  window->updateFrameRegion();
}

compiz::WindowInputRemoverLock::Ptr
UnityWindow::GetInputRemover ()
{
  if (!input_remover_.expired ())
    return input_remover_.lock ();

  compiz::WindowInputRemoverLock::Ptr
      ret (new compiz::WindowInputRemoverLock (
             new compiz::WindowInputRemover (screen->dpy (),
                                             window->id (),
                                             window->id ())));
  input_remover_ = ret;
  return ret;
}

unsigned int
UnityWindow::GetNoCoreInstanceMask ()
{
  return PAINT_WINDOW_NO_CORE_INSTANCE_MASK;
}

bool UnityWindow::handleEvent(XEvent *event)
{
  bool handled = false;

  switch(event->type)
  {
    case MotionNotify:
      if (close_icon_state_ != decoration::WidgetState::PRESSED)
      {
        auto old_state = close_icon_state_;

        if (close_button_geo_.IsPointInside(event->xmotion.x_root, event->xmotion.y_root))
        {
          close_icon_state_ = decoration::WidgetState::PRELIGHT;
        }
        else
        {
          close_icon_state_ = decoration::WidgetState::NORMAL;
        }

        if (old_state != close_icon_state_)
        {
          cWindow->addDamageRect(CompRectFromNuxGeo(close_button_geo_));
        }
      }
      break;

    case ButtonPress:
      if (event->xbutton.button == Button1 &&
          close_button_geo_.IsPointInside(event->xbutton.x_root, event->xbutton.y_root))
      {
        close_icon_state_ = decoration::WidgetState::PRESSED;
        cWindow->addDamageRect(CompRectFromNuxGeo(close_button_geo_));
        handled = true;
      }
      else if (event->xbutton.button == Button2 &&
              (GetScaledGeometry().IsPointInside(event->xbutton.x_root, event->xbutton.y_root) ||
               GetLayoutWindowGeometry().IsPointInside(event->xbutton.x_root, event->xbutton.y_root)))
      {
        middle_clicked_ = true;
        handled = true;
      }
      break;

    case ButtonRelease:
      {
        bool was_pressed = (close_icon_state_ == decoration::WidgetState::PRESSED);

        if (close_icon_state_ != decoration::WidgetState::NORMAL)
        {
          close_icon_state_ = decoration::WidgetState::NORMAL;
          cWindow->addDamageRect(CompRectFromNuxGeo(close_button_geo_));
        }

        if (was_pressed)
        {
          if (close_button_geo_.IsPointInside(event->xbutton.x_root, event->xbutton.y_root))
          {
            window->close(0);
            handled = true;
          }
        }

        if (middle_clicked_)
        {
          if (event->xbutton.button == Button2 &&
             (GetScaledGeometry().IsPointInside(event->xbutton.x_root, event->xbutton.y_root) ||
              GetLayoutWindowGeometry().IsPointInside(event->xbutton.x_root, event->xbutton.y_root)))
          {
            window->close(0);
            handled = true;
          }

          middle_clicked_ = false;
        }
      }
      break;

    default:
      if (!event->xany.send_event && screen->XShape() &&
          event->type == screen->shapeEvent() + ShapeNotify)
      {
        if (mShowdesktopHandler)
        {
          mShowdesktopHandler->HandleShapeEvent();
          handled = true;
        }
      }
  }

  return handled;
}

/* called whenever we need to repaint parts of the screen */
bool UnityScreen::glPaintOutput(const GLScreenPaintAttrib& attrib,
                                const GLMatrix& transform,
                                const CompRegion& region,
                                CompOutput* output,
                                unsigned int mask)
{
  bool ret;

  /*
   * Very important!
   * Don't waste GPU and CPU rendering the shell on every frame if you don't
   * need to. Doing so on every frame causes Nux to hog the GPU and slow down
   * ALL rendering. (LP: #988079)
   */
  bool force = forcePaintOnTop();
  doShellRepaint = force ||
                   ( !region.isEmpty() &&
                     ( !wt->GetDrawList().empty() ||
                       !wt->GetPresentationListGeometries().empty() ||
                       (mask & PAINT_SCREEN_FULL_MASK)
                     )
                   );

  allowWindowPaint = true;
  _last_output = output;
  paint_panel_under_dash_ = false;

  // CompRegion has no clear() method. So this is the fastest alternative.
  fullscreenRegion = CompRegion();
  nuxRegion = CompRegion();
  windows_for_monitor_.clear();

  /* glPaintOutput is part of the opengl plugin, so we need the GLScreen base class. */
  ret = gScreen->glPaintOutput(attrib, transform, region, output, mask);

  if (doShellRepaint && !force && fullscreenRegion.contains(*output))
    doShellRepaint = false;

  if (doShellRepaint)
    paintDisplay();

  return ret;
}

/* called whenever a plugin needs to paint the entire scene
 * transformed */

void UnityScreen::glPaintTransformedOutput(const GLScreenPaintAttrib& attrib,
                                           const GLMatrix& transform,
                                           const CompRegion& region,
                                           CompOutput* output,
                                           unsigned int mask)
{
  allowWindowPaint = false;

  /* PAINT_SCREEN_FULL_MASK means that we are ignoring the damage
   * region and redrawing the whole screen, so we should make all
   * nux windows be added to the presentation list that intersect
   * this output.
   *
   * However, damaging nux has a side effect of notifying compiz
   * through onRedrawRequested that we need to queue another frame.
   * In most cases that would be desirable, and in the case where
   * we did that in damageCutoff, it would not be a problem as compiz
   * does not queue up new frames for damage that can be processed
   * on the current frame. However, we're now past damage cutoff, but
   * a change in circumstances has required that we redraw all the nux
   * windows on this frame. As such, we need to ensure that damagePending
   * is not called as a result of queuing windows for redraw, as that
   * would effectively result in a damage feedback loop in plugins that
   * require screen transformations (eg, new frame -> plugin redraws full
   * screen -> we reach this point and request another redraw implicitly)
   */
  if (mask & PAINT_SCREEN_FULL_MASK)
  {
    ignore_redraw_request_ = true;
    compizDamageNux(CompRegionRef(output->region()));
    ignore_redraw_request_ = false;
  }

  gScreen->glPaintTransformedOutput(attrib, transform, region, output, mask);
  paintPanelShadow(region);
}

void UnityScreen::updateBlurDamage()
{
  /* If there are enabled helpers, we want to apply damage
   * based on how old our tracking fbo is since we may need
   * to redraw some of the blur regions if there has been
   * damage since we last bound it
   *
   * XXX: Unfortunately there's a nasty feedback loop here, and not
   * a whole lot we can do about it. If part of the damage from any frame
   * intersects a nux window, we have to mark the entire region that the
   * nux window covers as damaged, because nux does not have any concept
   * of geometry clipping. That damage will feed back to us on the next frame.
   */
  if (BackgroundEffectHelper::HasEnabledHelpers())
  {
    cScreen->applyDamageForFrameAge(back_buffer_age_);

    /*
     * Prioritise user interaction over active blur updates. So the general
     * slowness of the active blur doesn't affect the UI interaction performance.
     *
     * Also, BackgroundEffectHelper::ProcessDamage() is causing a feedback loop
     * while the dash is open. Calling it results in the NEXT frame (and the
     * current one?) to get some damage. This GetDrawList().empty() check avoids
     * that feedback loop and allows us to idle correctly.
     *
     * We are doing damage processing for the blurs here, as this represents
     * the most up to date compiz damage under the nux windows.
     */
    if (wt->GetDrawList().empty())
    {
      CompRect::vector const& rects(buffered_compiz_damage_this_frame_.rects());
      for (CompRect const& r : rects)
      {
        BackgroundEffectHelper::ProcessDamage(NuxGeometryFromCompRect(r));
      }
    }
  }
}

void UnityScreen::damageCutoff()
{
  if (force_draw_countdown_ > 0)
  {
    typedef nux::WindowCompositor::WeakBaseWindowPtr WeakBaseWindowPtr;

    /* We have to force-redraw the whole scene because
     * of a bug in the nvidia driver that causes framebuffers
     * to be trashed on resume for a few swaps */
    wt->GetWindowCompositor().ForEachBaseWindow([] (WeakBaseWindowPtr const& w) {
      w->QueueDraw();
    });

    --force_draw_countdown_;
  }

  /* At this point we want to take all of the compiz damage
   * for this frame and use it to determine which blur regions
   * need to be redrawn. We don't want to do this any later because
   * the nux damage is logically on top of the blurs and doesn't
   * affect them */
  updateBlurDamage();

  /* Determine nux region damage last */
  cScreen->damageCutoff();

  CompRegion damage_buffer, last_damage_buffer;

  do
  {
    last_damage_buffer = damage_buffer;

    /* First apply any damage accumulated to nux to see
     * what windows need to be redrawn there */
    compizDamageNux(buffered_compiz_damage_this_frame_);

    /* Apply the redraw regions to compiz so that we can
     * draw this frame with that region included */
    determineNuxDamage(damage_buffer);

    /* We want to track the nux damage here as we will use it to
     * determine if we need to present other nux windows too */
    cScreen->damageRegion(damage_buffer);

    /* If we had to put more damage into the damage buffer then
     * damage compiz with it and keep going */
  } while (last_damage_buffer != damage_buffer);

  /* Clear damage buffer */
  buffered_compiz_damage_last_frame_ = buffered_compiz_damage_this_frame_;
  buffered_compiz_damage_this_frame_ = CompRegion();

  /* Tell nux that any damaged windows should be redrawn on the next
   * frame and not this one */
  wt->ForeignFrameCutoff();

  /* We need to track this per-frame to figure out whether or not
   * to bind the contents fbo on each monitor pass */
  dirty_helpers_on_this_frame_ = BackgroundEffectHelper::HasDirtyHelpers();
}

void UnityScreen::preparePaint(int ms)
{
  cScreen->preparePaint(ms);

  big_tick_ += ms*1000;
  tick_source_->tick(big_tick_);

  for (ShowdesktopHandlerWindowInterface *wi : ShowdesktopHandler::animating_windows)
    wi->HandleAnimations (ms);

  didShellRepaint = false;
  panelShadowPainted = CompRegion();
  firstWindowAboveShell = NULL;
}

void UnityScreen::donePaint()
{
  /*
   * It's only safe to clear the draw list if drawing actually occurred
   * (i.e. the shell was not obscured behind a fullscreen window).
   * If you clear the draw list and drawing has not occured then you'd be
   * left with all your views thinking they're queued for drawing still and
   * would refuse to redraw when you return from fullscreen.
   * I think this is a Nux bug. ClearDrawList should ideally also mark all
   * the queued views as draw_cmd_queued_=false.
   */

  /* To prevent any potential overflow problems, we are assuming here
   * that compiz caps the maximum number of frames tracked at 10, so
   * don't increment the age any more than local::MAX_BUFFER_AGE */
  if (back_buffer_age_ < local::MAX_BUFFER_AGE)
    ++back_buffer_age_;

  if (didShellRepaint)
    wt->ClearDrawList();

  /* Tell nux that a new frame is now beginning and any damaged windows should
   * now be painted on this frame */
  wt->ForeignFrameEnded();

  if (animation_controller_->HasRunningAnimations())
    onRedrawRequested();

  for (auto it = ShowdesktopHandler::animating_windows.begin(); it != ShowdesktopHandler::animating_windows.end();)
  {
    auto const& wi = *it;
    auto action = wi->HandleAnimations(0);

    if (action == ShowdesktopHandlerWindowInterface::PostPaintAction::Remove)
    {
      wi->DeleteHandler();
      it = ShowdesktopHandler::animating_windows.erase(it);
      continue;
    }
    else if (action == ShowdesktopHandlerWindowInterface::PostPaintAction::Damage)
    {
      wi->AddDamage();
    }

    ++it;
  }

  cScreen->donePaint();
}

void redraw_view_if_damaged(nux::ObjectPtr<CairoBaseWindow> const& view, CompRegion const& damage)
{
  if (!view || view->IsRedrawNeeded())
    return;

  auto const& geo = view->GetAbsoluteGeometry();

  if (damage.intersects(CompRectFromNuxGeo(geo)))
    view->RedrawBlur();
}

void UnityScreen::compizDamageNux(CompRegion const& damage)
{
  /* Ask nux to present anything in our damage region
   *
   * Note: This is using a new nux API, to "present" windows
   * to the screen, as opposed to drawing them. The difference is
   * important. The former will just draw the window backing texture
   * directly to the screen, the latter will re-draw the entire window.
   *
   * The former is a lot faster, do not use QueueDraw unless the contents
   * of the window need to be re-drawn.
   */
  auto const& rects = damage.rects();

  for (CompRect const& r : rects)
  {
    auto const& geo = NuxGeometryFromCompRect(r);
    wt->PresentWindowsIntersectingGeometryOnThisFrame(geo);
  }
  
  auto const& launchers = launcher_controller_->launchers();

  for (auto const& launcher : launchers)
  {
    if (!launcher->Hidden())
    {
      redraw_view_if_damaged(launcher->GetActiveTooltip(), damage);
    }
  }

  if (QuicklistManager* qm = QuicklistManager::Default())
  {
    redraw_view_if_damaged(qm->Current(), damage);
  }
}

/* Grab changed nux regions and add damage rects for them */
void UnityScreen::determineNuxDamage(CompRegion& nux_damage)
{
  /* Fetch all the dirty geometry from nux and aggregate it */
  auto const& dirty = wt->GetPresentationListGeometries();
  auto const& panels_geometries = panel_controller_->GetGeometries();

  for (auto const& dirty_geo : dirty)
  {
    nux_damage += CompRegionFromNuxGeo(dirty_geo);

    /* Special case, we need to redraw the panel shadow on panel updates */
    for (auto const& panel_geo : panels_geometries)
    {
      if (!dirty_geo.IsIntersecting(panel_geo))
        continue;

      for (CompOutput const& o : screen->outputDevs())
      {
        CompRect shadowRect;
        FillShadowRectForOutput(shadowRect, o);
        nux_damage += shadowRect;
      }
    }
  }
}

void UnityScreen::addSupportedAtoms(std::vector<Atom>& atoms)
{
  screen->addSupportedAtoms(atoms);
  deco_manager_->AddSupportedAtoms(atoms);
}

/* handle X Events */
void UnityScreen::handleEvent(XEvent* event)
{
  bool skip_other_plugins = false;
  PluginAdapter& wm = PluginAdapter::Default();

  if (deco_manager_->HandleEventBefore(event))
    return;

  switch (event->type)
  {
    case FocusIn:
    case FocusOut:
      if (event->xfocus.mode == NotifyGrab)
        wm.OnScreenGrabbed();
      else if (event->xfocus.mode == NotifyUngrab)
        wm.OnScreenUngrabbed();
      else if (!screen->grabbed() && event->xfocus.mode == NotifyWhileGrabbed)
        wm.OnScreenGrabbed();

      if (_key_nav_mode_requested)
      {
        // Close any overlay that is open.
        if (launcher_controller_->IsOverlayOpen())
        {
          dash_controller_->HideDash();
          hud_controller_->HideHud();
        }
        launcher_controller_->KeyNavGrab();
      }
      _key_nav_mode_requested = false;
      break;
    case MotionNotify:
      if (wm.IsScaleActive())
      {
        if (CompWindow *w = screen->findWindow(sScreen->getSelectedWindow()))
          skip_other_plugins = UnityWindow::get(w)->handleEvent(event);
      }
      else if (switcher_controller_->detail())
      {
        Window win = switcher_controller_->GetCurrentSelection().window_;
        CompWindow* w = screen->findWindow(win);

        if (w)
          skip_other_plugins = UnityWindow::get(w)->handleEvent(event);
      }
      break;
    case ButtonPress:
      if (shortcut_controller_->Visible())
      {
        shortcut_controller_->Hide();
      }

      if (super_keypressed_)
      {
        launcher_controller_->KeyNavTerminate(false);
        EnableCancelAction(CancelActionTarget::LAUNCHER_SWITCHER, false);
      }
      if (wm.IsScaleActive())
      {
        if (spread_filter_ && spread_filter_->Visible())
          skip_other_plugins = spread_filter_->GetAbsoluteGeometry().IsPointInside(event->xbutton.x_root, event->xbutton.y_root);

        if (!skip_other_plugins)
        {
          if (CompWindow *w = screen->findWindow(sScreen->getSelectedWindow()))
            skip_other_plugins = UnityWindow::get(w)->handleEvent(event);
        }
      }
      else if (switcher_controller_->detail())
      {
        Window win = switcher_controller_->GetCurrentSelection().window_;
        CompWindow* w = screen->findWindow(win);

        if (w)
          skip_other_plugins = UnityWindow::get(w)->handleEvent(event);
      }

      if (dash_controller_->IsVisible())
      {
        int panel_height = panel_style_.PanelHeight(dash_controller_->Monitor());
        nux::Point pt(event->xbutton.x_root, event->xbutton.y_root);
        nux::Geometry const& dash = dash_controller_->GetInputWindowGeometry();
        nux::Geometry const& dash_geo = nux::Geometry(dash.x, dash.y, dash.width,
                                                      dash.height + panel_height);

        Window dash_xid = dash_controller_->window()->GetInputWindowId();
        Window top_xid = wm.GetTopWindowAbove(dash_xid);
        nux::Geometry const& always_on_top_geo = wm.GetWindowGeometry(top_xid);

        bool indicator_clicked = panel_controller_->IsMouseInsideIndicator(pt);
        bool outside_dash = !dash_geo.IsInside(pt) && !DoesPointIntersectUnityGeos(pt);

        if ((outside_dash || indicator_clicked) && !always_on_top_geo.IsInside(pt))
        {
          if (indicator_clicked)
          {
            // We must skip the Dash hide animation, otherwise the indicators
            // wont recive the mouse click event
            dash_controller_->QuicklyHideDash();
          }
          else
          {
            dash_controller_->HideDash();
          }
        }
      }
      else if (hud_controller_->IsVisible())
      {
        nux::Point pt(event->xbutton.x_root, event->xbutton.y_root);
        nux::Geometry const& hud_geo = hud_controller_->GetInputWindowGeometry();

        Window hud_xid = hud_controller_->window()->GetInputWindowId();
        Window top_xid = wm.GetTopWindowAbove(hud_xid);
        nux::Geometry const& on_top_geo = wm.GetWindowGeometry(top_xid);

        if (!hud_geo.IsInside(pt) && !DoesPointIntersectUnityGeos(pt) && !on_top_geo.IsInside(pt))
        {
          hud_controller_->HideHud();
        }
      }
      else if (switcher_controller_->Visible())
      {
        nux::Point pt(event->xbutton.x_root, event->xbutton.y_root);
        nux::Geometry const& switcher_geo = switcher_controller_->GetInputWindowGeometry();

        if (!switcher_geo.IsInside(pt))
        {
          switcher_controller_->Hide(false);
        }
      }
      break;
    case ButtonRelease:

      if (switcher_controller_->detail())
      {
        Window win = switcher_controller_->GetCurrentSelection().window_;
        CompWindow* w = screen->findWindow(win);

        if (w)
          skip_other_plugins = UnityWindow::get(w)->handleEvent(event);
      }
      else if (wm.IsScaleActive())
      {
        if (spread_filter_ && spread_filter_->Visible())
          skip_other_plugins = spread_filter_->GetAbsoluteGeometry().IsPointInside(event->xbutton.x_root, event->xbutton.y_root);

        if (!skip_other_plugins)
        {
          if (CompWindow *w = screen->findWindow(sScreen->getSelectedWindow()))
            skip_other_plugins = skip_other_plugins || UnityWindow::get(w)->handleEvent(event);
        }
      }
      break;
    case KeyPress:
    {
      if (shortcut_controller_->Visible())
      {
        shortcut_controller_->Hide();
      }

      if (super_keypressed_)
      {
        /* We need an idle to postpone this action, after the current event
         * has been processed */
        sources_.AddIdle([this] {
          shortcut_controller_->SetEnabled(false);
          shortcut_controller_->Hide();
          LOG_DEBUG(logger) << "Hiding shortcut controller due to keypress event.";
          EnableCancelAction(CancelActionTarget::SHORTCUT_HINT, false);

          return false;
        });
      }

      KeySym key_sym = XkbKeycodeToKeysym(event->xany.display, event->xkey.keycode, 0, 0);

      if (launcher_controller_->KeyNavIsActive())
      {
        if (key_sym == XK_Up)
        {
          launcher_controller_->KeyNavPrevious();
          break;
        }
        else if (key_sym == XK_Down)
        {
          launcher_controller_->KeyNavNext();
          break;
        }
      }
      else if (switcher_controller_->Visible())
      {
        auto const& close_key = wm.close_window_key();

        if (key_sym == close_key.second && XModifiersToNux(event->xkey.state) == close_key.first)
        {
          switcher_controller_->Hide(false);
          skip_other_plugins = true;
          break;
        }
      }

      if (super_keypressed_)
      {
        if (IsKeypadKey(key_sym))
        {
          key_sym = XkbKeycodeToKeysym(event->xany.display, event->xkey.keycode, 0, 1);
          key_sym = key_sym - XK_KP_0 + XK_0;
        }

        skip_other_plugins = launcher_controller_->HandleLauncherKeyEvent(XModifiersToNux(event->xkey.state), key_sym, event->xkey.time);
        if (!skip_other_plugins)
          skip_other_plugins = dash_controller_->CheckShortcutActivation(XKeysymToString(key_sym));

        if (skip_other_plugins && launcher_controller_->KeyNavIsActive())
        {
          launcher_controller_->KeyNavTerminate(false);
          EnableCancelAction(CancelActionTarget::LAUNCHER_SWITCHER, false);
        }
      }

      if (spread_filter_ && spread_filter_->Visible())
      {
        if (key_sym == XK_Escape)
        {
          skip_other_plugins = true;
          spread_filter_->text = "";
        }
      }

      break;
    }
    case MapRequest:
      ShowdesktopHandler::InhibitLeaveShowdesktopMode (event->xmaprequest.window);
      break;
    case PropertyNotify:
      if (bghash_ && event->xproperty.window == GDK_ROOT_WINDOW() &&
          event->xproperty.atom == bghash_->ColorAtomId())
      {
        bghash_->RefreshColor();
      }
      break;
    default:
        if (screen->shapeEvent() + ShapeNotify == event->type)
        {
          Window xid = event->xany.window;
          CompWindow *w = screen->findWindow(xid);

          if (w)
          {
            UnityWindow *uw = UnityWindow::get(w);
            uw->handleEvent(event);
          }
        }
      break;
  }

  compiz::CompizMinimizedWindowHandler<UnityScreen, UnityWindow>::handleEvent(event);

  // avoid further propagation (key conflict for instance)
  if (!skip_other_plugins)
    screen->handleEvent(event);

  if (deco_manager_->HandleEventAfter(event))
    return;

  if (event->type == MapRequest)
    ShowdesktopHandler::AllowLeaveShowdesktopMode(event->xmaprequest.window);

  if (switcher_controller_->IsMouseDisabled() && switcher_controller_->Visible() &&
      (event->type == MotionNotify || event->type == ButtonPress || event->type == ButtonRelease))
  {
    skip_other_plugins = true;
  }

  if (spread_filter_ && spread_filter_->Visible())
    skip_other_plugins = false;

  if (!skip_other_plugins &&
      screen->otherGrabExist("deco", "move", "switcher", "resize", nullptr))
  {
    wt->ProcessForeignEvent(event, nullptr);
  }
}

void UnityScreen::damageRegion(const CompRegion &region)
{
  buffered_compiz_damage_this_frame_ += region;
  cScreen->damageRegion(region);
}

void UnityScreen::handleCompizEvent(const char* plugin,
                                    const char* event,
                                    CompOption::Vector& option)
{
  PluginAdapter& adapter = PluginAdapter::Default();
  adapter.NotifyCompizEvent(plugin, event, option);
  compiz::CompizMinimizedWindowHandler<UnityScreen, UnityWindow>::handleCompizEvent(plugin, event, option);
  screen->handleCompizEvent(plugin, event, option);
}

bool UnityScreen::showMenuBarInitiate(CompAction* action,
                                      CompAction::State state,
                                      CompOption::Vector& options)
{
  if (state & CompAction::StateInitKey)
  {
    action->setState(action->state() | CompAction::StateTermKey);
    menus_->show_menus = true;
  }

  return false;
}

bool UnityScreen::showMenuBarTerminate(CompAction* action,
                                       CompAction::State state,
                                       CompOption::Vector& options)
{
  if (state & CompAction::StateTermKey)
  {
    action->setState(action->state() & ~CompAction::StateTermKey);
    menus_->show_menus = false;
  }

  return false;
}

bool UnityScreen::showLauncherKeyInitiate(CompAction* action,
                                          CompAction::State state,
                                          CompOption::Vector& options)
{
  // to receive the Terminate event
  if (state & CompAction::StateInitKey)
    action->setState(action->state() | CompAction::StateTermKey);

  super_keypressed_ = true;
  int when = options[7].value().i();  // XEvent time in millisec
  launcher_controller_->HandleLauncherKeyPress(when);
  EnsureSuperKeybindings ();

  if (!shortcut_controller_->Visible() &&
      shortcut_controller_->IsEnabled())
  {
    if (shortcut_controller_->Show())
    {
      LOG_DEBUG(logger) << "Showing shortcut hint.";
      EnableCancelAction(CancelActionTarget::SHORTCUT_HINT, true, action->key().modifiers());
    }
  }

  return true;
}

bool UnityScreen::showLauncherKeyTerminate(CompAction* action,
                                           CompAction::State state,
                                           CompOption::Vector& options)
{
  // Remember StateCancel and StateCommit will be broadcast to all actions
  // so we need to verify that we are actually being toggled...
  if (!(state & CompAction::StateTermKey))
    return false;

  if (state & CompAction::StateCancel)
    return false;

  bool was_tap = state & CompAction::StateTermTapped;
  bool tap_handled = false;
  LOG_DEBUG(logger) << "Super released: " << (was_tap ? "tapped" : "released");
  int when = options[7].value().i();  // XEvent time in millisec

  // hack...if the scale just wasn't activated AND the 'when' time is within time to start the
  // dash then assume was_tap is also true, since the ScalePlugin doesn't accept that state...
  PluginAdapter& adapter = PluginAdapter::Default();
  if (adapter.IsScaleActive() && !scale_just_activated_ &&
      launcher_controller_->AboutToShowDash(true, when))
  {
    adapter.TerminateScale();
    was_tap = true;
  }
  else if (scale_just_activated_)
  {
    scale_just_activated_ = false;
  }

  if (launcher_controller_->AboutToShowDash(was_tap, when))
  {
    if (hud_controller_->IsVisible())
    {
      hud_controller_->HideHud();
    }

    if (QuicklistManager::Default()->Current())
    {
      QuicklistManager::Default()->Current()->Hide();
    }

    if (!dash_controller_->IsVisible())
    {
      if (dash_controller_->ShowDash())
      {
        tap_handled = true;
        ubus_manager_.SendMessage(UBUS_PLACE_ENTRY_ACTIVATE_REQUEST,
                                  g_variant_new("(sus)", "home.scope", dash::GOTO_DASH_URI, ""));
      }
    }
    else
    {
      dash_controller_->HideDash();
      tap_handled = true;
    }
  }

  super_keypressed_ = false;
  launcher_controller_->KeyNavTerminate(true);
  launcher_controller_->HandleLauncherKeyRelease(was_tap, when);
  EnableCancelAction(CancelActionTarget::LAUNCHER_SWITCHER, false);

  shortcut_controller_->SetEnabled(optionGetShortcutOverlay());
  shortcut_controller_->Hide();
  LOG_DEBUG(logger) << "Hiding shortcut controller";
  EnableCancelAction(CancelActionTarget::SHORTCUT_HINT, false);

  action->setState (action->state() & (unsigned)~(CompAction::StateTermKey));
  return (was_tap && tap_handled) || !was_tap;
}

bool UnityScreen::showPanelFirstMenuKeyInitiate(CompAction* action,
                                                CompAction::State state,
                                                CompOption::Vector& options)
{
  /* In order to avoid too many events when keeping the keybinding pressed,
   * that would make the unity-panel-service to go crazy (see bug #948522)
   * we need to filter them, just considering an event every 750 ms */
  int event_time = options[7].value().i();  // XEvent time in millisec

  if (event_time - first_menu_keypress_time_ < 750)
  {
    first_menu_keypress_time_ = event_time;
    return false;
  }

  first_menu_keypress_time_ = event_time;

  /* Even if we do nothing on key terminate, we must enable it, not to to hide
   * the menus entries after that a menu has been shown and hidden via the
   * keyboard and the Alt key is still pressed */
  action->setState(action->state() | CompAction::StateTermKey);
  menus_->open_first.emit();

  return true;
}

bool UnityScreen::showPanelFirstMenuKeyTerminate(CompAction* action,
                                                 CompAction::State state,
                                                 CompOption::Vector& options)
{
  action->setState (action->state() & (unsigned)~(CompAction::StateTermKey));
  return true;
}

void UnityScreen::SendExecuteCommand()
{
  if (hud_controller_->IsVisible())
  {
    hud_controller_->HideHud();
  }

  PluginAdapter& adapter = PluginAdapter::Default();
  if (adapter.IsScaleActive())
  {
    adapter.TerminateScale();
  }

  if (dash_controller_->IsCommandLensOpen())
  {
    ubus_manager_.SendMessage(UBUS_OVERLAY_CLOSE_REQUEST);
  }
  else
  {
    ubus_manager_.SendMessage(UBUS_DASH_ABOUT_TO_SHOW, NULL, glib::Source::Priority::HIGH);

    ubus_manager_.SendMessage(UBUS_PLACE_ENTRY_ACTIVATE_REQUEST,
                              g_variant_new("(sus)", "commands.scope", dash::ScopeHandledType::GOTO_DASH_URI, ""),
                              glib::Source::Priority::LOW);
  }
}

bool UnityScreen::executeCommand(CompAction* action,
                                 CompAction::State state,
                                 CompOption::Vector& options)
{
  SendExecuteCommand();
  return true;
}

bool UnityScreen::showDesktopKeyInitiate(CompAction* action,
                                         CompAction::State state,
                                         CompOption::Vector& options)
{
  WindowManager::Default().ShowDesktop();
  return true;
}

bool UnityScreen::setKeyboardFocusKeyInitiate(CompAction* action,
                                              CompAction::State state,
                                              CompOption::Vector& options)
{
  _key_nav_mode_requested = true;
  return true;
}

bool UnityScreen::altTabInitiateCommon(CompAction* action, switcher::ShowMode show_mode)
{
  if (!grab_index_)
  {
    if (switcher_controller_->IsMouseDisabled())
    {
      grab_index_ = screen->pushGrab (screen->invisibleCursor(), "unity-switcher");
    }
    else
    {
      grab_index_ = screen->pushGrab (screen->normalCursor(), "unity-switcher");
    }
  }

  launcher_controller_->ClearTooltips();

  /* Create a new keybinding for scroll buttons and current modifiers */
  CompAction scroll_up;
  CompAction scroll_down;
  scroll_up.setButton(CompAction::ButtonBinding(local::SCROLL_UP_BUTTON, action->key().modifiers()));
  scroll_down.setButton(CompAction::ButtonBinding(local::SCROLL_DOWN_BUTTON, action->key().modifiers()));
  screen->addAction(&scroll_up);
  screen->addAction(&scroll_down);

  menus_->show_menus = false;
  SetUpAndShowSwitcher(show_mode);

  return true;
}

void UnityScreen::SetUpAndShowSwitcher(switcher::ShowMode show_mode)
{
  RaiseInputWindows();

  if (!optionGetAltTabBiasViewport())
  {
    if (show_mode == switcher::ShowMode::CURRENT_VIEWPORT)
      show_mode = switcher::ShowMode::ALL;
    else
      show_mode = switcher::ShowMode::CURRENT_VIEWPORT;
  }

  auto results = launcher_controller_->GetAltTabIcons(show_mode == switcher::ShowMode::CURRENT_VIEWPORT,
                                                      switcher_controller_->IsShowDesktopDisabled());

  if (switcher_controller_->CanShowSwitcher(results))
    switcher_controller_->Show(show_mode, switcher::SortMode::FOCUS_ORDER, results);
}

bool UnityScreen::altTabTerminateCommon(CompAction* action,
                                       CompAction::State state,
                                       CompOption::Vector& options)
{
  if (grab_index_)
  {
    // remove grab before calling hide so workspace switcher doesn't fail
    screen->removeGrab(grab_index_, NULL);
    grab_index_ = 0;
  }

  /* Removing the scroll actions */
  CompAction scroll_up;
  CompAction scroll_down;
  scroll_up.setButton(CompAction::ButtonBinding(local::SCROLL_UP_BUTTON, action->key().modifiers()));
  scroll_down.setButton(CompAction::ButtonBinding(local::SCROLL_DOWN_BUTTON, action->key().modifiers()));
  screen->removeAction(&scroll_up);
  screen->removeAction(&scroll_down);

  bool accept_state = (state & CompAction::StateCancel) == 0;
  switcher_controller_->Hide(accept_state);

  action->setState (action->state() & (unsigned)~(CompAction::StateTermKey));
  return true;
}

bool UnityScreen::altTabForwardInitiate(CompAction* action,
                                        CompAction::State state,
                                        CompOption::Vector& options)
{
  if (switcher_controller_->Visible())
    switcher_controller_->Next();
  else
    altTabInitiateCommon(action, switcher::ShowMode::CURRENT_VIEWPORT);

  action->setState(action->state() | CompAction::StateTermKey);
  return true;
}

bool UnityScreen::altTabForwardAllInitiate(CompAction* action,
                                        CompAction::State state,
                                        CompOption::Vector& options)
{
  if (WindowManager::Default().IsWallActive())
    return false;
  else if (switcher_controller_->Visible())
    switcher_controller_->Next();
  else
    altTabInitiateCommon(action, switcher::ShowMode::ALL);

  action->setState(action->state() | CompAction::StateTermKey);
  return true;
}

bool UnityScreen::altTabPrevAllInitiate(CompAction* action, CompAction::State state, CompOption::Vector& options)
{
  if (switcher_controller_->Visible())
  {
    switcher_controller_->Prev();
    return true;
  }

  return false;
}

bool UnityScreen::altTabPrevInitiate(CompAction* action, CompAction::State state, CompOption::Vector& options)
{
  if (switcher_controller_->Visible())
  {
    switcher_controller_->Prev();
    return true;
  }

  return false;
}

bool UnityScreen::altTabNextWindowInitiate(CompAction* action, CompAction::State state, CompOption::Vector& options)
{
  if (!switcher_controller_->Visible())
  {
    altTabInitiateCommon(action, switcher::ShowMode::CURRENT_VIEWPORT);
    switcher_controller_->Select((switcher_controller_->StartIndex())); // always select the current application
    switcher_controller_->InitiateDetail();
  }
  else if (switcher_controller_->detail())
  {
    switcher_controller_->NextDetail();
  }
  else
  {
    switcher_controller_->detail = true;
  }

  action->setState(action->state() | CompAction::StateTermKey);
  return true;
}

bool UnityScreen::altTabPrevWindowInitiate(CompAction* action, CompAction::State state, CompOption::Vector& options)
{
  if (switcher_controller_->Visible())
  {
    switcher_controller_->PrevDetail();
    return true;
  }

  return false;
}

bool UnityScreen::launcherSwitcherForwardInitiate(CompAction* action, CompAction::State state, CompOption::Vector& options)
{
  if (!launcher_controller_->KeyNavIsActive())
  {
    int modifiers = action->key().modifiers();

    launcher_controller_->KeyNavActivate();

    EnableCancelAction(CancelActionTarget::LAUNCHER_SWITCHER, true, modifiers);

    KeyCode down_key = XKeysymToKeycode(screen->dpy(), XStringToKeysym("Down"));
    KeyCode up_key = XKeysymToKeycode(screen->dpy(), XStringToKeysym("Up"));

    CompAction down_action;
    down_action.setKey(CompAction::KeyBinding(down_key, modifiers));
    screen->addAction(&down_action);

    CompAction up_action;
    up_action.setKey(CompAction::KeyBinding(up_key, modifiers));
    screen->addAction(&up_action);
  }
  else
  {
    launcher_controller_->KeyNavNext();
  }

  action->setState(action->state() | CompAction::StateTermKey);
  return true;
}

bool UnityScreen::launcherSwitcherPrevInitiate(CompAction* action, CompAction::State state, CompOption::Vector& options)
{
  launcher_controller_->KeyNavPrevious();

  return true;
}

bool UnityScreen::launcherSwitcherTerminate(CompAction* action, CompAction::State state, CompOption::Vector& options)
{
  bool accept_state = (state & CompAction::StateCancel) == 0;
  launcher_controller_->KeyNavTerminate(accept_state);

  EnableCancelAction(CancelActionTarget::LAUNCHER_SWITCHER, false);

  KeyCode down_key = XKeysymToKeycode(screen->dpy(), XStringToKeysym("Down"));
  KeyCode up_key = XKeysymToKeycode(screen->dpy(), XStringToKeysym("Up"));

  CompAction down_action;
  down_action.setKey(CompAction::KeyBinding(down_key, action->key().modifiers()));
  screen->removeAction(&down_action);

  CompAction up_action;
  up_action.setKey(CompAction::KeyBinding(up_key, action->key().modifiers()));
  screen->removeAction(&up_action);

  action->setState (action->state() & (unsigned)~(CompAction::StateTermKey));
  return true;
}

void UnityScreen::OnLauncherStartKeyNav(GVariant* data)
{
  // Put the launcher BaseWindow at the top of the BaseWindow stack. The
  // input focus coming from the XinputWindow will be processed by the
  // launcher BaseWindow only. Then the Launcher BaseWindow will decide
  // which View will get the input focus.
  if (SaveInputThenFocus(launcher_controller_->KeyNavLauncherInputWindowId()))
    launcher_controller_->PushToFront();
}

void UnityScreen::OnLauncherEndKeyNav(GVariant* data)
{
  // Return input-focus to previously focused window (before key-nav-mode was
  // entered)
  if (data && g_variant_get_boolean(data))
    PluginAdapter::Default().RestoreInputFocus();
}

void UnityScreen::OnSwitcherDetailChanged(bool detail)
{
  if (detail)
  {
    for (LayoutWindow::Ptr const& target : switcher_controller_->ExternalRenderTargets())
    {
      if (CompWindow* window = screen->findWindow(target->xid))
      {
        auto* uwin = UnityWindow::get(window);
        uwin->close_icon_state_ = decoration::WidgetState::NORMAL;
        uwin->middle_clicked_ = false;
        fake_decorated_windows_.insert(uwin);
      }
    }
  }
  else
  {
    for (UnityWindow* uwin : fake_decorated_windows_)
      uwin->CleanupCachedTextures();

    fake_decorated_windows_.clear();
  }
}

bool UnityScreen::SaveInputThenFocus(const guint xid)
{
  // get CompWindow*
  newFocusedWindow = screen->findWindow(xid);

  // check if currently focused window isn't it self
  if (xid != screen->activeWindow())
    PluginAdapter::Default().SaveInputFocus();

  // set input-focus on window
  if (newFocusedWindow)
  {
    newFocusedWindow->moveInputFocusTo();
    return true;
  }
  return false;
}

bool UnityScreen::ShowHud()
{
  if (switcher_controller_->Visible())
  {
    LOG_ERROR(logger) << "Switcher is visible when showing HUD: this should never happen";
    return false; // early exit if the switcher is open
  }

  if (hud_controller_->IsVisible())
  {
    hud_controller_->HideHud();
  }
  else
  {
    // Handles closing KeyNav (Alt+F1) if the hud is about to show
    if (launcher_controller_->KeyNavIsActive())
      launcher_controller_->KeyNavTerminate(false);

    if (dash_controller_->IsVisible())
      dash_controller_->HideDash();

    if (QuicklistManager::Default()->Current())
      QuicklistManager::Default()->Current()->Hide();

    auto& wm = WindowManager::Default();

    if (wm.IsScreenGrabbed())
    {
      hud_ungrab_slot_ = wm.screen_ungrabbed.connect([this] { ShowHud(); });

      // Let's wait ungrab event for maximum a couple of seconds...
      sources_.AddTimeoutSeconds(2, [this] {
        hud_ungrab_slot_->disconnect();
        return false;
      }, local::HUD_UNGRAB_WAIT);

      return false;
    }

    hud_ungrab_slot_->disconnect();
    hud_controller_->ShowHud();
  }

  // Consume the event.
  return true;
}

bool UnityScreen::ShowHudInitiate(CompAction* action,
                                  CompAction::State state,
                                  CompOption::Vector& options)
{
  // Look to see if there is a keycode.  If there is, then this isn't a
  // modifier only keybinding.
  if (options[6].type() != CompOption::TypeUnset)
  {
    int key_code = options[6].value().i();
    LOG_DEBUG(logger) << "HUD initiate key code: " << key_code;
    // show it now, no timings or terminate needed.
    return ShowHud();
  }
  else
  {
    LOG_DEBUG(logger) << "HUD initiate key code option not set, modifier only keypress.";
  }


  // to receive the Terminate event
  if (state & CompAction::StateInitKey)
    action->setState(action->state() | CompAction::StateTermKey);
  hud_keypress_time_ = options[7].value().i();  // XEvent time in millisec

  // pass key through
  return false;
}

bool UnityScreen::ShowHudTerminate(CompAction* action,
                                   CompAction::State state,
                                   CompOption::Vector& options)
{
  // Remember StateCancel and StateCommit will be broadcast to all actions
  // so we need to verify that we are actually being toggled...
  if (!(state & CompAction::StateTermKey))
    return false;

  action->setState(action->state() & ~CompAction::StateTermKey);

  // If we have a modifier only keypress, check for tap and timing.
  if (!(state & CompAction::StateTermTapped))
    return false;

  int release_time = options[7].value().i();  // XEvent time in millisec
  int tap_duration = release_time - hud_keypress_time_;
  if (tap_duration > local::ALT_TAP_DURATION)
  {
    LOG_DEBUG(logger) << "Tap too long";
    return false;
  }

  return ShowHud();
}

bool UnityScreen::LockScreenInitiate(CompAction* action,
                                     CompAction::State state,
                                     CompOption::Vector& options)
{
  sources_.AddIdle([this] {
    session_controller_->LockScreen();
    return false;
  });

  return true;
}


unsigned UnityScreen::CompizModifiersToNux(unsigned input) const
{
  unsigned modifiers = 0;

  if (input & CompAltMask)
  {
    input &= ~CompAltMask;
    input |= Mod1Mask;
  }

  if (modifiers & CompSuperMask)
  {
    input &= ~CompSuperMask;
    input |= Mod4Mask;
  }

  return XModifiersToNux(input);
}

unsigned UnityScreen::XModifiersToNux(unsigned input) const
{
  unsigned modifiers = 0;

  if (input & Mod1Mask)
    modifiers |= nux::KEY_MODIFIER_ALT;

  if (input & ShiftMask)
    modifiers |= nux::KEY_MODIFIER_SHIFT;

  if (input & ControlMask)
    modifiers |= nux::KEY_MODIFIER_CTRL;

  if (input & Mod4Mask)
    modifiers |= nux::KEY_MODIFIER_SUPER;

  return modifiers;
}

void UnityScreen::UpdateCloseWindowKey(CompAction::KeyBinding const& keybind)
{
  KeySym keysym = XkbKeycodeToKeysym(screen->dpy(), keybind.keycode(), 0, 0);
  unsigned modifiers = CompizModifiersToNux(keybind.modifiers());

  WindowManager::Default().close_window_key = std::make_pair(modifiers, keysym);
}

void UnityScreen::UpdateActivateIndicatorsKey()
{
  CompAction::KeyBinding const& keybind = optionGetPanelFirstMenu().key();
  KeySym keysym = XkbKeycodeToKeysym(screen->dpy(), keybind.keycode(), 0, 0);
  unsigned modifiers = CompizModifiersToNux(keybind.modifiers());

  WindowManager::Default().activate_indicators_key = std::make_pair(modifiers, keysym);
}

bool UnityScreen::initPluginActions()
{
  PluginAdapter& adapter = PluginAdapter::Default();

  if (CompPlugin* p = CompPlugin::find("core"))
  {
    for (CompOption& option : p->vTable->getOptions())
    {
      if (option.name() == "close_window_key")
      {
        UpdateCloseWindowKey(option.value().action().key());
        break;
      }
    }
  }

  if (CompPlugin* p = CompPlugin::find("expo"))
  {
    MultiActionList expoActions;

    for (CompOption& option : p->vTable->getOptions())
    {
      std::string const& option_name = option.name();

      if (!expoActions.HasPrimary() &&
          (option_name == "expo_key" ||
           option_name == "expo_button" ||
           option_name == "expo_edge"))
      {
        CompAction* action = &option.value().action();
        expoActions.AddNewAction(option_name, action, true);
      }
      else if (option_name == "exit_button")
      {
        CompAction* action = &option.value().action();
        expoActions.AddNewAction(option_name, action, false);
      }
    }

    adapter.SetExpoAction(expoActions);
  }

  if (CompPlugin* p = CompPlugin::find("scale"))
  {
    MultiActionList scaleActions;

    for (CompOption& option : p->vTable->getOptions())
    {
      std::string const& option_name = option.name();

      if (option_name == "initiate_all_key" ||
          option_name == "initiate_all_edge" ||
          option_name == "initiate_key" ||
          option_name == "initiate_button" ||
          option_name == "initiate_edge" ||
          option_name == "initiate_group_key" ||
          option_name == "initiate_group_button" ||
          option_name == "initiate_group_edge" ||
          option_name == "initiate_output_key" ||
          option_name == "initiate_output_button" ||
          option_name == "initiate_output_edge")
      {
        CompAction* action = &option.value().action();
        scaleActions.AddNewAction(option_name, action, false);
      }
      else if (option_name == "initiate_all_button")
      {
        CompAction* action = &option.value().action();
        scaleActions.AddNewAction(option_name, action, true);
      }
    }

    adapter.SetScaleAction(scaleActions);
  }

  if (CompPlugin* p = CompPlugin::find("unitymtgrabhandles"))
  {
    foreach(CompOption & option, p->vTable->getOptions())
    {
      if (option.name() == "show_handles_key")
        adapter.SetShowHandlesAction(&option.value().action());
      else if (option.name() == "hide_handles_key")
        adapter.SetHideHandlesAction(&option.value().action());
      else if (option.name() == "toggle_handles_key")
        adapter.SetToggleHandlesAction(&option.value().action());
    }
  }

  if (CompPlugin* p = CompPlugin::find("decor"))
  {
    LOG_ERROR(logger) << "Decoration plugin is active, disabling it...";
    screen->finiPluginForScreen(p);
    p->vTable->finiScreen(screen);
    CompPlugin::getPlugins().remove(p);
    CompPlugin::unload(p);
  }

  return false;
}

/* Set up expo and scale actions on the launcher */
bool UnityScreen::initPluginForScreen(CompPlugin* p)
{
  if (p->vTable->name() == "expo" ||
      p->vTable->name() == "scale")
  {
    initPluginActions();
  }

  bool result = screen->initPluginForScreen(p);
  if (p->vTable->name() == "unityshell")
    initAltTabNextWindow();

  return result;
}

void UnityScreen::AddProperties(debug::IntrospectionData& introspection)
{}

std::string UnityScreen::GetName() const
{
  return "Unity";
}

void UnityScreen::RaiseInputWindows()
{
  std::vector<Window> const& xwns = nux::XInputWindow::NativeHandleList();

  for (auto window : xwns)
  {
    CompWindow* cwin = screen->findWindow(window);
    if (cwin)
      cwin->raise();
  }
}

/* detect occlusions
 *
 * core passes down the PAINT_WINDOW_OCCLUSION_DETECTION
 * mask when it is doing occlusion detection, so use that
 * order to fill our occlusion buffer which we'll flip
 * to nux later
 */
bool UnityWindow::glPaint(const GLWindowPaintAttrib& attrib,
                          const GLMatrix& matrix,
                          const CompRegion& region,
                          unsigned int mask)
{
  /*
   * The occlusion pass tests windows from TOP to BOTTOM. That's opposite to
   * the actual painting loop.
   *
   * Detect uScreen->fullscreenRegion here. That represents the region which
   * fully covers the shell on its output. It does not include regular windows
   * stacked above the shell like DnD icons or Onboard etc.
   */
  if (G_UNLIKELY(is_nux_window_))
  {
    if (mask & PAINT_WINDOW_OCCLUSION_DETECTION_MASK)
    {
      uScreen->nuxRegion += window->geometry();
      uScreen->nuxRegion -= uScreen->fullscreenRegion;
    }

    if (window->id() == screen->activeWindow() &&
        !(mask & PAINT_WINDOW_ON_TRANSFORMED_SCREEN_MASK))
    {
      if (!mask)
        uScreen->panelShadowPainted = CompRect();

      uScreen->paintPanelShadow(region);
    }

    return false;  // Ensure nux windows are never painted by compiz
  }
  else if (mask & PAINT_WINDOW_OCCLUSION_DETECTION_MASK)
  {
    static const unsigned int nonOcclusionBits =
                              PAINT_WINDOW_TRANSLUCENT_MASK |
                              PAINT_WINDOW_TRANSFORMED_MASK |
                              PAINT_WINDOW_NO_CORE_INSTANCE_MASK;

    if (window->isMapped() &&
        window->defaultViewport() == uScreen->screen->vp())
    {
      int monitor = window->outputDevice();

      auto it = uScreen->windows_for_monitor_.find(monitor);

      if (it != end(uScreen->windows_for_monitor_))
        ++(it->second);
      else
        uScreen->windows_for_monitor_[monitor] = 1;

      if (!(mask & nonOcclusionBits) &&
          (window->state() & CompWindowStateFullscreenMask && !window->minimized()) &&
          uScreen->windows_for_monitor_[monitor] == 1)
          // And I've been advised to test other things, but they don't work:
          // && (attrib.opacity == OPAQUE)) <-- Doesn't work; Only set in glDraw
          // && !window->alpha() <-- Doesn't work; Opaque windows often have alpha
      {
        uScreen->fullscreenRegion += window->geometry();
      }

      if (uScreen->nuxRegion.isEmpty())
        uScreen->firstWindowAboveShell = window;
    }
  }

  GLWindowPaintAttrib wAttrib = attrib;

  if (uScreen->lockscreen_controller_->IsLocked() && uScreen->lockscreen_controller_->opacity() == 1.0)
  {
    if (!window->minimized() && !CanBypassLockScreen())
    {
      // For some reasons PAINT_WINDOW_NO_CORE_INSTANCE_MASK doesn't work here
      // (well, it works too much, as it applies to menus too), so we need
      // to paint the windows at the proper opacity, overriding any other
      // paint plugin (animation, fade?) that might interfere with us.
      wAttrib.opacity = 0.0;
      int old_index = gWindow->glPaintGetCurrentIndex();
      gWindow->glPaintSetCurrentIndex(MAXSHORT);
      bool ret = gWindow->glPaint(wAttrib, matrix, region, mask);
      gWindow->glPaintSetCurrentIndex(old_index);
      deco_win_->Paint(matrix, wAttrib, region, mask);
      return ret;
    }
  }

  if (mMinimizeHandler)
  {
    mask |= mMinimizeHandler->getPaintMask ();
  }
  else if (mShowdesktopHandler)
  {
    mShowdesktopHandler->PaintOpacity (wAttrib.opacity);
    mask |= mShowdesktopHandler->GetPaintMask ();
  }

  std::vector<Window> const& tray_xids = uScreen->panel_controller_->GetTrayXids();
  if (std::find(tray_xids.begin(), tray_xids.end(), window->id()) != tray_xids.end() &&
      !uScreen->allowWindowPaint)
  {
    if (!uScreen->painting_tray_)
    {
      uScreen->tray_paint_mask_ = mask;
      mask |= PAINT_WINDOW_NO_CORE_INSTANCE_MASK;
    }
  }

  if (WindowManager::Default().IsScaleActive() &&
      uScreen->sScreen->getSelectedWindow() == window->id())
  {
    nux::Geometry const& scaled_geo = GetScaledGeometry();
    paintInnerGlow(scaled_geo, matrix, attrib, mask);
  }

  if (uScreen->session_controller_->Visible())
  {
    // Let's darken the other windows if the session dialog is visible
    wAttrib.brightness *= 0.75f;
  }

  bool ret = gWindow->glPaint(wAttrib, matrix, region, mask);
  deco_win_->Paint(matrix, wAttrib, region, mask);
  return ret;
}

/* handle window painting in an opengl context
 *
 * we want to paint underneath other windows here,
 * so we need to find if this window is actually
 * stacked on top of one of the nux input windows
 * and if so paint nux and stop us from painting
 * other windows or on top of the whole screen */
bool UnityWindow::glDraw(const GLMatrix& matrix,
#ifndef USE_MODERN_COMPIZ_GL
                         GLFragment::Attrib& attrib,
#else
                         const GLWindowPaintAttrib& attrib,
#endif
                         const CompRegion& region,
                         unsigned int mask)
{
  auto window_state = window->state();
  auto window_type = window->type();
  bool locked = uScreen->lockscreen_controller_->IsLocked();

  if (uScreen->doShellRepaint && !uScreen->paint_panel_under_dash_ && window_type == CompWindowTypeNormalMask)
  {
    if ((window_state & MAXIMIZE_STATE) && window->onCurrentDesktop() && !window->overrideRedirect() && window->managed())
    {
      CompPoint const& viewport = window->defaultViewport();
      unsigned output = window->outputDevice();

      if (viewport == uScreen->screen->vp() && output == uScreen->screen->currentOutputDev().id())
      {
        uScreen->paint_panel_under_dash_ = true;
      }
    }
  }

  if (uScreen->doShellRepaint &&
      window == uScreen->firstWindowAboveShell &&
      !uScreen->forcePaintOnTop() &&
      !uScreen->fullscreenRegion.contains(window->geometry()))
  {
    uScreen->paintDisplay();
  }
  else if (locked && CanBypassLockScreen())
  {
    uScreen->paintDisplay();
  }

  enum class DrawPanelShadow
  {
    NO,
    BELOW_WINDOW,
    OVER_WINDOW,
  };

  auto draw_panel_shadow = DrawPanelShadow::NO;

  if (!(mask & PAINT_WINDOW_ON_TRANSFORMED_SCREEN_MASK))
  {
    Window active_window = screen->activeWindow();

    if (G_UNLIKELY(window_type == CompWindowTypeDesktopMask))
    {
      uScreen->setPanelShadowMatrix(matrix);

      if (active_window == 0 || active_window == window->id())
      {
        if (PluginAdapter::Default().IsWindowOnTop(window->id()))
        {
          draw_panel_shadow = DrawPanelShadow::OVER_WINDOW;
        }
        uScreen->is_desktop_active_ = true;
      }
    }
    else
    {
      if (window->id() == active_window)
      {
        draw_panel_shadow = DrawPanelShadow::BELOW_WINDOW;
        uScreen->is_desktop_active_ = false;

        if (!(window_state & CompWindowStateMaximizedVertMask) &&
            !(window_state & CompWindowStateFullscreenMask) &&
            !(window_type & CompWindowTypeFullscreenMask))
        {
          WindowManager& wm = WindowManager::Default();
          auto const& output = uScreen->screen->currentOutputDev();
          int monitor = wm.MonitorGeometryIn(NuxGeometryFromCompRect(output));

          if (window->y() - window->border().top < output.y() + uScreen->panel_style_.PanelHeight(monitor))
          {
            draw_panel_shadow = DrawPanelShadow::OVER_WINDOW;
          }
        }
      }
      else if (decoration::Style::Get()->integrated_menus())
      {
        draw_panel_shadow = DrawPanelShadow::BELOW_WINDOW;
      }
      else
      {
        if (uScreen->is_desktop_active_)
        {
          if (PluginAdapter::Default().IsWindowOnTop(window->id()))
          {
            draw_panel_shadow = DrawPanelShadow::OVER_WINDOW;
            uScreen->panelShadowPainted = CompRegion();
          }
        }
      }
    }
  }

  if (locked)
    draw_panel_shadow = DrawPanelShadow::NO;

  if (draw_panel_shadow == DrawPanelShadow::BELOW_WINDOW)
    uScreen->paintPanelShadow(region);

  bool ret = gWindow->glDraw(matrix, attrib, region, mask);
  deco_win_->Draw(matrix, attrib, region, mask);

  if (draw_panel_shadow == DrawPanelShadow::OVER_WINDOW)
    uScreen->paintPanelShadow(region);

  return ret;
}

bool UnityWindow::damageRect(bool initial, CompRect const& rect)
{
  if (initial)
    deco_win_->Update();

  return cWindow->damageRect(initial, rect);
}

void
UnityScreen::OnMinimizeDurationChanged ()
{
  /* Update the compiz plugin setting with the new computed speed so that it
   * will be used in the following minimizations */
  if (CompPlugin* p = CompPlugin::find("animation"))
  {
    CompOption::Vector &opts = p->vTable->getOptions();

    for (CompOption &o : opts)
    {
      if (o.name() == "minimize_durations")
      {
        /* minimize_durations is a list value, but minimize applies only to
         * normal windows, so there's always one value */
        CompOption::Value& value = o.value();
        CompOption::Value::Vector& list = value.list();
        CompOption::Value::Vector::iterator i = list.begin();
        if (i != list.end())
          i->set(minimize_speed_controller_.getDuration());

        value.set(list);
        screen->setOptionForPlugin(p->vTable->name().c_str(),
                                   o.name().c_str(), value);
        break;
      }
    }
  }
  else
  {
    LOG_WARN(logger) << "Animation plugin not found. Can't set minimize speed.";
  }
}

void
UnityWindow::minimize ()
{
  if (!window->managed ())
    return;

  if (!mMinimizeHandler)
  {
    mMinimizeHandler.reset (new UnityMinimizedHandler (window, this));
    mMinimizeHandler->minimize ();
  }
}

void
UnityWindow::unminimize ()
{
  if (mMinimizeHandler)
  {
    mMinimizeHandler->unminimize ();
    mMinimizeHandler.reset ();
  }
}

bool
UnityWindow::focus ()
{
  if (!mMinimizeHandler)
    return window->focus ();

  if (window->overrideRedirect ())
    return false;

  if (!window->managed ())
    return false;

  if (!window->onCurrentDesktop ())
    return false;

  /* Only withdrawn windows
   * which are marked hidden
   * are excluded */
  if (!window->shaded () &&
      !window->minimized () &&
      (window->state () & CompWindowStateHiddenMask))
    return false;

  if (window->geometry ().x () + window->geometry ().width ()  <= 0 ||
      window->geometry ().y () + window->geometry ().height () <= 0 ||
      window->geometry ().x () >= (int) screen->width ()||
      window->geometry ().y () >= (int) screen->height ())
    return false;

  return true;
}

bool
UnityWindow::minimized () const
{
  return mMinimizeHandler.get () != nullptr;
}

/* Called whenever a window is mapped, unmapped, minimized etc */
void UnityWindow::windowNotify(CompWindowNotify n)
{
  PluginAdapter::Default().Notify(window, n);

  switch (n)
  {
    case CompWindowNotifyMap:
      deco_win_->Update();
      deco_win_->UpdateDecorationPosition();

      if (window->type() == CompWindowTypeDesktopMask)
      {
        if (!focus_desktop_timeout_)
        {
          focus_desktop_timeout_.reset(new glib::Timeout(1000, [this] {
            for (CompWindow *w : screen->clientList())
            {
              if (!(w->type() & NO_FOCUS_MASK) && w->focus ())
              {
                focus_desktop_timeout_ = nullptr;
                return false;
              }
            }

            window->moveInputFocusTo();

            focus_desktop_timeout_ = nullptr;
            return false;
          }));
        }
      }
    /* Fall through an re-evaluate wraps on map and unmap too */
    case CompWindowNotifyUnmap:
      if (uScreen->optionGetShowMinimizedWindows() && window->mapNum() &&
          !window->pendingUnmaps())
      {
        bool wasMinimized = window->minimized ();
        if (wasMinimized)
          window->unminimize ();
        window->focusSetEnabled (this, true);
        window->minimizeSetEnabled (this, true);
        window->unminimizeSetEnabled (this, true);
        window->minimizedSetEnabled (this, true);

        if (wasMinimized)
          window->minimize ();
      }
      else
      {
        window->focusSetEnabled (this, false);
        window->minimizeSetEnabled (this, false);
        window->unminimizeSetEnabled (this, false);
        window->minimizedSetEnabled (this, false);
      }

      deco_win_->Update();
      deco_win_->UpdateDecorationPosition();

      PluginAdapter::Default().UpdateShowDesktopState();
      break;
    case CompWindowNotifyBeforeDestroy:
      being_destroyed.emit();
      break;
    case CompWindowNotifyMinimize:
      /* Updating the count in dconf will trigger a "changed" signal to which
       * the method setting the new animation speed is attached */
      uScreen->minimize_speed_controller_.UpdateCount();
      break;
    case CompWindowNotifyUnreparent:
      deco_win_->Undecorate();
      break;
    case CompWindowNotifyReparent:
      deco_win_->Update();
      break;
    default:
      break;
  }


  window->windowNotify(n);

  if (mMinimizeHandler)
  {
    /* The minimize handler will short circuit the frame
     * region update func and ensure that the frame
     * does not have a region */
    mMinimizeHandler->windowNotify (n);
  }
  else if (mShowdesktopHandler)
  {
    if (n == CompWindowNotifyFocusChange)
      mShowdesktopHandler->WindowFocusChangeNotify ();
  }

  // We do this after the notify to ensure input focus has actually been moved.
  if (n == CompWindowNotifyFocusChange)
  {
    if (uScreen->dash_controller_->IsVisible())
    {
      uScreen->dash_controller_->ReFocusKeyInput();
    }
    else if (uScreen->hud_controller_->IsVisible())
    {
      uScreen->hud_controller_->ReFocusKeyInput();
    }
  }
}

void UnityWindow::stateChangeNotify(unsigned int lastState)
{
  if (window->state() & CompWindowStateFullscreenMask &&
      !(lastState & CompWindowStateFullscreenMask))
  {
    uScreen->fullscreen_windows_.push_back(window);
  }
  else if (lastState & CompWindowStateFullscreenMask &&
           !(window->state() & CompWindowStateFullscreenMask))
  {
    uScreen->fullscreen_windows_.remove(window);
  }

  deco_win_->Update();
  PluginAdapter::Default().NotifyStateChange(window, window->state(), lastState);
  window->stateChangeNotify(lastState);
}

void UnityWindow::updateFrameRegion(CompRegion &region)
{
  /* The minimize handler will short circuit the frame
   * region update func and ensure that the frame
   * does not have a region */

  if (mMinimizeHandler)
  {
    mMinimizeHandler->updateFrameRegion(region);
  }
  else if (mShowdesktopHandler)
  {
    mShowdesktopHandler->UpdateFrameRegion(region);
  }
  else
  {
    window->updateFrameRegion(region);
    deco_win_->UpdateFrameRegion(region);
  }
}

void UnityWindow::getOutputExtents(CompWindowExtents& output)
{
  window->getOutputExtents(output);
  deco_win_->UpdateOutputExtents(output);
}

void UnityWindow::moveNotify(int x, int y, bool immediate)
{
  deco_win_->UpdateDecorationPositionDelayed();
  PluginAdapter::Default().NotifyMoved(window, x, y);
  window->moveNotify(x, y, immediate);
}

void UnityWindow::resizeNotify(int x, int y, int w, int h)
{
  deco_win_->UpdateDecorationPositionDelayed();
  PluginAdapter::Default().NotifyResized(window, x, y, w, h);
  window->resizeNotify(x, y, w, h);
}

CompPoint UnityWindow::tryNotIntersectUI(CompPoint& pos)
{
  auto const& window_geo = window->borderRect();
  nux::Geometry target_monitor;
  nux::Point result(pos.x(), pos.y());

  // seriously why does compiz not track monitors XRandR style???
  auto const& monitors = UScreen::GetDefault()->GetMonitors();
  for (auto const& monitor : monitors)
  {
    if (monitor.IsInside(result))
    {
      target_monitor = monitor;
      break;
    }
  }

  auto const& launchers = uScreen->launcher_controller_->launchers();

  for (auto const& launcher : launchers)
  {
    if (launcher->options()->hide_mode == LAUNCHER_HIDE_AUTOHIDE && launcher->Hidden())
      continue;

    auto const& geo = launcher->GetAbsoluteGeometry();

    if (geo.IsInside(result))
    {
      if (geo.x + geo.width + 1 + window_geo.width() < target_monitor.x + target_monitor.width)
      {
        result.x = geo.x + geo.width + 1;
      }
    }
  }

  for (nux::Geometry const& geo : uScreen->panel_controller_->GetGeometries())
  {
    if (geo.IsInside(result))
    {
      if (geo.y + geo.height + window_geo.height() < target_monitor.y + target_monitor.height)
      {
        result.y = geo.y + geo.height;
      }
    }
  }

  pos.setX(result.x);
  pos.setY(result.y);
  return pos;
}


bool UnityWindow::place(CompPoint& pos)
{
  bool was_maximized = PluginAdapter::Default().MaximizeIfBigEnough(window);

  if (!was_maximized)
  {
    deco_win_->Update();
    bool result = window->place(pos);

    if (window->type() & NO_FOCUS_MASK)
      return result;

    pos = tryNotIntersectUI(pos);
    return result;
  }

  return true;
}


/* Start up nux after OpenGL is initialized */
void UnityScreen::initUnity(nux::NThread* thread, void* InitData)
{
  Timer timer;
  UnityScreen* self = reinterpret_cast<UnityScreen*>(InitData);
  self->initLauncher();

  nux::ColorLayer background(nux::color::Transparent);
  static_cast<nux::WindowThread*>(thread)->SetWindowBackgroundPaintLayer(&background);
  LOG_INFO(logger) << "UnityScreen::initUnity: " << timer.ElapsedSeconds() << "s";

  nux::GetWindowCompositor().sigHiddenViewWindow.connect(sigc::mem_fun(self, &UnityScreen::OnViewHidden));
}

void UnityScreen::onRedrawRequested()
{
  if (!ignore_redraw_request_)
    cScreen->damagePending();
}

/* Handle option changes and plug that into nux windows */
void UnityScreen::optionChanged(CompOption* opt, UnityshellOptions::Options num)
{
  // Note: perhaps we should put the options here into the controller.
  unity::launcher::Options::Ptr launcher_options = launcher_controller_->options();
  switch (num)
  {
    case UnityshellOptions::NumLaunchers:
      launcher_controller_->multiple_launchers = optionGetNumLaunchers() == 0;
      dash_controller_->use_primary = !launcher_controller_->multiple_launchers();
      hud_controller_->multiple_launchers = launcher_controller_->multiple_launchers();
      break;
    case UnityshellOptions::LauncherCaptureMouse:
      launcher_options->edge_resist = optionGetLauncherCaptureMouse();
      break;
    case UnityshellOptions::ScrollInactiveIcons:
      launcher_options->scroll_inactive_icons = optionGetScrollInactiveIcons();
      break;
    case UnityshellOptions::LauncherMinimizeWindow:
      launcher_options->minimize_window_on_click = optionGetLauncherMinimizeWindow();
      break;
    case UnityshellOptions::BackgroundColor:
    {
      auto override_color = NuxColorFromCompizColor(optionGetBackgroundColor());
      override_color.red = override_color.red / override_color.alpha;
      override_color.green = override_color.green / override_color.alpha;
      override_color.blue = override_color.blue / override_color.alpha;
      bghash_->OverrideColor(override_color);
      break;
    }
    case UnityshellOptions::OverrideDecorationTheme:
      if (optionGetOverrideDecorationTheme())
      {
        deco_manager_->active_shadow_color = NuxColorFromCompizColor(optionGetActiveShadowColor());
        deco_manager_->inactive_shadow_color = NuxColorFromCompizColor(optionGetInactiveShadowColor());
        deco_manager_->active_shadow_radius = optionGetActiveShadowRadius();
        deco_manager_->inactive_shadow_radius = optionGetInactiveShadowRadius();
        deco_manager_->shadow_offset = nux::Point(optionGetShadowXOffset(), optionGetShadowYOffset());
      }
      else
      {
        OnDecorationStyleChanged();
      }
      break;
    case UnityshellOptions::ActiveShadowColor:
      if (optionGetOverrideDecorationTheme())
        deco_manager_->active_shadow_color = NuxColorFromCompizColor(optionGetActiveShadowColor());
      break;
    case UnityshellOptions::InactiveShadowColor:
      if (optionGetOverrideDecorationTheme())
        deco_manager_->inactive_shadow_color = NuxColorFromCompizColor(optionGetInactiveShadowColor());
      break;
    case UnityshellOptions::ActiveShadowRadius:
      if (optionGetOverrideDecorationTheme())
        deco_manager_->active_shadow_radius = optionGetActiveShadowRadius();
      break;
    case UnityshellOptions::InactiveShadowRadius:
      if (optionGetOverrideDecorationTheme())
        deco_manager_->inactive_shadow_radius = optionGetInactiveShadowRadius();
      break;
    case UnityshellOptions::ShadowXOffset:
      if (optionGetOverrideDecorationTheme())
        deco_manager_->shadow_offset = nux::Point(optionGetShadowXOffset(), optionGetShadowYOffset());
      break;
    case UnityshellOptions::ShadowYOffset:
      if (optionGetOverrideDecorationTheme())
        deco_manager_->shadow_offset = nux::Point(optionGetShadowXOffset(), optionGetShadowYOffset());
      break;
    case UnityshellOptions::LauncherHideMode:
    {
      launcher_options->hide_mode = (launcher::LauncherHideMode) optionGetLauncherHideMode();
      hud_controller_->launcher_locked_out = (launcher_options->hide_mode == LAUNCHER_HIDE_NEVER);

      int scale_offset = (launcher_options->hide_mode == LAUNCHER_HIDE_NEVER) ? 0 : launcher_controller_->launcher().GetWidth();
      CompOption::Value v(scale_offset);
      screen->setOptionForPlugin("scale", "x_offset", v);
      break;
    }
    case UnityshellOptions::BacklightMode:
      launcher_options->backlight_mode = (unity::launcher::BacklightMode) optionGetBacklightMode();
      break;
    case UnityshellOptions::RevealTrigger:
      launcher_options->reveal_trigger = (unity::launcher::RevealTrigger) optionGetRevealTrigger();
      break;
    case UnityshellOptions::LaunchAnimation:
      launcher_options->launch_animation = (unity::launcher::LaunchAnimation) optionGetLaunchAnimation();
      break;
    case UnityshellOptions::UrgentAnimation:
      launcher_options->urgent_animation = (unity::launcher::UrgentAnimation) optionGetUrgentAnimation();
      break;
    case UnityshellOptions::PanelOpacity:
      panel_controller_->SetOpacity(optionGetPanelOpacity());
      break;
    case UnityshellOptions::PanelOpacityMaximizedToggle:
      panel_controller_->SetOpacityMaximizedToggle(optionGetPanelOpacityMaximizedToggle());
      break;
    case UnityshellOptions::MenusFadein:
      menus_->fadein = optionGetMenusFadein();
      break;
    case UnityshellOptions::MenusFadeout:
      menus_->fadeout = optionGetMenusFadeout();
      break;
    case UnityshellOptions::MenusDiscoveryFadein:
      menus_->discovery_fadein = optionGetMenusDiscoveryFadein();
      break;
    case UnityshellOptions::MenusDiscoveryFadeout:
      menus_->discovery_fadeout = optionGetMenusDiscoveryFadeout();
      break;
    case UnityshellOptions::MenusDiscoveryDuration:
      menus_->discovery = optionGetMenusDiscoveryDuration();
      break;
    case UnityshellOptions::LauncherOpacity:
      launcher_options->background_alpha = optionGetLauncherOpacity();
      break;
    case UnityshellOptions::IconSize:
    {
      launcher_options->icon_size = optionGetIconSize();
      launcher_options->tile_size = optionGetIconSize() + 6;

      hud_controller_->icon_size = launcher_options->icon_size();
      hud_controller_->tile_size = launcher_options->tile_size();
      break;
    }
    case UnityshellOptions::AutohideAnimation:
      launcher_options->auto_hide_animation = (unity::launcher::AutoHideAnimation) optionGetAutohideAnimation();
      break;
    case UnityshellOptions::DashBlurExperimental:
      BackgroundEffectHelper::blur_type = (unity::BlurType)optionGetDashBlurExperimental();
      break;
    case UnityshellOptions::AutomaximizeValue:
      PluginAdapter::Default().SetCoverageAreaBeforeAutomaximize(optionGetAutomaximizeValue() / 100.0f);
      break;
    case UnityshellOptions::DashTapDuration:
      launcher_options->super_tap_duration = optionGetDashTapDuration();
      break;
    case UnityshellOptions::AltTabTimeout:
      switcher_controller_->detail_on_timeout = optionGetAltTabTimeout();
    case UnityshellOptions::AltTabBiasViewport:
      PluginAdapter::Default().bias_active_to_viewport = optionGetAltTabBiasViewport();
      break;
    case UnityshellOptions::DisableShowDesktop:
      switcher_controller_->SetShowDesktopDisabled(optionGetDisableShowDesktop());
      break;
    case UnityshellOptions::DisableMouse:
      switcher_controller_->SetMouseDisabled(optionGetDisableMouse());
      break;
    case UnityshellOptions::ShowMinimizedWindows:
      compiz::CompizMinimizedWindowHandler<UnityScreen, UnityWindow>::setFunctions (optionGetShowMinimizedWindows ());
      screen->enterShowDesktopModeSetEnabled (this, optionGetShowMinimizedWindows ());
      screen->leaveShowDesktopModeSetEnabled (this, optionGetShowMinimizedWindows ());
      break;
    case UnityshellOptions::ShortcutOverlay:
      shortcut_controller_->SetEnabled(optionGetShortcutOverlay());
      break;
    case UnityshellOptions::DecayRate:
      launcher_options->edge_decay_rate = optionGetDecayRate() * 100;
      break;
    case UnityshellOptions::OvercomePressure:
      launcher_options->edge_overcome_pressure = optionGetOvercomePressure() * 100;
      break;
    case UnityshellOptions::StopVelocity:
      launcher_options->edge_stop_velocity = optionGetStopVelocity() * 100;
      break;
    case UnityshellOptions::RevealPressure:
      launcher_options->edge_reveal_pressure = optionGetRevealPressure() * 100;
      break;
    case UnityshellOptions::EdgeResponsiveness:
      launcher_options->edge_responsiveness = optionGetEdgeResponsiveness();
      break;
    case UnityshellOptions::EdgePassedDisabledMs:
      launcher_options->edge_passed_disabled_ms = optionGetEdgePassedDisabledMs();
      break;
    case UnityshellOptions::PanelFirstMenu:
      UpdateActivateIndicatorsKey();
      break;
    default:
      break;
  }
}

void UnityScreen::NeedsRelayout()
{
  needsRelayout = true;
}

void UnityScreen::ScheduleRelayout(guint timeout)
{
  if (!sources_.GetSource(local::RELAYOUT_TIMEOUT))
  {
    sources_.AddTimeout(timeout, [this] {
      NeedsRelayout();
      Relayout();

      cScreen->damageScreen();

      return false;
    }, local::RELAYOUT_TIMEOUT);
  }
}

void UnityScreen::Relayout()
{
  if (!needsRelayout)
    return;

  UScreen *uscreen = UScreen::GetDefault();
  int primary_monitor = uscreen->GetPrimaryMonitor();
  auto const& geo = uscreen->GetMonitorGeometry(primary_monitor);
  wt->SetWindowSize(geo.width, geo.height);

  LOG_DEBUG(logger) << "Setting to primary screen rect; " << geo;
  needsRelayout = false;

  DamagePanelShadow();
}

/* Handle changes in the number of workspaces by showing the switcher
 * or not showing the switcher */
bool UnityScreen::setOptionForPlugin(const char* plugin, const char* name,
                                     CompOption::Value& v)
{
  bool status = screen->setOptionForPlugin(plugin, name, v);

  if (status)
  {
    if (strcmp(plugin, "core") == 0)
    {
      if (strcmp(name, "hsize") == 0 || strcmp(name, "vsize") == 0)
      {
        WindowManager& wm = WindowManager::Default();
        wm.viewport_layout_changed.emit(screen->vpSize().width(), screen->vpSize().height());
      }
      else if (strcmp(name, "close_window_key") == 0)
      {
        UpdateCloseWindowKey(v.action().key());
      }
    }
  }
  return status;
}

void UnityScreen::outputChangeNotify()
{
  screen->outputChangeNotify ();

  auto gpu_device = nux::GetGraphicsDisplay()->GetGpuDevice();
  gpu_device->backup_texture0_ =
      gpu_device->CreateSystemCapableDeviceTexture(screen->width(), screen->height(),
                                                   1, nux::BITFMT_R8G8B8A8,
                                                   NUX_TRACKER_LOCATION);

  ScheduleRelayout(500);
}

bool UnityScreen::layoutSlotsAndAssignWindows()
{
  auto const& scaled_windows = sScreen->getWindows();

  for (auto const& output : screen->outputDevs())
  {
    ui::LayoutWindow::Vector layout_windows;
    int monitor = UScreen::GetDefault()->GetMonitorAtPosition(output.centerX(), output.centerY());
    double monitor_scale = unity_settings_.em(monitor)->DPIScale();

    for (ScaleWindow *sw : scaled_windows)
    {
      if (sw->window->outputDevice() == static_cast<int>(output.id()))
      {
        UnityWindow::get(sw->window)->deco_win_->scaled = true;
        layout_windows.emplace_back(std::make_shared<LayoutWindow>(sw->window->id()));
      }
    }

    auto max_bounds = NuxGeometryFromCompRect(output.workArea());
    if (launcher_controller_->options()->hide_mode != LAUNCHER_HIDE_NEVER)
    {
      int monitor_width = unity_settings_.LauncherWidth(monitor);
      max_bounds.x += monitor_width;
      max_bounds.width -= monitor_width;
    }

    nux::Geometry final_bounds;
    ui::LayoutSystem layout;
    layout.max_row_height = max_bounds.height;
    layout.spacing = local::SCALE_SPACING.CP(monitor_scale);
    int padding = local::SCALE_PADDING.CP(monitor_scale);
    max_bounds.Expand(-padding, -padding);
    layout.LayoutWindowsNearest(layout_windows, max_bounds, final_bounds);

    for (auto const& lw : layout_windows)
    {
      auto sw_it = std::find_if(scaled_windows.begin(), scaled_windows.end(), [&lw] (ScaleWindow* sw) {
        return sw->window->id() == lw->xid;
      });

      if (sw_it == scaled_windows.end())
        continue;

      ScaleWindow* sw = *sw_it;
      ScaleSlot slot(CompRectFromNuxGeo(lw->result));
      slot.scale = lw->scale;

      float sx = lw->geo.width * slot.scale;
      float sy = lw->geo.height * slot.scale;
      float cx = (slot.x1() + slot.x2()) / 2;
      float cy = (slot.y1() + slot.y2()) / 2;

      CompWindow *w = sw->window;
      cx += w->input().left * slot.scale;
      cy += w->input().top * slot.scale;

      slot.setGeometry(cx - sx / 2, cy - sy / 2, sx, sy);
      slot.filled = true;

      sw->setSlot(slot);
    }
  }

  return true;
}

void UnityScreen::OnDashRealized()
{
  RaiseOSK();
}

void UnityScreen::OnLockScreenRequested()
{
  if (switcher_controller_->Visible())
    switcher_controller_->Hide(false);

  if (dash_controller_->IsVisible())
    dash_controller_->HideDash();

  if (hud_controller_->IsVisible())
    hud_controller_->HideHud();

  menus_->Indicators()->CloseActiveEntry();
  launcher_controller_->ClearTooltips();

  if (launcher_controller_->KeyNavIsActive())
    launcher_controller_->KeyNavTerminate(false);

  if (QuicklistManager::Default()->Current())
    QuicklistManager::Default()->Current()->Hide();

  auto& wm = WindowManager::Default();

  if (wm.IsScaleActive())
    wm.TerminateScale();

  if (wm.IsExpoActive())
    wm.TerminateExpo();

  RaiseOSK();
}

void UnityScreen::OnScreenLocked()
{
  SaveLockStamp(true);

  for (auto& option : getOptions())
  {
    if (option.isAction())
    {
      auto& value = option.value();

      if (value != mOptions[UnityshellOptions::PanelFirstMenu].value())
        screen->removeAction(&value.action());
    }
  }

  for (auto& action : getActions())
    screen->removeAction(&action);

  // We notify that super/alt have been released, to avoid to leave unity in inconsistent state
  CompOption::Vector options(8);
  options[7].setName("time", CompOption::TypeInt);
  options[7].value().set<int>(screen->getCurrentTime());

  showLauncherKeyTerminate(&optionGetShowLauncher(), CompAction::StateTermKey, options);
  showMenuBarTerminate(&optionGetShowMenuBar(), CompAction::StateTermKey, options);
}

void UnityScreen::OnScreenUnlocked()
{
  SaveLockStamp(false);

  for (auto& option : getOptions())
  {
    if (option.isAction())
      screen->addAction(&option.value().action());
  }

  for (auto& action : getActions())
    screen->addAction(&action);
}

void UnityScreen::SaveLockStamp(bool save)
{
  auto const& cache_dir = DesktopUtilities::GetUserRuntimeDirectory();

  if (cache_dir.empty())
    return;

  if (save)
  {
    glib::Error error;
    g_file_set_contents((cache_dir+local::LOCKED_STAMP).c_str(), "", 0, &error);

    if (error)
    {
      LOG_ERROR(logger) << "Impossible to save the unity locked stamp file: " << error;
    }
  }
  else
  {
    if (g_unlink((cache_dir+local::LOCKED_STAMP).c_str()) < 0)
    {
      LOG_ERROR(logger) << "Impossible to delete the unity locked stamp file";
    }
  }
}

void UnityScreen::RaiseOSK()
{
  /* stack the onboard window above us */
  if (onboard_)
  {
    if (nux::BaseWindow* dash = dash_controller_->window())
    {
      Window xid = dash->GetInputWindowId();
      XSetTransientForHint(screen->dpy(), onboard_->id(), xid);
      onboard_->raise();
    }
  }
}

/* Start up the launcher */
void UnityScreen::initLauncher()
{
  Timer timer;

  bghash_.reset(new BGHash());

  auto xdnd_collection_window = std::make_shared<XdndCollectionWindowImp>();
  auto xdnd_start_stop_notifier = std::make_shared<XdndStartStopNotifierImp>();
  auto xdnd_manager = std::make_shared<XdndManagerImp>(xdnd_start_stop_notifier, xdnd_collection_window);
  auto edge_barriers = std::make_shared<ui::EdgeBarrierController>();

  launcher_controller_ = std::make_shared<launcher::Controller>(xdnd_manager, edge_barriers);
  AddChild(launcher_controller_.get());

  switcher_controller_ = std::make_shared<switcher::Controller>();
  switcher_controller_->detail.changed.connect(sigc::mem_fun(this, &UnityScreen::OnSwitcherDetailChanged));
  AddChild(switcher_controller_.get());

  LOG_INFO(logger) << "initLauncher-Launcher " << timer.ElapsedSeconds() << "s";

  /* Setup panel */
  timer.Reset();
  panel_controller_ = std::make_shared<panel::Controller>(menus_, edge_barriers);
  AddChild(panel_controller_.get());
  LOG_INFO(logger) << "initLauncher-Panel " << timer.ElapsedSeconds() << "s";

  /* Setup Places */
  dash_controller_ = std::make_shared<dash::Controller>();
  dash_controller_->on_realize.connect(sigc::mem_fun(this, &UnityScreen::OnDashRealized));
  AddChild(dash_controller_.get());

  /* Setup Hud */
  hud_controller_ = std::make_shared<hud::Controller>();
  auto hide_mode = (unity::launcher::LauncherHideMode) optionGetLauncherHideMode();
  hud_controller_->launcher_locked_out = (hide_mode == unity::launcher::LauncherHideMode::LAUNCHER_HIDE_NEVER);
  hud_controller_->multiple_launchers = (optionGetNumLaunchers() == 0);
  hud_controller_->icon_size = launcher_controller_->options()->icon_size();
  hud_controller_->tile_size = launcher_controller_->options()->tile_size();
  AddChild(hud_controller_.get());
  LOG_INFO(logger) << "initLauncher-hud " << timer.ElapsedSeconds() << "s";

  // Setup Shortcut Hint
  auto base_window_raiser = std::make_shared<shortcut::BaseWindowRaiserImp>();
  auto shortcuts_modeller = std::make_shared<shortcut::CompizModeller>();
  shortcut_controller_ = std::make_shared<shortcut::Controller>(base_window_raiser, shortcuts_modeller);
  AddChild(shortcut_controller_.get());
  ShowFirstRunHints();

  // Setup Session Controller
  auto manager = std::make_shared<session::GnomeManager>();
  manager->lock_requested.connect(sigc::mem_fun(this, &UnityScreen::OnLockScreenRequested));
  manager->prompt_lock_requested.connect(sigc::mem_fun(this, &UnityScreen::OnLockScreenRequested));
  manager->locked.connect(sigc::mem_fun(this, &UnityScreen::OnScreenLocked));
  manager->unlocked.connect(sigc::mem_fun(this, &UnityScreen::OnScreenUnlocked));
  session_dbus_manager_ = std::make_shared<session::DBusManager>(manager);
  session_controller_ = std::make_shared<session::Controller>(manager);
  AddChild(session_controller_.get());

  // Setup Lockscreen Controller
  screensaver_dbus_manager_ = std::make_shared<lockscreen::DBusManager>(manager);
  lockscreen_controller_ = std::make_shared<lockscreen::Controller>(screensaver_dbus_manager_, manager);
  UpdateActivateIndicatorsKey();

  if (g_file_test((DesktopUtilities::GetUserRuntimeDirectory()+local::LOCKED_STAMP).c_str(), G_FILE_TEST_EXISTS))
    manager->PromptLockScreen();

  auto on_launcher_size_changed = [this] (nux::Area* area, int w, int h) {
    /* The launcher geometry includes 1px used to draw the right margin
     * that must not be considered when drawing an overlay */

    auto* launcher = static_cast<Launcher*>(area);
    int launcher_width = w - (1_em).CP(unity_settings_.em(launcher->monitor)->DPIScale());

    unity::Settings::Instance().SetLauncherWidth(launcher_width, launcher->monitor);
    shortcut_controller_->SetAdjustment(launcher_width, panel_style_.PanelHeight(launcher->monitor));

    CompOption::Value v(launcher_width);
    screen->setOptionForPlugin("expo", "x_offset", v);

    if (launcher_controller_->options()->hide_mode == LAUNCHER_HIDE_NEVER)
      v.set(0);

    screen->setOptionForPlugin("scale", "x_offset", v);
  };

  auto check_launchers_size = [this, on_launcher_size_changed] {
    launcher_size_connections_.Clear();

    for (auto const& launcher : launcher_controller_->launchers())
    {
      launcher_size_connections_.Add(launcher->size_changed.connect(on_launcher_size_changed));
      on_launcher_size_changed(launcher.GetPointer(), launcher->GetWidth(), launcher->GetHeight());
    }
  };

  UScreen::GetDefault()->changed.connect([this, check_launchers_size] (int, std::vector<nux::Geometry> const&) {
    check_launchers_size();
  });

  check_launchers_size();

  launcher_controller_->options()->scroll_inactive_icons = optionGetScrollInactiveIcons();
  launcher_controller_->options()->minimize_window_on_click = optionGetLauncherMinimizeWindow();

  ScheduleRelayout(0);
}

switcher::Controller::Ptr UnityScreen::switcher_controller()
{
  return switcher_controller_;
}

launcher::Controller::Ptr UnityScreen::launcher_controller()
{
  return launcher_controller_;
}

lockscreen::Controller::Ptr UnityScreen::lockscreen_controller()
{
  return lockscreen_controller_;
}

void UnityScreen::InitGesturesSupport()
{
  std::unique_ptr<nux::GestureBroker> gesture_broker(new UnityGestureBroker);
  wt->GetWindowCompositor().SetGestureBroker(std::move(gesture_broker));

  gestures_sub_launcher_.reset(new nux::GesturesSubscription);
  gestures_sub_launcher_->SetGestureClasses(nux::DRAG_GESTURE);
  gestures_sub_launcher_->SetNumTouches(4);
  gestures_sub_launcher_->SetWindowId(GDK_ROOT_WINDOW());
  gestures_sub_launcher_->Activate();

  gestures_sub_dash_.reset(new nux::GesturesSubscription);
  gestures_sub_dash_->SetGestureClasses(nux::TAP_GESTURE);
  gestures_sub_dash_->SetNumTouches(4);
  gestures_sub_dash_->SetWindowId(GDK_ROOT_WINDOW());
  gestures_sub_dash_->Activate();

  gestures_sub_windows_.reset(new nux::GesturesSubscription);
  gestures_sub_windows_->SetGestureClasses(nux::TOUCH_GESTURE
                                         | nux::DRAG_GESTURE
                                         | nux::PINCH_GESTURE);
  gestures_sub_windows_->SetNumTouches(3);
  gestures_sub_windows_->SetWindowId(GDK_ROOT_WINDOW());
  gestures_sub_windows_->Activate();
}

CompAction::Vector& UnityScreen::getActions()
{
  return menus_->KeyGrabber()->GetActions();
}

void UnityScreen::ShowFirstRunHints()
{
  sources_.AddTimeoutSeconds(1, [this] {
    auto const& config_dir = DesktopUtilities::GetUserConfigDirectory();
    if (!config_dir.empty() && !g_file_test((config_dir+local::FIRST_RUN_STAMP).c_str(), G_FILE_TEST_EXISTS))
    {
      // We focus the panel, so the shortcut hint will be hidden at first user input
      auto const& panels = panel_controller_->panels();
      if (!panels.empty())
      {
        auto panel_win = static_cast<nux::BaseWindow*>(panels.front()->GetTopLevelViewWindow());
        SaveInputThenFocus(panel_win->GetInputWindowId());
      }
      shortcut_controller_->first_run = true;
      shortcut_controller_->Show();

      glib::Error error;
      g_file_set_contents((config_dir+local::FIRST_RUN_STAMP).c_str(), "", 0, &error);

      if (error)
      {
        LOG_ERROR(logger) << "Impossible to save the unity stamp file: " << error;
      }
    }
    return false;
  });
}

/* Window init */

namespace
{
bool WindowHasInconsistentShapeRects(Display *d, Window  w)
{
  int n;
  Atom *atoms = XListProperties(d, w, &n);
  bool has_inconsistent_shape = false;
  static Atom unity_shape_rects_atom = XInternAtom(d, "_UNITY_SAVED_WINDOW_SHAPE", False);

  for (int i = 0; i < n; ++i)
    if (atoms[i] == unity_shape_rects_atom)
      has_inconsistent_shape = true;

  XFree (atoms);
  return has_inconsistent_shape;
}
}

UnityWindow::UnityWindow(CompWindow* window)
  : BaseSwitchWindow(static_cast<BaseSwitchScreen*>(uScreen), window)
  , PluginClassHandler<UnityWindow, CompWindow>(window)
  , window(window)
  , cWindow(CompositeWindow::get(window))
  , gWindow(GLWindow::get(window))
  , close_icon_state_(decoration::WidgetState::NORMAL)
  , deco_win_(uScreen->deco_manager_->HandleWindow(window))
  , need_fake_deco_redraw_(false)
  , is_nux_window_(PluginAdapter::IsNuxWindow(window))
{
  WindowInterface::setHandler(window);
  GLWindowInterface::setHandler(gWindow);
  ScaleWindowInterface::setHandler(ScaleWindow::get(window));

  PluginAdapter::Default().OnLeaveDesktop();

  /* This needs to happen before we set our wrapable functions, since we
   * need to ask core (and not ourselves) whether or not the window is
   * minimized */
  if (uScreen->optionGetShowMinimizedWindows() && window->mapNum() &&
      WindowHasInconsistentShapeRects(screen->dpy (), window->id()))
  {
    /* Query the core function */
    window->minimizedSetEnabled (this, false);

    bool wasMinimized = window->minimized ();
    if (wasMinimized)
      window->unminimize ();
    window->minimizedSetEnabled (this, true);

    if (wasMinimized)
      window->minimize ();
  }
  else
  {
    window->minimizeSetEnabled (this, false);
    window->unminimizeSetEnabled (this, false);
    window->minimizedSetEnabled (this, false);
  }

  /* Keep this after the optionGetShowMinimizedWindows branch */

  if (window->state() & CompWindowStateFullscreenMask)
    uScreen->fullscreen_windows_.push_back(window);

  if (window->type() == CompWindowTypeUtilMask && window->resName() == "onboard")
  {
    uScreen->onboard_ = window;
    uScreen->RaiseOSK();
  }
}


void UnityWindow::AddProperties(debug::IntrospectionData& introspection)
{
  Window xid = window->id();
  auto const& swins = uScreen->sScreen->getWindows();
  bool scaled = std::find(swins.begin(), swins.end(), ScaleWindow::get(window)) != swins.end();
  WindowManager& wm = WindowManager::Default();

  introspection
    .add(scaled ? GetScaledGeometry() : wm.GetWindowGeometry(xid))
    .add("xid", xid)
    .add("title", wm.GetWindowName(xid))
    .add("fake_decorated", uScreen->fake_decorated_windows_.find(this) != uScreen->fake_decorated_windows_.end())
    .add("maximized", wm.IsWindowMaximized(xid))
    .add("horizontally_maximized", wm.IsWindowHorizontallyMaximized(xid))
    .add("vertically_maximized", wm.IsWindowVerticallyMaximized(xid))
    .add("minimized", wm.IsWindowMinimized(xid))
    .add("scaled", scaled)
    .add("scaled_close_geo", close_button_geo_)
    .add("scaled_close_x", close_button_geo_.x)
    .add("scaled_close_y", close_button_geo_.y)
    .add("scaled_close_width", close_button_geo_.width)
    .add("scaled_close_height", close_button_geo_.height);
}

std::string UnityWindow::GetName() const
{
  return "Window";
}


void UnityWindow::DrawTexture(GLTexture::List const& textures,
                              GLWindowPaintAttrib const& attrib,
                              GLMatrix const& transform,
                              unsigned int mask,
                              int x, int y,
                              double scale)
{
  for (auto const& texture : textures)
  {
    if (!texture)
      continue;

    gWindow->vertexBuffer()->begin();

    if (texture->width() && texture->height())
    {
      GLTexture::MatrixList ml({texture->matrix()});
      CompRegion texture_region(0, 0, texture->width(), texture->height());
      gWindow->glAddGeometry(ml, texture_region, texture_region);
    }

    if (gWindow->vertexBuffer()->end())
    {
      GLMatrix wTransform(transform);
      wTransform.translate(x, y, 0.0f);
      wTransform.scale(scale, scale, 1.0f);

      gWindow->glDrawTexture(texture, wTransform, attrib, mask);
    }
  }
}

void UnityWindow::RenderDecoration(compiz_utils::CairoContext const& ctx, double aspect)
{
  if (aspect <= 0)
    return;

  using namespace decoration;

  aspect *= deco_win_->dpi_scale();
  double w = ctx.width() / aspect;
  double h = ctx.height() / aspect;
  Style::Get()->DrawSide(Side::TOP, WidgetState::NORMAL, ctx, w, h);
}

void UnityWindow::RenderTitle(compiz_utils::CairoContext const& ctx, int x, int y, int width, int height, double aspect)
{
  using namespace decoration;
  auto const& style = Style::Get();
  auto const& title = deco_win_->title();
  auto text_size = style->TitleNaturalSize(title);
  x += style->TitleIndent();
  y += (height - text_size.height)/2;

  cairo_save(ctx);
  cairo_scale(ctx, 1.0f/aspect, 1.0f/aspect);
  cairo_translate(ctx, x, y);
  style->DrawTitle(title, WidgetState::NORMAL, ctx, width - x, height);
  cairo_restore(ctx);
}

void UnityWindow::BuildDecorationTexture()
{
  auto const& border = decoration::Style::Get()->Border();

  if (border.top)
  {
    double dpi_scale = deco_win_->dpi_scale();
    compiz_utils::CairoContext context(window->borderRect().width(), border.top * dpi_scale, dpi_scale);
    RenderDecoration(context);
    decoration_tex_ = context;
  }
}

void UnityWindow::CleanupCachedTextures()
{
  decoration_tex_.reset();
  decoration_selected_tex_.reset();
  decoration_title_.clear();
}

void UnityWindow::paintFakeDecoration(nux::Geometry const& geo, GLWindowPaintAttrib const& attrib, GLMatrix const& transform, unsigned int mask, bool highlighted, double scale)
{
  mask |= PAINT_WINDOW_BLEND_MASK;

  if (!decoration_tex_ && compiz_utils::IsWindowFullyDecorable(window))
    BuildDecorationTexture();

  if (!highlighted)
  {
    if (decoration_tex_)
      DrawTexture(*decoration_tex_, attrib, transform, mask, geo.x, geo.y, scale);

    close_button_geo_.Set(0, 0, 0, 0);
  }
  else
  {
    auto const& style = decoration::Style::Get();
    double dpi_scale = deco_win_->dpi_scale();
    int width = geo.width;
    int height = style->Border().top * dpi_scale;
    auto const& padding = style->Padding(decoration::Side::TOP);
    bool redraw_decoration = true;
    compiz_utils::SimpleTexture::Ptr close_texture;

    if (decoration_selected_tex_)
    {
      auto* texture = decoration_selected_tex_->texture();
      if (texture && texture->width() == width && texture->height() == height)
      {
        if (decoration_title_ == deco_win_->title())
          redraw_decoration = false;
      }
    }

    if (window->actions() & CompWindowActionCloseMask)
    {
      using namespace decoration;
      close_texture = DataPool::Get()->ButtonTexture(dpi_scale, WindowButtonType::CLOSE, close_icon_state_);
    }

    if (redraw_decoration)
    {
      if (width != 0 && height != 0)
      {
        compiz_utils::CairoContext context(width, height, scale * dpi_scale);
        RenderDecoration(context, scale);

        // Draw window title
        int text_x = padding.left + (close_texture ? close_texture->width() : 0) / dpi_scale;
        RenderTitle(context, text_x, padding.top, (width - padding.right) / dpi_scale, height / dpi_scale, scale);
        decoration_selected_tex_ = context;
        decoration_title_ = deco_win_->title();
        uScreen->damageRegion(CompRegionFromNuxGeo(geo));
        need_fake_deco_redraw_ = true;

        if (decoration_tex_)
          DrawTexture(*decoration_tex_, attrib, transform, mask, geo.x, geo.y, scale);

        return; // Let's draw this at next repaint cycle
      }
      else
      {
        decoration_selected_tex_.reset();
        redraw_decoration = false;
      }
    }
    else
    {
      need_fake_deco_redraw_ = false;
    }

    if (decoration_selected_tex_)
      DrawTexture(*decoration_selected_tex_, attrib, transform, mask, geo.x, geo.y);

    if (close_texture)
    {
      int w = close_texture->width();
      int h = close_texture->height();
      int x = geo.x + padding.left * dpi_scale;
      int y = geo.y + padding.top * dpi_scale + (height - w) / 2.0f;

      close_button_geo_.Set(x, y, w, h);
      DrawTexture(*close_texture, attrib, transform, mask, x, y);
    }
    else
    {
      close_button_geo_.Set(0, 0, 0, 0);
    }
  }

  uScreen->fake_decorated_windows_.insert(this);
}

void UnityWindow::scalePaintDecoration(GLWindowPaintAttrib const& attrib,
                                       GLMatrix const& transform,
                                       CompRegion const& region,
                                       unsigned int mask)
{
  ScaleWindow* scale_win = ScaleWindow::get(window);
  scale_win->scalePaintDecoration(attrib, transform, region, mask);

  if (!scale_win->hasSlot()) // animation not finished
    return;

  auto state = uScreen->sScreen->getState();

  if (state != ScaleScreen::Wait && state != ScaleScreen::Out && !need_fake_deco_redraw_)
    return;

  nux::Geometry const& scale_geo = GetScaledGeometry();
  auto const& pos = scale_win->getCurrentPosition();
  auto deco_attrib = attrib;
  deco_attrib.opacity = COMPIZ_COMPOSITE_OPAQUE;

  bool highlighted = (uScreen->sScreen->getSelectedWindow() == window->id());
  paintFakeDecoration(scale_geo, deco_attrib, transform, mask, highlighted, pos.scale);
}

nux::Geometry UnityWindow::GetLayoutWindowGeometry()
{
  auto const& layout_window = uScreen->GetSwitcherDetailLayoutWindow(window->id());

  if (layout_window)
    return layout_window->result;

  return nux::Geometry();
}

nux::Geometry UnityWindow::GetScaledGeometry()
{
  WindowManager& wm = WindowManager::Default();

  if (!wm.IsScaleActive())
    return nux::Geometry();

  ScaleWindow* scale_win = ScaleWindow::get(window);

  ScalePosition const& pos = scale_win->getCurrentPosition();
  auto const& border_rect = window->borderRect();
  auto const& deco_ext = window->border();

  const unsigned width = std::round(border_rect.width() * pos.scale);
  const unsigned height = std::round(border_rect.height() * pos.scale);
  const int x = pos.x() + window->x() - std::round(deco_ext.left * pos.scale);
  const int y = pos.y() + window->y() - std::round(deco_ext.top * pos.scale);

  return nux::Geometry(x, y, width, height);
}

void UnityWindow::OnInitiateSpread()
{
  close_icon_state_ = decoration::WidgetState::NORMAL;
  middle_clicked_ = false;
  deco_win_->scaled = true;

  if (IsInShowdesktopMode())
  {
    if (mShowdesktopHandler)
    {
      mShowdesktopHandler->FadeIn();
    }
  }
}

void UnityWindow::OnTerminateSpread()
{
  CleanupCachedTextures();
  deco_win_->scaled = false;

  if (IsInShowdesktopMode())
  {
    if (!(screen->activeWindow() == window->id()))
    {
      if (!mShowdesktopHandler)
        mShowdesktopHandler.reset(new ShowdesktopHandler(static_cast <ShowdesktopHandlerWindowInterface *>(this),
                                                         static_cast <compiz::WindowInputRemoverLockAcquireInterface *>(this)));
      mShowdesktopHandler->FadeOut();
    }
    else
    {
      window->setShowDesktopMode(false);
    }
  }
}

void UnityWindow::paintInnerGlow(nux::Geometry glow_geo, GLMatrix const& matrix, GLWindowPaintAttrib const& attrib, unsigned mask)
{
  using namespace decoration;
  auto const& style = Style::Get();
  double dpi_scale = deco_win_->dpi_scale();
  unsigned glow_size = std::round(style->GlowSize() * dpi_scale);
  auto const& glow_texture = DataPool::Get()->GlowTexture();

  if (!glow_size || !glow_texture)
    return;

  auto const& radius = style->CornerRadius();
  int decoration_radius = std::max({radius.top, radius.left, radius.right, radius.bottom});

  if (decoration_radius > 0)
  {
    // We paint the glow below the window edges to correctly
    // render the rounded corners
    int inside_glow = decoration_radius * dpi_scale / 4;
    glow_size += inside_glow;
    glow_geo.Expand(-inside_glow, -inside_glow);
  }

  glow::Quads const& quads = computeGlowQuads(glow_geo, *glow_texture, glow_size);
  paintGlow(matrix, attrib, quads, *glow_texture, style->GlowColor(), mask);
}

void UnityWindow::paintThumbnail(nux::Geometry const& geo, float alpha, float parent_alpha, float scale_ratio, unsigned deco_height, bool selected)
{
  GLMatrix matrix;
  matrix.toScreenSpace(uScreen->_last_output, -DEFAULT_Z_CAMERA);
  last_bound = geo;

  GLWindowPaintAttrib attrib = gWindow->lastPaintAttrib();
  attrib.opacity = (alpha * parent_alpha * COMPIZ_COMPOSITE_OPAQUE);
  unsigned mask = gWindow->lastMask();
  nux::Geometry thumb_geo = geo;

  if (selected)
    paintInnerGlow(thumb_geo, matrix, attrib, mask);

  thumb_geo.y += std::round(deco_height * 0.5f * scale_ratio);
  nux::Geometry const& g = thumb_geo;

  paintThumb(attrib, matrix, mask, g.x, g.y, g.width, g.height, g.width, g.height);

  mask |= PAINT_WINDOW_BLEND_MASK;
  attrib.opacity = parent_alpha * COMPIZ_COMPOSITE_OPAQUE;

  // The thumbnail is still animating, don't draw the decoration as selected
  if (selected && alpha < 1.0f)
    selected = false;

  paintFakeDecoration(geo, attrib, matrix, mask, selected, scale_ratio);
}

UnityWindow::~UnityWindow()
{
  if (uScreen->newFocusedWindow && UnityWindow::get(uScreen->newFocusedWindow) == this)
    uScreen->newFocusedWindow = NULL;

  uScreen->deco_manager_->UnHandleWindow(window);

  if (!window->destroyed ())
  {
    bool wasMinimized = window->minimized ();
    if (wasMinimized)
      window->unminimize ();
    window->focusSetEnabled (this, false);
    window->minimizeSetEnabled (this, false);
    window->unminimizeSetEnabled (this, false);
    if (wasMinimized)
      window->minimize ();
  }

  ShowdesktopHandler::animating_windows.remove (static_cast <ShowdesktopHandlerWindowInterface *> (this));

  if (window->state () & CompWindowStateFullscreenMask)
    uScreen->fullscreen_windows_.remove(window);

  if (window == uScreen->onboard_)
    uScreen->onboard_ = nullptr;

  uScreen->fake_decorated_windows_.erase(this);
  PluginAdapter::Default().OnWindowClosed(window);
}


/* vtable init */
bool UnityPluginVTable::init()
{
  if (!CompPlugin::checkPluginABI("core", CORE_ABIVERSION))
    return false;
  if (!CompPlugin::checkPluginABI("composite", COMPIZ_COMPOSITE_ABI))
    return false;
  if (!CompPlugin::checkPluginABI("opengl", COMPIZ_OPENGL_ABI))
    return false;

  /*
   * GTK needs to be initialized or else unity's gdk/gtk calls will crash.
   * This is already done in compiz' main() if using ubuntu packages, but not
   * if you're using the regular (upstream) compiz.
   * Admittedly this is the same as what the "gtkloader" plugin does. But it
   * is faster, more efficient (one less plugin in memory), and more reliable
   * to do the init here where its needed. And yes, init'ing multiple times is
   * safe, and does nothing after the first init.
   */
  if (!gtk_init_check(&programArgc, &programArgv))
  {
    compLogMessage("unityshell", CompLogLevelError, "GTK init failed\n");
    return false;
  }

  return true;
}

namespace debug
{

ScreenIntrospection::ScreenIntrospection(CompScreen* screen)
  : screen_(screen)
{}

std::string ScreenIntrospection::GetName() const
{
  return "Screen";
}

void ScreenIntrospection::AddProperties(debug::IntrospectionData& introspection)
{}

Introspectable::IntrospectableList ScreenIntrospection::GetIntrospectableChildren()
{
  IntrospectableList children({uScreen->spread_filter_.get()});

  for (auto const& win : screen_->windows())
    children.push_back(UnityWindow::get(win));

  return children;
}

} // debug namespace

namespace
{

void reset_glib_logging()
{
  // Reinstate the default glib logger.
  g_log_set_default_handler(g_log_default_handler, NULL);
}

void configure_logging()
{
  // The default behaviour of the logging infrastructure is to send all output
  // to std::cout for warning or above.

  // TODO: write a file output handler that keeps track of backups.
  nux::logging::configure_logging(::getenv("UNITY_LOG_SEVERITY"));
  g_log_set_default_handler(capture_g_log_calls, NULL);
}

/* Checks whether an extension is supported by the GLX or OpenGL implementation
 * given the extension name and the list of supported extensions. */

#ifndef USE_GLES
gboolean is_extension_supported(const gchar* extensions, const gchar* extension)
{
  if (extensions != NULL && extension != NULL)
  {
    const gsize len = strlen(extension);
    gchar* p = (gchar*) extensions;
    gchar* end = p + strlen(p);

    while (p < end)
    {
      const gsize size = strcspn(p, " ");
      if (len == size && strncmp(extension, p, size) == 0)
        return TRUE;
      p += size + 1;
    }
  }

  return FALSE;
}

/* Gets the OpenGL version as a floating-point number given the string. */
gfloat get_opengl_version_f32(const gchar* version_string)
{
  gfloat version = 0.0f;
  gint32 i;

  for (i = 0; isdigit(version_string[i]); ++i)
    version = version * 10.0f + (version_string[i] - 48);

  if ((version_string[i] == '.' || version_string[i] == ',') &&
      isdigit(version_string[i + 1]))
  {
    version = version * 10.0f + (version_string[i + 1] - 48);
    return (version + 0.1f) * 0.1f;
  }
  else
    return 0.0f;
}
#endif

nux::logging::Level glog_level_to_nux(GLogLevelFlags log_level)
{
  // For some weird reason, ERROR is more critical than CRITICAL in gnome.
  if (log_level & G_LOG_LEVEL_ERROR)
    return nux::logging::Critical;
  if (log_level & G_LOG_LEVEL_CRITICAL)
    return nux::logging::Error;
  if (log_level & G_LOG_LEVEL_WARNING)
    return nux::logging::Warning;
  if (log_level & G_LOG_LEVEL_MESSAGE ||
      log_level & G_LOG_LEVEL_INFO)
    return nux::logging::Info;
  // default to debug.
  return nux::logging::Debug;
}

void capture_g_log_calls(const gchar* log_domain,
                         GLogLevelFlags log_level,
                         const gchar* message,
                         gpointer user_data)
{
  // If the environment variable is set, we capture the backtrace.
  static bool glog_backtrace = ::getenv("UNITY_LOG_GLOG_BACKTRACE");
  // If nothing else, all log messages from unity should be identified as such
  std::string module("unity");
  if (log_domain)
  {
    module += '.' + log_domain;
  }
  nux::logging::Logger logger(module);
  nux::logging::Level level = glog_level_to_nux(log_level);
  if (level >= logger.GetEffectiveLogLevel())
  {
    std::string backtrace;
    if (glog_backtrace && level >= nux::logging::Warning)
    {
      backtrace = "\n" + nux::logging::Backtrace();
    }
    nux::logging::LogStream(level, logger.module(), "<unknown>", 0).stream()
      << message << backtrace;
  }
}

} // anonymous namespace
} // namespace unity