~ubuntu-branches/ubuntu/oneiric/unity/oneiric

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
// -*- Mode: C++; indent-tabs-mode: nil; tab-width: 2 -*-
/* Compiz unity plugin
 * unity.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 "IconRenderer.h"
#include "Launcher.h"
#include "LauncherIcon.h"
#include "LauncherController.h"
#include "GeisAdapter.h"
#include "DevicesSettings.h"
#include "PluginAdapter.h"
#include "QuicklistManager.h"
#include "StartupNotifyService.h"
#include "Timer.h"
#include "KeyboardUtil.h"
#include "unityshell.h"
#include "BackgroundEffectHelper.h"

#include <dbus/dbus.h>
#include <dbus/dbus-glib.h>
#include <glib/gi18n-lib.h>
#include <gtk/gtk.h>
#include <gdk/gdk.h>
#include <libnotify/notify.h>

#include <sstream>

#include <core/atoms.h>

#include "unitya11y.h"

#include "ubus-server.h"
#include "UBusMessages.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"

using namespace unity::switcher;

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

using ::unity::util::Timer;

namespace
{

nux::logging::Logger logger("unity.shell");

UnityScreen* uScreen = 0;

void configure_logging();
void capture_g_log_calls(const gchar* log_domain,
                         GLogLevelFlags log_level,
                         const gchar* message,
                         gpointer user_data);
gboolean is_extension_supported(const gchar* extensions, const gchar* extension);
gfloat get_opengl_version_f32(const gchar* version_string);

}

UnityScreen::UnityScreen(CompScreen* screen)
  : BaseSwitchScreen (screen)
  , PluginClassHandler <UnityScreen, CompScreen> (screen)
  , screen(screen)
  , cScreen(CompositeScreen::get(screen))
  , gScreen(GLScreen::get(screen))
  , launcher(nullptr)
  , controller(nullptr)
  , panelController(nullptr)
  , switcherController(nullptr)
  , gestureEngine(nullptr)
  , wt(nullptr)
  , launcherWindow(nullptr)
  , panelWindow(nullptr)
  , debugger(nullptr)
  , needsRelayout(false)
  , relayoutSourceId(0)
  , _edge_trigger_handle(0)
  , _edge_pointerY(0)
  , newFocusedWindow(nullptr)
  , doShellRepaint(false)
  , allowWindowPaint(false)
  , damaged(false)
  , _key_nav_mode_requested(false)
  , _last_output(nullptr)
  , switcher_desktop_icon(nullptr)
  , mActiveFbo (0)
  , dash_is_open_ (false)
  , grab_index_ (0)
  , painting_tray_ (false)
{
  Timer timer;
  gfloat version;
  gchar* extensions;
  bool  failed = false;
  configure_logging();
  LOG_DEBUG(logger) << __PRETTY_FUNCTION__;
  int (*old_handler)(Display*, XErrorEvent*);
  old_handler = XSetErrorHandler(NULL);

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

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

     g_thread_init(NULL);
     dbus_g_thread_init();

     unity_a11y_preset_environment();

     XSetErrorHandler(old_handler);

     /* Wrap compiz interfaces */
     ScreenInterface::setHandler(screen);
     CompositeScreenInterface::setHandler(cScreen);
     GLScreenInterface::setHandler(gScreen);

     PluginAdapter::Initialize(screen);
     WindowManager::SetDefault(PluginAdapter::Default());

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

     nux::NuxInitialize(0);
     wt = nux::CreateFromForeignWindow(cScreen->output(),
				       glXGetCurrentContext(),
				       &UnityScreen::initUnity,
				       this);

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

     unity_a11y_init(wt);

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

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

     debugger = new DebugDBusInterface(this);

     _edge_timeout = optionGetLauncherRevealEdgeTimeout ();
     _in_paint = false;

     if (GL::fbo)
     {
       foreach (CompOutput & o, screen->outputDevs())
	     uScreen->mFbos[&o] = UnityFBO::Ptr (new UnityFBO(&o));

       uScreen->mFbos[&(screen->fullscreenOutput ())] = UnityFBO::Ptr (new UnityFBO(&(screen->fullscreenOutput ())));
     }

     optionSetLauncherHideModeNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));
     optionSetBacklightModeNotify(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));
     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));
     optionSetDevicesOptionNotify(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));
     optionSetPanelFirstMenuInitiate(boost::bind(&UnityScreen::showPanelFirstMenuKeyInitiate, this, _1, _2, _3));
     optionSetPanelFirstMenuTerminate(boost::bind(&UnityScreen::showPanelFirstMenuKeyTerminate, this, _1, _2, _3));
     optionSetLauncherRevealEdgeInitiate(boost::bind(&UnityScreen::launcherRevealEdgeInitiate, this, _1, _2, _3));
     optionSetLauncherRevealEdgeTimeoutNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));
     optionSetAutomaximizeValueNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));
     optionSetAltTabTimeoutNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));
     optionSetAltTabBiasViewportNotify(boost::bind(&UnityScreen::optionChanged, this, _1, _2));

     optionSetAltTabForwardInitiate(boost::bind(&UnityScreen::altTabForwardInitiate, this, _1, _2, _3));
     optionSetAltTabForwardTerminate(boost::bind(&UnityScreen::altTabTerminateCommon, this, _1, _2, _3));
     optionSetAltTabPrevInitiate(boost::bind(&UnityScreen::altTabPrevInitiate, this, _1, _2, _3));

     optionSetAltTabDetailStartInitiate(boost::bind(&UnityScreen::altTabDetailStartInitiate, this, _1, _2, _3));
     optionSetAltTabDetailStopInitiate(boost::bind(&UnityScreen::altTabDetailStopInitiate, 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));

     optionSetAltTabLeftInitiate (boost::bind (&UnityScreen::altTabPrevInitiate, this, _1, _2, _3));
     optionSetAltTabRightInitiate (boost::bind (&UnityScreen::altTabForwardInitiate, this, _1, _2, _3));
     optionSetShowMinimizedWindowsNotify (boost::bind (&UnityScreen::optionChanged, this, _1, _2));

     for (unsigned int i = 0; i < G_N_ELEMENTS(_ubus_handles); i++)
       _ubus_handles[i] = 0;

     UBusServer* ubus = ubus_server_get_default();
     _ubus_handles[0] = ubus_server_register_interest(ubus,
						      UBUS_LAUNCHER_START_KEY_NAV,
						      (UBusCallback)&UnityScreen::OnLauncherStartKeyNav,
						      this);

     _ubus_handles[1] = ubus_server_register_interest(ubus,
						      UBUS_LAUNCHER_END_KEY_NAV,
						      (UBusCallback)&UnityScreen::OnLauncherEndKeyNav,
						      this);

     _ubus_handles[2] = ubus_server_register_interest(ubus,
						      UBUS_QUICKLIST_END_KEY_NAV,
						      (UBusCallback)&UnityScreen::OnQuicklistEndKeyNav,
						      this);

     g_timeout_add(0, &UnityScreen::initPluginActions, this);
     super_keypressed_ = false;

     GeisAdapter::Default()->Run();
     gestureEngine = new GestureEngine(screen);

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

     BackgroundEffectHelper::updates_enabled = true;

     ubus_manager_.RegisterInterest(UBUS_PLACE_VIEW_SHOWN, [&](GVariant * args) { dash_is_open_ = true; });
     ubus_manager_.RegisterInterest(UBUS_PLACE_VIEW_HIDDEN, [&](GVariant * args) { dash_is_open_ = false; });
      LOG_INFO(logger) << "UnityScreen constructed: " << timer.ElapsedSeconds() << "s";
  }
}

UnityScreen::~UnityScreen()
{
  if (switcher_desktop_icon)
    switcher_desktop_icon->UnReference();
  panelController->UnReference();
  delete controller;
  delete switcherController;
  launcherWindow->UnReference();

  notify_uninit();

  unity_a11y_finalize();

  UBusServer* ubus = ubus_server_get_default();
  for (unsigned int i = 0; i < G_N_ELEMENTS(_ubus_handles); i++)
  {
    if (_ubus_handles[i] != 0)
      ubus_server_unregister_interest(ubus, _ubus_handles[i]);
  }

  if (relayoutSourceId != 0)
    g_source_remove(relayoutSourceId);

  ::unity::ui::IconRenderer::DestroyTextures();
  QuicklistManager::Destroy();

  delete wt;
}

void UnityScreen::initAltTabNextWindow()
{
  KeyboardUtil key_util (screen->dpy());
  guint above_tab_keycode = key_util.GetKeycodeAboveKeySymbol (XStringToKeysym("Tab"));
  KeySym above_tab_keysym = XKeycodeToKeysym (screen->dpy(), above_tab_keycode, 0);

  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
  {
    printf ("Could not find key above tab!\n");
  }

}

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

  _shortcut_actions.clear ();

  for (auto icon : *(launcher->GetModel()))
  {
    guint64 shortcut = icon->GetShortcut();
    if (shortcut == 0)
      continue;
    CreateSuperNewAction(static_cast<char>(shortcut));
    CreateSuperNewAction(static_cast<char>(shortcut), true);
    CreateSuperNewAction(static_cast<char>(shortcut), false, true);
  }

  for (auto shortcut : dashController->GetAllShortcuts())
    CreateSuperNewAction(shortcut);
}

void UnityScreen::CreateSuperNewAction(char shortcut, bool use_shift, bool use_numpad)
{
    CompActionPtr action(new CompAction());

    CompAction::KeyBinding binding;
    std::ostringstream sout;
    if (use_shift)
      sout << "<Shift><Super>"  << shortcut;
    else
      sout << "<Super>" << ((use_numpad) ? "KP_" : "") << shortcut;

    binding.fromString(sout.str());

    action->setKey(binding);

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

void UnityScreen::nuxPrologue()
{
  /* 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);

  /* reset matrices */
  glPushAttrib(GL_VIEWPORT_BIT | GL_ENABLE_BIT |
               GL_TEXTURE_BIT | GL_COLOR_BUFFER_BIT | GL_SCISSOR_BIT);

  glMatrixMode(GL_PROJECTION);
  glPushMatrix();

  glMatrixMode(GL_MODELVIEW);
  glPushMatrix();

  glGetError();
}

void UnityScreen::nuxEpilogue()
{
  (*GL::bindFramebuffer)(GL_FRAMEBUFFER_EXT, mActiveFbo);

  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();
  glDepthRange(0, 1);
  glViewport(-1, -1, 2, 2);
  glRasterPos2f(0, 0);

  gScreen->resetRasterPos();

  glMatrixMode(GL_PROJECTION);
  glPopMatrix();
  glMatrixMode(GL_MODELVIEW);
  glPopMatrix();

  glDrawBuffer(GL_BACK);
  glReadBuffer(GL_BACK);

  glPopAttrib();

  glDisable(GL_SCISSOR_TEST);
}

void UnityScreen::OnLauncherHiddenChanged()
{
  if (launcher->Hidden())
    screen->addAction(&optionGetLauncherRevealEdge());
  else
    screen->removeAction(&optionGetLauncherRevealEdge());
}

void UnityScreen::paintPanelShadow(const GLMatrix& matrix)
{
  if (relayoutSourceId > 0)
    return;

  if (PluginAdapter::Default()->IsExpoActive())
    return;

  nuxPrologue();

  CompOutput* output = _last_output;
  float vc[4];
  float h = 20.0f;
  float w = 1.0f;
  float panel_h = 24.0f;

  float x1 = output->x();
  float y1 = output->y() + panel_h;
  float x2 = x1 + output->width();
  float y2 = y1 + h;

  vc[0] = x1;
  vc[1] = x2;
  vc[2] = y1;
  vc[3] = y2;

  if (!dash_is_open_ && panelController->opacity() > 0.0f)
  {
    foreach(GLTexture * tex, _shadow_texture)
    {
      glEnable(GL_BLEND);
      glColor4f(1.0f, 1.0f, 1.0f, panelController->opacity());
      glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

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

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

      glBegin(GL_QUADS);
      {
        glTexCoord2f(COMP_TEX_COORD_X(tex->matrix(), 0), COMP_TEX_COORD_Y(tex->matrix(), 0));
        glVertex2f(vc[0], vc[2]);

        glTexCoord2f(COMP_TEX_COORD_X(tex->matrix(), 0), COMP_TEX_COORD_Y(tex->matrix(), h));
        glVertex2f(vc[0], vc[3]);

        glTexCoord2f(COMP_TEX_COORD_X(tex->matrix(), w), COMP_TEX_COORD_Y(tex->matrix(), h));
        glVertex2f(vc[1], vc[3]);

        glTexCoord2f(COMP_TEX_COORD_X(tex->matrix(), w), COMP_TEX_COORD_Y(tex->matrix(), 0));
        glVertex2f(vc[1], vc[2]);
      }
      glEnd();

      tex->disable();
      glDisable(GL_BLEND);
    }
  }
  nuxEpilogue();
}

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::paintDisplay(const CompRegion& region, const GLMatrix& transform, unsigned int mask)
{
  CompOutput *output = _last_output;
  Window     tray_xid = panelController->GetTrayXid ();
  bool       bound = mFbos[output]->bound ();


  if (bound)
  {
    mFbos[output]->unbind ();

    /* Draw the bit of the relevant framebuffer for each output */
    mFbos[output]->paint ();
  }

  nuxPrologue();

  nux::ObjectPtr<nux::IOpenGLTexture2D> device_texture =
  nux::GetGraphicsDisplay()->GetGpuDevice()->CreateTexture2DFromID(mFbos[output]->texture(),
  output->width(), output->height(), 1, nux::BITFMT_R8G8B8A8);

  nux::GetGraphicsDisplay()->GetGpuDevice()->backup_texture0_ = device_texture;

  nux::Geometry geo = nux::Geometry (output->x (), output->y (), output->width (), output->height ());
  BackgroundEffectHelper::monitor_rect_ = geo;

  _in_paint = true;
  wt->RenderInterfaceFromForeignCmd (&geo);
  _in_paint = false;
  nuxEpilogue();

  if (tray_xid && !allowWindowPaint)
  {
    CompWindow *tray = screen->findWindow (tray_xid);

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

      attrib.setOpacity (OPAQUE);
      attrib.setBrightness (BRIGHT);
      attrib.setSaturation (COLOR);

      oTransform.toScreenSpace (output, -DEFAULT_Z_CAMERA);

      glPushMatrix ();
      glLoadMatrixf (oTransform.getMatrix ());

      painting_tray_ = true;

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

      glPopMatrix ();
    }
  }

 if (switcherController->Visible ())
  {
    LayoutWindowList targets = switcherController->ExternalRenderTargets ();

    for (LayoutWindow::Ptr target : targets)
    {
      CompWindow* window = screen->findWindow(target->xid);
      if (window)
      {
        UnityWindow *unity_window = UnityWindow::get (window);

        unity_window->paintThumbnail (target->result, target->alpha);
      }
    }
  }

  doShellRepaint = false;
  damaged = false;
}

bool UnityScreen::forcePaintOnTop ()
{
    return !allowWindowPaint ||
	    ((switcherController->Visible() ||
	      dash_is_open_) && !fullscreen_windows_.empty () && (!(screen->grabbed () && !screen->otherGrabExist (NULL))));
}

void UnityWindow::paintThumbnail (nux::Geometry const& bounding, float alpha)
{
  GLMatrix matrix;
  matrix.toScreenSpace (UnityScreen::get (screen)->_last_output, -DEFAULT_Z_CAMERA);

  nux::Geometry geo = bounding;
  last_bound = geo;

  GLWindowPaintAttrib attrib = gWindow->lastPaintAttrib ();
  attrib.opacity = (GLushort) (alpha * G_MAXUSHORT);

  paintThumb (attrib,
              matrix,
              0,
              geo.x,
              geo.y,
              geo.width,
              geo.height,
              geo.width,
              geo.height);
}

void UnityScreen::enterShowDesktopMode ()
{
  for (CompWindow *w : screen->windows ())
  {
    if (UnityShowdesktopHandler::shouldHide (w))
      UnityWindow::get (w)->enterShowDesktop ();
    if (w->type() & CompWindowTypeDesktopMask)
      w->moveInputFocusTo();
  }

  PluginAdapter::Default()->OnShowDesktop();

  screen->enterShowDesktopMode ();
}

void UnityScreen::leaveShowDesktopMode (CompWindow *w)
{
  for (CompWindow *cw : screen->windows ())
    UnityWindow::get (cw)->leaveShowDesktop ();

  PluginAdapter::Default()->OnLeaveDesktop();

  screen->leaveShowDesktopMode (w);
}

void UnityWindow::enterShowDesktop ()
{
  if (!mShowdesktopHandler)
    mShowdesktopHandler = new UnityShowdesktopHandler (window);

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

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

bool UnityWindow::handleAnimations (unsigned int ms)
{
  if (mShowdesktopHandler)
    if (mShowdesktopHandler->animate (ms))
    { 
      delete mShowdesktopHandler;
      mShowdesktopHandler = NULL;
      return true;
    }

  return false;
}

/* 300 ms */
const unsigned int UnityShowdesktopHandler::fade_time = 300;
CompWindowList UnityShowdesktopHandler::animating_windows (0);

bool UnityShowdesktopHandler::shouldHide (CompWindow *w)
{
  if (!w->managed ())
    return false;

  if (w->grabbed ())
    return false;

  if (w->wmType () & (CompWindowTypeDesktopMask |
                      CompWindowTypeDockMask))
   return false;

  if (w->state () & CompWindowStateSkipPagerMask)
    return false;

  return true;
}

UnityShowdesktopHandler::UnityShowdesktopHandler (CompWindow *w) :
  mWindow (w),
  mRemover (new compiz::WindowInputRemover (screen->dpy (), w->id ())),
  mState (Visible),
  mProgress (0.0f)
{
}

UnityShowdesktopHandler::~UnityShowdesktopHandler ()
{
  if (mRemover)
    delete mRemover;
}

void UnityShowdesktopHandler::fadeOut ()
{
  mState = UnityShowdesktopHandler::FadeOut;
  mProgress = 1.0f;

  mWasHidden = mWindow->state () & CompWindowStateHiddenMask;

  if (!mWasHidden)
  {
    mWindow->changeState (mWindow->state () | CompWindowStateHiddenMask);
    mWindow->windowNotify (CompWindowNotifyHide);
    mRemover->save ();
    mRemover->remove ();
  }

  CompositeWindow::get (mWindow)->addDamage ();

  if (std::find (animating_windows.begin(),
                 animating_windows.end(),
                 mWindow) == animating_windows.end())
    animating_windows.push_back(mWindow);
}

void UnityShowdesktopHandler::fadeIn ()
{
  mState = UnityShowdesktopHandler::FadeIn;

  if (!mWasHidden)
  {
    mWindow->changeState (mWindow->state () & ~CompWindowStateHiddenMask);
    mWindow->windowNotify (CompWindowNotifyShow);
    mRemover->restore ();
  }

  CompositeWindow::get (mWindow)->addDamage ();
}

bool UnityShowdesktopHandler::animate (unsigned int ms)
{
  float inc = fade_time / (float) ms;

  if (mState == UnityShowdesktopHandler::FadeOut)
  {
    mProgress -= inc;
    if (mProgress <= 0.0f)
    {
      mProgress = 0.0f;
      mState = Invisible;
    }
    else
      CompositeWindow::get (mWindow)->addDamage ();
  }
  else if (mState == FadeIn)
  {
    mProgress += inc;
    if (mProgress >= 1.0f)
    {
      mProgress = 1.0f;
      mState = Visible;

      return true;
    }
    else
      CompositeWindow::get (mWindow)->addDamage ();
  }

  return false;
}

void UnityShowdesktopHandler::paintAttrib (GLWindowPaintAttrib &attrib)
{
  attrib.opacity = static_cast <int> (static_cast <float> (attrib.opacity) * mProgress);
}

unsigned int UnityShowdesktopHandler::getPaintMask ()
{
    return 0;
}

void UnityShowdesktopHandler::handleEvent (XEvent *event)
{
  /* Ignore sent events from the InputRemover */
  if (screen->XShape () && event->type ==
      screen->shapeEvent () + ShapeNotify &&
      !event->xany.send_event)
  {
    if (mRemover)
    {
      mRemover->save ();
      mRemover->remove ();
    }
  }
}

void UnityShowdesktopHandler::windowNotify (CompWindowNotify n)
{
  if (n == CompWindowNotifyFocusChange && mWindow->minimized ())
  {
    for (CompWindow *w : animating_windows)
      w->focusSetEnabled (UnityWindow::get (w), false);

    mWindow->moveInputFocusToOtherWindow ();

    for (CompWindow *w : animating_windows)
      w->focusSetEnabled (UnityWindow::get (w), true);
  }
}

void UnityShowdesktopHandler::updateFrameRegion (CompRegion &r)
{
  unsigned int oldUpdateFrameRegionIndex;
  r = CompRegion ();

  /* Ensure no other plugins can touch this frame region */
  oldUpdateFrameRegionIndex = mWindow->updateFrameRegionGetCurrentIndex ();
  mWindow->updateFrameRegionSetCurrentIndex (MAXSHORT);
  mWindow->updateFrameRegion (r);
  mWindow->updateFrameRegionSetCurrentIndex (oldUpdateFrameRegionIndex);
}

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

  /* bind the framebuffer here
   * - it will be unbound and flushed
   *   to the backbuffer when some
   *   plugin requests to draw a
   *   a transformed screen or when
   *   we have finished this draw cycle.
   *   once an fbo is bound any further
   *   attempts to bind it will only increment
   *   its bind reference so make sure that
   *   you always unbind as much as you bind */
  mFbos[output]->bind ();

  doShellRepaint = true;
  allowWindowPaint = true;
  _last_output = output;

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

  if (doShellRepaint)
    paintDisplay(region, transform, mask);

  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;
  gScreen->glPaintTransformedOutput(attrib, transform, region, output, mask);

}

void UnityScreen::preparePaint(int ms)
{
  CompWindowList remove_windows;

  cScreen->preparePaint(ms);

  for (CompWindow *w : UnityShowdesktopHandler::animating_windows)
    if (UnityWindow::get (w)->handleAnimations (ms))
      remove_windows.push_back(w);

  for (CompWindow *w : remove_windows)
    UnityShowdesktopHandler::animating_windows.remove (w);

  if (damaged)
  {
    damaged = false;
    damageNuxRegions();
  }

}

/* Grab changed nux regions and add damage rects for them */
void UnityScreen::damageNuxRegions()
{
  CompRegion nux_damage;

  if (damaged)
    return;

  std::vector<nux::Geometry> dirty = wt->GetDrawList();
  damaged = true;

  for (std::vector<nux::Geometry>::iterator it = dirty.begin(), end = dirty.end();
       it != end; ++it)
  {
    nux::Geometry const& geo = *it;
    nux_damage = CompRegion(geo.x, geo.y, geo.width, geo.height);
    cScreen->damageRegion(nux_damage);
  }

  nux::Geometry geo = wt->GetWindowCompositor().GetTooltipMainWindowGeometry();
  nux_damage = CompRegion(geo.x, geo.y, geo.width, geo.height);
  cScreen->damageRegion(nux_damage);

  geo = lastTooltipArea;
  nux_damage = CompRegion(lastTooltipArea.x, lastTooltipArea.y,
                          lastTooltipArea.width, lastTooltipArea.height);
  cScreen->damageRegion(nux_damage);

  wt->ClearDrawList();

  lastTooltipArea = geo;
}

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

  switch (event->type)
  {
    case FocusIn:
    case FocusOut:
      if (event->xfocus.mode == NotifyGrab)
        PluginAdapter::Default()->OnScreenGrabbed();
      else if (event->xfocus.mode == NotifyUngrab)
        PluginAdapter::Default()->OnScreenUngrabbed();
      cScreen->damageScreen();  // evil hack
      if (_key_nav_mode_requested)
        launcher->startKeyNavMode();
      _key_nav_mode_requested = false;
      break;
    case KeyPress:
      KeySym key_sym;
      char key_string[2];
      int result;
      if ((result = XLookupString(&(event->xkey), key_string, 2, &key_sym, 0)) > 0)
      {
        key_string[result] = 0;
        if (super_keypressed_) {
          skip_other_plugins = launcher->CheckSuperShortcutPressed(screen->dpy(), key_sym, event->xkey.keycode, event->xkey.state, key_string);
          if (!skip_other_plugins) {
            skip_other_plugins = dashController->CheckShortcutActivation(key_string);
            if (skip_other_plugins)
              launcher->SetLatestShortcut(key_string[0]);
          }
        }
      }
      default:
        if (screen->shapeEvent () + ShapeNotify == event->type)
        {
          Window xid = event->xany.window;
          CompWindow *w = screen->findWindow(xid);

          if (w)
          {
            UnityWindow *uw = UnityWindow::get (w);

            if (uw->mShowdesktopHandler)
              uw->mShowdesktopHandler->handleEvent(event);
          }
        }
      break;
  }

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

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

  if (event->type == PropertyNotify)
  {
    if (event->xproperty.atom == Atoms::mwmHints)
    {
      PluginAdapter::Default ()->NotifyNewDecorationState(event->xproperty.window);
    }
  }

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

  if (event->type == cScreen->damageEvent() + XDamageNotify)
  {
    XDamageNotifyEvent *de = (XDamageNotifyEvent *) event;
    CompWindow* w = screen->findWindow (de->drawable);

    if (w)
    {
      nux::Geometry damage (de->area.x, de->area.y, de->area.width, de->area.height);

      CompWindow::Geometry geom = w->geometry ();
      damage.x += geom.x () + geom.border ();
      damage.y += geom.y () + geom.border ();

      BackgroundEffectHelper::ProcessDamage(damage);
    }
  }
}

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

  if (dash_is_open_ && 
      strcmp(event, "start_viewport_switch") == 0)
  {
    ubus_server_send_message(ubus_server_get_default(), UBUS_PLACE_VIEW_CLOSE_REQUEST, NULL);
  }

  screen->handleCompizEvent(plugin, event, option);
}

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;
  launcher->StartKeyShowLauncher();
  EnsureSuperKeybindings ();
  return false;
}

bool UnityScreen::showLauncherKeyTerminate(CompAction* action,
                                           CompAction::State state,
                                           CompOption::Vector& options)
{
  super_keypressed_ = false;
  launcher->EndKeyShowLauncher();
  return false;
}

bool UnityScreen::showPanelFirstMenuKeyInitiate(CompAction* action,
                                                CompAction::State state,
                                                CompOption::Vector& options)
{
  grab_index_ = screen->pushGrab (None, "unityshell");
  // to receive the Terminate event
  action->setState(action->state() | CompAction::StateTermKey);
  panelController->StartFirstMenuShow();
  return false;
}

bool UnityScreen::showPanelFirstMenuKeyTerminate(CompAction* action,
                                                 CompAction::State state,
                                                 CompOption::Vector& options)
{
  screen->removeGrab(grab_index_, NULL);
  action->setState (action->state() & (unsigned)~(CompAction::StateTermKey));
  panelController->EndFirstMenuShow();
  return false;
}

gboolean UnityScreen::OnEdgeTriggerTimeout(gpointer data)
{
  UnityScreen* self = reinterpret_cast<UnityScreen*>(data);

  if (pointerX <= 1)
  {
    if (pointerY <= 24)
      return true;

    if (abs(pointerY - self->_edge_pointerY) <= 5)
    {
      self->launcher->EdgeRevealTriggered(pointerX, pointerY);
    }
    else
    {
      /* We are still in the edge, but moving in Y, maybe we need another chance */

      if (abs(pointerY - self->_edge_pointerY) > 20)
      {
        /* We're quite far from the first hit spot, let's wait again */
        self->_edge_pointerY = pointerY;
        return true;
      }
      else
      {
        /* We're quite near to the first hit spot, so we can reduce our timeout */
        self->_edge_pointerY = pointerY;
        g_source_remove(self->_edge_trigger_handle);
        self->_edge_trigger_handle = g_timeout_add(self->_edge_timeout/2,
                                                   &UnityScreen::OnEdgeTriggerTimeout,
                                                   self);
        return false;
      }
    }
  }

  self->_edge_trigger_handle = 0;
  return false;
}

bool UnityScreen::launcherRevealEdgeInitiate(CompAction* action,
                                             CompAction::State state,
                                             CompOption::Vector& options)
{
  if (screen->grabbed())
    return false;

  if (_edge_trigger_handle)
    g_source_remove(_edge_trigger_handle);

  if (pointerX <= 1)
  {
    _edge_pointerY = pointerY;
    _edge_trigger_handle = g_timeout_add(_edge_timeout,
                                         &UnityScreen::OnEdgeTriggerTimeout,
                                         this);
  }

  return false;
}

void UnityScreen::SendExecuteCommand()
{
  ubus_server_send_message(ubus_server_get_default(),
                           UBUS_PLACE_ENTRY_ACTIVATE_REQUEST,
                           g_variant_new("(sus)",
                                         "commands.lens",
                                         0,
                                         ""));
}

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

void UnityScreen::restartLauncherKeyNav()
{
  // set input-focus on launcher-window and start key-nav mode
  if (newFocusedWindow != NULL)
  {
    newFocusedWindow->moveInputFocusTo();
    launcher->startKeyNavMode();
  }
}

void UnityScreen::startLauncherKeyNav()
{
  // get CompWindow* of launcher-window
  newFocusedWindow = screen->findWindow(launcherWindow->GetInputWindowId());

  // check if currently focused window isn't the launcher-window
  if (newFocusedWindow != screen->findWindow(screen->activeWindow()))
    PluginAdapter::Default ()->saveInputFocus ();

  // set input-focus on launcher-window and start key-nav mode
  if (newFocusedWindow != NULL)
  {
    // 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.
    launcherWindow->PushToFront();
    newFocusedWindow->moveInputFocusTo();
  }
}

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

bool UnityScreen::altTabInitiateCommon(CompAction *action,
                                      CompAction::State state,
                                      CompOption::Vector& options)
{
  std::vector<AbstractLauncherIcon*> results;

  if (!grab_index_)
    grab_index_ = screen->pushGrab (screen->invisibleCursor(), "unity-switcher");
  if (!grab_index_)
    return false;

  if (!switcher_desktop_icon)
  {
    switcher_desktop_icon = new DesktopLauncherIcon(launcher);
    switcher_desktop_icon->SinkReference();
  }

  results.push_back(switcher_desktop_icon);

  LauncherModel::iterator it;
  for (it = launcher->GetModel()->begin(); it != launcher->GetModel()->end(); it++)
    if ((*it)->ShowInSwitcher())
      results.push_back(*it);

  screen->addAction (&optionGetAltTabRight ());
  screen->addAction (&optionGetAltTabDetailStart ());
  screen->addAction (&optionGetAltTabDetailStop ());
  screen->addAction (&optionGetAltTabLeft ());

  // maybe check launcher position/hide state?

  int device = screen->outputDeviceForPoint (pointerX, pointerY);
  switcherController->SetWorkspace(nux::Geometry(screen->outputDevs()[device].x1() + 100,
                                                 screen->outputDevs()[device].y1() + 100,
                                                 screen->outputDevs()[device].width() - 200,
                                                 screen->outputDevs()[device].height() - 200));
  switcherController->Show(SwitcherController::ALL, SwitcherController::FOCUS_ORDER, false, results);
  return true;
}

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;

    screen->removeAction (&optionGetAltTabRight ());
    screen->removeAction (&optionGetAltTabDetailStart ());
    screen->removeAction (&optionGetAltTabDetailStop ());
    screen->removeAction (&optionGetAltTabLeft ());

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

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

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

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


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

  return false;
}

bool UnityScreen::altTabDetailStartInitiate(CompAction* action, CompAction::State state, CompOption::Vector& options)
{
  if (switcherController->Visible())
    switcherController->SetDetail(true);

  return false;
}

bool UnityScreen::altTabDetailStopInitiate(CompAction* action, CompAction::State state, CompOption::Vector& options)
{
  if (switcherController->Visible())
    switcherController->SetDetail(false);

  return false;
}

bool UnityScreen::altTabNextWindowInitiate(CompAction* action, CompAction::State state, CompOption::Vector& options)
{
  if (!switcherController->Visible())
  {
    altTabInitiateCommon(action, state, options);
    switcherController->Select(1); // always select the current application
  }
  
  switcherController->NextDetail();

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

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

void UnityScreen::OnLauncherStartKeyNav(GVariant* data, void* value)
{
  UnityScreen* self = reinterpret_cast<UnityScreen*>(value);
  self->startLauncherKeyNav();
}

void UnityScreen::OnLauncherEndKeyNav(GVariant* data, void* value)
{
  bool preserve_focus = false;

  if (data)
  {
    preserve_focus = g_variant_get_boolean(data);
  }

  // Return input-focus to previously focused window (before key-nav-mode was
  // entered)
  if (preserve_focus)
    PluginAdapter::Default ()->restoreInputFocus ();
}

void UnityScreen::OnQuicklistEndKeyNav(GVariant* data, void* value)
{
  UnityScreen* self = reinterpret_cast<UnityScreen*>(value);
  self->restartLauncherKeyNav();
}

gboolean UnityScreen::initPluginActions(gpointer data)
{
  CompPlugin* p = CompPlugin::find("expo");

  if (p)
  {
    MultiActionList expoActions(0);

    foreach(CompOption & option, p->vTable->getOptions())
    {
      if (option.name() == "expo_key" ||
          option.name() == "expo_button" ||
          option.name() == "expo_edge")
      {
        CompAction* action = &option.value().action();
        expoActions.AddNewAction(action, false);
        break;
      }
    }

    PluginAdapter::Default()->SetExpoAction(expoActions);
  }

  p = CompPlugin::find("scale");

  if (p)
  {
    MultiActionList scaleActions(0);

    foreach(CompOption & option, p->vTable->getOptions())
    {
      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(action, false);
      }
      else if (option.name() == "initiate_all_button")
      {
        CompAction* action = &option.value().action();
        scaleActions.AddNewAction(action, true);
      }
    }

    PluginAdapter::Default()->SetScaleAction(scaleActions);
  }

  p = CompPlugin::find("unitymtgrabhandles");

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

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

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

void UnityScreen::AddProperties(GVariantBuilder* builder)
{
}

const gchar* UnityScreen::GetName()
{
  return "Unity";
}

bool isNuxWindow (CompWindow* value) 
{ 
  std::vector<Window> const& xwns = nux::XInputWindow::NativeHandleList();
  auto id = value->id();

  // iterate loop by hand rather than use std::find as this is considerably faster
  // we care about performance here becuase of the high frequency in which this function is
  // called (nearly every frame)
  unsigned int size = xwns.size();
  for (unsigned int i = 0; i < size; ++i)
  {
    if (xwns[i] == id)
      return true;
  }
  return false;
}

const CompWindowList& UnityScreen::getWindowPaintList()
{
  CompWindowList& pl = _withRemovedNuxWindows = cScreen->getWindowPaintList();
  pl.remove_if(isNuxWindow);

  return pl;
}

/* 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)
{
  GLWindowPaintAttrib wAttrib = attrib;

  if (mMinimizeHandler)
  {
    typedef compiz::CompizMinimizedWindowHandler<UnityScreen, UnityWindow> minimized_window_handler_unity;

    compiz::CompizMinimizedWindowHandler<UnityScreen, UnityWindow>::Ptr compizMinimizeHandler =
        boost::dynamic_pointer_cast <minimized_window_handler_unity> (mMinimizeHandler);
    mask |= compizMinimizeHandler->getPaintMask ();
  }
  else if (mShowdesktopHandler)
  {
    mShowdesktopHandler->paintAttrib (wAttrib);
    mask |= mShowdesktopHandler->getPaintMask ();
  }

  if (uScreen->panelController->GetTrayXid () == window->id () && !uScreen->allowWindowPaint)
  {
    if (!uScreen->painting_tray_)
    {
      uScreen->tray_paint_mask_ = mask;
      mask |= PAINT_WINDOW_NO_CORE_INSTANCE_MASK;
    }
  }

  return gWindow->glPaint(wAttrib, matrix, region, mask);
}

/* 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,
                         GLFragment::Attrib& attrib,
                         const CompRegion& region,
                         unsigned int mask)
{
  if (uScreen->doShellRepaint && !uScreen->forcePaintOnTop ())
  {
    std::vector<Window> const& xwns = nux::XInputWindow::NativeHandleList();
    unsigned int size = xwns.size();

    for (CompWindow* w = window; w && uScreen->doShellRepaint; w = w->prev)
    {
      auto id = w->id();
      for (unsigned int i = 0; i < size; ++i)
      {
        if (xwns[i] == id)
        {
          uScreen->paintDisplay(region, matrix, mask);
          break;
        }
      }
    }
  }

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

  if (window->type() == CompWindowTypeDesktopMask)
  {
    uScreen->paintPanelShadow(matrix);
  }

  return ret;
}

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

  if (!mMinimizeHandler)
  {
    mMinimizeHandler = compiz::MinimizedWindowHandler::Ptr (new compiz::CompizMinimizedWindowHandler<UnityScreen, UnityWindow> (window));
    mMinimizeHandler->minimize ();
  }
}

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

bool
UnityWindow::focus ()
{
  if (!mMinimizeHandler.get ())
    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 ()
{
  return mMinimizeHandler.get () != NULL;
}

gboolean
UnityWindow::FocusDesktopTimeout(gpointer data)
{
  UnityWindow *self = reinterpret_cast<UnityWindow*>(data);

  self->focusdesktop_handle_ = 0;

  for (CompWindow *w : screen->clientList ())
  {
    if (!(w->type() & NO_FOCUS_MASK) && w->focus ())
      return FALSE;
  }
  self->window->moveInputFocusTo();

  return FALSE;
}

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

  switch (n)
  {
    case CompWindowNotifyMap:
      if (window->type() == CompWindowTypeDesktopMask) {
        if (!focusdesktop_handle_)
           focusdesktop_handle_ = g_timeout_add (1000, &UnityWindow::FocusDesktopTimeout, this);
      }
      break;
    case CompWindowNotifyUnmap:
      if (UnityScreen::get (screen)->optionGetShowMinimizedWindows () &&
          window->mapNum ())
      {
        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);
      }
        break;
      default:
        break;
  }


  window->windowNotify(n);

  if (mMinimizeHandler.get () != NULL)
  {
    /* The minimize handler will short circuit the frame
     * region update func and ensure that the frame
     * does not have a region */
    typedef compiz::CompizMinimizedWindowHandler<UnityScreen, UnityWindow> minimized_window_handler_unity;

    compiz::CompizMinimizedWindowHandler<UnityScreen, UnityWindow>::Ptr compizMinimizeHandler =
        boost::dynamic_pointer_cast <minimized_window_handler_unity> (mMinimizeHandler);
    compizMinimizeHandler->windowNotify (n);
  }
  else if (mShowdesktopHandler)
  {
    mShowdesktopHandler->windowNotify (n);
  }

  // We do this after the notify to ensure input focus has actually been moved.
  if (n == CompWindowNotifyFocusChange)
  {
    UnityScreen* us = UnityScreen::get(screen);
    CompWindow *lw;
    
    if (us->dash_is_open_)
    {
      lw = screen->findWindow(us->launcherWindow->GetInputWindowId());
      lw->moveInputFocusTo();
    }
  }
}

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

  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 */
  typedef compiz::CompizMinimizedWindowHandler<UnityScreen, UnityWindow> minimized_window_handler_unity;

  compiz::CompizMinimizedWindowHandler<UnityScreen, UnityWindow>::Ptr compizMinimizeHandler =
      boost::dynamic_pointer_cast <minimized_window_handler_unity> (mMinimizeHandler);

  if (compizMinimizeHandler)
    compizMinimizeHandler->updateFrameRegion (region);
  else if (mShowdesktopHandler)
    mShowdesktopHandler->updateFrameRegion (region);
  else
    window->updateFrameRegion (region);
}

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

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

CompPoint UnityWindow::tryNotIntersectUI(CompPoint& pos)
{
  UnityScreen* us = UnityScreen::get(screen);
  Launcher::LauncherHideMode hideMode = us->launcher->GetHideMode();
  nux::Geometry geo = us->launcher->GetAbsoluteGeometry();
  CompRegion allowedWorkArea (screen->workArea ());
  CompRect launcherGeo(geo.x, geo.y, geo.width, geo.height);
  CompRegion wRegion (window->borderRect ());
  CompRegion intRegion;

  wRegion.translate (pos.x () - wRegion.boundingRect ().x (),
                     pos.y () - wRegion.boundingRect ().y ());

  /* subtract launcher and panel geometries from allowed workarea */
  if (!us->launcher->Hidden ())
  {
    switch (hideMode)
    {
      case Launcher::LAUNCHER_HIDE_DODGE_WINDOWS:
      case Launcher::LAUNCHER_HIDE_DODGE_ACTIVE_WINDOW:
        allowedWorkArea -= launcherGeo;
        break;

      default:
        break;
    }
  }

  for (nux::Geometry &g : us->panelController->GetGeometries ())
  {
    CompRect pg (g.x, g.y, g.width, g.height);
    allowedWorkArea -= pg;
  }

  /* Invert allowed work area */
  allowedWorkArea = CompRegion (screen->workArea ()) - allowedWorkArea;

  /* Now intersect the window region with the allowed work area
   * region, such that it splits up into a number of rects */
  intRegion = wRegion.intersected (allowedWorkArea);

  if (intRegion.rects ().size () > 1)
  {
    /* Now find the largest rect, this will be the area that we want to move to */
    CompRect largest;

    for (CompRect &r : intRegion.rects ())
    {
      if (r.area () > largest.area ())
        largest = r;
    }

    /* Now pad the largest rect with the other rectangles that
     * were intersecting, padding the opposite side to the one
     * that they are currently on on the large rect
     */

    intRegion -= largest;

    for (CompRect &r : intRegion.rects ())
    {
      if (r.x1 () > largest.x2 ())
        largest.setX (largest.x () - r.width ());
      else if (r.x2 () < largest.x ())
        largest.setWidth (largest.width () + r.width ());

      if (r.y1 () > largest.y2 ())
        largest.setY (largest.y () - r.height ());
      else if (r.y2 () < largest.y ())
        largest.setWidth (largest.height () + r.height ());
    }

    pos = largest.pos ();
  }

  if (launcherGeo.contains(pos))
    pos.setX(launcherGeo.x() + launcherGeo.width() + 1);

  return pos;
}

bool UnityWindow::place(CompPoint& pos)
{
  bool result = window->place(pos);

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

  pos = tryNotIntersectUI(pos);
  return result;
}

/* Configure callback for the launcher window */
void UnityScreen::launcherWindowConfigureCallback(int WindowWidth, int WindowHeight,
                                                  nux::Geometry& geo, void* user_data)
{
  UnityScreen* self = reinterpret_cast<UnityScreen*>(user_data);
  geo = nux::Geometry(self->_primary_monitor.x, self->_primary_monitor.y + 24,
                      geo.width, self->_primary_monitor.height - 24);
}

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

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

gboolean UnityScreen::OnRedrawTimeout(gpointer data)
{
  UnityScreen *self = reinterpret_cast<UnityScreen*>(data);

  self->_redraw_handle = 0;
  self->onRedrawRequested();

  return FALSE;
}

void UnityScreen::onRedrawRequested()
{
  // disable blur updates so we dont waste perf. This can stall the blur during animations
  // but ensures a smooth animation.
  if (_in_paint)
  {
    if (!_redraw_handle)
      _redraw_handle = g_timeout_add (0, &UnityScreen::OnRedrawTimeout, this);
  }
  else
  {
    damageNuxRegions();
  }
}

/* Handle option changes and plug that into nux windows */
void UnityScreen::optionChanged(CompOption* opt, UnityshellOptions::Options num)
{
  switch (num)
  {
    case UnityshellOptions::LauncherHideMode:
      launcher->SetHideMode((Launcher::LauncherHideMode) optionGetLauncherHideMode());
      break;
    case UnityshellOptions::BacklightMode:
      launcher->SetBacklightMode((Launcher::BacklightMode) optionGetBacklightMode());
      break;
    case UnityshellOptions::LaunchAnimation:
      launcher->SetLaunchAnimation((Launcher::LaunchAnimation) optionGetLaunchAnimation());
      break;
    case UnityshellOptions::UrgentAnimation:
      launcher->SetUrgentAnimation((Launcher::UrgentAnimation) optionGetUrgentAnimation());
      break;
    case UnityshellOptions::PanelOpacity:
      panelController->SetOpacity(optionGetPanelOpacity());
      break;
    case UnityshellOptions::LauncherOpacity:
      launcher->SetBackgroundAlpha(optionGetLauncherOpacity());
      break;
    case UnityshellOptions::IconSize:
    {
      CompPlugin         *p = CompPlugin::find ("expo");

      launcher->SetIconSize(optionGetIconSize() + 6, optionGetIconSize());
      dashController->launcher_width = optionGetIconSize() + 18;

      if (p)
      {
        CompOption::Vector &opts = p->vTable->getOptions ();

        for (CompOption &o : opts)
        {
          if (o.name () == std::string ("x_offset"))
          {
            CompOption::Value v;
            v.set (static_cast <int> (optionGetIconSize() + 18));

            screen->setOptionForPlugin (p->vTable->name ().c_str (), o.name ().c_str (), v);
            break;
          }
        }
      }
      break;
    }
    case UnityshellOptions::AutohideAnimation:
      launcher->SetAutoHideAnimation((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::DevicesOption:
      unity::DevicesSettings::GetDefault().SetDevicesOption((unity::DevicesSettings::DevicesOption) optionGetDevicesOption());
      break;
    case UnityshellOptions::LauncherRevealEdgeTimeout:
      _edge_timeout = optionGetLauncherRevealEdgeTimeout();
      break;
    case UnityshellOptions::AltTabTimeout:
      switcherController->detail_on_timeout = optionGetAltTabTimeout();
    case UnityshellOptions::AltTabBiasViewport:
      PluginAdapter::Default()->bias_active_to_viewport = optionGetAltTabBiasViewport();
      break;
    case UnityshellOptions::ShowMinimizedWindows:
      compiz::CompizMinimizedWindowHandler<UnityScreen, UnityWindow>::setFunctions (optionGetShowMinimizedWindows ());
      screen->enterShowDesktopModeSetEnabled (this, optionGetShowMinimizedWindows ());
      screen->leaveShowDesktopModeSetEnabled (this, optionGetShowMinimizedWindows ());
      break;
    default:
      break;
  }
}

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

void UnityScreen::ScheduleRelayout(guint timeout)
{
  if (relayoutSourceId == 0)
    relayoutSourceId = g_timeout_add(timeout, &UnityScreen::RelayoutTimeout, this);
}

void UnityScreen::Relayout()
{
  GdkRectangle rect;
  nux::Geometry lCurGeom;
  int panel_height = 24;

  if (!needsRelayout)
    return;

  if (GL::fbo)
  {
    foreach (CompOutput &o, screen->outputDevs ())
      uScreen->mFbos[&o] = UnityFBO::Ptr (new UnityFBO (&o));

    uScreen->mFbos[&(screen->fullscreenOutput ())] = UnityFBO::Ptr (new UnityFBO (&(screen->fullscreenOutput ())));
  }

  UScreen *uscreen = UScreen::GetDefault();
  int primary_monitor = uscreen->GetPrimaryMonitor();
  auto geo = uscreen->GetMonitorGeometry(primary_monitor);

  rect.x = geo.x;
  rect.y = geo.y;
  rect.width = geo.width;
  rect.height = geo.height;
  _primary_monitor = rect;

  wt->SetWindowSize(rect.width, rect.height);

  lCurGeom = launcherWindow->GetGeometry();
  launcher->SetMaximumHeight(rect.height - panel_height);

  g_debug("Setting to primary screen rect: x=%d y=%d w=%d h=%d",
          rect.x,
          rect.y,
          rect.width,
          rect.height);

  launcherWindow->SetGeometry(nux::Geometry(rect.x,
                                            rect.y + panel_height,
                                            lCurGeom.width,
                                            rect.height - panel_height));
  launcher->SetGeometry(nux::Geometry(rect.x,
                                      rect.y + panel_height,
                                      lCurGeom.width,
                                      rect.height - panel_height));
  needsRelayout = false;
}

gboolean UnityScreen::RelayoutTimeout(gpointer data)
{
  UnityScreen* uScr = reinterpret_cast<UnityScreen*>(data);

  uScreen->mFbos.clear ();

  uScr->NeedsRelayout ();
  uScr->Relayout();
  uScr->relayoutSourceId = 0;

  uScr->cScreen->damageScreen();

  return FALSE;
}

/* 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 && strcmp(name, "hsize") == 0)
    {
      controller->UpdateNumWorkspaces(screen->vpSize().width() * screen->vpSize().height());
    }
  }
  return status;
}

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

  ScheduleRelayout(500);
}

void UnityFBO::paint ()
{
  //CompositeScreen *cScreen = CompositeScreen::get (screen);
  //unsigned int    mask = cScreen->damageMask ();
  float texx, texy, texwidth, texheight;

  /* Must be completely unbound before painting */
  if (mBoundCnt)
    return;

  /* Draw the bit of the relevant framebuffer for each output */
  GLMatrix transform;

  glViewport (output->x (), screen->height () - output->y2 (), output->width (), output->height ());
  GLScreen::get (screen)->clearOutput (output, GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  transform.toScreenSpace (output, -DEFAULT_Z_CAMERA);
  glPushMatrix ();
  glLoadMatrixf (transform.getMatrix ());

  /* Note that texcoords here are normalized, so it's just (0,0)-(1,1) */
  texx = 0.0;
  texy = 0.0;
  texwidth = 1.0f;
  texheight = 1.0f;

  if (mFBTexture)
  {
    glEnable (GL_TEXTURE_2D);
    GL::activeTexture (GL_TEXTURE0_ARB);
    glBindTexture (GL_TEXTURE_2D, mFBTexture);
    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    glPushAttrib (GL_SCISSOR_BIT);
    glEnable (GL_SCISSOR_TEST);

    glScissor (output->x1 (), screen->height () - output->y2 (),
               output->width (), output->height ());

    /* FIXME: This needs to be GL_TRIANGLE_STRIP */
    glBegin (GL_QUADS);
    glTexCoord2f (texx, texy + texheight);
    glVertex2i   (output->x1 (), output->y1 ());
    glTexCoord2f (texx, texy);
    glVertex2i   (output->x1 (), output->y2 ());
    glTexCoord2f (texx + texwidth, texy);
    glVertex2i   (output->x2 (), output->y2 ());
    glTexCoord2f (texx + texwidth, texy + texheight);
    glVertex2i   (output->x2 (),  output->y1 ());
    glEnd ();

    GL::activeTexture (GL_TEXTURE0_ARB);
    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glBindTexture (GL_TEXTURE_2D, 0);
    glEnable (GL_TEXTURE_2D);

    glDisable (GL_SCISSOR_TEST);
    glPopAttrib ();
  }

  glPopMatrix();
}

void UnityFBO::unbind ()
{
  mBoundCnt--;

  if (mBoundCnt)
    return;

  uScreen->setActiveFbo (0);
  (*GL::bindFramebuffer) (GL_FRAMEBUFFER_EXT, 0);

  glDrawBuffer (GL_BACK);
  glReadBuffer (GL_BACK);

}

bool UnityFBO::bound ()
{
  return mBoundCnt > 0;
}

bool UnityFBO::status ()
{
  return mFboStatus;
}

void UnityFBO::bind ()
{
  if (mBoundCnt)
  {
    mBoundCnt++;
    return;
  }

  if (!mFBTexture)
  {
    glGenTextures (1, &mFBTexture);

    glBindTexture (GL_TEXTURE_2D, mFBTexture);
    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, output->width(), output->height(), 0, GL_BGRA,
#if IMAGE_BYTE_ORDER == MSBFirst
                 GL_UNSIGNED_INT_8_8_8_8_REV,
#else
                 GL_UNSIGNED_BYTE,
#endif
                 NULL);

    glBindTexture (GL_TEXTURE_2D, 0);
  }

  glGetError ();

  (*GL::bindFramebuffer) (GL_FRAMEBUFFER_EXT, mFboHandle);

  (*GL::framebufferTexture2D) (GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT,
                               GL_TEXTURE_2D, mFBTexture, 0);

  (*GL::framebufferTexture2D) (GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT,
                               GL_TEXTURE_2D, 0, 0);

  /* Ensure that a framebuffer is actually available */
  if (!mFboStatus)
  {
    GLint status = (*GL::checkFramebufferStatus) (GL_DRAW_FRAMEBUFFER);

    if (status != GL_FRAMEBUFFER_COMPLETE)
    {
      switch (status)
      {
        case GL_FRAMEBUFFER_UNDEFINED:
          compLogMessage ("unity", CompLogLevelWarn, "no window");
          break;
        case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
          compLogMessage ("unity", CompLogLevelWarn, "attachment incomplete");
          break;
        case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
          compLogMessage ("unity", CompLogLevelWarn, "no buffers attached to fbo");
          break;
        case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER:
          compLogMessage ("unity", CompLogLevelWarn, "some attachment in glDrawBuffers doesn't exist in FBO");
          break;
        case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER:
          compLogMessage ("unity", CompLogLevelWarn, "some attachment in glReadBuffers doesn't exist in FBO");
          break;
        case GL_FRAMEBUFFER_UNSUPPORTED:
          compLogMessage ("unity", CompLogLevelWarn, "unsupported internal format");
          break;
        case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:
          compLogMessage ("unity", CompLogLevelWarn, "different levels of sampling for each attachment");
          break;
        case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS:
          compLogMessage ("unity", CompLogLevelWarn, "number of layers is different");
          break;
        default:
          compLogMessage ("unity", CompLogLevelWarn, "unable to bind the framebuffer for an unknown reason");
          break;
      }

      GL::bindFramebuffer (GL_FRAMEBUFFER_EXT, 0);
      GL::deleteFramebuffers (1, &mFboHandle);

      glDrawBuffer (GL_BACK);
      glReadBuffer (GL_BACK);

      mFboHandle = 0;

      mFboStatus = false;
      uScreen->setActiveFbo (0);
    }
    else
      mFboStatus = true;
  }

  if (mFboStatus)
  {
    uScreen->setActiveFbo (mFboHandle);

    glDrawBuffer (GL_COLOR_ATTACHMENT0_EXT);
    glReadBuffer (GL_COLOR_ATTACHMENT0_EXT);

    glViewport (0,
               0,
               output->width(),
               output->height());

    mBoundCnt++;
  }
}

UnityFBO::UnityFBO (CompOutput *o)
 : mFboStatus (false)
 , mFBTexture (0)
 , output (o)
 , mBoundCnt (0)
{
  (*GL::genFramebuffers) (1, &mFboHandle);
}

UnityFBO::~UnityFBO ()
{
  (*GL::deleteFramebuffers) (1, &mFboHandle);

  if (mFBTexture)
    glDeleteTextures (1, &mFBTexture);
}

/* Start up the launcher */
void UnityScreen::initLauncher(nux::NThread* thread, void* InitData)
{
  Timer timer;
  UnityScreen* self = reinterpret_cast<UnityScreen*>(InitData);

  self->launcherWindow = new nux::BaseWindow(TEXT("LauncherWindow"));
  self->launcherWindow->SinkReference();

  self->launcher = new Launcher(self->launcherWindow);
  self->launcher->display = self->screen->dpy();
  self->launcher->hidden_changed.connect(sigc::mem_fun(self, &UnityScreen::OnLauncherHiddenChanged));

  self->AddChild(self->launcher);

  nux::HLayout* layout = new nux::HLayout(NUX_TRACKER_LOCATION);
  layout->AddView(self->launcher, 1);
  layout->SetContentDistribution(nux::eStackLeft);
  layout->SetVerticalExternalMargin(0);
  layout->SetHorizontalExternalMargin(0);

  self->controller = new LauncherController(self->launcher);

  self->launcherWindow->SetConfigureNotifyCallback(&UnityScreen::launcherWindowConfigureCallback, self);
  self->launcherWindow->SetLayout(layout);
  self->launcherWindow->SetBackgroundColor(nux::Color(0x00000000));
  self->launcherWindow->ShowWindow(true);
  self->launcherWindow->EnableInputWindow(true, "launcher", false, false);
  self->launcherWindow->InputWindowEnableStruts(true);
  self->launcherWindow->SetEnterFocusInputArea(self->launcher);

  self->switcherController = new SwitcherController();
  /* FIXME: this should not be manual, should be managed with a
     show/hide callback like in GAIL*/
  if (unity_a11y_initialized () == TRUE)
    {
      AtkObject *atk_obj = NULL;

      atk_obj = unity_util_accessible_add_window (self->launcherWindow);

      atk_object_set_name (atk_obj, _("Launcher"));
    }

  self->launcher->SetIconSize(54, 48);
  self->launcher->SetBacklightMode(Launcher::BACKLIGHT_ALWAYS_ON);

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

  /* Setup panel */
  timer.Reset();
  self->panelController = new PanelController();
  self->AddChild(self->panelController);
  LOG_INFO(logger) << "initLauncher-Panel " << timer.ElapsedSeconds() << "s";

  /* Setup Places */
  self->dashController = DashController::Ptr(new DashController());

  /* FIXME: this should not be manual, should be managed with a
     show/hide callback like in GAIL
  if (unity_a11y_initialized() == TRUE)
  {
    AtkObject* atk_obj = NULL;

    atk_obj = unity_util_accessible_add_window(self->placesController->GetWindow());

    atk_object_set_name(atk_obj, _("Places"));
  }
  */

  self->launcher->SetHideMode(Launcher::LAUNCHER_HIDE_DODGE_WINDOWS);
  self->launcher->SetLaunchAnimation(Launcher::LAUNCH_ANIMATION_PULSE);
  self->launcher->SetUrgentAnimation(Launcher::URGENT_ANIMATION_WIGGLE);
  self->ScheduleRelayout(0);

  self->OnLauncherHiddenChanged();
}

/* Window init */
UnityWindow::UnityWindow(CompWindow* window)
  : BaseSwitchWindow (dynamic_cast<BaseSwitchScreen *> (UnityScreen::get (screen)), window)
  , PluginClassHandler<UnityWindow, CompWindow>(window)
  , window(window)
  , gWindow(GLWindow::get(window))
  , mShowdesktopHandler(nullptr)
  , focusdesktop_handle_(0)
{
  WindowInterface::setHandler(window);
  GLWindowInterface::setHandler(gWindow);

  if (UnityScreen::get (screen)->optionGetShowMinimizedWindows () &&
      window->mapNum ())
  {
    bool wasMinimized = window->minimized ();
    if (wasMinimized)
      window->unminimize ();
    window->minimizeSetEnabled (this, true);
    window->unminimizeSetEnabled (this, true);
    window->minimizedSetEnabled (this, true);

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

  if (window->state () & CompWindowStateFullscreenMask)
    UnityScreen::get (screen)->fullscreen_windows_.push_back(window);
  
  if (window->resName() == "onboard")
  {
    Window xid = UnityScreen::get (screen)->dashController->window()->GetInputWindowId();
    XSetTransientForHint (screen->dpy(), window->id(), xid);
  }
}

UnityWindow::~UnityWindow()
{
  UnityScreen* us = UnityScreen::get(screen);
  if (us->newFocusedWindow && (UnityWindow::get(us->newFocusedWindow) == this))
    us->newFocusedWindow = NULL;

  UnityShowdesktopHandler::animating_windows.remove (window);

  if (mMinimizeHandler)
  {
    unminimize ();
    window->focusSetEnabled (this, false);
    window->minimizeSetEnabled (this, false);
    window->unminimizeSetEnabled (this, false);
    window->minimizedSetEnabled (this, false);
    window->minimize ();

    mMinimizeHandler.reset ();
  }
  if (mShowdesktopHandler)
    delete mShowdesktopHandler;
    
  if (focusdesktop_handle_)
    g_source_remove(focusdesktop_handle_);

  if (window->state () & CompWindowStateFullscreenMask)
    UnityScreen::get (screen)->fullscreen_windows_.remove(window);

  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;

  return true;
}


namespace
{

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

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)
{
  // Since we aren't entirely sure if log_domain contains anything, lets have
  // a glib prefix.
  std::string module("glib");
  if (log_domain)
  {
    module += std::string(".") + log_domain;
  }
  nux::logging::Logger logger(module);
  nux::logging::Level level = glog_level_to_nux(log_level);
  if (logger.GetEffectiveLogLevel() >= level)
  {
    nux::logging::LogStream(level, logger.module(), "<unknown>", 0).stream()
        << message;
  }
}

} // anonymous namespace