File: unityPlatformX11.c

package info (click to toggle)
open-vm-tools 1%3A8.4.2-261024-1
  • links: PTS, VCS
  • area: contrib
  • in suites: squeeze
  • size: 20,368 kB
  • ctags: 30,043
  • sloc: ansic: 164,785; sh: 10,713; cpp: 6,525; makefile: 3,386
file content (3304 lines) | stat: -rw-r--r-- 97,055 bytes parent folder | download | duplicates (2)
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
/*********************************************************
 * Copyright (C) 2007-2008 VMware, Inc. All rights reserved.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA.
 *
 *********************************************************/

/**
 * @file unityPlatformX11.c
 *
 * Implementation of Unity for guest operating systems that use the X11 windowing
 * system. This file holds the basic things such as initialization/destruction of the
 * UnityPlatform object, overall event handling, and handling of some Unity
 * RPCs that are not window-centric.
 */

#include "unityX11.h"
#include "appUtil.h"
#include "region.h"
#include <sys/time.h>

#include <X11/extensions/Xinerama.h>
#include <X11/extensions/XTest.h>

typedef struct {
   Window realWindowID;
   XEvent xevent;
} UnityTemporaryEvent;

static UnitySpecialWindow *USWindowCreate(UnityPlatform *up,
                                           UnitySpecialEventHandler evHandler,
                                           Window *windows,
                                           int windowCount);
static void USWindowUpdate(UnityPlatform *up,
                           UnitySpecialWindow *usw,
                           Window *windows,
                           int windowCount);
static UnitySpecialWindow *USWindowLookup(UnityPlatform *up, Window window);
static void USWindowDestroy(UnityPlatform *up, UnitySpecialWindow *usw);

static void UnityPlatformProcessXEvent(UnityPlatform *up,
                                       const XEvent *xevent,
                                       Window realEventWindow);
static Window UnityPlatformGetRealEventWindow(UnityPlatform *up, const XEvent *xevent);
static void USRootWindowsProcessEvent(UnityPlatform *up,
                                       UnitySpecialWindow *usw,
                                       const XEvent *xevent,
                                       Window window);
static int UnityPlatformXErrorHandler(Display *dpy, XErrorEvent *xev);
static UnitySpecialWindow *UnityPlatformMakeRootWindowsObject(UnityPlatform *up);

static void UnityPlatformSendClientMessageFull(Display *d,
                                               Window destWindow,
                                               Window w,
                                               Atom messageType,
                                               int format,
                                               int numItems,
                                               const void *data);
static void UnityPlatformStackDnDDetWnd(UnityPlatform *up);
static void UnityPlatformDnDSendClientMessage(UnityPlatform *up,
                                              Window destWindow,
                                              Window w,
                                              Atom messageType,
                                              int format,
                                              int numItems,
                                              const void *data);

static Bool GetRelevantWMWindow(UnityPlatform *up,
                                UnityWindowId windowId,
                                Window *wmWindow);
static Bool SetWindowStickiness(UnityPlatform *up,
                                UnityWindowId windowId,
                                Bool wantSticky);

static const GuestCapabilities platformUnityCaps[] = {
   UNITY_CAP_WORK_AREA,
   UNITY_CAP_START_MENU,
   UNITY_CAP_MULTI_MON,
   UNITY_CAP_VIRTUAL_DESK,
   UNITY_CAP_STICKY_WINDOWS,
};

/*
 * Has to be global for UnityPlatformXErrorHandler
 */
static int unityX11ErrorCount = 0;

/*
 *----------------------------------------------------------------------------
 *
 * UnityPlatformIsSupported --
 *
 *      Determine whether this guest supports unity.
 *
 * Results:
 *      TRUE if the guest supports Unity
 *      FALSE otherwise
 *
 * Side effects:
 *      None
 *
 *----------------------------------------------------------------------------
 */

Bool
UnityPlatformIsSupported(void)
{
   Display *dpy;
   int major;
   int event_base;
   int error_base;

   dpy = GDK_DISPLAY();
   /*
    * Unity/X11 doesn't yet work with the new vmwgfx driver.  Until that is
    * fixed, we have to disable the feature.
    *
    * As for detecting which driver is in use, the legacy driver provides the
    * VMWARE_CTRL extension for resolution and topology operations, while the
    * new driver is instead controlled via XRandR.  If we don't find said
    * extension, then we'll assume the new driver is in use and disable Unity.
    */
   if (XQueryExtension(dpy, "VMWARE_CTRL", &major, &event_base, &error_base) ==
       False) {
      Debug("Unity is not yet supported under the vmwgfx driver.\n");
      return FALSE;
   }

   return TRUE;
}


/*
 *----------------------------------------------------------------------------
 *
 * UnityPlatformInit --
 *
 *      Initialize the UnityPlatform object that represents the platform-specific state.
 *
 * Results:
 *      Pointer to newly allocated UnityPlatform data.
 *
 * Side effects:
 *      No.
 *
 *----------------------------------------------------------------------------
 */

UnityPlatform *
UnityPlatformInit(UnityWindowTracker *tracker,                            // IN
                  UnityUpdateChannel *updateChannel,                      // IN
                  int *blockedWnd,                                        // IN, not used
                  DesktopSwitchCallbackManager *desktopSwitchCallbackMgr) // IN, not used
{
   UnityPlatform *up;
   char *displayName;

   ASSERT(tracker);
   ASSERT(updateChannel);

   Debug("UnityPlatformInit: Running\n");

   up = Util_SafeCalloc(1, sizeof *up);
   up->tracker = tracker;
   up->updateChannel = updateChannel;

   up->savedScreenSaverTimeout = -1;

   /*
    * Because GDK filters events heavily, and we need to do a lot of low-level X work, we
    * just open another connection to the same display.
    */
   displayName = gdk_get_display();
   up->display = XOpenDisplay(displayName);
   if (!up->display) {
      free(up);
      return NULL; // We couldn't connect to the display for some strange reason
   }
   XSetErrorHandler(UnityPlatformXErrorHandler);
   XSynchronize(up->display, TRUE); // So error counting works properly...

   /*
    * Certain applications, like gnome-session during logout, may grab the X
    * server before displaying a modal window.  With the server grabbed, we're
    * unable to correctly track and display windows.
    *
    * The following snippet attempts to work around this by using the XTest
    * extension's ability to make ourselves impervious to X server grabs.
    */
   {
      int dummy1;
      int dummy2;
      int major;
      int minor;

      if ((XTestQueryExtension(up->display, &dummy1, &dummy2,
                               &major, &minor) == True) &&
          ((major > 2) || (major == 2 && minor >= 2))) {
         if (XTestGrabControl(up->display, True) != 1) {
            Debug("XTestGrabControl failed.\n");
         }
      } else {
         Debug("XTest extension not available.\n");
      }
   }

   up->allWindows = HashTable_Alloc(128, HASH_INT_KEY, NULL);
   up->specialWindows = HashTable_Alloc(32, HASH_INT_KEY, NULL);
   up->desktopWindow = NULL;
   up->desktopInfo.initialDesktop = UNITY_X11_INITIALDESKTOP_UNSET;

   /*
    * Find the values of all the atoms
    */
#  define INIT_ATOM(x) up->atoms.x = XInternAtom(up->display, #x, False)

   INIT_ATOM(_NET_WM_WINDOW_TYPE);
   INIT_ATOM(_NET_WM_WINDOW_TYPE_DESKTOP);
   INIT_ATOM(_NET_WM_WINDOW_TYPE_DOCK);
   INIT_ATOM(_NET_WM_WINDOW_TYPE_TOOLBAR);
   INIT_ATOM(_NET_WM_WINDOW_TYPE_TOOLTIP);
   INIT_ATOM(_NET_WM_WINDOW_TYPE_DROPDOWN_MENU);
   INIT_ATOM(_NET_WM_WINDOW_TYPE_POPUP_MENU);
   INIT_ATOM(_NET_WM_WINDOW_TYPE_MENU);
   INIT_ATOM(_NET_WM_WINDOW_TYPE_UTILITY);
   INIT_ATOM(_NET_WM_WINDOW_TYPE_SPLASH);
   INIT_ATOM(_NET_WM_WINDOW_TYPE_DIALOG);
   INIT_ATOM(_NET_WM_WINDOW_TYPE_NORMAL);
   INIT_ATOM(_NET_WM_WINDOW_TYPE_DND);
   INIT_ATOM(_NET_WM_STATE);
   INIT_ATOM(_NET_WM_STATE_HIDDEN);
   INIT_ATOM(_NET_WM_STATE_MODAL);
   INIT_ATOM(_NET_WM_STATE_STICKY);
   INIT_ATOM(_NET_WM_STATE_MAXIMIZED_HORZ);
   INIT_ATOM(_NET_WM_STATE_MAXIMIZED_VERT);
   INIT_ATOM(_NET_WM_STATE_MINIMIZED);
   INIT_ATOM(_NET_WM_STATE_SHADED);
   INIT_ATOM(_NET_WM_STATE_SKIP_TASKBAR);
   INIT_ATOM(_NET_WM_STATE_SKIP_PAGER);
   INIT_ATOM(_NET_WM_STATE_FULLSCREEN);
   INIT_ATOM(_NET_WM_STATE_ABOVE);
   INIT_ATOM(_NET_WM_STATE_BELOW);
   INIT_ATOM(_NET_WM_STATE_DEMANDS_ATTENTION);
   INIT_ATOM(_NET_WM_USER_TIME);
   INIT_ATOM(_NET_WM_USER_TIME_WINDOW);
   INIT_ATOM(_NET_ACTIVE_WINDOW);
   INIT_ATOM(_NET_RESTACK_WINDOW);
   INIT_ATOM(_NET_WM_ICON);
   INIT_ATOM(_NET_WM_PID);
   INIT_ATOM(_NET_WM_STRUT);
   INIT_ATOM(_NET_WM_STRUT_PARTIAL);
   INIT_ATOM(_NET_MOVERESIZE_WINDOW);
   INIT_ATOM(_NET_CLOSE_WINDOW);
   INIT_ATOM(_NET_WM_ALLOWED_ACTIONS);
   INIT_ATOM(_NET_WM_ACTION_MOVE);
   INIT_ATOM(_NET_WM_ACTION_RESIZE);
   INIT_ATOM(_NET_WM_ACTION_MINIMIZE);
   INIT_ATOM(_NET_WM_ACTION_SHADE);
   INIT_ATOM(_NET_WM_ACTION_STICK);
   INIT_ATOM(_NET_WM_ACTION_MAXIMIZE_HORZ);
   INIT_ATOM(_NET_WM_ACTION_MAXIMIZE_VERT);
   INIT_ATOM(_NET_WM_ACTION_FULLSCREEN);
   INIT_ATOM(_NET_WM_ACTION_CHANGE_DESKTOP);
   INIT_ATOM(_NET_WM_ACTION_CLOSE);
   INIT_ATOM(_NET_NUMBER_OF_DESKTOPS);
   INIT_ATOM(_NET_WM_DESKTOP);
   INIT_ATOM(_NET_CURRENT_DESKTOP);
   INIT_ATOM(_NET_DESKTOP_LAYOUT);
   INIT_ATOM(_NET_SUPPORTED);
   INIT_ATOM(_NET_FRAME_EXTENTS);
   INIT_ATOM(WM_CLASS);
   INIT_ATOM(WM_CLIENT_LEADER);
   INIT_ATOM(WM_DELETE_WINDOW);
   INIT_ATOM(WM_ICON);
   INIT_ATOM(WM_NAME);
   INIT_ATOM(WM_PROTOCOLS);
   INIT_ATOM(WM_STATE);
   INIT_ATOM(WM_TRANSIENT_FOR);
   INIT_ATOM(WM_WINDOW_ROLE);

#  undef INIT_ATOM

#if defined(VM_HAVE_X11_SHAPE_EXT)
   if (!XShapeQueryExtension(up->display, &up->shapeEventBase, &up->shapeErrorBase)) {
      up->shapeEventBase = 0;
   }
#endif

   return up;
}


/*
 *----------------------------------------------------------------------------
 *
 * UnityPlatformCleanup --
 *
 *      One-time platform-specific cleanup code.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */

void
UnityPlatformCleanup(UnityPlatform *up) // IN
{
   if (!up) {
      return;
   }

   /*
    * Caller should've called Unity_Exit first.
    */
   ASSERT(!up->isRunning);
   ASSERT(up->glibSource == NULL);

   if (up->specialWindows) {
      HashTable_Free(up->specialWindows);
      up->specialWindows = NULL;
   }
   if (up->allWindows) {
      HashTable_Free(up->allWindows);
      up->allWindows = NULL;
   }

   if (up->display) {
      XCloseDisplay(up->display);
      up->display = NULL;
   }

   free(up->desktopInfo.guestDesktopToUnity);
   up->desktopInfo.guestDesktopToUnity = NULL;
   free(up->desktopInfo.unityDesktopToGuest);
   up->desktopInfo.unityDesktopToGuest = NULL;
   up->desktopWindow = NULL;

   free(up);
}


/*
 *----------------------------------------------------------------------------
 *
 * UnityPlatformRegisterCaps --
 *
 *      Register guest platform specific capabilities with the VMX.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */

void
UnityPlatformRegisterCaps(UnityPlatform *up) // IN
{
   ASSERT(up);

   if (!RpcOut_sendOne(NULL, NULL, UNITY_RPC_SHOW_TASKBAR_CAP " %d",
                       Unity_IsSupported() ? 1 : 0)) {
      Debug("Could not set unity show taskbar cap\n");
   }

   AppUtil_SendGuestCaps(platformUnityCaps, ARRAYSIZE(platformUnityCaps), TRUE);
}


/*
 *----------------------------------------------------------------------------
 *
 * UnityPlatformUnregisterCaps --
 *
 *      Unregister guest platform specific capabilities with the VMX.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */

void
UnityPlatformUnregisterCaps(UnityPlatform *up) // IN
{
   /*
    * This function may potentially be called during UnityPlatform destruction.
    */
   if (!up) {
      return;
   }

   AppUtil_SendGuestCaps(platformUnityCaps, ARRAYSIZE(platformUnityCaps), FALSE);

   if (!RpcOut_sendOne(NULL, NULL, UNITY_RPC_SHOW_TASKBAR_CAP " 0")) {
      Debug("Failed to unregister Unity taskbar capability\n");
   }
}


/*****************************************************************************
 * Unity main loop and event handling                                        *
 *****************************************************************************/


/*
 *-----------------------------------------------------------------------------
 *
 * USWindowCreate --
 *
 *      Creates a new UnitySpecialWindow. Ownership of the 'windows' memory is taken over
 *      by the newly created object, but that memory MUST be malloc'd...
 *
 * Results:
 *      New UnitySpecialWindow object.
 *
 * Side effects:
 *      Allocates memory.
 *
 *-----------------------------------------------------------------------------
 */

static UnitySpecialWindow *
USWindowCreate(UnityPlatform *up,                    // IN
               UnitySpecialEventHandler evHandler,   // IN
               Window *windows,                      // IN
               int windowCount)                      // IN
{
   UnitySpecialWindow *usw;

   ASSERT(up);

   usw = Util_SafeCalloc(1, sizeof *usw);
   usw->evHandler = evHandler;
   USWindowUpdate(up, usw, windows, windowCount);

   return usw;
}


/*
 *-----------------------------------------------------------------------------
 *
 * USWindowUpdate --
 *
 *      Updates this USWindow with a new list of X windows. Ownership of the 'windows'
 *      memory is taken over by this USWindow object. That memory MUST be malloc'd...
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Old window list may be destroyed and freed.
 *
 *-----------------------------------------------------------------------------
 */

static void
USWindowUpdate(UnityPlatform *up,       // IN
               UnitySpecialWindow *usw, // IN
               Window *windows,         // IN
               int windowCount)         // IN
{
   int i;

   ASSERT(up);
   ASSERT(usw);

   for (i = 0; i < usw->numWindows; i++) {
      XSelectInput(up->display, usw->windows[i], 0);
      HashTable_Delete(up->specialWindows, GUINT_TO_POINTER(usw->windows[i]));
   }

   free(usw->windows);
   usw->windows = windows;
   usw->numWindows = windowCount;

   for (i = 0; i < windowCount; i++) {
      HashTable_Insert(up->specialWindows, GUINT_TO_POINTER(windows[i]), usw);
   }
}


/*
 *-----------------------------------------------------------------------------
 *
 * USWindowLookup --
 *
 *      Looks up a special window
 *
 * Results:
 *      UnitySpecialWindow object
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

static UnitySpecialWindow *
USWindowLookup(UnityPlatform *up, // IN
               Window window)     // IN
{
   UnitySpecialWindow *retval = NULL;

   HashTable_Lookup(up->specialWindows, GUINT_TO_POINTER(window), (void **)&retval);

   return retval;
}


/*
 *-----------------------------------------------------------------------------
 *
 * USWindowDestroy --
 *
 *      Destroys a UnitySpecialWindow
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Memory is freed.
 *
 *-----------------------------------------------------------------------------
 */

static void
USWindowDestroy(UnityPlatform *up,       // IN
                UnitySpecialWindow *usw) // IN
{
   int i;

   ASSERT(up);
   ASSERT(usw);

   for (i = 0; i < usw->numWindows; i++) {
      HashTable_Delete(up->specialWindows, GUINT_TO_POINTER(usw->windows[i]));

      if (usw->windowsAreOwned) {
         XDestroyWindow(up->display, usw->windows[i]);
      } else {
         /*
          * For now, assume we don't have any special windows that get extension events
          * and need a call like XScreenSaverSelectInput...
          */
         XSelectInput(up->display, usw->windows[i], 0);
      }
   }
   free(usw->windows);

   free(usw);
}


/*
 *-----------------------------------------------------------------------------
 *
 * UnityPlatformMakeRootWindowsObject --
 *
 *      Creates a UnitySpecialWindow to handle the root windows.
 *
 * Results:
 *      UnitySpecialWindow
 *
 * Side effects:
 *      Selects for events on the root windows.
 *
 *-----------------------------------------------------------------------------
 */

static UnitySpecialWindow *
UnityPlatformMakeRootWindowsObject(UnityPlatform *up) // IN
{
   static const long eventMask =
      StructureNotifyMask
      | PropertyChangeMask
      | SubstructureNotifyMask
      | FocusChangeMask;
   int i;
   int numRootWindows;
   Window *rootWindows;

   ASSERT(up);

   numRootWindows = ScreenCount(up->display);
   ASSERT(numRootWindows > 0);

   rootWindows = Util_SafeCalloc(numRootWindows, sizeof rootWindows[0]);
   for (i = 0; i < numRootWindows; i++) {
      rootWindows[i] = RootWindow(up->display, i);
   }

   for (i = 0; i < numRootWindows; i++) {
      XSelectInput(up->display, rootWindows[i], eventMask);
   }

   return USWindowCreate(up, USRootWindowsProcessEvent, rootWindows, numRootWindows);
}


/*
 *-----------------------------------------------------------------------------
 *
 * UnityPlatformGetErrorCount --
 *
 *      Retrieves the current count of X11 errors received by Unity.
 *
 * Results:
 *      Current error count.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

int
UnityPlatformGetErrorCount(UnityPlatform *up) // IN
{
   return unityX11ErrorCount;
}


/*
 *-----------------------------------------------------------------------------
 *
 * UnityPlatformResetErrorCount --
 *
 *      Resets the Unity X11 error count to zero.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Error count reset.
 *
 *-----------------------------------------------------------------------------
 */

void
UnityPlatformResetErrorCount(UnityPlatform *up) // IN
{
   unityX11ErrorCount = 0;
}


/*
 *-----------------------------------------------------------------------------
 *
 * UnityPlatformXErrorHandler --
 *
 *      Handler for all X event errors.
 *
 * Results:
 *      1.
 *
 * Side effects:
 *      Updates our X11 error counter.
 *
 *-----------------------------------------------------------------------------
 */

static int
UnityPlatformXErrorHandler(Display *dpy,     // IN
                           XErrorEvent *xev) // IN
{
   char buf[1024];
   XGetErrorText(dpy, xev->error_code, buf, sizeof buf);
   Debug("> VMwareUserXErrorHandler: error %s on resource %#lx for request %d\n",
         buf, xev->resourceid, xev->request_code);

   unityX11ErrorCount++;

   return 1;
}


/*
 *-----------------------------------------------------------------------------
 *
 * UnityPlatformGetServerTime --
 *
 *      Returns an educated guess at the X server's current timestamp
 *
 * Results:
 *      X server timestamp
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

Time
UnityPlatformGetServerTime(UnityPlatform *up) // IN
{
   Time retval;
   struct timeval tv;

   gettimeofday(&tv, NULL);
   retval = up->eventTimeDiff + (tv.tv_sec * 1000) + (tv.tv_usec / 1000);

   Debug("UserTime is guessed at %lu\n", retval);

   return retval;
}


/*
 *-----------------------------------------------------------------------------
 *
 * ComparePointers --
 *
 *      Compares two pointers to see whether they're equal.
 *
 * Results:
 *      -1, 0, or 1 (same meaning as strcmp return values)
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

static INLINE int
ComparePointers(const void *p1, // IN
                const void *p2) // IN
{
   /*
    * Helper function for UnityPlatformKillHelperThreads
    */
   const void * const *ptr1 = p1;
   const void * const *ptr2 = p2;
   ptrdiff_t diff = (*ptr2 - *ptr1);

   if (diff < 0) {
      return -1;
   } else if (diff > 0) {
      return 1;
   }

   return 0;
}


/*
 *----------------------------------------------------------------------------
 *
 * UnityPlatformKillHelperThreads --
 *
 *      Tears down the Unity "running" state.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Restores system settings.
 *
 *----------------------------------------------------------------------------
 */

void
UnityPlatformKillHelperThreads(UnityPlatform *up) // IN
{
   UnityPlatformWindow **upwList;
   UnitySpecialWindow **uswList;
   size_t i;
   size_t numWindows;

   if (!up || !up->isRunning) {
      ASSERT(up->glibSource == NULL);
      return;
   }

   UnityX11EventTeardownSource(up);

   up->desktopInfo.numDesktops = 0; // Zero means host has not set virtual desktop config
   UnityX11RestoreSystemSettings(up);

   HashTable_ToArray(up->allWindows,
                     (void ***)&upwList,
                     &numWindows);
   qsort(upwList, numWindows, sizeof *upwList, ComparePointers);
   for (i = 0; i < numWindows; i++) {
      if (i < (numWindows - 1) && upwList[i] == upwList[i + 1]) {
         continue;
      }

      UPWindow_Unref(up, upwList[i]);
   }
   free(upwList);

   up->workAreas = NULL;
   up->rootWindows = NULL;
   HashTable_ToArray(up->specialWindows,
                     (void ***)&uswList,
                     &numWindows);
   qsort(uswList, numWindows, sizeof *uswList, ComparePointers);
   for (i = 0; i < numWindows; i++) {
      if (i < (numWindows - 1) && uswList[i] == uswList[i + 1]) {
         continue;
      }

      USWindowDestroy(up, uswList[i]);
   }
   free(uswList);

   XSync(up->display, TRUE);
   up->desktopInfo.initialDesktop = UNITY_X11_INITIALDESKTOP_UNSET;
   up->isRunning = FALSE;

   Debug("Leaving unity mode\n");
}


/*
 *-----------------------------------------------------------------------------
 *
 * UnityX11GetWMProtocols --
 *
 *      Updates the list of protocols supported by the window manager.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

static void
UnityX11GetWMProtocols(UnityPlatform *up) // IN
{
   Atom propertyType;
   int propertyFormat;
   unsigned long itemsReturned;
   unsigned long bytesRemaining;
   Atom *valueReturned = NULL;

   ASSERT(up);

   memset(up->wmProtocols, 0, sizeof up->wmProtocols);
   if (XGetWindowProperty(up->display, up->rootWindows->windows[0],
                          up->atoms._NET_SUPPORTED, 0,
                          1024, False, AnyPropertyType,
                          &propertyType, &propertyFormat, &itemsReturned,
                          &bytesRemaining, (unsigned char **)&valueReturned)
      != Success) {
      return;
   }

   if ((propertyType == XA_ATOM || propertyType == XA_CARDINAL)
       && propertyFormat == 32) {
      int i;

      for (i = 0; i < itemsReturned; i++) {
         if (valueReturned[i] == up->atoms._NET_MOVERESIZE_WINDOW) {
            up->wmProtocols[UNITY_X11_WM__NET_MOVERESIZE_WINDOW] = TRUE;
         } else if (valueReturned[i] == up->atoms._NET_CLOSE_WINDOW) {
            up->wmProtocols[UNITY_X11_WM__NET_CLOSE_WINDOW] = TRUE;
         } else if (valueReturned[i] == up->atoms._NET_RESTACK_WINDOW) {
            up->wmProtocols[UNITY_X11_WM__NET_RESTACK_WINDOW] = TRUE;
         } else if (valueReturned[i] == up->atoms._NET_ACTIVE_WINDOW) {
            up->wmProtocols[UNITY_X11_WM__NET_ACTIVE_WINDOW] = TRUE;
         } else if (valueReturned[i] == up->atoms._NET_WM_ACTION_MINIMIZE) {
            up->wmProtocols[UNITY_X11_WM__NET_WM_ACTION_MINIMIZE] = TRUE;
         } else if (valueReturned[i] == up->atoms._NET_WM_ACTION_CLOSE) {
            up->wmProtocols[UNITY_X11_WM__NET_WM_ACTION_CLOSE] = TRUE;
         } else if (valueReturned[i] == up->atoms._NET_WM_ACTION_SHADE) {
            up->wmProtocols[UNITY_X11_WM__NET_WM_ACTION_SHADE] = TRUE;
         } else if (valueReturned[i] == up->atoms._NET_WM_ACTION_STICK) {
            up->wmProtocols[UNITY_X11_WM__NET_WM_ACTION_STICK] = TRUE;
         } else if (valueReturned[i] == up->atoms._NET_WM_ACTION_FULLSCREEN) {
            up->wmProtocols[UNITY_X11_WM__NET_WM_ACTION_FULLSCREEN] = TRUE;
         } else if (valueReturned[i] == up->atoms._NET_WM_ACTION_MAXIMIZE_HORZ) {
            up->wmProtocols[UNITY_X11_WM__NET_WM_ACTION_MAXIMIZE_HORZ] = TRUE;
         } else if (valueReturned[i] == up->atoms._NET_WM_ACTION_MAXIMIZE_VERT) {
            up->wmProtocols[UNITY_X11_WM__NET_WM_ACTION_MAXIMIZE_VERT] = TRUE;
         } else if (valueReturned[i] == up->atoms._NET_FRAME_EXTENTS) {
            up->wmProtocols[UNITY_X11_WM__NET_FRAME_EXTENTS] = TRUE;
         } else if (valueReturned[i] == up->atoms._NET_WM_STRUT_PARTIAL) {
            up->wmProtocols[UNITY_X11_WM__NET_WM_STRUT_PARTIAL] = TRUE;
         } else if (valueReturned[i] == up->atoms._NET_WM_STATE_HIDDEN) {
            up->wmProtocols[UNITY_X11_WM__NET_WM_STATE_HIDDEN] = TRUE;
         } else if (valueReturned[i] == up->atoms._NET_WM_STATE_MINIMIZED) {
            up->wmProtocols[UNITY_X11_WM__NET_WM_STATE_MINIMIZED] = TRUE;
         }
      }
   }

   XFree(valueReturned);
}


/*
 *----------------------------------------------------------------------------
 *
 * UnityPlatformStartHelperThreads --
 *
 *      Start Unity running.
 *
 * Results:
 *      TRUE if successful
 *      FALSE otherwise
 *
 * Side effects:
 *      Saves and changes system settings.
 *      Starts watching for windowing system events.
 *
 *----------------------------------------------------------------------------
 */

Bool
UnityPlatformStartHelperThreads(UnityPlatform *up) // IN
{
   ASSERT(up);
   ASSERT(up->glibSource == NULL);

   XSync(up->display, TRUE);
   up->rootWindows = UnityPlatformMakeRootWindowsObject(up);
   up->isRunning = TRUE;
   up->eventTimeDiff = 0;

   UnityX11SaveSystemSettings(up);

   UnityX11GetWMProtocols(up);

   if (up->desktopInfo.numDesktops) {
      UnityDesktopId activeDesktop;

      UnityPlatformSyncDesktopConfig(up);

      if (up->desktopInfo.initialDesktop != UNITY_X11_INITIALDESKTOP_UNSET) {
         Debug("%s: Setting activeDesktop to initialDesktop (%u).\n", __func__,
               up->desktopInfo.initialDesktop);
         activeDesktop = up->desktopInfo.initialDesktop;
      } else {
         activeDesktop = UnityWindowTracker_GetActiveDesktop(up->tracker);
      }
      if (UnityPlatformSetDesktopActive(up, activeDesktop)) {;
         /*
          * XXX Rather than setting this directly here, should we instead wait for a
          * PropertyNotify event from the window manager to one of the root windows?
          * Doing so may be safer in that it confirms that our request was honored by
          * the window manager.
          */
         UnityWindowTracker_ChangeActiveDesktop(up->tracker, activeDesktop);
      }
   }

   if (up->needWorkAreas) {
      /*
       * UNEXPECTED: The host called SetDesktopWorkArea before entering Unity mode, so we
       * need to go back and apply the remembered work area info.
       */

      UnityPlatformSetDesktopWorkAreas(up, up->needWorkAreas, up->needNumWorkAreas);
      free(up->needWorkAreas);
      up->needWorkAreas = NULL;
   }

   /*
    * Set up a callback in the glib main loop to listen for incoming X events on the
    * unity display connection.
    */
   UnityX11EventEstablishSource(up);

   return TRUE;
}


/*
 *----------------------------------------------------------------------------
 *
 * UnityPlatformIsUnityRunning --
 *
 *      Check to see if we are still in the unity mode.
 *
 * Results:
 *      TRUE if we are in Unity mode
 *      FALSE otherwise.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */

Bool
UnityPlatformIsUnityRunning(UnityPlatform *up) // IN
{
   ASSERT(up);

   return up->isRunning;
}


/*
 *----------------------------------------------------------------------------
 *
 * UnityPlatformLock --
 *
 *      Does nothing - our implementation is not threaded.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None (really).
 *
 *----------------------------------------------------------------------------
 */

void
UnityPlatformLock(UnityPlatform *up) // IN
{
}


/*
 *----------------------------------------------------------------------------
 *
 * UnityPlatformUnlock --
 *
 *      Does nothing - our implementation is not threaded.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */

void
UnityPlatformUnlock(UnityPlatform *up) // IN
{
}


/*
 *----------------------------------------------------------------------------
 *
 * UnityPlatformUpdateZOrder --
 *
 *      Push the Z-Order of all windows into the window tracker.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */

static void
UnityPlatformUpdateZOrder(UnityPlatform *up) // IN
{
   UnityWindowId *elements;
   size_t numElements;
   UnityPlatformWindow *curWindow;

   ASSERT(up);
   if (!up->stackingChanged) {
      return;
   }

   elements = alloca(UNITY_MAX_WINDOWS * sizeof elements[0]);
   for (numElements = 0, curWindow = up->topWindow;
        curWindow; curWindow = curWindow->lowerWindow) {
      if (curWindow->isRelevant) {
         elements[numElements++] = curWindow->toplevelWindow;
      }
   }

   UnityWindowTracker_SetZOrder(up->tracker,
                                elements,
                                numElements);
   up->stackingChanged = FALSE;
}


/*
 *----------------------------------------------------------------------------
 *
 * UnityPlatformUpdateWindowState --
 *
 *      Walk through /all/ the windows on the guest, pushing everything we know about
 *      them into the unity window tracker.
 *
 * Results:
 *      TRUE indicating we need help from the common code to generate
 *      remove window events (see unity.c)
 *
 * Side effects:
 *      None
 *
 *----------------------------------------------------------------------------
 */

Bool
UnityPlatformUpdateWindowState(UnityPlatform *up,               // IN
                               UnityWindowTracker *tracker)     // IN
{
   int curRoot;
   Window lowerWindow = None;

   if (!up || !up->rootWindows) {
      Debug("BUG: UpdateWindowState was called before we are fully in Unity mode...\n");
      return FALSE;
   }

   for (curRoot = 0; curRoot < up->rootWindows->numWindows; curRoot++) {
      int i;
      Window dummyWin;
      Window *children;
      unsigned int numChildren;

      XQueryTree(up->display, up->rootWindows->windows[curRoot],
                 &dummyWin, &dummyWin, &children, &numChildren);

      for (i = 0; i < numChildren; i++) {
         UnityPlatformWindow *upw;

         if (!HashTable_Lookup(up->allWindows,
                               GUINT_TO_POINTER(children[i]),
                               (void **)&upw)) {
            upw = UPWindow_Create(up, children[i]);
            if (!upw) {
               continue; // Window may have disappeared since the XQueryTree
            }
            UPWindow_CheckRelevance(up, upw, NULL);
            UPWindow_Restack(up, upw, lowerWindow);
         }

	 lowerWindow = upw->toplevelWindow;
      }

      XFree(children);
   }

   UnityPlatformUpdateZOrder(up);
   /*
    * up is not populated with the window layout structure when
    * UnityPlatformUpdateDnDDetWnd is intially called.
    */
   UnityPlatformStackDnDDetWnd(up);

   if (up->needTaskbarSetting) {
      up->needTaskbarSetting = FALSE;
      /*
       * This is called in this seemingly random spot to make sure that the taskbar
       * visibility is properly set once we have a full picture of the windowing system
       * state. Although the routine is called prior to this by SaveSystemSettings(), the
       * up->allWindows hash table is not complete until this point, which occurs at a
       * random time of the host's choosing.
       */
      UnityPlatformSetTaskbarVisible(up, up->currentSettings[UNITY_UI_TASKBAR_VISIBLE]);
   }

   return FALSE;
}


/*
 *-----------------------------------------------------------------------------
 *
 * UnityX11HandleEvents --
 *
 *      Handle incoming events
 *
 * Results:
 *      TRUE if the main loop should continue watching for events from the display.
 *
 * Side effects:
 *      Events read from the X display and processed.
 *
 *-----------------------------------------------------------------------------
 */

gboolean
UnityX11HandleEvents(gpointer data) // IN
{
   UnityPlatform *up = (UnityPlatform *) data;
   GList *incomingEvents = NULL;
   Bool restackDetWnd = FALSE;

   ASSERT(up);
   ASSERT(up->isRunning);

   Debug("Starting unity event handling\n");
   while (XEventsQueued(up->display, QueuedAfterFlush)) {
      /*
       * This outer loop is here to make sure we really process all available events
       * before returning.
       */

      while (XEventsQueued(up->display, QueuedAlready)) {
         UnityTemporaryEvent *ev;

         ev = Util_SafeCalloc(1, sizeof *ev);
         XNextEvent(up->display, &ev->xevent);
         ev->realWindowID = UnityPlatformGetRealEventWindow(up, &ev->xevent);

         /*
          * Restack dnd detection window when either
          *   1.  the desktop window may overlap detection window, or
          *   2.  a window is inserted directly above the desktop (and therefore
          *       below the DND window).
          */
         if (up->desktopWindow &&
             ev->xevent.type == ConfigureNotify &&
             (up->desktopWindow->toplevelWindow == ev->realWindowID ||
              up->desktopWindow->toplevelWindow == ev->xevent.xconfigure.above)) {
            restackDetWnd = TRUE;
         }

         if (ev->xevent.type == DestroyNotify) {
            /*
             * Unfortunately, X's event-driven model has an inherent race condition for
             * parties that are observing events on windows that are controlled by other
             * applications. Basically, if we're processing an event on a window, that
             * window may have already been destroyed, and there doesn't seem to really
             * be a way to detect this. We just have to try to cut down the probability
             * of those as much as possible, by discarding any events on a window if
             * they're immediately followed by a DestroyNotify on the same window...
             */
            GList *curItem;
            GList *nextItem = NULL;

            for (curItem = incomingEvents; curItem; curItem = nextItem) {
               UnityTemporaryEvent *otherEvent = curItem->data;
               nextItem = curItem->next;

               if (otherEvent->realWindowID == ev->realWindowID) {
                  free(curItem->data);
                  incomingEvents = g_list_remove_link(incomingEvents, curItem);
               }
            }
         }

         incomingEvents = g_list_append(incomingEvents, ev);
      }

      while (incomingEvents) {
         GList *nextItem;
         UnityTemporaryEvent *tempEvent = incomingEvents->data;

         UnityPlatformProcessXEvent(up, &tempEvent->xevent, tempEvent->realWindowID);

         nextItem = incomingEvents->next;
         free(incomingEvents->data);
         g_list_free_1(incomingEvents);
         incomingEvents = nextItem;
      }

      if (restackDetWnd) {
         UnityPlatformStackDnDDetWnd(up);
      }
      UnityPlatformUpdateZOrder(up);
      UnityPlatformDoUpdate(up, TRUE);
   }

   return TRUE;
}


/*
 *-----------------------------------------------------------------------------
 *
 * UnityPlatformGetEventString --
 *
 *      Allows stringifying events for debugging purposes
 *
 * Results:
 *      A stringified version of the event name. It's a static value - do not free this.
 *
 * Side effects:
 *      None.
 *-----------------------------------------------------------------------------
 */

const char *
UnityPlatformGetEventString(UnityPlatform *up, // IN
                            int type)          // IN
{
#if defined(VM_HAVE_X11_SHAPE_EXT)
   if (up->shapeEventBase
       && type == (up->shapeEventBase + ShapeNotify)) {
      return "ShapeNotify";
   }
#endif

   switch (type) {
   case KeyPress: return "KeyPress";
   case KeyRelease: return "KeyRelease";
   case ButtonPress: return "ButtonPress";
   case ButtonRelease: return "ButtonRelease";
   case MotionNotify: return "MotionNotify";
   case EnterNotify: return "EnterNotify";
   case LeaveNotify: return "LeaveNotify";
   case FocusIn: return "FocusIn";
   case FocusOut: return "FocusOut";
   case KeymapNotify: return "KeymapNotify";
   case Expose: return "Expose";
   case GraphicsExpose: return "GraphicsExpose";
   case NoExpose: return "NoExpose";
   case VisibilityNotify: return "VisibilityNotify";
   case CreateNotify: return "CreateNotify";
   case DestroyNotify: return "DestroyNotify";
   case UnmapNotify: return "UnmapNotify";
   case MapNotify: return "MapNotify";
   case MapRequest: return "MapRequest";
   case ReparentNotify: return "ReparentNotify";
   case ConfigureNotify: return "ConfigureNotify";
   case ConfigureRequest: return "ConfigureRequest";
   case GravityNotify: return "GravityNotify";
   case ResizeRequest: return "ResizeRequest";
   case CirculateNotify: return "CirculateNotify";
   case CirculateRequest: return "CirculateRequest";
   case PropertyNotify: return "PropertyNotify";
   case SelectionClear: return "SelectionClear";
   case SelectionRequest: return "SelectionRequest";
   case SelectionNotify: return "SelectionNotify";
   case ColormapNotify: return "ColormapNotify";
   case ClientMessage: return "ClientMessage";
   case MappingNotify: return "MappingNotify";
   default: return "<Unknown>";
   }
}


/*
 *-----------------------------------------------------------------------------
 *
 * UnityPlatformGetRealEventWindow --
 *
 *      For debugging purposes, retrieves the window that the event happened on (as
 *      opposed to the window the event was sent to)
 *
 * Results:
 *      The window that the event actually happened on.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

static Window
UnityPlatformGetRealEventWindow(UnityPlatform *up,    // IN
                                const XEvent *xevent) // IN
{
#if defined(VM_HAVE_X11_SHAPE_EXT)
   if (up->shapeEventBase
       && xevent->type == (up->shapeEventBase + ShapeNotify)) {
      XShapeEvent *sev = (XShapeEvent *) xevent;

      return sev->window;
   }
#endif

   switch (xevent->type) {
   case CreateNotify:
      return xevent->xcreatewindow.window;

   case DestroyNotify:
      return xevent->xdestroywindow.window;

   case MapNotify:
      return xevent->xmap.window;

   case UnmapNotify:
      return xevent->xunmap.window;

   case ReparentNotify:
      return xevent->xreparent.window;

   case ConfigureNotify:
      return xevent->xconfigure.window;

   case CirculateNotify:
      return xevent->xcirculate.window;

   case PropertyNotify:
      return xevent->xproperty.window;

   case FocusIn:
   case FocusOut:
      return xevent->xfocus.window;

   default:
      return xevent->xany.window;

   }
}


/*
 *-----------------------------------------------------------------------------
 *
 * UnityPlatformUpdateEventTimeDiff --
 *
 *      Updates our idea of the difference between X server time and our local time.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Updated event time diff.
 *
 *-----------------------------------------------------------------------------
 */

static void
UnityPlatformUpdateEventTimeDiff(UnityPlatform *up,    // IN
                                 const XEvent *xevent) // IN
{
   Time serverTime;
   Time localTime;
   struct timeval localTv;

   switch (xevent->type) {
   case KeyPress:
   case KeyRelease:
      serverTime = xevent->xkey.time;
      break;
   case ButtonPress:
   case ButtonRelease:
      serverTime = xevent->xbutton.time;
      break;
   case MotionNotify:
      serverTime = xevent->xmotion.time;
      break;
   case EnterNotify:
   case LeaveNotify:
      serverTime = xevent->xcrossing.time;
      break;
   case PropertyNotify:
      serverTime = xevent->xproperty.time;
      break;
   case SelectionClear:
      serverTime = xevent->xselectionclear.time;
      break;
   case SelectionRequest:
      serverTime = xevent->xselectionrequest.time;
      break;
   case SelectionNotify:
      serverTime = xevent->xselection.time;
      break;

   default:
      return;
   }

   gettimeofday(&localTv, NULL);
   localTime = (localTv.tv_sec * 1000) + (localTv.tv_usec / 1000); // Convert to ms
   up->eventTimeDiff = serverTime - localTime;
}


/*
 *-----------------------------------------------------------------------------
 *
 * UnityPlatformProcessXEvent --
 *
 *      Processes an incoming X event.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      May create or destroy UnityPlatformWindow objects.
 *
 *-----------------------------------------------------------------------------
 */

static void
UnityPlatformProcessXEvent(UnityPlatform *up,      // IN
                           const XEvent *xevent,   // IN
                           Window realEventWindow) // IN
{
   UnityPlatformWindow *upw = NULL;
   const char *eventName;

   ASSERT(up);
   ASSERT(xevent);

   UnityPlatformUpdateEventTimeDiff(up, xevent);

   eventName = UnityPlatformGetEventString(up, xevent->type);
   upw = UPWindow_Lookup(up, realEventWindow);
   if (!upw) {
      UnitySpecialWindow *usw = USWindowLookup(up, realEventWindow);
      if (usw) {
         if (usw->evHandler) {
            usw->evHandler(up, usw, xevent, realEventWindow);
         }

         return;
      } else if (xevent->type == CreateNotify) {
         /* Ignore decoration widgets.  They'll be reparented later. */
         if (UnityX11Util_IsWindowDecorationWidget(up, realEventWindow)) {
            Debug("%s: Window %#lx is a decoration widget.  Ignore it.\n",
                  __func__, realEventWindow);
            return;
         }

         /*
          * It may be a new window that we don't know about yet. Let's create an object
          * to track it.
          */
         upw = UPWindow_Create(up, realEventWindow);
         if (upw) {
            UPWindow_CheckRelevance(up, upw, NULL);
         } else {
            Debug("UnityX11ThreadProcessEvent BOMBED:"
                  " %s on window %#lx (reported to %#lx)\n",
                  eventName, realEventWindow, xevent->xany.window);
         }
      } else {
         /*
          * If we use them on non-CreateNotify events, the above lines of code wind up
          * trying to create objects for crazy windows that don't exist...
          */
         Debug("Ignoring %s event on unknown window %#lx (reported to %#lx)\n",
               eventName, realEventWindow, xevent->xany.window);
      }
   }

   if (upw) {
      UPWindow_ProcessEvent(up, upw, realEventWindow, xevent);
      if (upw->deleteWhenSafe) {
         Debug("%s: refs %u, deleteWhenSafe %u\n", __func__, upw->refs,
               upw->deleteWhenSafe);
         UPWindow_Unref(up, upw);
      }
   }
}


/*
 *-----------------------------------------------------------------------------
 *
 * UnityPlatformIsRootWindow --
 *
 *      Checks whether a given window ID is the root window. Necessary because each
 *      screen has a separate root window, which makes checking a little more complicated
 *      than ==.
 *
 * Results:
 *      TRUE if the given window is a root window, FALSE otherwise.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

Bool
UnityPlatformIsRootWindow(UnityPlatform *up, // IN
                          Window window)     // IN
{
   ASSERT(up);

   return (USWindowLookup(up, window) == up->rootWindows);
}


/*
 *-----------------------------------------------------------------------------
 *
 * UnityX11SetCurrentDesktop --
 *
 *      Sets the active virtual desktop.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Changes the virtual desktop.
 *
 *-----------------------------------------------------------------------------
 */

void
UnityX11SetCurrentDesktop(UnityPlatform *up,     // IN
                          uint32 currentDesktop) // IN: guest-side desktop ID
{
   Atom data[5] = {0,0,0,0,0};

   ASSERT(up);
   ASSERT(up->rootWindows->windows);

   up->desktopInfo.currentDesktop = currentDesktop;
   data[0] = currentDesktop;
   data[1] = UnityPlatformGetServerTime(up);
   UnityPlatformSendClientMessage(up,
				  up->rootWindows->windows[0],
				  up->rootWindows->windows[0],
				  up->atoms._NET_CURRENT_DESKTOP,
				  32, 5, data);
}


/*
 *-----------------------------------------------------------------------------
 *
 * UnityX11GetCurrentDesktop --
 *
 *      Gets the active virtual desktop.
 *
 * Results:
 *      The active virtual desktop. If it cannot be retrieved for any reason, a
 *      reasonable default of '0' will be returned.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

uint32
UnityX11GetCurrentDesktop(UnityPlatform *up) // IN
{
   Atom propertyType;
   int propertyFormat;
   unsigned long itemsReturned;
   unsigned long bytesRemaining;
   Atom *valueReturned;
   uint32 currentDesktop;

   ASSERT(up);
   ASSERT(up->rootWindows);

   if (XGetWindowProperty(up->display, up->rootWindows->windows[0],
                          up->atoms._NET_CURRENT_DESKTOP, 0,
                          1024, False, AnyPropertyType,
                          &propertyType, &propertyFormat, &itemsReturned,
                          &bytesRemaining, (unsigned char **)&valueReturned)
       == Success
       && propertyType == XA_CARDINAL
       && propertyFormat == 32) {
      ASSERT(itemsReturned == 1);

      currentDesktop = valueReturned[0];
   } else {
      currentDesktop = 0;
   }
   XFree(valueReturned);

   return currentDesktop;
}


/*
 *-----------------------------------------------------------------------------
 *
 * USRootWindowsUpdateCurrentDesktop --
 *
 *      Looks at the root window to figure out the current desktop
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Updates UnityWindowTracker.
 *
 *-----------------------------------------------------------------------------
 */

static void
USRootWindowsUpdateCurrentDesktop(UnityPlatform *up,       // IN
                                  UnitySpecialWindow *usw, // IN
                                  Window window)           // IN
{
   uint32 currentDesktop;
   UnityDesktopId unityDesktop;

   /*
    * XXX right now this is going to break if there are multiple screens in the guest,
    * since each one can have an independant 'current' desktop...
    */

   ASSERT(up);
   currentDesktop = UnityX11GetCurrentDesktop(up);

   if (currentDesktop >= up->desktopInfo.numDesktops) {
      Warning("Active desktop is out of range for some strange reason\n");
      currentDesktop = 0;
   }

   unityDesktop = up->desktopInfo.guestDesktopToUnity[currentDesktop];
   Debug("%s: currentDesktop %u, unityDesktop %u\n", __func__, currentDesktop, unityDesktop);
   UnityWindowTracker_ChangeActiveDesktop(up->tracker, unityDesktop);
}


/*
 *-----------------------------------------------------------------------------
 *
 * USRootWindowsProcessEvent --
 *
 *      Processes an event that occurred on one of the root windows.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

static void
USRootWindowsProcessEvent(UnityPlatform *up,       // IN
                          UnitySpecialWindow *usw, // IN
                          const XEvent *xevent,    // IN
                          Window window)           // IN
{

   /*
    * XXX Do we need to handle situations where the root window changes size? Any other
    * properties?
    */
   switch (xevent->type) {
   case PropertyNotify:
      if (xevent->xproperty.atom == up->atoms._NET_CURRENT_DESKTOP) {
         USRootWindowsUpdateCurrentDesktop(up, usw, window);
      } else if (xevent->xproperty.atom == up->atoms._NET_NUMBER_OF_DESKTOPS) {
         size_t numDesktops;

         numDesktops = UnityPlatformGetNumVirtualDesktops(up);
         if (numDesktops != up->desktopInfo.numDesktops) {
            UnityPlatformSyncDesktopConfig(up);
         }
      } else if (xevent->xproperty.atom == up->atoms._NET_DESKTOP_LAYOUT) {
         Atom layoutData[4];

         UnityPlatformGetVirtualDesktopLayout(up, layoutData);
         if (memcmp(layoutData, up->desktopInfo.layoutData, sizeof layoutData) != 0) {
            UnityPlatformSyncDesktopConfig(up);
         }
      }
      break;
   }
}


/*
 *-----------------------------------------------------------------------------
 *
 * UnityPlatformWMProtocolSupported --
 *
 *      Returns whether the window manager supports a particular protocol.
 *
 * Results:
 *      TRUE if the protocol is supported, FALSE otherwise.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

Bool
UnityPlatformWMProtocolSupported(UnityPlatform *up,         // IN
                                 UnityX11WMProtocol proto)  // IN
{
   ASSERT(up);
   ASSERT(proto < UNITY_X11_MAX_WM_PROTOCOLS);

   return up->wmProtocols[proto];
}


/*
 *----------------------------------------------------------------------------
 *
 * UnityPlatformSendClientMessageFull --
 *
 *      Sends an XSendEvent.
 *
 * Results:
 *
 * Side effects:
 *
 *----------------------------------------------------------------------------
 */


static void
UnityPlatformSendClientMessageFull(Display *d,        // IN
                                   Window destWindow, // IN: Window to send msg to
                                   Window w,          // IN: What the msg's "To:"
                                                      // header should be, so to speak.
                                   Atom messageType,  // IN
                                   int format,        // IN
                                   int numItems,      // IN
                                   const void *data)  // IN
{
   XClientMessageEvent ev;
   int i;

   memset(&ev, 0, sizeof ev);
   ev.type = ClientMessage;
   ev.window = w;
   ev.message_type = messageType;
   ev.format = format;
   switch (format) {
   case 8:
      ASSERT(numItems <= ARRAYSIZE(ev.data.b));
      for (i = 0; i < numItems; i++) {
         const char *datab = data;
         ev.data.b[i] = datab[i];
      }
      break;
   case 16:
      ASSERT(numItems <= ARRAYSIZE(ev.data.s));
      for (i = 0; i < numItems; i++) {
         const short *datas = data;
         ev.data.s[i] = datas[i];
      }
      break;
   case 32:
      ASSERT(numItems <= ARRAYSIZE(ev.data.l));
      for (i = 0; i < numItems; i++) {
         const Atom *datal = data;
         ev.data.l[i] = datal[i];
      }
      break;
   }
   if (! XSendEvent(d, destWindow, False,
                    PropertyChangeMask|SubstructureRedirectMask|SubstructureNotifyMask, (XEvent *)&ev)) {
      Debug("XSendEvent failed\n");
   }
}

/*
 *-----------------------------------------------------------------------------
 *
 * UnityPlatformSendClientMessage --
 *
 *      Sends an XClientMessageEvent (such as one of the _NET_WM messages)
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

void
UnityPlatformSendClientMessage(UnityPlatform *up, // IN
                               Window destWindow, // IN: Window to actually send msg to
                               Window w,          // IN: What the msg's "To:" header
                                                  // should be, so to speak.
                               Atom messageType,  // IN
                               int format,        // IN
                               int numItems,      // IN
                               const void *data)  // IN
{
   UnityPlatformSendClientMessageFull(up->display, destWindow, w, messageType,
                                      format, numItems, data);
}


/*****************************************************************************
 * Misc Unity RPCs that need to be handled                                   *
 *****************************************************************************/


/*
 *----------------------------------------------------------------------------
 *
 * UnityPlatformSetTopWindowGroup --
 *
 *      Set the group of windows on top of all others.
 *
 * Results:
 *      TRUE if success,
 *      FALSE otherwise.
 *
 * Side effects:
 *      None
 *
 *----------------------------------------------------------------------------
 */

Bool
UnityPlatformSetTopWindowGroup(UnityPlatform *up,        // IN: Platform data
                               UnityWindowId *windows,   // IN: array of window ids
                               unsigned int windowCount) // IN: # of windows in the array
{
   Window sibling = None;
   int i;

   ASSERT(up);
   ASSERT(windows);
   ASSERT(windowCount);

   /*
    * Restack everything bottom to top.
    */
   for (i = 0; i < windowCount; i++) {
      UnityPlatformWindow *upw;
      Window curWindow;
      Atom data[5] = {0,0,0,0,0};

      upw = UPWindow_Lookup(up, windows[i]);
      if (!upw) {
         continue;
      }

      curWindow = upw->clientWindow ? upw->clientWindow : upw->toplevelWindow;
      UPWindow_SetUserTime(up, upw);

      if (UnityPlatformWMProtocolSupported(up, UNITY_X11_WM__NET_RESTACK_WINDOW)) {
         data[0] = 2;           // Magic source indicator to give full control
         data[1] = sibling;
         data[2] = Above;

         UnityPlatformSendClientMessage(up, up->rootWindows->windows[0],
                                        curWindow,
                                        up->atoms._NET_RESTACK_WINDOW,
                                        32, 5, data);
      } else {
         XWindowChanges winch = {
            .stack_mode = Above,
            .sibling = sibling
         };
         unsigned int valueMask = CWStackMode;

         if (sibling != None) {
            valueMask |= CWSibling;
         }

         /*
          * As of writing, Metacity doesn't support _NET_RESTACK_WINDOW and
          * will block our attempt to raise a window unless it's active, so
          * we activate the window first.
          */
         if (UnityPlatformWMProtocolSupported(up, UNITY_X11_WM__NET_ACTIVE_WINDOW)) {
            data[0] = 2;           // Magic source indicator to give full control
            data[1] = UnityPlatformGetServerTime(up);
            data[2] = None;
            UnityPlatformSendClientMessage(up, up->rootWindows->windows[0],
                                           curWindow,
                                           up->atoms._NET_ACTIVE_WINDOW,
                                           32, 5, data);
         }

         XReconfigureWMWindow(up->display, upw->toplevelWindow, 0, valueMask, &winch);
      }

      sibling = upw->toplevelWindow;
   }

   XSync(up->display, False);

   return TRUE;
}


/*
 *-----------------------------------------------------------------------------
 *
 * UnityPlatformDnDSendClientMessage --
 *
 *      XXX This is a hack because UnityPlatformSendClientMessage doesn't work
 *      for dnd windows.
 *      Sends an XClientMessageEvent (such as one of the _NET_WM messages)
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

static void
UnityPlatformDnDSendClientMessage(UnityPlatform *up, // IN
                                  Window destWindow, // IN: Window to send msg to
                                  Window w,          // IN: What the msg's "To:"
                                                     // header should be, so to speak.
                                  Atom messageType,  // IN
                                  int format,        // IN
                                  int numItems,      // IN
                                  const void *data)  // IN
{
   UnityPlatformSendClientMessageFull(GDK_DISPLAY(), destWindow, w,
                                      messageType, format, numItems, data);
}


/*
 *----------------------------------------------------------------------------
 *
 * UnityPlatformStackDnDDetWnd --
 *
 *      Updates the stacking order of the dnd detection window.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */

static void
UnityPlatformStackDnDDetWnd(UnityPlatform *up)
{
   static const Atom onDesktop[] = { 0xFFFFFFFF, 0, 0, 0, 0 };

   if (!up->dnd.setMode || !up->dnd.detWnd) {
      Debug("%s: DnD not yet initialized.\n", __func__);
      return;
   }

   if (!up->desktopWindow) {
      Debug("Desktop Window not cached. Tracker isn't populated.\n");
      return;
   }

   /* Show the window on every desktop. */
   UnityPlatformDnDSendClientMessage(up,
                                     up->rootWindows->windows[0],
                                     GDK_WINDOW_XWINDOW(up->dnd.detWnd->window),
                                     up->atoms._NET_WM_DESKTOP,
                                     32, 5, onDesktop);

   if (up->desktopWindow) {
      XWindowChanges ch;
      XSetWindowAttributes sa;
      Window desktop = up->desktopWindow->toplevelWindow;

      /* Prevent the window manager from managing our detection window. */
      sa.override_redirect = True;
      XChangeWindowAttributes(GDK_DISPLAY(),
                              GDK_WINDOW_XWINDOW(up->dnd.detWnd->window),
                              CWOverrideRedirect, &sa);

      /* Resize and restack the detection window. */
      ch.x = 0;
      ch.y = 0;
      ch.width = 65535;
      ch.height = 65535;
      ch.sibling = desktop;
      ch.stack_mode = Above;

      XConfigureWindow(GDK_DISPLAY(), GDK_WINDOW_XWINDOW(up->dnd.detWnd->window),
                       CWX|CWY|CWWidth|CWHeight|CWStackMode | CWSibling, &ch);

      Debug("Restacking dnd detection window.\n");
   } else {
      /*
       * Attempt to rely on window manager if we cannot find a window to stack
       * above.
       */
      Atom position[] = { _NET_WM_STATE_ADD,
      up->atoms._NET_WM_STATE_STICKY,
      up->atoms._NET_WM_STATE_BELOW, 0, 0 };

      Debug("Unable to locate desktop window to restack detection window above.\n");
      UnityPlatformDnDSendClientMessage(up,
                                        up->rootWindows->windows[0],
                                        GDK_WINDOW_XWINDOW(up->dnd.detWnd->window),
                                        up->atoms._NET_WM_STATE,
                                        32, 5, position);
      XMoveResizeWindow(GDK_DISPLAY(),
                        GDK_WINDOW_XWINDOW(up->dnd.detWnd->window),
                        0, 0, 65535, 65535);
   }
}


/*
 *------------------------------------------------------------------------------
 *
 * UnityPlatformUpdateDnDDetWnd --
 *
 *     Shows/hides a full-screen drag detection wnd for unity guest->host DnD.
 *
 * Results:
 *     None.
 *
 * Side effects:
 *     None.
 *
 *------------------------------------------------------------------------------
 */

void
UnityPlatformUpdateDnDDetWnd(UnityPlatform *up, // IN
                             Bool show)         // IN
{

   if (!up || !up->dnd.setMode || !up->dnd.detWnd) {
      /*
       * This function may potentially be called during UnityPlatform destruction.
       */
      return;
   }

   if (show) {
      gtk_widget_show(up->dnd.detWnd);
      UnityPlatformStackDnDDetWnd(up);
      Debug("Showing dnd detection window.\n");
   } else {
      gtk_widget_hide(up->dnd.detWnd);
      Debug("Hiding dnd detection window.\n");
   }

   up->dnd.setMode(show);
}


/*
 *------------------------------------------------------------------------------
 *
 * UnityPlatformSetActiveDnDDetWnd --
 *
 *     Set current full-screen drag detection wnd. The caller retains ownership
 *     of the data. The caller is responsible for updating the active dnd det
 *     wnd.
 *
 * Results:
 *     None.
 *
 * Side effects:
 *     None.
 *
 *------------------------------------------------------------------------------
 */

void
UnityPlatformSetActiveDnDDetWnd(UnityPlatform *up, // IN
                                UnityDnD *data)      // IN
{
   up->dnd = *data;
}


/*
 *------------------------------------------------------------------------------
 *
 * UnityPlatformSetDesktopWorkAreas --
 *
 *     Sets the work areas for all screens.
 *
 * Results:
 *     None.
 *
 * Side effects:
 *     None.
 *
 *------------------------------------------------------------------------------
 */

Bool
UnityPlatformSetDesktopWorkAreas(UnityPlatform *up,     // IN
                                 UnityRect workAreas[], // IN
                                 uint32 numWorkAreas)   // IN
{
   int iScreens;
   int i;
   XineramaScreenInfo *screenInfo = NULL;
   int numScreens;
   RegionPtr strutsRegion;
   RegionPtr screenRegion;
   RegionPtr workAreasRegion;
   XID (*strutInfos)[12];
   int numStrutInfos;

   if (!up->rootWindows) {
      /*
       * We're not in Unity mode yet. Save the info until we are.
       */

      up->needWorkAreas = Util_SafeMalloc(numWorkAreas * sizeof *up->needWorkAreas);
      memcpy(up->needWorkAreas, workAreas, numWorkAreas * sizeof *up->needWorkAreas);
      up->needNumWorkAreas = numWorkAreas;
      return TRUE;
   }

   if (!UnityPlatformWMProtocolSupported(up, UNITY_X11_WM__NET_WM_STRUT_PARTIAL)) {
      Debug("Window manager does not support _NET_WM_STRUT_PARTIAL - not setting desktop work area.\n");
      return FALSE;
   }

   ASSERT(up);
   ASSERT(up->rootWindows);

   /*
    * Get the geometry of all attached screens.  If we're running multi-mon,
    * we'll query the Xinerama extension.  Otherwise we just fall back to
    * examining our root window's geometry.
    */
   if (XineramaQueryExtension(up->display, &i, &i)) {
      screenInfo = XineramaQueryScreens(up->display, &numScreens);
   }

   if (!screenInfo) {
      uint32 rootX;
      uint32 rootY;
      uint32 rootWidth;
      uint32 rootHeight;
      uint32 dummy;
      Window winDummy;

      if (numWorkAreas > 1) {
         Debug("Xinerama extension not present, or XineramaQueryScreens failed,"
               " but multiple work areas were requested.\n");
         return FALSE;
      }

      if (!XGetGeometry(up->display, up->rootWindows->windows[0], &winDummy,
                        &rootX, &rootY, &rootWidth, &rootHeight,
                        &dummy, &dummy)) {
         return FALSE;
      }

      screenInfo = Util_SafeCalloc(1, sizeof *screenInfo);
      numScreens = 1;

      screenInfo->x_org = rootX;
      screenInfo->y_org = rootY;
      screenInfo->width = rootWidth;
      screenInfo->height = rootHeight;
   }

   /*
    * New and improved wild'n'crazy scheme to map the host's work area
    * coordinates to a collection of struts.
    *
    * This implementation depends upon the y-x banded rectangles
    * implementation of lib/region.
    *
    * In short, here's how things go:
    *
    *    1.  For each Xinerama screen (or the root window in case we have no
    *        Xinerama) and host work area, a region is created.  A strut
    *        region is then created by subtracting the work area region from
    *        the screen region.
    *
    *    2.  This remaining region will contain between 0 and 4 rectangles,
    *        each of which will be transformed into a strut window.
    *
    *        For each of these rectangles, we infer based on their dimensions
    *        which screen boundary the resulting strut should be bound to.
    *
    *        a.  Boxes touching both the left and right sides of the screen
    *            are either top or bottom struts, depending on whether they
    *            also touch the top or bottom edge.
    *
    *        b.  Any remaining box will touch either the left OR the right
    *            side, but not both.  (Such an irregular layout cannot be
    *            described by the work areas RPC.)  That box's strut will
    *            then be attached to the same side of the screen.
    *
    * While also not perfect, this algorithm should do a better job of creating
    * struts along their correct sides of a screen than its predecessor.  It
    * will let us assume the common case that what we define as a strut attached
    * to the left or right side really should be attached to the left or right,
    * rather than attached to the top or bottom and spanning the height of the
    * display.
    *
    * Pathological case:
    *    1.  Screen geometry: 1280x960.
    *        Left strut: 100px wide, 600px tall.  Touches top of screen.
    *        Right strut: 1180px wide, 100px tall.  Touches top of screen.
    *
    *    2.  Note that these struts touch each other.  We'd interpret the resulting
    *        work area as follows:
    *
    *        Top strut: 1280px wide, 100px tall.
    *        Left strut: 100px wide, 500px tall, starting from y = 100.
    *
    * I believe this sort of layout to be uncommon enough that we can accept
    * failure here.  If we -really- want to get these things right, then
    * we should send strut information explicitly, rather than having the
    * guest try to deduce it from work area geometry.
    */

   /*
    * One strut per screen edge = at most 4 strutInfos.
    */
   strutInfos = alloca(4 * sizeof *strutInfos * numScreens);
   memset(strutInfos, 0, 4 * sizeof *strutInfos * numScreens);
   numStrutInfos = 0;

   for (iScreens = 0; iScreens < numScreens; iScreens++) {
      int iRects;

      xRectangle screenRect;
      xRectangle workAreaRect;

      /*
       * Steps 1a. Create screen, work area regions.
       */
      screenRect.x = screenInfo[iScreens].x_org;
      screenRect.y = screenInfo[iScreens].y_org;
      screenRect.width = screenInfo[iScreens].width;
      screenRect.height = screenInfo[iScreens].height;
      screenRect.info.type = UpdateRect;

      workAreaRect.x = workAreas[iScreens].x;
      workAreaRect.y = workAreas[iScreens].y;
      workAreaRect.width = workAreas[iScreens].width;
      workAreaRect.height = workAreas[iScreens].height;
      workAreaRect.info.type = UpdateRect;

      screenRegion = miRectsToRegion(1, &screenRect, 0);
      workAreasRegion = miRectsToRegion(1, &workAreaRect, 0);

      /*
       * Step 1b.  Create struts region by subtracting work area from screen.
       */
      strutsRegion = miRegionCreate(NULL, 0);
      miSubtract(strutsRegion, screenRegion, workAreasRegion);
      miRegionDestroy(workAreasRegion);
      miRegionDestroy(screenRegion);

      /*
       * Step 2.  Transform struts region rectangles into individual struts.
       */
      for (iRects = 0; iRects < REGION_NUM_RECTS(strutsRegion);
           iRects++, numStrutInfos++) {
         BoxPtr p = REGION_RECTS(strutsRegion) + iRects;
         int bounds = 0;
#define TOUCHES_LEFT          0x1
#define TOUCHES_RIGHT         0x2
#define TOUCHES_TOP           0x4
#define TOUCHES_BOTTOM        0x8

         if (p->x1 == screenRect.x) { bounds |= TOUCHES_LEFT; }
         if (p->x2 == screenRect.x + screenRect.width) { bounds |= TOUCHES_RIGHT; }
         if (p->y1 == screenRect.y) { bounds |= TOUCHES_TOP; }
         if (p->y2 == screenRect.y + screenRect.height) { bounds |= TOUCHES_BOTTOM; }

         /*
          * strutInfos is passed directly to
          * XSetProperty(..._NET_WM_STRUTS_PARTIAL).  I.e., look up that
          * property's entry in NetWM/wm-spec for more info on the indices.
          *
          * I went the switch/case route only because it does a better job
          * (for me) of organizing & showing -all- possible cases.  YMMV.
          *
          * The region code treats rectanges as ranges from [x1,x2) and
          * [y1,y2).  In other words, x2 and y2 are OUTSIDE the region.  I
          * guess it makes calculating widths/heights easier.  However, the
          * strut width/height dimensions are INCLUSIVE, so we'll subtract 1
          * from the "end" (as opposed to "start") value.
          *
          * (Ex:  A 1600x1200 display with a 25px top strut would be marked
          * as top = 25, top_start_x = 0, top_end_x = 1599.)
          */
         switch (bounds) {
         case TOUCHES_LEFT | TOUCHES_RIGHT | TOUCHES_TOP:
            /* Top strut. */
            strutInfos[numStrutInfos][2] = p->y2 - p->y1;
            strutInfos[numStrutInfos][8] = p->x1;
            strutInfos[numStrutInfos][9] = p->x2 - 1;
            break;
         case TOUCHES_LEFT | TOUCHES_RIGHT | TOUCHES_BOTTOM:
            /* Bottom strut. */
            strutInfos[numStrutInfos][3] = p->y2 - p->y1;
            strutInfos[numStrutInfos][10] = p->x1;
            strutInfos[numStrutInfos][11] = p->x2 - 1;
            break;
         case TOUCHES_LEFT:
         case TOUCHES_LEFT | TOUCHES_TOP:
         case TOUCHES_LEFT | TOUCHES_BOTTOM:
         case TOUCHES_LEFT | TOUCHES_TOP | TOUCHES_BOTTOM:
            /* Left strut. */
            strutInfos[numStrutInfos][0] = p->x2 - p->x1;
            strutInfos[numStrutInfos][4] = p->y1;
            strutInfos[numStrutInfos][5] = p->y2 - 1;
            break;
         case TOUCHES_RIGHT:
         case TOUCHES_RIGHT | TOUCHES_TOP:
         case TOUCHES_RIGHT | TOUCHES_BOTTOM:
         case TOUCHES_RIGHT | TOUCHES_TOP | TOUCHES_BOTTOM:
            /* Right strut. */
            strutInfos[numStrutInfos][1] = p->x2 - p->x1;
            strutInfos[numStrutInfos][6] = p->y1;
            strutInfos[numStrutInfos][7] = p->y2 - 1;
            break;
         case TOUCHES_LEFT | TOUCHES_RIGHT | TOUCHES_TOP | TOUCHES_BOTTOM:
            Warning("%s: Struts occupy entire display.", __func__);
            /* FALLTHROUGH */
         default:
            Warning("%s: Irregular strut configuration: bounds %4x\n", __func__, bounds);
            miRegionDestroy(strutsRegion);
            goto out;
            break;
         }
      }
#undef TOUCHES_LEFT
#undef TOUCHES_RIGHT
#undef TOUCHES_TOP
#undef TOUCHES_BOTTOM

      miRegionDestroy(strutsRegion);
   }

   /*
    * The first step is making sure we have enough windows in existence to list the
    * _NET_WM_STRUT_PARTIAL properties for each screen.
    */
   if (!up->workAreas
       || up->workAreas->numWindows != numStrutInfos) {
      Window *newWinList;

      newWinList = Util_SafeCalloc(numStrutInfos, sizeof *newWinList);
      if (up->workAreas) {
         memcpy(newWinList, up->workAreas->windows,
                MIN(numStrutInfos, up->workAreas->numWindows) * sizeof *newWinList);
      }

      /*
       * Destroy unneeded windows
       */
      for (i = numStrutInfos; i < (up->workAreas ? up->workAreas->numWindows : 0); i++) {
         XDestroyWindow(up->display, up->workAreas->windows[i]);
      }

      /*
       * Create additional windows as needed.
       */
      for (i = up->workAreas ? up->workAreas->numWindows : 0; i < numStrutInfos; i++) {
         static const char strutWindowName[] = "vmware-user workarea struts";
         Atom allDesktops = -1;
         newWinList[i] = XCreateWindow(up->display, up->rootWindows->windows[0],
                                       -50, -50, 1, 1, 0, CopyFromParent, InputOnly,
                                       CopyFromParent, 0, NULL);
         XChangeProperty(up->display, newWinList[i], up->atoms._NET_WM_WINDOW_TYPE,
                         XA_ATOM, 32, PropModeReplace,
                         (unsigned char *)&up->atoms._NET_WM_WINDOW_TYPE_DOCK, 1);
         XChangeProperty(up->display, newWinList[i], up->atoms._NET_WM_DESKTOP,
                         XA_CARDINAL, 32, PropModeReplace,
                         (unsigned char *)&allDesktops, 1);
         XStoreName(up->display, newWinList[i], strutWindowName);
         XMapWindow(up->display, newWinList[i]);
      }

      if (up->workAreas) {
         USWindowUpdate(up, up->workAreas, newWinList, numStrutInfos);
      } else {
         up->workAreas = USWindowCreate(up, NULL, newWinList, numStrutInfos);
         up->workAreas->windowsAreOwned = TRUE;
      }
   }

   /*
    * Now actually set the _NET_WM_STRUT_PARTIAL property on our special 'struts'
    * windows.
    */
   for (i = 0; i < numStrutInfos; i++) {
      Window strutWindow;

      strutWindow = up->workAreas->windows[i];

      XChangeProperty(up->display, strutWindow, up->atoms._NET_WM_STRUT_PARTIAL, XA_CARDINAL,
                      32, PropModeReplace, (unsigned char *)strutInfos[i], ARRAYSIZE(strutInfos[i]));
   }

out:
   free(screenInfo);

   return TRUE;
}


/*
 *-----------------------------------------------------------------------------
 *
 * UnityPlatformGetNumVirtualDesktops --
 *
 *      Retrieves the number of virtual desktops currently set in the guest.
 *
 * Results:
 *      Number of desktops.
 *
 * Side effects:
 *      None
 *
 *-----------------------------------------------------------------------------
 */

size_t
UnityPlatformGetNumVirtualDesktops(UnityPlatform *up) // IN
{
   Atom propertyType;
   int propertyFormat;
   unsigned long itemsReturned;
   unsigned long bytesRemaining;
   Atom *valueReturned;
   size_t retval;

   ASSERT(up);
   if (XGetWindowProperty(up->display, up->rootWindows->windows[0],
                          up->atoms._NET_NUMBER_OF_DESKTOPS, 0,
                          1024, False, AnyPropertyType,
                          &propertyType, &propertyFormat, &itemsReturned,
                          &bytesRemaining, (unsigned char **)&valueReturned)
       == Success
       && propertyType == XA_CARDINAL
       && propertyFormat == 32) {
      ASSERT(itemsReturned == 1);

      retval = valueReturned[0];
   } else {
      retval = 1;
   }
   XFree(valueReturned);

   return retval;
}


/*
 *-----------------------------------------------------------------------------
 *
 * UnityPlatformGetVirtualDesktopLayout --
 *
 *      Retrieves the guest's current virtual desktop layout info, and stores it in
 *      'layoutData' (an array of 4 Atoms).
 *
 * Results:
 *      Desktop layout stored in 'layoutData'
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

void
UnityPlatformGetVirtualDesktopLayout(UnityPlatform *up, // IN
                                     Atom *layoutData)  // OUT
{
   Atom propertyType;
   int propertyFormat;
   unsigned long itemsReturned;
   unsigned long bytesRemaining;
   Atom *valueReturned;

   ASSERT(up);

   layoutData[3] = _NET_WM_TOPLEFT;
   if (XGetWindowProperty(up->display, up->rootWindows->windows[0],
                          up->atoms._NET_DESKTOP_LAYOUT, 0,
                          1024, False, AnyPropertyType,
                          &propertyType, &propertyFormat, &itemsReturned,
                          &bytesRemaining, (unsigned char **)&valueReturned)
       == Success
       && propertyType == XA_CARDINAL
       && propertyFormat == 32) {
      ASSERT(itemsReturned == 3 || itemsReturned == 4);

      memcpy(layoutData,
             valueReturned,
             itemsReturned * sizeof *valueReturned);
   } else {
      layoutData[0] = _NET_WM_ORIENTATION_HORZ;
      layoutData[1] = 0;
      layoutData[2] = 1;
   }
   XFree(valueReturned);
}


/*
 *-----------------------------------------------------------------------------
 *
 * UnityPlatformSyncDesktopConfig --
 *
 *      This routine takes the virtual desktop configuration stored in UnityPlatform and
 *      makes sure that the guest's actual virtual desktop configuration matches. This is
 *      done in three situations:
 *        1. Updating the guest's virtual desktop config to match the host's, right after
 *        the host's virtual desktop config has changed.
 *        2. Forcing the guest's virtual desktop config back to the host's, right after
 *        the user uses the guest's pager to alter the guest virtual desktop config.
 *        3. Restoring the guest's virtual desktop configuration when exiting Unity mode.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Guest windows may jump to different virtual desktops if desktops are removed.
 *
 *-----------------------------------------------------------------------------
 */

void
UnityPlatformSyncDesktopConfig(UnityPlatform *up) // IN
{
   Atom data[5] = {0, 0, 0, 0, 0};

   ASSERT(up);

   if (!up->rootWindows || !up->display) {
      return; // This function might be called while not in Unity mode
   }

   data[0] = up->desktopInfo.numDesktops;
   UnityPlatformSendClientMessage(up,
				  up->rootWindows->windows[0],
				  up->rootWindows->windows[0],
				  up->atoms._NET_NUMBER_OF_DESKTOPS,
				  32, 5,
				  data);
   XChangeProperty(up->display, up->rootWindows->windows[0],
                   up->atoms._NET_DESKTOP_LAYOUT, XA_CARDINAL,
                   32, PropModeReplace, (unsigned char *)up->desktopInfo.layoutData, 4);
}


/*
 *------------------------------------------------------------------------------
 *
 * UnityPlatformSetDesktopConfig --
 *
 *     Set the virtual desktop configuration as specified by the host.
 *
 * Results:
 *     Returns TRUE if successful, and FALSE otherwise.
 *
 * Side effects:
 *     None.
 *
 *------------------------------------------------------------------------------
 */

Bool
UnityPlatformSetDesktopConfig(UnityPlatform *up,                             // IN
                              const UnityVirtualDesktopArray *desktopConfig) // IN
{
   int i;
   int x;
   int y;
   UnityVirtualDesktop minDesktop;
   UnityVirtualDesktop maxDesktop;
   UnityVirtualDesktop desktopSpread;
   int unityDesktopLayout[MAX_VIRT_DESK][MAX_VIRT_DESK];
   int guestDesktopLayout[MAX_VIRT_DESK][MAX_VIRT_DESK];

   ASSERT(up);
   ASSERT(desktopConfig);
   ASSERT(desktopConfig->desktopCount >= 1);

   /*
    * This long section of code mainly exists to verify that the host's virtual desktop
    * setup can be represented on our end, and to figure out how best to do it. We could
    * do this simply, if we didn't have to deal with the possibility of having 5 virtual
    * desktops in a 3x2 layout, which is a very real possibility on Linux hosts...
    */
   memset(unityDesktopLayout, 0xFF, sizeof unityDesktopLayout); // Set all entries to -1
   minDesktop = desktopConfig->desktops[0];
   maxDesktop = minDesktop;
   for (i = 1; i < desktopConfig->desktopCount; i++) {
      if (desktopConfig->desktops[i].x < minDesktop.x) {
         minDesktop.x = desktopConfig->desktops[i].x;
      }
      if (desktopConfig->desktops[i].y < minDesktop.y) {
         minDesktop.y = desktopConfig->desktops[i].y;
      }
      if (desktopConfig->desktops[i].x > maxDesktop.x) {
         maxDesktop.x = desktopConfig->desktops[i].x;
      }
      if (desktopConfig->desktops[i].y > maxDesktop.y) {
         maxDesktop.y = desktopConfig->desktops[i].y;
      }
   }
   desktopSpread.x = maxDesktop.x - minDesktop.x;
   desktopSpread.y = maxDesktop.y - minDesktop.y;

   for (i = 0; i < desktopConfig->desktopCount; i++) {
      int32 localX = desktopConfig->desktops[i].x - minDesktop.x;
      int32 localY = desktopConfig->desktops[i].y - minDesktop.y;

      if (localY >= MAX_VIRT_DESK || localX >= MAX_VIRT_DESK) {
         Warning("Unity virtual desktop layout has holes that are too big to handle\n");
         return FALSE;
      }

      unityDesktopLayout[localX][localY] = i;
   }

   for (x = 0; x < desktopSpread.x; x++) {
      for (y = 0; y < desktopSpread.y; y++) {
         if (unityDesktopLayout[x][y] < 0) {
            Warning("Unity virtual desktop layout has holes that we can't handle.\n");
            return FALSE;
         }
      }
   }

   /*
    * Check along the left edge to make sure that there aren't any gaps between virtual
    * desktops.
    */
   for (x = desktopSpread.x, y = 0; y <= desktopSpread.y; y++) {
      if (unityDesktopLayout[x][y] < 0) {
         break;
      }
   }
   for (; y <= desktopSpread.y; y++) {
      if (unityDesktopLayout[x][y] >= 0) {
         Warning("Unity virtual desktop layout has holes along the right edge.\n");
         return FALSE;
      }
   }

   /*
    * Check along the bottom edge to make sure that there aren't any gaps between virtual
    * desktops.
    */
   for (y = desktopSpread.y, x = 0; x <= desktopSpread.x; x++) {
      if (unityDesktopLayout[x][y] < 0) {
         break;
      }
   }
   for (; x <= desktopSpread.x; x++) {
      if (unityDesktopLayout[x][y] >= 0) {
         Warning("Unity virtual desktop layout has holes along the bottom edge.\n");
         return FALSE;
      }
   }

   /*
    * Now we know we have a workable virtual desktop layout - let's figure out how to
    * communicate it to the window manager & pager.
    */
   up->desktopInfo.layoutData[0] = _NET_WM_ORIENTATION_HORZ; // Orientation
   up->desktopInfo.layoutData[1] = (desktopSpread.x + 1); // # of columns
   up->desktopInfo.layoutData[2] = (desktopSpread.y + 1); // # of rows
   up->desktopInfo.layoutData[3] = _NET_WM_TOPLEFT; // Starting corner

   if (((desktopSpread.x + 1) * (desktopSpread.y + 1)) >= desktopConfig->desktopCount
       && desktopSpread.x > 0
       && desktopSpread.y > 1
       && unityDesktopLayout[desktopSpread.x][desktopSpread.y - 1] < 0) {
      /*
       * We know there is are least two holes at the end of the layout, /and/ the holes
       * go up the right side, so therefore we need to use vertical orientation for the
       * EWMH layout.
       */
      up->desktopInfo.layoutData[0] = _NET_WM_ORIENTATION_VERT;
   }

   /*
    * Figure out what the guest-side desktop IDs will be, based on our chosen
    * orientation.
    */
   i = 0;
   memset(guestDesktopLayout, 0xFF, sizeof guestDesktopLayout); // Set all entries to -1
   if (up->desktopInfo.layoutData[0] == _NET_WM_ORIENTATION_HORZ) {
      for (y = 0; y <= desktopSpread.y; y++) {
         for (x = 0; x <= desktopSpread.x; x++) {
            if (unityDesktopLayout[x][y] >= 0) {
               guestDesktopLayout[x][y] = i++;
            }
         }
      }
   } else {
      for (x = 0; x <= desktopSpread.x; x++) {
         for (y = 0; y <= desktopSpread.y; y++) {
            if (unityDesktopLayout[x][y] >= 0) {
               guestDesktopLayout[x][y] = i++;
            }
         }
      }
   }

   up->desktopInfo.numDesktops = desktopConfig->desktopCount;

   /*
    * Build tables to translate between guest-side and Unity-side desktop IDs.
    */
   up->desktopInfo.guestDesktopToUnity =
      Util_SafeRealloc(up->desktopInfo.guestDesktopToUnity,
                       up->desktopInfo.numDesktops
                       * sizeof up->desktopInfo.guestDesktopToUnity[0]);
   up->desktopInfo.unityDesktopToGuest =
      Util_SafeRealloc(up->desktopInfo.unityDesktopToGuest,
                       up->desktopInfo.numDesktops
                       * sizeof up->desktopInfo.unityDesktopToGuest[0]);
   for (i = 0; i < up->desktopInfo.numDesktops; i++) {
      int guestNum;
      UnityVirtualDesktop curDesk = desktopConfig->desktops[i];

      guestNum = guestDesktopLayout[curDesk.x - minDesktop.x][curDesk.y - minDesktop.y];
      up->desktopInfo.guestDesktopToUnity[guestNum] = i;
      up->desktopInfo.unityDesktopToGuest[i] = guestNum;
   }

   /*
    * Make the configuration actually take effect.
    */
   UnityPlatformSyncDesktopConfig(up);

   return TRUE;
}


/*
 *------------------------------------------------------------------------------
 *
 * UnityPlatformSetInitialDesktop --
 *
 *     Set a desktop specified by the desktop id as the initial state.
 *
 * Results:
 *     Returns TRUE if successful, and FALSE otherwise.
 *
 * Side effects:
 *     Some windows might be hidden and some shown.
 *
 *------------------------------------------------------------------------------
 */

Bool
UnityPlatformSetInitialDesktop(UnityPlatform *up,         // IN
                               UnityDesktopId desktopId)  // IN
{
   ASSERT(up);
   up->desktopInfo.initialDesktop = desktopId;
   return UnityPlatformSetDesktopActive(up, desktopId);
}


/*
 *------------------------------------------------------------------------------
 *
 * UnityPlatformSetDesktopActive --
 *
 *     Switch to the specified virtual desktop. The desktopId is an index
 *     into the desktop configuration array.
 *
 * Results:
 *     Returns TRUE if successful, and FALSE otherwise.
 *
 * Side effects:
 *     None.
 *
 *------------------------------------------------------------------------------
 */

Bool
UnityPlatformSetDesktopActive(UnityPlatform *up,         // IN
                              UnityDesktopId desktopId)  // IN
{
   ASSERT(up);

   /*
    * Update the uwt with the new active desktop info.
    */

   UnityWindowTracker_ChangeActiveDesktop(up->tracker, desktopId);

   if (desktopId >= up->desktopInfo.numDesktops) {
      return FALSE;
   }

   if (!up->rootWindows) {
      /*
       * We may not be into Unity mode yet, but we pretend it succeeded, and then do the
       * switch later for real.
       */
      return TRUE;
   }

   UnityX11SetCurrentDesktop(up, up->desktopInfo.unityDesktopToGuest[desktopId]);

   return TRUE;
}


/*
 *-----------------------------------------------------------------------------
 *
 * UnityPlatformDoUpdate --
 *
 *      This function is used to (possibly asynchronously) collect Unity window
 *      updates and send them to the host via the RPCI update channel.
 *
 * Results:
 *      Updates will be collected.  Updates may be sent.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

void
UnityPlatformDoUpdate(UnityPlatform *up,        // IN:
                      Bool incremental)         // IN: Incremental vs. full update
{
   ASSERT(up);
   ASSERT(up->updateChannel);

   if (!incremental) {
      UnityPlatformUpdateWindowState(up, up->tracker);
   }

   UnityWindowTracker_RequestUpdates(up->tracker,
                                     incremental ? UNITY_UPDATE_INCREMENTAL : 0,
                                     &up->updateChannel->updates);

   /*
    * Notify the host iff UnityWindowTracker_RequestUpdates pushed a valid
    * update into the UpdateChannel buffer.
    */
   if (DynBuf_GetSize(&up->updateChannel->updates) > (up->updateChannel->cmdSize + 2)) {
#ifdef VMX86_DEBUG
      const char *dataBuf = DynBuf_Get(&up->updateChannel->updates);
      size_t dataSize = DynBuf_GetSize(&up->updateChannel->updates);
      ASSERT(dataBuf[up->updateChannel->cmdSize] != '\0');
      ASSERT(dataBuf[dataSize - 1] == '\0');
#endif

      /* The update must be double nul terminated. */
      DynBuf_AppendString(&up->updateChannel->updates, "");

      if (!UnitySendUpdates(up->updateChannel)) {
         /* XXX We should probably exit Unity. */
         Debug("UPDATE TRANSMISSION FAILED! --------------------\n");
         /*
          * At this point, the update buffer contains a stream of updates
          * terminated by a double nul. Rather than flush the input stream,
          * let's "unseal" it by removing the second nul, allowing further
          * updates to be appended and sent later.
          */
         DynBuf_SetSize(&up->updateChannel->updates,
                        DynBuf_GetSize(&up->updateChannel->updates) - 1);
      }
   }
}


/*
 *----------------------------------------------------------------------------
 *
 * Unity_UnityToLocalPoint --
 *
 *      Initializes localPt structure based on the input unityPt structure.
 *      Translate point from Unity coordinate to local coordinate.
 *
 * Results:
 *      None
 *
 * Side effects:
 *      None
 *----------------------------------------------------------------------------
 */

void
Unity_UnityToLocalPoint(UnityPoint *localPt, // IN/OUT
                        UnityPoint *unityPt) // IN
{
   ASSERT(localPt);
   ASSERT(unityPt);
   localPt->x = unityPt->x;
   localPt->y = unityPt->y;
}


/*
 *----------------------------------------------------------------------------
 *
 * Unity_LocalToUnityPoint --
 *
 *      Initializes unityPt structure based on the input localPt structure.
 *      Translate point from local coordinate to Unity coordinate.
 *
 * Results:
 *      None
 *
 * Side effects:
 *      None
 *----------------------------------------------------------------------------
 */

void
Unity_LocalToUnityPoint(UnityPoint *unityPt, // IN/OUT
                        UnityPoint *localPt) // IN
{
   ASSERT(unityPt);
   ASSERT(localPt);
   unityPt->x = localPt->x;
   unityPt->y = localPt->y;
}


/*
 ******************************************************************************
 * UnityPlatformStickWindow --                                           */ /**
 *
 * @brief "Stick" a window to the desktop.
 *
 * @param[in] up       Platform context.
 * @param[in] windowId Operand window.
 *
 * @retval TRUE  Success.
 * @retval FALSE Failure.
 *
 ******************************************************************************
 */

Bool
UnityPlatformStickWindow(UnityPlatform *up,      // IN
                         UnityWindowId windowId) // IN
{
   return SetWindowStickiness(up, windowId, TRUE);
}


/*
 ******************************************************************************
 * UnityPlatformUnstickWindow --                                         */ /**
 *
 * @brief "Unstick" a window from the desktop.
 *
 * @param[in] up       Platform context.
 * @param[in] windowId Operand window.
 *
 * @retval TRUE  Success.
 * @retval FALSE Failure.
 *
 ******************************************************************************
 */

Bool
UnityPlatformUnstickWindow(UnityPlatform *up,      // IN
                           UnityWindowId windowId) // IN
{
   return SetWindowStickiness(up, windowId, FALSE);
}


/*
 *-----------------------------------------------------------------------------
 *
 * UnityPlatformSetConfigDesktopColor --
 *
 *      Set the preferred desktop background color for use when in Unity Mode.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

void
UnityPlatformSetConfigDesktopColor(UnityPlatform *up, int desktopColor)
{
   ASSERT(up);
}


/*
 *-----------------------------------------------------------------------------
 *
 * UnityPlatformRequestWindowContents --
 *
 *     Validate the list of supplied window IDs and once validated add them to a list
 *     of windows whose contents should be sent to the host.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

Bool
UnityPlatformRequestWindowContents(UnityPlatform *up,
                                   UnityWindowId windowIds[],
                                   uint32 numWindowIds)
{
   ASSERT(up);

   /* Not implemented */
   return FALSE;
}


/*
 *-----------------------------------------------------------------------------
 *
 * UnityPlatformConfirmMinimizeOperation --
 *
 *     Minimize a window (if allowed) by the host.
 *
 * Results:
 *     Returns TRUE if successful, and FALSE otherwise.
 *
 * Side effects:
 *     None.
 *
 *------------------------------------------------------------------------------
 */

Bool
UnityPlatformConfirmMinimizeOperation(UnityPlatform *up,        // IN
                                      UnityWindowId windowId,   // IN
                                      uint32 sequence,          // IN
                                      Bool allow)               // IN
{
   ASSERT(up);
   return FALSE;
}


/*
 *-----------------------------------------------------------------------------
 *
 * UnityPlatformSetInterlockMinimizeOperation --
 *
 *     Enable (or Disable) the interlocking (relaying) of minimize operations
 *     through the host.
 *
 * Results:
 *     None.
 *
 * Side effects:
 *     None.
 *
 *------------------------------------------------------------------------------
 */

void UnityPlatformSetInterlockMinimizeOperation(UnityPlatform *up,   // IN
                                                Bool enabled)        // IN
{
   ASSERT(up);
}


/*
 *------------------------------------------------------------------------------
 *
 * UnityPlatformWillRemoveWindow --
 *
 *    Called when a window is removed from the UnityWindowTracker.
 *
 *    NOTE: This function is called with the platform lock held.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    None.
 *------------------------------------------------------------------------------
 */

void
UnityPlatformWillRemoveWindow(UnityPlatform *up,      // IN
                              UnityWindowId windowId) // IN
{
   ASSERT(up);
}


/*
 ******************************************************************************
 * Begin file-scope functions.
 *
 */


/*
 ******************************************************************************
 * GetRelevantWMWindow --                                                */ /**
 *
 * @brief Given a UnityWindowId, return the X11 window relevant to WM operations.
 *
 * Starting with a Unity window, look for and return its associated
 * clientWindow.  If there is no clientWindow, then return the top-level window.
 *
 * @param[in]  up        Unity/X11 context.
 * @param[in]  windowId  Window search for.
 * @param[out] wmWindow  Set to the relevant X11 window.
 *
 * @todo Consider exporting this for use in unityPlatformX11Window.c.
 *
 * @retval TRUE  Relevant window found and recorded in @a wmWindow.
 * @retval FALSE Unable to find @a windowId.
 *
 ******************************************************************************
 */

static Bool
GetRelevantWMWindow(UnityPlatform *up,          // IN
                    UnityWindowId windowId,     // IN
                    Window *wmWindow)           // OUT
{
   UnityPlatformWindow *upw;

   ASSERT(up);

   upw = UPWindow_Lookup(up, windowId);
   if (!upw) {
      return FALSE;
   }

   *wmWindow = upw->clientWindow ? upw->clientWindow : upw->toplevelWindow;
   return TRUE;
}


/*
 ******************************************************************************
 * SetWindowStickiness --                                                */ /**
 *
 * @brief Sets or clears a window's sticky state.
 *
 * @param[in] up         Unity/X11 context.
 * @param[in] windowId   Operand window.
 * @param[in] wantSticky Set to TRUE to stick a window, FALSE to unstick it.
 *
 * @retval TRUE  Request successfully sent to X server.
 * @retval FALSE Request failed.
 *
 ******************************************************************************
 */

static Bool
SetWindowStickiness(UnityPlatform *up,          // IN
                    UnityWindowId windowId,     // IN
                    Bool wantSticky)            // IN
{
   GdkWindow *gdkWindow;
   Window curWindow;

   ASSERT(up);

   if (!GetRelevantWMWindow(up, windowId, &curWindow)) {
      Debug("%s: Lookup against window %#x failed.\n", __func__, windowId);
      return FALSE;
   }

   gdkWindow = gdk_window_foreign_new(curWindow);
   if (gdkWindow == NULL) {
      Debug("%s: Unable to create Gdk window?! (%#x)\n", __func__, windowId);
      return FALSE;
   }

   if (wantSticky) {
      gdk_window_stick(gdkWindow);
   } else {
      gdk_window_unstick(gdkWindow);
   }

   gdk_flush();
   g_object_unref(G_OBJECT(gdkWindow));

   return TRUE;
}


/*
 *
 * End file-scope functions.
 ******************************************************************************
 */