File: unityPlatformX11Window.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 (4156 lines) | stat: -rw-r--r-- 128,557 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
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
/*********************************************************
 * 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.
 *
 *********************************************************/

/*
 * unityPlatformX11Window.c --
 *
 *    Implementation of Unity for guest operating systems that use the X11 windowing
 *    system. This file implements per-window operations (move, minimize, etc.)
 */

#include "unityX11.h"
#include "base64.h"
#include "region.h"
#include "imageUtil.h"
#include <time.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

#include "Uri.h"
#include "appUtil.h"
#include "ghIntegration.h"

/*
 * Utility routines
 */
static Bool UnityPlatformFindWindows(UnityPlatform *up,
                                     Window currentWindow,
                                     Window *toplevelWindow,
                                     Window *clientWindow,
                                     Window *rootWindow);
static Bool UPWindowPushFullUpdate(UnityPlatform *up, UnityPlatformWindow *upw);
static void UPWindowSetRelevance(UnityPlatform *up,
                                 UnityPlatformWindow *upw,
                                 Bool isRelevant);
static void UPWindowUpdateActions(UnityPlatform *up, UnityPlatformWindow *upw);
static void UPWindowUpdateDesktop(UnityPlatform *up, UnityPlatformWindow *upw);
static void UPWindowUpdateIcon(UnityPlatform *up, UnityPlatformWindow *upw);
static void UPWindowUpdateProtocols(UnityPlatform *up, UnityPlatformWindow *upw);
#if defined(VM_HAVE_X11_SHAPE_EXT)
static void UPWindowUpdateShape(UnityPlatform *up, UnityPlatformWindow *upw);
#endif
static void UPWindowUpdateState(UnityPlatform *up,
                                UnityPlatformWindow *upw,
                                const XPropertyEvent *xevent);
static void UPWindowUpdateTitle(UnityPlatform *up, UnityPlatformWindow *upw);
static void UPWindowUpdateType(UnityPlatform *up, UnityPlatformWindow *upw);
static void UPWindowProcessConfigureEvent(UnityPlatform *up,
                                          UnityPlatformWindow *upw,
                                          const XEvent *xevent);
static void UPWindowProcessPropertyEvent(UnityPlatform *up,
                                         UnityPlatformWindow *upw,
                                         const XEvent *xevent);
static void UPWindowProcessShapeEvent(UnityPlatform *up,
                                      UnityPlatformWindow *upw,
                                      const XEvent *xevent);
static Bool UPWindowGetDesktop(UnityPlatform *up,
                               UnityPlatformWindow *upw,
                               int *guestDesktop);
static void UPWindowSetWindows(UnityPlatform *up,
                               UnityPlatformWindow *upw,
                               Window toplevelWindow,
                               Window clientWindow);
static Window UPWindowLookupClientLeader(UnityPlatform *up,
                                         UnityPlatformWindow *upw);
static void UPWindowUpdateFrameExtents(UnityPlatform *up,
                                       UnityPlatformWindow *upw);


#ifdef VMX86_DEVEL
/*
 *-----------------------------------------------------------------------------
 *
 * CompareStackingOrder --
 *
 *      Very crudely compares the stacking orders of "relevant" windows as kept
 *      by the X server and ourselves.  (By relevant, we mean only windows which
 *      are relayed to the window tracker.)
 *
 *      If there's a mismatch, Debug() statements are generated showing which
 *      indices do not match and the corresponding window IDs.  If there is a match,
 *      then the current stacking order is displayed.  (The latter is useless on
 *      its own, but it's a handy bit of data to refer to when a mismatch is
 *      discovered.)
 *
 * Results:
 *      Additional noise is sent to the Tools log via Debug().
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

static void
CompareStackingOrder(UnityPlatform *up,         // IN
                     Window rootWindow,         // IN
                     const char *callerName)    // IN
{
   Window *relevantUChildren = NULL;
   Window *relevantXChildren = NULL;
   Window *trackerChildren = NULL;
   unsigned int i;
   unsigned int numXRelevant;   // relevant windows from the X server
   unsigned int numURelevant;   // relevant windows according to Unity
   unsigned int nWindows;       // Generic limit referring to all of *children variables
                                //    after we determine that they are all the same
                                //    size.  Likely that it will be optimized out.
   GList *unityList = NULL;

   /*
    * First query the X server for a list of its top-level windows sorted
    * from bottom to top stacking order.
    */
   {
      Window dummyroot;
      Window dummyparent;
      Window *children = NULL;
      unsigned int nchildren;

      if (!XQueryTree(up->display, rootWindow, &dummyroot, &dummyparent,
                      &children, &nchildren)) {
         Debug("%s: XQueryTree failed\n", __func__);
         goto out;
      }

      /*
       * Now, filter out all of the relevant top-level windows into a local buffer
       * from the stack.
       */
      relevantXChildren = g_new(Window, nchildren);

      for (i = 0, numXRelevant = 0; i < nchildren; i++) {
         UnityPlatformWindow *tmpupw;
         tmpupw = UPWindow_Lookup(up, children[i]);
         if (tmpupw && tmpupw->isRelevant) {
            relevantXChildren[numXRelevant++] = children[i];
         }
      }

      XFree(children);
   }

   /*
    * Do the same as above but for the windows known to Unity.  These lists should
    * -usually- match, but may get out of sync when a window disappears, for example.
    * However, it's also -usually- only a matter of time before subsequent events show
    * up and bring them back into sync.
    *
    * Note that this list is created by -prepending- windows.  This is done because
    * while we store windows in top-bottom stacking order, the X server maintains
    * windows in bottom-top stacking order.  For ease of comparison, I'm reversing
    * our order in order to match the X server.
    */
   {
      UnityPlatformWindow *myupw;
      for (myupw = up->topWindow, numURelevant = 0;
           myupw;
           myupw = myupw->lowerWindow) {
         if (myupw->isRelevant) {
            unityList = g_list_prepend(unityList, (gpointer)myupw->toplevelWindow);
            ++numURelevant;
         }
      }
   }

   /*
    * The following check ensures that all three window collections are the same
    * size.  With that in mind, for the sake of readability I'll use a variable,
    * nWindows, to refer to this common size through the remainer of the function.
    */
   if (numURelevant != numXRelevant ||
       numURelevant != up->tracker->count) {
      Debug("%s: mismatch (count): server %u, unity %u, uwt %u\n", __func__,
            numXRelevant, numURelevant, up->tracker->count);
      goto out;
   }

   nWindows = numURelevant;

   /*
    * We're now sure that all sets of windows to be compared are the same size.
    * Go ahead and allocate and populate new arrays for window set comparisons.
    */

   relevantUChildren = g_new(Window, nWindows);
   trackerChildren = g_new(Window, nWindows);

   /*
    * Convert the now sorted (see above re: g_list_prepend) Unity window list to
    * an array for easy comparison with * the X server's array.
    */
   {
      GList *listIter;
      for (listIter = unityList, i = 0;
           listIter;
           listIter = listIter->next, i++) {
         relevantUChildren[i] = (Window)listIter->data;
      }
   }

   /*
    * Once again, UWT stores windows in top-bottom stacking order, but we're
    * comparing an array in bottom-top stacking order.  This loop just copies
    * and reverses the UWT's zorder array.
    */
   for (i = 0; i < nWindows; i++) {
      trackerChildren[i] = up->tracker->zorder[(nWindows - 1) - i];
   }

   {
      size_t childrenSize = nWindows * sizeof *relevantUChildren;

      if (memcmp(relevantXChildren, relevantUChildren, childrenSize) ||
          memcmp(relevantXChildren, trackerChildren, childrenSize)) {
         Debug("%s: mismatch!\n", callerName);
         Debug("%s: %8s %10s %10s %10s\n", callerName, "index", "X Server",
               "Unity", "UWT");

         for (i = 0; i < nWindows; i++) {
            if (relevantXChildren[i] != relevantUChildren[i] ||
                relevantXChildren[i] != trackerChildren[i]) {
               Debug("%s: [%6u] %#10lx %#10lx %#10lx\n", callerName, i,
                     relevantXChildren[i], relevantUChildren[i],
                     trackerChildren[i]);
            }
         }
      } else {
         Debug("%s: match (%u windows).\n", callerName, nWindows);
         for (i = 0; i < nWindows; i++) {
            Debug("%s:   [%u] %#lx\n", callerName, i, relevantXChildren[i]);
         }
      }
   }

out:
   g_free(relevantXChildren);
   g_free(relevantUChildren);
   g_free(trackerChildren);
   g_list_free(unityList);
}
#endif


/*
 *-----------------------------------------------------------------------------
 *
 * UnityPlatformFindClientWindow --
 *
 *      In X, the immediate children of the root window are almost always window manager
 *      windows that hold the app's windows. Sometimes we want to find the actual app's
 *      window to operate on, usually identfied by the WM_STATE property. Given a random
 *      window ID, this function figures out which is which.
 *
 * Results:
 *      TRUE if successful, FALSE otherwise.
 *
 *-----------------------------------------------------------------------------
 */

static Bool
UnityPlatformFindWindows(UnityPlatform *up,      // IN
                         Window currentWindow,   // IN
                         Window *toplevelWindow, // OUT
                         Window *clientWindow,   // OUT
                         Window *rootWindow)     // OUT
{
   Bool retval = FALSE;

   Window rootWin;
   Window parentWin;
   Window *children = NULL;
   unsigned int numChildren;

   Atom propertyType;
   int propertyFormat;
   unsigned long itemsReturned;
   unsigned long bytesRemaining;
   unsigned char *valueReturned = NULL;

   ASSERT(up);
   ASSERT(toplevelWindow);
   ASSERT(clientWindow);
   ASSERT(rootWindow);

   /* Check for the WM_STATE property on the window */
   UnityPlatformResetErrorCount(up);
   XGetWindowProperty(up->display, (Window)currentWindow, up->atoms.WM_STATE, 0,
                      1024, False, AnyPropertyType,
                      &propertyType, &propertyFormat, &itemsReturned,
                      &bytesRemaining, &valueReturned);
   XFree(valueReturned);
   if (UnityPlatformGetErrorCount(up)) {
      Debug("Retrieving WM_STATE failed\n");
      return FALSE;
   }

   XQueryTree(up->display, currentWindow, &rootWin, &parentWin,
              &children, &numChildren);
   if (UnityPlatformGetErrorCount(up)) {
      Debug("XQueryTree failed\n");
      return FALSE;
   }

   if (propertyType != None) {
      /*
       * If WM_STATE exists on this window, we were given a client window
       */
      *clientWindow = currentWindow;
      *rootWindow = rootWin;

      XFree(children);
      children = NULL;

      /*
       * This loop ensures that parentWin is the direct child of the root.
       *
       * XXX this will break for any window managers that use subwindows to implement
       * virtual desktops.
       */
      while (parentWin != rootWin) {
         currentWindow = parentWin;

         XQueryTree(up->display, currentWindow, &rootWin,
                    &parentWin, &children, &numChildren);
         XFree(children);
         children = NULL;
      }
      *toplevelWindow = currentWindow;

      retval = TRUE;
   } else if (parentWin == rootWin) {
      int i;
      GQueue *windowQueue;

      /*
       * Do a breadth-first search down the window tree to find the child that has the
       * WM_STATE property.
       */
      ASSERT(UnityPlatformIsRootWindow(up, rootWin));

      *toplevelWindow = currentWindow;
      *rootWindow = rootWin;
      *clientWindow = None;

      windowQueue = g_queue_new();

      while (numChildren || !g_queue_is_empty(windowQueue)) {
         Window childWindow;

         for (i = 0; i < numChildren; i++) {
            g_queue_push_tail(windowQueue, GUINT_TO_POINTER(children[i]));
         }
         XFree(children);
         children = NULL;

         childWindow = GPOINTER_TO_UINT(g_queue_pop_head(windowQueue));

         propertyType = None;
         valueReturned = NULL;
         itemsReturned = 0;
         XGetWindowProperty(up->display, childWindow, up->atoms.WM_STATE, 0,
                            1024, False, AnyPropertyType,
                            &propertyType, &propertyFormat, &itemsReturned,
                            &bytesRemaining, &valueReturned);
         XFree(valueReturned);

         if (UnityPlatformGetErrorCount(up)) {
            g_queue_free(windowQueue);
            Debug("Getting WM_STATE on a child failed\n");
            return FALSE;
         }

         if (itemsReturned) {
            *clientWindow = childWindow;
            break;
         }

         XQueryTree(up->display, childWindow, &rootWin,
                    &parentWin, &children, &numChildren);
         if (UnityPlatformGetErrorCount(up)) {
            g_queue_free(windowQueue);
            Debug("XQueryTree failed\n");
            return FALSE;
         }
      }

      g_queue_free(windowQueue);

      retval = TRUE;
   } /* else, retval is FALSE */

   XFree(children);

   if (retval && (*toplevelWindow == *rootWindow || *clientWindow == *rootWindow)) {
      Panic("Creating a UnityPlatformWindow of a root window is a big error\n");
   }

   return retval;
}


/*
 *-----------------------------------------------------------------------------
 *
 * UPWindowSetWindows --
 *
 *      Updates the X11 windows that a UnityPlatformWindow represents. Used mainly if a
 *      window is created or reparented.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Updates internal Unity state.
 *
 *-----------------------------------------------------------------------------
 */

static void
UPWindowSetWindows(UnityPlatform *up,        // IN
                   UnityPlatformWindow *upw, // IN
                   Window toplevelWindow,    // IN
                   Window clientWindow)      // IN
{
   UnityPlatformWindow *scratchUpw;
   Bool wasRelevant;

   ASSERT(up);
   ASSERT(upw);

   wasRelevant = upw->isRelevant;

   Debug("%s: %#lx::%#lx -> %#lx::%#lx\n", __func__, upw->toplevelWindow,
         upw->clientWindow, toplevelWindow, clientWindow);
   UPWindowSetRelevance(up, upw, FALSE);
   if (upw->toplevelWindow) {
      XSelectInput(up->display, upw->toplevelWindow, 0);
      HashTable_Delete(up->allWindows, GUINT_TO_POINTER(upw->toplevelWindow));
   }
   if (upw->clientWindow) {
      XSelectInput(up->display, upw->clientWindow, 0);
      HashTable_Delete(up->allWindows, GUINT_TO_POINTER(upw->clientWindow));
   }
#if defined(VM_HAVE_X11_SHAPE_EXT)
   if (up->shapeEventBase) {
      XShapeSelectInput(up->display, upw->toplevelWindow, 0);

      if (upw->clientWindow) {
         XShapeSelectInput(up->display, upw->clientWindow, 0);
      }
   }
#endif

   /*
    * Okay, now we may have two UnityPlatformWindows running around, one each for
    * the top-level and client windows in response to their CreateNotify events,
    * and this routine wishes to unify both in a single UPW.
    *
    * XXX The current course of action is this:
    *    1.  If either our operand top-level or client windows belong to
    *        any other UnityPlatformWindows, said UPWs will be dereferenced.
    *    2.  We'll then assign the operand windows to the current UPW.
    */
   scratchUpw = UPWindow_Lookup(up, toplevelWindow);
   if (scratchUpw && scratchUpw != upw) {
      UPWindow_Unref(up, scratchUpw);
   }
   scratchUpw = UPWindow_Lookup(up, clientWindow);
   if (scratchUpw && scratchUpw != upw) {
      UPWindow_Unref(up, scratchUpw);
   }

   upw->toplevelWindow = toplevelWindow;
   upw->clientWindow = clientWindow;

   /*
    * Start listening to events on this window. We want these even if the window is of no
    * interest to us, because the specified events may make the window interesting to us.
    */
   if (clientWindow) {
      XSelectInput(up->display, clientWindow, PropertyChangeMask | StructureNotifyMask);
   }

   XSelectInput(up->display,
                toplevelWindow,
                FocusChangeMask | PropertyChangeMask | StructureNotifyMask);

#if defined(VM_HAVE_X11_SHAPE_EXT)
   if (up->shapeEventBase) {
      XShapeSelectInput(up->display, toplevelWindow, ShapeNotifyMask);

      if (upw->clientWindow) {
         XShapeSelectInput(up->display, upw->clientWindow, ShapeNotifyMask);
      }
   }
#endif

   HashTable_Insert(up->allWindows, GUINT_TO_POINTER(upw->toplevelWindow), upw);
   if (upw->clientWindow) {
      HashTable_Insert(up->allWindows, GUINT_TO_POINTER(upw->clientWindow), upw);
   }
   UPWindowSetRelevance(up, upw, wasRelevant);
}


/*
 *-----------------------------------------------------------------------------
 *
 * UPWindow_Create --
 *
 *      Creates a UnityPlatformWindow for the specified UnityWindowId. The resulting
 *      object will have a reference count of 1 that is owned by the caller.
 *
 * Results:
 *      The newly created UnityPlatformWindow.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

UnityPlatformWindow *
UPWindow_Create(UnityPlatform *up,     // IN
                Window window)         // IN
{
   UnityPlatformWindow *upw;
   Window toplevelWindow;
   Window clientWindow;
   Window rootWindow;

   ASSERT(up);
   ASSERT(window != None);

   if (!UnityPlatformFindWindows(up, window,
                                 &toplevelWindow, &clientWindow, &rootWindow)) {
      Debug("FindWindows failed on %#lx\n", window);
      return NULL;
   }

   if (HashTable_Lookup(up->allWindows,
                        GUINT_TO_POINTER(toplevelWindow),
                        (void **)&upw)) {
      Debug("Lookup of window %#lx returned %#lx\n",
            toplevelWindow, upw->toplevelWindow);
      abort();
   }

   if (HashTable_Lookup(up->allWindows,
                        GUINT_TO_POINTER(clientWindow),
                        (void **)&upw)) {
      Debug("Lookup of clientWindow %#lx returned existing toplevel %#lx\n",
            clientWindow, upw->toplevelWindow);
      return NULL;
   }

   upw = Util_SafeCalloc(1, sizeof *upw);
   upw->refs = 1;

   Debug("Creating new window for %#lx/%#lx/%#lx\n",
         toplevelWindow, clientWindow, rootWindow);
   upw->rootWindow = rootWindow;
   for (upw->screenNumber = 0;
        upw->screenNumber < up->rootWindows->numWindows
        && up->rootWindows->windows[upw->screenNumber] != rootWindow;
        upw->screenNumber++);
   ASSERT (upw->screenNumber < up->rootWindows->numWindows);

   DynBuf_Init(&upw->iconPng.data);
   DynBuf_SetSize(&upw->iconPng.data, 0);

   UPWindowSetWindows(up, upw, toplevelWindow, clientWindow);

   /*
    * Put newly created windows on the top of the stack by default.
    */
   upw->higherWindow = NULL;
   upw->lowerWindow = up->topWindow;
   if (upw->lowerWindow) {
      upw->lowerWindow->higherWindow = upw;
   }
   up->topWindow = upw;

   return upw;
}


/*
 *-----------------------------------------------------------------------------
 *
 * UPWindow_Ref --
 *
 *      Increases the reference count on the UnityPlatformWindow object by one.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

void
UPWindow_Ref(UnityPlatform *up,        // IN
             UnityPlatformWindow *upw) // IN
{
   upw->refs++;
}


/*
 *-----------------------------------------------------------------------------
 *
 * UPWindow_Unref --
 *
 *      Decreases the reference count on the UnityPlatformWindow object by one.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      May destroy the object if no references remain.
 *
 *-----------------------------------------------------------------------------
 */

void
UPWindow_Unref(UnityPlatform *up,        // IN
               UnityPlatformWindow *upw) // IN
{
   upw->refs--;

   if (upw->refs <= 0) { // Window needs destroying
      UPWindowSetRelevance(up, upw, FALSE);

      /*
       * Filter out windows that have been already destroyed on the X11 side, but which
       * still may have had refcounts active.
       */
      if (upw->windowType != UNITY_WINDOW_TYPE_NONE) {
         XSelectInput(up->display, upw->toplevelWindow, 0);

#if defined(VM_HAVE_X11_SHAPE_EXT)
         if (up->shapeEventBase) {
            XShapeSelectInput(up->display, upw->toplevelWindow, 0);
         }
#endif

         if (upw->clientWindow) {
            XSelectInput(up->display, upw->clientWindow, 0);
         }
      }

      HashTable_Delete(up->allWindows, GUINT_TO_POINTER(upw->toplevelWindow));
      if (upw->clientWindow) {
         HashTable_Delete(up->allWindows, GUINT_TO_POINTER(upw->clientWindow));
      }

      DynBuf_Destroy(&upw->iconPng.data);

      if (upw->higherWindow) {
         upw->higherWindow->lowerWindow = upw->lowerWindow;
      }
      if (upw->lowerWindow) {
         upw->lowerWindow->higherWindow = upw->higherWindow;
      }
      if (upw == up->topWindow) {
         up->topWindow = upw->lowerWindow;
      }

      free(upw);
   }
}


/*
 *-----------------------------------------------------------------------------
 *
 * UPWindow_Lookup --
 *
 *      Retrieves the UnityPlatformWindow object associated with a given Window ID
 *
 * Results:
 *      The UnityPlatformWindow object, or NULL if it was not found
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

UnityPlatformWindow *
UPWindow_Lookup(UnityPlatform *up, // IN
                Window window)     // IN
{
   UnityPlatformWindow *retval = NULL;

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

   return retval;
}

#if 0 // Very useful if ever debugging the window stacking code, but slow otherwise.
/*
 *-----------------------------------------------------------------------------
 *
 * UPWindowCheckStack --
 *
 *      Sanity check on the linked list of windows for Z-ordering.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      May ASSERT() if things are broken.
 *
 *-----------------------------------------------------------------------------
 */

static void
UPWindowCheckStack(UnityPlatform *up)
{
   UnityPlatformWindow **upwList;
   size_t numWindows;
   size_t i;
   UnityPlatformWindow *curWindow;

   HashTable_ToArray(up->allWindows,
                     (void ***)&upwList,
                     &numWindows);
   for (i = 0; i < numWindows; i++) {
      for (curWindow = up->topWindow;
           curWindow;
           curWindow = curWindow->lowerWindow) {
         if (curWindow == upwList[i]) {
            break;
         }
      }

      if (curWindow != upwList[i]) {
         Debug("%s: Wanted %p. Complete window stack is: ", __FUNCTION__, upwList[i]);
         for (curWindow = up->topWindow;
              curWindow;
              curWindow = curWindow->lowerWindow) {
            if (curWindow == upwList[i]) {
               Debug("%p ->", curWindow);
            } else {
               Debug("[%p] ->", curWindow);
            }
         }
         Debug("NULL\n");

         Debug("%s: Window stack downwards from %p: ", __FUNCTION__, upwList[i]);
         for (curWindow = upwList[i];
              curWindow;
              curWindow = curWindow->lowerWindow) {
            if (curWindow == upwList[i]) {
               Debug("[%p] ->", curWindow);
            } else {
               Debug("%p ->", curWindow);
            }
         }
         Debug("NULL\n");

         Debug("%s: Window stack upwards from %p: ", __FUNCTION__, upwList[i]);
         for (curWindow = upwList[i];
              curWindow;
              curWindow = curWindow->higherWindow) {
            if (curWindow == upwList[i]) {
               Debug("[%p] <-", curWindow);
            } else {
               Debug("%p <-", curWindow);
            }
         }
         Debug("NULL\n");
      }

      ASSERT(curWindow == upwList[i]);
   }
   for (curWindow = up->topWindow;
        curWindow;
        curWindow = curWindow->lowerWindow) {
      for (i = 0; i < numWindows; i++) {
         if (curWindow == upwList[i]) {
            break;
         }
      }
      ASSERT(i < numWindows);
   }

   free(upwList);
}


/*
 *-----------------------------------------------------------------------------
 *
 * UPWindowCheckCycle --
 *
 *      Checks to make sure there are no loops in the window stack.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      May ASSERT().
 *
 *-----------------------------------------------------------------------------
 */

static void
UPWindowCheckCycle(UnityPlatform *up)
{
   UnityPlatformWindow *upw;
   UnityPlatformWindow *curWindow;

   for (upw = up->topWindow; upw; upw = upw->lowerWindow) {
      for (curWindow = upw->lowerWindow; curWindow; curWindow = curWindow->lowerWindow) {
         ASSERT(curWindow != upw);
      }
   }

   for (upw = up->topWindow; upw->lowerWindow; upw = upw->lowerWindow) {
      /* Find lowest window */
   }

   for (; upw; upw = upw->higherWindow) {
      for (curWindow = upw->higherWindow; curWindow; curWindow = curWindow->higherWindow) {
         ASSERT(curWindow != upw);
      }
   }
}
#endif


/*
 *-----------------------------------------------------------------------------
 *
 * UPWindow_Restack --
 *
 *      Changes the Z order list of the specified window so it is
 *      immediately above another window.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Updates UnityWindowTracker with the latest ZOrder.
 *
 *-----------------------------------------------------------------------------
 */

void
UPWindow_Restack(UnityPlatform *up,        // IN
		 UnityPlatformWindow *upw, // IN
		 Window above)             // IN - None indicates stack at bottom
{
   UnityPlatformWindow *newLowerWindow = NULL;

   ASSERT(up);
   ASSERT(upw);

   if (above != None) {
      newLowerWindow = UPWindow_Lookup(up, above);

      if (!newLowerWindow) {
         if (upw != up->topWindow) {
            Debug("%s: Couldn't find the window to stack above [%#lx].\n",
                  __func__, above);
            return;
         } else {
            return;
         }
      }
   }
   ASSERT(newLowerWindow != upw);

   if (newLowerWindow != upw->lowerWindow) {
      /*
       * Stacking order has changed. Move this window to the right place in the stack.
       *
       * 1. Remove 'upw' from the old location in the linked list.
       * 2. Find the 'upw' that it is now above.
       * 3. Insert it into the right location in the list.
       */

      ASSERT(upw->higherWindow != upw);
      ASSERT(upw->lowerWindow != upw);
      if (upw->higherWindow) {
         upw->higherWindow->lowerWindow = upw->lowerWindow;
      } else {
         up->topWindow = upw->lowerWindow;
      }

      ASSERT(upw->higherWindow != upw);
      ASSERT(upw->lowerWindow != upw);
      if (upw->lowerWindow) {
         upw->lowerWindow->higherWindow = upw->higherWindow;
      }
      upw->higherWindow = NULL;
      upw->lowerWindow = NULL;

      ASSERT(upw->higherWindow != upw);
      ASSERT(upw->lowerWindow != upw);
      upw->lowerWindow = newLowerWindow;
      if (newLowerWindow) {
         upw->higherWindow = newLowerWindow->higherWindow;
         upw->lowerWindow->higherWindow = upw;
         ASSERT(newLowerWindow != upw);
      } else {
         /*
          * This window is meant to go to the bottom of the stack.
          */
         upw->lowerWindow = NULL;
         upw->higherWindow = up->topWindow;

         while (upw->higherWindow && upw->higherWindow->lowerWindow) {
            upw->higherWindow = upw->higherWindow->lowerWindow;
         }
         ASSERT(newLowerWindow != upw);
      }

      ASSERT(newLowerWindow != upw);
      ASSERT(upw->higherWindow != upw);
      ASSERT(upw->lowerWindow != upw);
      if (upw->higherWindow) {
         ASSERT(upw->higherWindow->lowerWindow == newLowerWindow);
         upw->higherWindow->lowerWindow = upw;
      } else {
         up->topWindow = upw;
      }

      ASSERT(upw->higherWindow != upw);
      ASSERT(upw->lowerWindow != upw);
      if (upw->isRelevant) {
         up->stackingChanged = TRUE;
         Debug("Stacking order has changed\n");
      }
   }
}


/*
 *-----------------------------------------------------------------------------
 *
 * UPWindowSetRelevance --
 *
 *      Changes the "relevance" of a particular window. Normally, the decision of whether
 *      to do this should be made only by CheckRelevance().
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      May add or remove the window in UnityWindowTracker.
 *
 *-----------------------------------------------------------------------------
 */

static void
UPWindowSetRelevance(UnityPlatform *up,        // IN
                     UnityPlatformWindow *upw, // IN
                     Bool isRelevant)          // IN
{
   if ((isRelevant && upw->isRelevant) || (!isRelevant && !upw->isRelevant)) {
      return;
   }

   upw->isRelevant = isRelevant;
   if (isRelevant) {
      DynBuf windowPath;
      DynBuf execPath;

      DynBuf_Init(&windowPath);
      DynBuf_Init(&execPath);

      if (upw->windowType == UNITY_WINDOW_TYPE_NORMAL) {
         Bool retval;
         retval = UnityPlatformGetWindowPath(up,
                                             upw->toplevelWindow,
                                             &windowPath,
                                             &execPath);
         if (!retval) {
            Debug("GetWindowPath didn't know how to identify the window...\n");
         }
      }

      Debug("Adding window %#lx to tracker\n", upw->toplevelWindow);
      UnityWindowTracker_AddWindowWithData(up->tracker,
                                           upw->toplevelWindow,
                                           &windowPath,
                                           &execPath,
                                           upw);
      DynBuf_Destroy(&windowPath);
      DynBuf_Destroy(&execPath);

      UPWindowPushFullUpdate(up, upw);
   } else {
      Debug("Removing window %#lx from tracker\n", upw->toplevelWindow);
      UnityWindowTracker_RemoveWindow(up->tracker, upw->toplevelWindow);
      UnityPlatformDoUpdate(up, TRUE);
   }

   up->stackingChanged = TRUE;
}


/*
 *-----------------------------------------------------------------------------
 *
 * UPWindow_CheckRelevance --
 *
 *      Looks at the current state of a window to figure out whether we want to relay it
 *      through UnityWindowTracker.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Updates various cached metadata in UnityPlatformWindow, such as windowType and
 *      isOverrideRedirect.
 *
 *-----------------------------------------------------------------------------
 */

void
UPWindow_CheckRelevance(UnityPlatform *up,        // IN
                        UnityPlatformWindow *upw, // IN
                        const XEvent *motivator)  // IN - optional
{
   XWindowAttributes winAttr;
   int shouldBeRelevant = -1;
   Bool regetDesktop = FALSE;

   if (motivator) {
      /*
       * We have an event that may have modified the relevance of this window. See what
       * we need to do.
       */
      switch (motivator->type) {
      case PropertyNotify:
         {
            XPropertyEvent *event = (XPropertyEvent *)motivator;
            if (upw->waitingForWmState &&
                event->atom == up->atoms.WM_STATE &&
                event->state == PropertyNewValue) {
               Window toplevelWindow = 0;
               Window clientWindow = 0;
               Window rootWindow = 0;
               Bool success;

               regetDesktop = TRUE;
               Debug("%s: PropertyNotify: New WM_STATE on %#lx (current upw: %#lx::%#lx)\n",
                     __func__, event->window, upw->toplevelWindow, upw->clientWindow);
               success = UnityPlatformFindWindows(up, event->window,
                                                  &toplevelWindow, &clientWindow,
                                                  &rootWindow);
               if (success) {
                  UPWindowSetWindows(up, upw, toplevelWindow, clientWindow);
                  upw->waitingForWmState = FALSE;
                  Debug("%s: PropertyNotify: new upw: %#lx::%#lx\n",
                        __func__, upw->toplevelWindow, upw->clientWindow);
               } else {
                  Debug("%s: PropertyNotify: FindWindows failed again!\n", __func__);
                  return;
               }
            } else if (event->atom == up->atoms.WM_WINDOW_ROLE &&
                       event->state == PropertyNewValue &&
                       UnityX11Util_IsWindowDecorationWidget(up, upw->toplevelWindow)) {
               Debug("%s: Window %#lx is a decoration widget.  Ignore it.\n",
                     __func__, upw->toplevelWindow);
               upw->deleteWhenSafe = TRUE;
               return;
            } else if (event->atom == up->atoms._NET_WM_DESKTOP) {
               if (upw->wantSetDesktopNumberOnUnmap) {
                  /*
                   * We're to preserve _NET_WM_DESKTOP across unmapping and remapping a
                   * window (most likely a taskbar).  If we see PropertyDelete, assume
                   * it's ours and reset the _NET_WM_DESKTOP property.  If, however, we
                   * instead see a PropertyNewValue (the only other possibility, hence
                   * no "else" below), then we assume some other client wished to change
                   * the property, and we forget about restoring _NET_WM_DESKTOP when
                   * we remap the window later.
                   */
                  if (event->state == PropertyDelete) {
                     Debug("%s: PropertyDelete: _NET_WM_DESKTOP: %#lx.  Resetting to %d.\n",
                           __func__, upw->clientWindow, upw->onUnmapDesktopNumber);
                     UPWindow_SetEWMHDesktop(up, upw, upw->onUnmapDesktopNumber);
                  }
                  upw->wantSetDesktopNumberOnUnmap = FALSE;
                  return;
               }
               regetDesktop = TRUE;
            } else if (event->atom != up->atoms._NET_WM_WINDOW_TYPE) {
               return;
            }
         }
         break;

      case ConfigureNotify:
         if ((motivator->xconfigure.override_redirect ? TRUE : FALSE)
             == upw->isOverrideRedirect) {
            return;
         }
         break;

      case UnmapNotify:
         /*
          * XXX should we ignore UnmapNotify events if they come from non-override
          * redirect windows?
          */

         /*
          * If a window is override redirect (e.g. tooltips), then we may need to show
          * & hide it based on map & unmap, because we won't get WM_STATE updates to
          * help us do minimize/restore.
          */
         break;

      case MapNotify:
         if (upw->wantSetDesktopNumberOnUnmap) {
            Debug("%s: Expected PropertyDelete before MapNotify.\n", __func__);
            upw->wantSetDesktopNumberOnUnmap = FALSE;
         }
         regetDesktop = TRUE;
         break;

      case ReparentNotify:
         {
            Window toplevelWindow = 0;
            Window clientWindow = 0;
            Window rootWindow = 0;
            const XReparentEvent *reparent = &motivator->xreparent;
            Bool success;

            regetDesktop = TRUE;
            Debug("%s: ReparentNotify: %#lx reparented to %#lx (current upw: %#lx::%#lx)\n",
                  __func__, reparent->window, reparent->parent,
                  upw->toplevelWindow, upw->clientWindow);
            success = UnityPlatformFindWindows(up, reparent->window,
                                               &toplevelWindow, &clientWindow,
                                               &rootWindow);
            if (success) {
               UPWindowSetWindows(up, upw, toplevelWindow, clientWindow);
            } else {
               Debug("%s: ReparentNotify: UnityPlatformFindWindows failed."
                     "  Waiting for WM_STATE.\n", __func__);
               upw->waitingForWmState = TRUE;
               return;
            }
         }
         break;

      case DestroyNotify:
         shouldBeRelevant = FALSE;
         break;

      default:
         return;
      }
   } else {
      regetDesktop = TRUE;
   }

   if (shouldBeRelevant == -1) {
      Bool onCurrentDesktop = TRUE;
      Bool isInvisible = FALSE;
      Bool ignoreThisWindow = FALSE;

      UnityPlatformResetErrorCount(up);

      XGetWindowAttributes(up->display, upw->toplevelWindow, &winAttr);
      if (UnityPlatformGetErrorCount(up)) {
         shouldBeRelevant = FALSE;
         goto out;
      }

      if (regetDesktop) {
         if (!UPWindowGetDesktop(up, upw, &upw->desktopNumber)) {
            upw->desktopNumber = -1;
         } else {
            if (upw->wantSetDesktopNumberOnUnmap) {
               upw->onUnmapDesktopNumber = upw->desktopNumber;
            }
         }
      }
      if (upw->desktopNumber < up->desktopInfo.numDesktops
          && upw->desktopNumber >= 0
          && up->desktopInfo.guestDesktopToUnity[upw->desktopNumber] !=
          UnityWindowTracker_GetActiveDesktop(up->tracker)) {
         onCurrentDesktop = FALSE;
      }
      upw->isViewable = (winAttr.map_state == IsViewable);
      if (!upw->wasViewable) {
         if (upw->isViewable) {
            upw->wasViewable = upw->isViewable;
         } else {
            /*
             * Check if it's in iconic state (i.e. minimized), which means it was viewable
             * previously as far as we're concerned.
             */

            Atom propertyType;
            int propertyFormat;
            unsigned long itemsReturned = 0;
            unsigned long bytesRemaining;
            Atom *valueReturned = NULL;
            Window mainWindow = upw->clientWindow ? upw->clientWindow : upw->toplevelWindow;

            if (XGetWindowProperty(up->display, mainWindow, up->atoms.WM_STATE, 0,
                                   1024, False, AnyPropertyType,
                                   &propertyType, &propertyFormat, &itemsReturned,
                                   &bytesRemaining, (unsigned char **) &valueReturned)
                == Success
                && itemsReturned > 0
                && propertyType == up->atoms.WM_STATE
                && propertyFormat == 32
                && valueReturned[0] == IconicState) {
               upw->wasViewable = TRUE;
               Debug("Found window %#lx/%#lx initially in iconic state\n",
                     upw->toplevelWindow, upw->clientWindow);
            } else {
               upw->wasViewable = FALSE;
            }

            XFree(valueReturned);
         }
      }
      upw->isOverrideRedirect = winAttr.override_redirect ? TRUE : FALSE;

      /*
       * More crazy tests to determine whether a window should be added to the window
       * tracker.
       */

      if (winAttr.class == InputOnly) {
         /* This is intrinsically true. */
         isInvisible = TRUE;
      } else if (!upw->isViewable && onCurrentDesktop && !upw->clientWindow) {
         /*
          * Evaluate the map state.  There are reasons why we'd like to keep unmapped
          * windows in the tracker.
          *
          *    1.  The window may be on another desktop.
          *    2.  The window may be minimized.
          *
          * upw->clientWindow == None implies that there is no window in the hierarchy
          * with a WM_STATE property.  No WM_STATE property means that the window can't
          * be "minimized".
          *
          * I'm using these implications because it saves me from having to explicitly
          * query for/examine WM_STATE here.
          */
         isInvisible = TRUE;
      } else if (winAttr.width <= 1 && winAttr.height <= 1) {
         isInvisible = TRUE;
      } else if ((winAttr.x + winAttr.width) < 0
                 || (winAttr.y + winAttr.height) < 0) {
         /*
          * XXX This isn't clear to me.  What if winAttr.x > parent's width?
          */
         isInvisible = TRUE;
      }

      if (!isInvisible) {
         char *wmname = NULL;

         /*
          **************************************
          * This section should hold all the ugly app-specific filtering that might be
          * needed for UnityX11.
          */

         if (XFetchName(up->display,
                        upw->clientWindow ? upw->clientWindow : upw->toplevelWindow,
                        &wmname) != 0) {
            if (!strcmp(wmname, "gksu")
                && winAttr.override_redirect) {
               ignoreThisWindow = TRUE;
            }

            XFree(wmname);
         }

         /*
          * End app-specific filtering.
          *******************************************
          */
      }

      if (isInvisible) {
         shouldBeRelevant = FALSE;
      } else if (ignoreThisWindow) {
         shouldBeRelevant = FALSE;
      } else {
         Atom netWmWindowType = up->atoms._NET_WM_WINDOW_TYPE_NORMAL;
         Atom netWmPropertyType;
         int netWmPropertyFormat = 0;
         unsigned long itemsReturned, bytesRemaining;
         unsigned char *valueReturned = NULL;
         Window mainWindow;

         mainWindow = upw->clientWindow ? upw->clientWindow : upw->toplevelWindow;
         XGetWindowProperty(up->display, mainWindow,
                            up->atoms._NET_WM_WINDOW_TYPE, 0,
                            1024, False, AnyPropertyType,
                            &netWmPropertyType, &netWmPropertyFormat, &itemsReturned,
                            &bytesRemaining, &valueReturned);

         if (UnityPlatformGetErrorCount(up)) {
            Debug("Error retrieving window type property\n");
            shouldBeRelevant = FALSE;
            goto out;
         }

         if (netWmPropertyType == XA_ATOM && itemsReturned && !bytesRemaining) {
            netWmWindowType = *((Atom *) valueReturned);
         }
         XFree(valueReturned);

         shouldBeRelevant = TRUE;
         if (netWmWindowType == up->atoms._NET_WM_WINDOW_TYPE_DESKTOP) {
            shouldBeRelevant = FALSE;
            upw->windowType = UNITY_WINDOW_TYPE_DESKTOP;
            up->desktopWindow = upw;
         } else if (netWmWindowType == up->atoms._NET_WM_WINDOW_TYPE_DND) {
            shouldBeRelevant = FALSE;
         } else if (netWmWindowType == up->atoms._NET_WM_WINDOW_TYPE_DOCK) {
            shouldBeRelevant = up->currentSettings[UNITY_UI_TASKBAR_VISIBLE];
            upw->windowType = UNITY_WINDOW_TYPE_DOCK;
         } else if (netWmWindowType == up->atoms._NET_WM_WINDOW_TYPE_UTILITY) {
            upw->windowType = UNITY_WINDOW_TYPE_PANEL;
         } else if (netWmWindowType == up->atoms._NET_WM_WINDOW_TYPE_DIALOG) {
            upw->windowType = UNITY_WINDOW_TYPE_DIALOG;
         } else if (netWmWindowType == up->atoms._NET_WM_WINDOW_TYPE_MENU
                    || netWmWindowType == up->atoms._NET_WM_WINDOW_TYPE_POPUP_MENU
                    || netWmWindowType == up->atoms._NET_WM_WINDOW_TYPE_DROPDOWN_MENU) {
            upw->windowType = UNITY_WINDOW_TYPE_MENU;
         } else if (netWmWindowType == up->atoms._NET_WM_WINDOW_TYPE_SPLASH) {
            upw->windowType = UNITY_WINDOW_TYPE_SPLASH;
         } else if (netWmWindowType == up->atoms._NET_WM_WINDOW_TYPE_TOOLBAR) {
            upw->windowType = UNITY_WINDOW_TYPE_TOOLBAR;
         } else if (netWmWindowType == up->atoms._NET_WM_WINDOW_TYPE_TOOLTIP) {
            upw->windowType = UNITY_WINDOW_TYPE_TOOLTIP;
         } else {
            upw->windowType = UNITY_WINDOW_TYPE_NORMAL;
         }
      }
   }

out:
   ASSERT(shouldBeRelevant >= 0);

   Debug("Relevance for (%p) %#lx/%#lx/%#lx is %d (window type %d)\n",
         upw, upw->toplevelWindow, upw->clientWindow, upw->rootWindow,
         shouldBeRelevant, upw->windowType);

   UPWindowSetRelevance(up, upw, shouldBeRelevant ? TRUE : FALSE);
}


/*
 *-----------------------------------------------------------------------------
 *
 * UPWindow_SetUserTime --
 *
 *      Updates the _NET_WM_USER_TIME property on a window so the window manager
 *      will let us restack the window.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Updated timestamp.
 *
 *-----------------------------------------------------------------------------
 */

void
UPWindow_SetUserTime(UnityPlatform *up,        // IN
                     UnityPlatformWindow *upw) // IN
{
   Atom dummy;
   Window focusWindow;
   Atom propertyType;
   int propertyFormat;
   unsigned long itemsReturned, bytesRemaining;
   unsigned char *valueReturned = NULL;

   focusWindow = upw->clientWindow ? upw->clientWindow : upw->toplevelWindow;

   XGetWindowProperty(up->display, focusWindow, up->atoms._NET_WM_USER_TIME_WINDOW, 0,
                      1024, False, XA_WINDOW, &propertyType, &propertyFormat,
                      &itemsReturned, &bytesRemaining, &valueReturned);
   if (valueReturned) {
      focusWindow = *(Window *)valueReturned;
      XFree(valueReturned);
   }

   dummy = UnityPlatformGetServerTime(up);
   XChangeProperty(up->display, focusWindow,
                   up->atoms._NET_WM_USER_TIME, XA_CARDINAL,
                   32, PropModeReplace, (unsigned char *)&dummy, 1);
}


/*
 *-----------------------------------------------------------------------------
 *
 * UPWindowGetActualWindowAndPosition --
 *
 *      Figures out the right arguments to call XMoveResizeWindow with when
 *      moving/resizing a window.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Puts the window and coordinates to use in 'actualWindow' and 'actualRect'.
 *
 *-----------------------------------------------------------------------------
 */

static void
UPWindowGetActualWindowAndPosition(UnityPlatform *up,                // IN
                                   const UnityPlatformWindow *upw,   // IN
                                   const UnityRect *orig,            // IN
                                   const XWindowAttributes *origTop, // IN
                                   Window *actualWindow,             // IN/OUT
                                   UnityRect *actualRect)            // IN/OUT
{
   XWindowAttributes clientWinAttr;
   Atom propertyType;
   int propertyFormat = 0;
   unsigned long itemsReturned = 0;
   unsigned long bytesRemaining;
   unsigned char *valueReturned = NULL;
   int frameSizeTop;
   int frameSizeBottom;
   int frameSizeLeft;
   int frameSizeRight;

   ASSERT(up);
   ASSERT(upw);
   ASSERT(orig);
   ASSERT(actualWindow);
   ASSERT(actualRect);

   *actualRect = *orig;
   if (!upw->clientWindow) {
      *actualWindow = upw->toplevelWindow;
      return;
   }

   *actualWindow = upw->clientWindow;

   /*
    * We need to figure out how to adjust the 'orig' rect (which is in toplevelWindow
    * coordinates) and turn it into clientWindow coordinates. Because window managers
    * ignore requests to modify their frame windows (toplevelWindow), we have to request
    * the change on the clientWindow instead.
    */
   if (UnityPlatformWMProtocolSupported(up, UNITY_X11_WM__NET_FRAME_EXTENTS)
       && XGetWindowProperty(up->display, upw->clientWindow, up->atoms._NET_FRAME_EXTENTS, 0,
                             1024, False, XA_CARDINAL,
                             &propertyType, &propertyFormat, &itemsReturned,
                             &bytesRemaining, &valueReturned) == Success
       && propertyFormat == 32
       && itemsReturned >= 4) {
      Atom *atomValue = (Atom *)valueReturned;

      frameSizeLeft = atomValue[0];
      frameSizeRight = atomValue[1];
      frameSizeTop = atomValue[2];
      frameSizeBottom = atomValue[3];
   } else {
      /*
       * Query the current clientWindow and calculate how to adjust the frame coords to
       * client coords.
       */
      clientWinAttr.x = clientWinAttr.y = 0;
      clientWinAttr.width = origTop->width;
      clientWinAttr.height = origTop->height;

      XGetWindowAttributes(up->display, upw->clientWindow, &clientWinAttr);

      frameSizeLeft = clientWinAttr.x;
      frameSizeRight = origTop->width - (clientWinAttr.x + clientWinAttr.width);
      frameSizeTop = clientWinAttr.y;
      frameSizeBottom = origTop->height - (clientWinAttr.y + clientWinAttr.height);
   }

   /*
    * It turns out that with metacity, we don't have to adjust x/y for the frame size,
    * only the width & height. XXX we should see how other window managers behave.
    */
#if 0
   actualRect->x += frameSizeLeft;
   actualRect->y += frameSizeTop;
#endif

   actualRect->width -= frameSizeLeft + frameSizeRight;
   actualRect->height -= frameSizeTop + frameSizeBottom;

   XFree(valueReturned);
}


/*
 *----------------------------------------------------------------------------
 *
 * UnityPlatformMoveResizeWindow --
 *
 *      Moves and/or resizes the given window to the specified location. Does not
 *      attempt to move and/or resize window if (a) the destination rectangle does not
 *      intersect with the virtual screen rectangle (b) window is minimized.
 *
 *      If the input width & height match the current width & height, then this
 *      function will end up just moving the window. Similarly if the input
 *      x & y coordinates match the current coordinates, then it will end up just
 *      resizing the window.
 *
 * Results:
 *      Even if the move/resize operaion is not execuated or it fails, window's
 *      current coordinates are always sent back.
 *
 *      Function does not return FALSE if the attempt to move and/or resize fails.
 *      This is because the host will be comparing input and output parameters to
 *      decide whether the window really moved and/or resized.
 *
 *      In a very rare case, when attempt to get window's current coordinates fail,
 *      returns FALSE.
 *
 * Side effects:
 *      None
 *
 *----------------------------------------------------------------------------
 */

Bool
UnityPlatformMoveResizeWindow(UnityPlatform *up,         // IN
                              UnityWindowId window,      // IN: Window handle
                              UnityRect *moveResizeRect) // IN/OUT: Desired coordinates,
                                                         // before and after
                                                         // the operation.
{
   UnityPlatformWindow *upw;
   Bool retval = FALSE;
   XWindowAttributes winAttr;
   XWindowAttributes newAttr;
   UnityRect desiredRect;

   ASSERT(moveResizeRect);

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

   desiredRect = *moveResizeRect;

   UnityPlatformResetErrorCount(up);
   XGetWindowAttributes(up->display, upw->toplevelWindow, &winAttr);
   if (UnityPlatformGetErrorCount(up)) {
      return FALSE;
   }

   if (winAttr.x == moveResizeRect->x
       && winAttr.y == moveResizeRect->y
       && winAttr.width == moveResizeRect->width
       && winAttr.height == moveResizeRect->height) {
      return TRUE;
   }

   /*
    * _NET_MOVERESIZE_WINDOW is preferable in general (because it saves us extra X
    * calls), but it is broken in metacity and there's no way to detect whether it works
    * or not.
    */
#if defined(VM_CAN_TRUST__NET_MOVERESIZE_WINDOW)
   if (UnityPlatformWMProtocolSupported(up, UNITY_X11_WM__NET_MOVERESIZE_WINDOW)
       && upw->clientWindow) {
      Atom data[5] = {0, 0, 0, 0, 0};

      /*
       * The first datum in the EWMH _NET_MOVERESIZE_WINDOW message contains a bunch of
       * bits to signify what information is in the request and where the request came
       * from. The (0xF << 8) bits (lower nibble of the upper byte) signify that the request contains x, y, width, and
       * height data. The (2 << 12) bits (higher nibble of the upper byte) signifies that the request was made by the
       * pager/taskbar. StaticGravity is 10 in the lower byte.
       */
      data[0] = (0xF << 8) | (2 << 12) | StaticGravity;

      data[1] = moveResizeRect->x;
      data[2] = moveResizeRect->y;
      data[3] = moveResizeRect->width;
      data[4] = moveResizeRect->height;
      UnityPlatformSendClientMessage(up, upw->rootWindow, upw->clientWindow,
                                     up->atoms._NET_MOVERESIZE_WINDOW,
                                     32, 5, data);
      Debug("MoveResizeWindow implemented using _NET_MOVERESIZE_WINDOW\n");
   } else
#endif
   {
      if (upw->desktopNumber == up->desktopInfo.currentDesktop ||
          upw->desktopNumber == -1) {
         UnityRect actualRect;
         Window actualWindow;

         UPWindowGetActualWindowAndPosition(up, upw, moveResizeRect, &winAttr, &actualWindow, &actualRect);

         XMoveResizeWindow(up->display, actualWindow,
                           actualRect.x, actualRect.y,
                           actualRect.width, actualRect.height);
         Debug("MoveResizeWindow implemented using XMoveResizeWindow (requested (%d, %d) +(%d, %d) on %#lx\n",
               actualRect.x, actualRect.y, actualRect.width, actualRect.height,
               actualWindow);
      } else {
         Debug("Trying to move window %#lx that is on desktop %d instead of the current desktop %u\n",
               upw->toplevelWindow, upw->desktopNumber, up->desktopInfo.currentDesktop);
         return FALSE;
      }
   }

   XSync(up->display, False);
   XGetWindowAttributes(up->display, upw->toplevelWindow, &newAttr);
   moveResizeRect->x = newAttr.x;
   moveResizeRect->y = newAttr.y;
   moveResizeRect->width = newAttr.width;
   moveResizeRect->height = newAttr.height;

   retval = TRUE;

   Debug("MoveResizeWindow(%#lx/%#lx): original (%d,%d)+(%d,%d), desired (%d,%d)+(%d,%d), actual (%d,%d)+(%d,%d) = %d\n",
         upw->toplevelWindow, upw->clientWindow,
         winAttr.x, winAttr.y, winAttr.width, winAttr.height,
         desiredRect.x, desiredRect.y, desiredRect.width, desiredRect.height,
         moveResizeRect->x, moveResizeRect->y,
         moveResizeRect->width, moveResizeRect->height,
         retval);

   return retval;
}


/*
 *----------------------------------------------------------------------------
 *
 * UnityPlatformCloseWindow --
 *
 *      Close the window. Send WM_DELETE message to the specified window.
 *      Just because the message was posted successfully, doesn't mean the
 *      window will be closed (this is up to the underlying application/user
 *      actions).
 *
 * Results:
 *      TRUE if we were successful in posting the close message to the window.
 *      FALSE otherwise.
 *
 * Side effects:
 *      The window might be closed (and, potentially, an application exits)
 *
 *----------------------------------------------------------------------------
 */

Bool
UnityPlatformCloseWindow(UnityPlatform *up,         // IN: Platform data
                         UnityWindowId window)      // IN: window handle
{
   UnityPlatformWindow *upw;

   ASSERT(up);

   upw = UPWindow_Lookup(up, window);

   Debug("Closing window %#x\n", window);

   if (!upw) {
      return FALSE;
   }

   if (upw->clientWindow &&
       UnityPlatformWMProtocolSupported(up, UNITY_X11_WM__NET_CLOSE_WINDOW)) {
      Atom data[] = {0,
                     2, // Bit to indicate that the pager requested it
                     0,
                     0,
                     0};
      data[0] = UnityPlatformGetServerTime(up);
      UnityPlatformSendClientMessage(up, upw->rootWindow, upw->clientWindow,
                                     up->atoms._NET_CLOSE_WINDOW, 32, 5,
                                     data);
   } else if (UPWindow_ProtocolSupported(up, upw, UNITY_X11_WIN_WM_DELETE_WINDOW)){
      Atom data[1];
      Window destWin = upw->clientWindow ? upw->clientWindow : upw->toplevelWindow;

      data[0] = up->atoms.WM_DELETE_WINDOW;

      UnityPlatformSendClientMessage(up, destWin, destWin,
                                     up->atoms.WM_DELETE_WINDOW, 32, 1,
                                     data);
   } else {
      XDestroyWindow(up->display, upw->toplevelWindow);
      XFlush(up->display);
   }

   return TRUE;
}


/*
 *-----------------------------------------------------------------------------
 *
 * UnityPlatformArgvToWindowPaths --
 *
 *      Encodes the string array 'argv' into two window paths, one uniquely
 *      representing a window and another its owning application.
 *
 * Results:
 *      TRUE on success, FALSE on failure.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

static Bool
UnityPlatformArgvToWindowPaths(UnityPlatform *up,        // IN
                               UnityPlatformWindow *upw, // IN
                               char **inArgv,            // IN
                               int argc,                 // IN
                               char *cwd,                // IN
                               gchar **windowUri,        // OUT
                               gchar **execUri)          // OUT
{
   int numQueryArgs;
   int i;
   int err;
   char **argv;
   char *windowQueryString = NULL;
   char *execQueryString = NULL;
   const char *uriString = NULL;
   const char *desktopUriString = NULL;
   Bool retval = FALSE;

   ASSERT(argc);
   ASSERT(windowUri);
   ASSERT(execUri);

   argv = inArgv;

   while (argc && AppUtil_AppIsSkippable(argv[0])) {
      argv++;
      argc--;
   }

   if (!argc) {
      Debug("%s: all args determined skippable.\n", __func__);
      return FALSE;
   }

   desktopUriString = GHIX11_FindDesktopUriByExec(argv[0]);

   if (!desktopUriString) {
      if (argv[0][0] != '/') {
         char *ctmp = NULL;
         if ((ctmp = AppUtil_CanonicalizeAppName(argv[0], cwd))) {
            char **newArgv;
            newArgv = alloca(argc * sizeof argv[0]);
            memcpy(newArgv, argv, argc * sizeof argv[0]);
            argv = newArgv;
            i = strlen(ctmp) + 1;
            argv[0] = alloca(i);
            memcpy(argv[0], ctmp, i);
            g_free(ctmp);
         } else {
            Debug("%s: Program %s not found\n", __FUNCTION__, argv[0]);
            return FALSE;
         }
      }

      /*
       * If the program in question takes any arguments, they will be appended as URI
       * query parameters.  (I.e., we're adding only arguments from argv[1] and beyond.)
       */
      numQueryArgs = argc - 1;

      if (numQueryArgs > 0) {
         UriQueryListA *queryList;
         int j;

         /*
          * First build query string containing only program arguments.
          */
         queryList = alloca(numQueryArgs * sizeof *queryList);
         for (i = 1, j = 0; i < argc; i++, j++) {
            queryList[j].key = "argv[]";
            queryList[j].value = argv[i];
            queryList[j].next = &queryList[j + 1];
         }

         /*
          * Terminate queryList.
          */
         queryList[numQueryArgs - 1].next = NULL;

         if (uriComposeQueryMallocA(&execQueryString, queryList)) {
            Debug("uriComposeQueryMallocA failed\n");
            return FALSE;
         }
      }
   }

   /*
    * Now, if we are to identify a specific window, go ahead and tack on its
    * XID in a second buffer.  Please see UnityPlatformGetWindowPath for more
    * an explanation about keeping the XID separate.
    */
   if (upw) {
      Window xid = upw->clientWindow ? upw->clientWindow : upw->toplevelWindow;
      /*
       * The XID is used to allow GHI to retrieve icons for more apps...
       */
      windowQueryString = execQueryString ?
         g_strdup_printf("%s&WindowXID=%lu", execQueryString, xid) :
         g_strdup_printf("WindowXID=%lu", xid);
   }

   if (desktopUriString) {
      uriString = desktopUriString;
   } else {
      char *mutableUriString = alloca(10 + 3 * strlen(argv[0])); // This formula comes from URI.h
      err = uriUnixFilenameToUriStringA(argv[0], mutableUriString);
      if (err) {
         Debug("uriUnixFilenameToUriStringA failed\n");
         goto out;
      }
      uriString = mutableUriString;
   }

   /*
    * We could use uriparser to construct the whole URI with querystring for us, but
    * there doesn't seem to be any advantage to that right now, and it'd involve more
    * steps.
    */

   *windowUri = windowQueryString ?
      g_strdup_printf("%s?%s", uriString, windowQueryString) :
      g_strdup(uriString);

   *execUri = execQueryString ?
      g_strdup_printf("%s?%s", uriString, execQueryString) :
      g_strdup(uriString);

   retval = TRUE;

out:
   g_free(windowQueryString);
   g_free(execQueryString);

   return retval;
}


/*
 *-----------------------------------------------------------------------------
 *
 * UnityPlatformReadProcessPath --
 *
 *      Reads the cmdline of a process and stuffs it with and without window ID
 *      into supplied gchar ** arguments in URI-encoded form.
 *
 * Results:
 *      TRUE if successful, FALSE otherwise.
 *
 * Side effects:
 *      Values of windowUri and execUri may point to strings.
 *
 *-----------------------------------------------------------------------------
 */

static Bool
UnityPlatformReadProcessPath(UnityPlatform *up,        // IN
                             UnityPlatformWindow *upw, // IN
                             pid_t pid,                // IN
                             gchar **windowUri,        // OUT
                             gchar **execUri)          // OUT
{
#if defined(linux)
   FILE *fh;
   char cbuf[256];
   char cwdbuf[PATH_MAX];
   int i;

   Str_Snprintf(cbuf, sizeof cbuf, "/proc/%d/cwd", pid);
   i = readlink(cbuf, cwdbuf, sizeof cwdbuf);
   if (i <= 0) {
      /* Lookup of cwd failed.  We'll try our best without it. */
      i = 0;
   }
   cwdbuf[i] = '\0';

   Str_Snprintf(cbuf, sizeof cbuf, "/proc/%d/cmdline", pid);

   fh = fopen(cbuf, "r");
   if (fh) {
      size_t nitems;
      char *argv[2048];
      int argc, i;

      nitems = fread(cbuf, 1, sizeof cbuf, fh);
      fclose(fh);

      if (!nitems) {
         return FALSE;
      }

      for (argc = i = 0; i < nitems; i++) {
         if (i == 0 || cbuf[i - 1] == '\0') {
            argv[argc++] = &cbuf[i];
         }
      }
      argv[argc] = NULL;

      return UnityPlatformArgvToWindowPaths(up, upw, argv, argc,
                                            cwdbuf[0] ? cwdbuf : NULL,
                                            windowUri, execUri);
   }
#endif

   return FALSE;
}


/*
 *-----------------------------------------------------------------------------
 *
 * UnityX11GetWindowPaths --
 *
 *      Internal routine used to retrieve the window path for the purpose of getting its
 *      icons and for the unity.get.window.path operation.
 *
 * Results:
 *      TRUE on success, FALSE on failure.
 *
 * Side effects:
 *      Allocates memory to be returned to caller via g_free.
 *
 *-----------------------------------------------------------------------------
 */

static Bool
UnityX11GetWindowPaths(UnityPlatform *up,        // IN
                       UnityPlatformWindow *upw, // IN
                       gchar **windowUri,        // OUT
                       gchar **execUri)          // OUT
{

   Atom propertyType;
   int propertyFormat;
   unsigned long itemsReturned = 0;
   unsigned long bytesRemaining;
   unsigned char *valueReturned = NULL;
   char **argv = NULL;
   int argc;
   XClassHint classHint = {NULL, NULL};
   int ret;
   Window checkWindow;
   Bool retval = FALSE;
   Bool triedLeader = FALSE;

   checkWindow = upw->clientWindow ? upw->clientWindow : upw->toplevelWindow;

tryLeader:
   UnityPlatformResetErrorCount(up);
   ret = XGetWindowProperty(up->display, checkWindow, up->atoms._NET_WM_PID, 0,
                            1024, False, AnyPropertyType,
                            &propertyType, &propertyFormat, &itemsReturned,
                            &bytesRemaining, &valueReturned);
   if (UnityPlatformGetErrorCount(up) || ret != Success) {
      return FALSE;
   }

   if (propertyType == XA_CARDINAL && itemsReturned >= 1) {
      pid_t windowPid = 0;

      switch (propertyFormat) {
      case 16:
         windowPid = * (CARD16 *)valueReturned;
         break;
      case 32:
         windowPid = *(XID *)valueReturned;
         break;
      default:
         Debug("Unknown propertyFormat %d while retrieving _NET_WM_PID\n",
               propertyFormat);
         break;
      }

      if (windowPid) {
         retval = UnityPlatformReadProcessPath(up, upw, windowPid, windowUri,
                                               execUri);
      }
   }
   XFree(valueReturned);

   if (!retval && XGetCommand(up->display, checkWindow, &argv, &argc)) {
      retval = UnityPlatformArgvToWindowPaths(up, upw, argv, argc, NULL,
                                              windowUri, execUri);
      XFreeStringList(argv);
   }

   if (!retval && XGetClassHint(up->display, checkWindow, &classHint)) {
      /*
       * Try finding the WM_CLASS on $PATH.
       */

      char *fakeArgv[2] = {NULL, NULL};

      if (classHint.res_name && *classHint.res_name) {
         fakeArgv[0] = classHint.res_name;
      } else if (classHint.res_class && *classHint.res_class) {
         fakeArgv[0] = classHint.res_class;
      }

      if (fakeArgv[0] && *(fakeArgv[0])) {
         retval = UnityPlatformArgvToWindowPaths(up, upw, fakeArgv, 1, NULL,
                                                 windowUri, execUri);
      }

      XFree(classHint.res_name);
      XFree(classHint.res_class);
   }

   if (!retval && !triedLeader) {
      /*
       * Last ditch - look for a client leader window and try all of the above
       * again.
       */
      checkWindow = UPWindowLookupClientLeader(up, upw);
      if (checkWindow != None) {
         triedLeader = TRUE;
         goto tryLeader;
      }
   }

   Debug("UnityX11GetWindowPath(%#lx) returning %s\n", upw->toplevelWindow,
         retval ? "TRUE" : "FALSE");

   return retval;
}


/*
 *----------------------------------------------------------------------------
 *
 * UnityPlatformGetWindowPath --
 *
 *      Get the information needed to re-launch a window and retrieve further
 *      information on it.
 *
 *      windowPathUtf8 uniquely identifies an X11 window (windowUri),
 *      execPathUtf8 uniquely identifies the window's owning
 *      executable (execUri).
 *
 *      windowUri is handy for getting icons and other data associated with a
 *      specific window, whereas execUri is handy for uniquely identifying
 *      applications for GHI.  (The host uses our returned strings to uniquely
 *      identify applications, and we don't want it to consider the window ID
 *      for that purpose, as it causes the host to believe that two windows
 *      from the same application are really associated with separate
 *      applications.)
 *
 * Results:
 *      TRUE if everything went ok, FALSE otherwise.
 *
 * Side effects:
 *      Original buffer contents are overwritten.
 *
 *----------------------------------------------------------------------------
 */

Bool
UnityPlatformGetWindowPath(UnityPlatform *up,        // IN: Platform data
                           UnityWindowId window,     // IN: window handle
                           DynBuf *windowPathUtf8,   // IN/OUT: full path to the window
                           DynBuf *execPathUtf8)     // IN/OUT: full path to the binary
{
   UnityPlatformWindow *upw;
   Bool retval = FALSE;
   gchar *windowUri;
   gchar *execUri;

   ASSERT(up);

   upw = UPWindow_Lookup(up, window);

   if (!upw) {
      Debug("GetWindowPath FAILED!\n");
      return FALSE;
   }

   retval = UnityX11GetWindowPaths(up, upw, &windowUri, &execUri);

   if (!retval) {
      Debug("GetWindowPath didn't know how to identify the window...\n");
   } else {
      Debug("GetWindowPath window %#x results in: \n"
            "   windowUri = %s\n"
            "   execUri = %s\n",
            window, windowUri, execUri);

      DynBuf_SetSize(windowPathUtf8, 0);
      DynBuf_SetSize(execPathUtf8, 0);
      DynBuf_AppendString(windowPathUtf8, windowUri);
      DynBuf_AppendString(execPathUtf8, execUri);

      g_free(windowUri);
      g_free(execUri);
      retval = TRUE;
   }

   return retval;
}


/*
 *------------------------------------------------------------------------------
 *
 * UnityPlatformGetWindowContents --
 *
 *     Read the correct bits off the window regardless of whether it's minimized
 *     or obscured. Return the result as a PNG in the imageData DynBuf.
 *
 * Results:
 *     Returns TRUE in case success and FALSE otherwise.
 *
 * Side effects:
 *     None.
 *
 *------------------------------------------------------------------------------
 */

Bool
UnityPlatformGetWindowContents(UnityPlatform *up,     // IN
                               UnityWindowId window,  // IN
                               DynBuf *imageData,     // IN
                               uint32 *width,         // OUT
                               uint32 *height)        // OUT
{
   UnityPlatformWindow *upw;
   Pixmap pixmap = 0;
   XWindowAttributes attrs;
   XImage *ximage = NULL;
   GC xgc = 0;
   XGCValues gcvalues;
   Bool result = FALSE;
   ImageInfo vmimage = { 0 };

   ASSERT(up);
   ASSERT(imageData);
   ASSERT(width);
   ASSERT(height);

   upw = UPWindow_Lookup(up, window);

   if (!upw) {
      return FALSE;
   }

   UnityPlatformResetErrorCount(up);
   if (!XGetWindowAttributes(up->display, upw->toplevelWindow, &attrs)
       || UnityPlatformGetErrorCount(up)) {
      return FALSE;
   }
   pixmap = XCreatePixmap(up->display, upw->toplevelWindow,
                          attrs.width, attrs.height, attrs.depth);
   if (UnityPlatformGetErrorCount(up)) {
      return FALSE;
   }

   gcvalues.background = gcvalues.foreground = 0;
   gcvalues.subwindow_mode = IncludeInferiors;
   gcvalues.fill_style = FillSolid;
   XFillRectangle(up->display, pixmap, xgc, 0, 0, attrs.width, attrs.height);
   xgc = XCreateGC(up->display, pixmap,
                   GCFillStyle |
                   GCBackground |
                   GCForeground |
                   GCSubwindowMode,
                   &gcvalues);
   if (UnityPlatformGetErrorCount(up)) {
      goto out;
   }

   XCopyArea(up->display, upw->toplevelWindow, pixmap, xgc, 0, 0,
             attrs.width, attrs.height, 0, 0);
   if (UnityPlatformGetErrorCount(up)) {
      goto out;
   }

   ximage = XGetImage(up->display, pixmap, 0, 0,
                      attrs.width, attrs.height, ~0, XYPixmap);

   if (!ximage || UnityPlatformGetErrorCount(up)) {
      goto out;
   }

   vmimage.width = ximage->width;
   vmimage.height = ximage->height;
   vmimage.depth = ximage->depth;
   vmimage.bpp = ximage->bitmap_unit;
   vmimage.redMask = ximage->red_mask;
   vmimage.greenMask = ximage->green_mask;
   vmimage.blueMask = ximage->blue_mask;
   vmimage.bytesPerLine = ximage->bytes_per_line;
   vmimage.data = ximage->data;

   if (ImageUtil_ConstructPNGBuffer(&vmimage, NULL, imageData)) {
      result = TRUE;
   }

   if (result) {
      *width = vmimage.width;
      *height = vmimage.height;
   }

  out:
   if (ximage) {
      XDestroyImage(ximage);
   }

   if (xgc) {
      XFreeGC(up->display, xgc);
   }

   if (pixmap) {
      XFreePixmap(up->display, pixmap);
   }

   return result;
}


/*
 *------------------------------------------------------------------------------
 *
 * UnityPlatformGetIconData --
 *
 *     Read part or all of a particular icon on a window.  Return the result as a PNG in
 *     the imageData DynBuf, and also return the full length of the PNG in fullLength.
 *
 * Results:
 *     Returns TRUE if successful, and FALSE otherwise.
 *
 * Side effects:
 *     None.
 *
 *------------------------------------------------------------------------------
 */

Bool
UnityPlatformGetIconData(UnityPlatform *up,       // IN
                         UnityWindowId window,    // IN
                         UnityIconType iconType,  // IN
                         UnityIconSize iconSize,  // IN
                         uint32 dataOffset,       // IN
                         uint32 dataLength,       // IN
                         DynBuf *imageData,       // OUT
                         uint32 *fullLength)      // OUT
{
   UnityPlatformWindow *upw;

   ASSERT(up);
   ASSERT(fullLength);
   ASSERT(imageData);

   upw = UPWindow_Lookup(up, window);

   if (!upw || !upw->clientWindow || iconType != UNITY_ICON_TYPE_MAIN) {
      return FALSE;
   }

   Debug("GetIconData %#lx\n", (Window)window);

   if (!DynBuf_GetSize(&upw->iconPng.data)
       || (upw->iconPng.size != iconSize)
       || (upw->iconPng.type != iconType)) {
      GPtrArray *pixbufs;
      Bool gotIcons = FALSE;

      pixbufs = AppUtil_CollectIconArray(NULL, upw->clientWindow);

      if (pixbufs && pixbufs->len) {
         GdkPixbuf *pixbuf;
         gchar *pngData;
         gsize pngDataSize;

         pixbuf = g_ptr_array_index(pixbufs, 0);

         if (gdk_pixbuf_save_to_buffer(pixbuf, &pngData, &pngDataSize,
                                       "png", NULL, NULL)) {
            DynBuf_Attach(&upw->iconPng.data, pngDataSize, pngData);
            gotIcons = TRUE;
         } else {
            DynBuf_SetSize(&upw->iconPng.data, 0);
         }

         upw->iconPng.size = iconSize;
         upw->iconPng.type = iconType;
      }

      AppUtil_FreeIconArray(pixbufs);

      if (!gotIcons) {
         return FALSE;
      }
   }

   *fullLength = DynBuf_GetSize(&upw->iconPng.data);
   if (dataOffset >= *fullLength) {
      DynBuf_SetSize(imageData, 0);
   } else {
      uint32 realLength;

      if ((dataOffset + dataLength) > *fullLength) {
         realLength = *fullLength - dataOffset;
      } else {
         realLength = dataLength;
      }
      DynBuf_Enlarge(imageData, realLength);
      DynBuf_SetSize(imageData, realLength);

      memcpy(imageData->data,
             ((const char *)DynBuf_Get(&upw->iconPng.data)) + dataOffset,
             realLength);
   }

   return TRUE;
}


/*
 *----------------------------------------------------------------------------
 *
 * UnityPlatformUnminimizeWindow --
 *
 *      Tell the window to restore from the minimized state to its original
 *      size.
 *
 * Results:
 *      TRUE always
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */

Bool
UnityPlatformUnminimizeWindow(UnityPlatform *up,    // IN
                              UnityWindowId window) // IN
{
   UnityPlatformWindow *upw;

   ASSERT(up);

   upw = UPWindow_Lookup(up, window);

   if (!upw || !upw->clientWindow) {
      Debug("Restoring FAILED!\n");
      return FALSE;
   }

   Debug("%s(%#lx)\n", __func__, upw->toplevelWindow);
   if (upw->isMinimized) {
      Atom data[5] = {0, 0, 0, 0, 0};

      Debug("Restoring window %#x\n", window);

      upw->isMinimized = FALSE;
      upw->wantInputFocus = TRUE;

      /*
       * Okay, client messages to update _NET_WM_STATE are intended only for
       * /mapped/ windows.  (That's my interpretation considering that wm-spec
       * only mentions mapped windows, and window managers seem to ignore the
       * request for minimized windows.)
       *
       * Rather than directly mapping the window, we'll instead request that
       * the window manager activate it.  Mapping the window has a negative
       * consequence of stripping the window of its _NET_WM_STATE and
       * _NET_WM_DESKTOP properties.  This is most visible when unminimizing
       * a sticky window -- the result is that it would lose its stickiness.
       */

      data[0] = 2;
      data[1] = UnityPlatformGetServerTime(up);
      data[2] = 0;
      UnityPlatformSendClientMessage(up, upw->rootWindow, upw->clientWindow,
                                     up->atoms._NET_ACTIVE_WINDOW, 32, 4, data);

      data[0] = _NET_WM_STATE_REMOVE;
      data[1] = up->atoms._NET_WM_STATE_HIDDEN;
      data[2] = up->atoms._NET_WM_STATE_MINIMIZED;
      data[3] = 2; // Message is from the pager/taskbar
      UnityPlatformSendClientMessage(up, upw->rootWindow, upw->clientWindow,
                                     up->atoms._NET_WM_STATE, 32, 4, data);
   } else {
      Debug("Window %#x is already restored\n", window);
   }

   return TRUE;
}


/*
 *-----------------------------------------------------------------------------
 *
 * UPWindowProcessPropertyEvent --
 *
 *      Processes an notification that a property has changed on an X11 window.
 *
 *      N.B. The UPWindowPushFullUpdate method creates a fake 'xevent' based on all the
 *      properties are set initially on a window, so before passing 'xevent' down the
 *      call chain, or using any additional fields from it, make sure that
 *      UPWindowPushFullUpdate fills in those fields properly.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

static void
UPWindowProcessPropertyEvent(UnityPlatform *up,        // IN
                             UnityPlatformWindow *upw, // IN
                             const XEvent *xevent)     // IN
{
   Atom eventAtom;

   ASSERT(up);
   ASSERT(upw);
   ASSERT(xevent);

   eventAtom = xevent->xproperty.atom;
   if (eventAtom == up->atoms._NET_WM_STATE ||
       eventAtom == up->atoms.WM_STATE) {
      UPWindowUpdateState(up, upw, &xevent->xproperty);
      if (eventAtom == up->atoms.WM_STATE) {
         UPWindowUpdateIcon(up, upw);
      }
   } else if (eventAtom == up->atoms.WM_NAME) {
      UPWindowUpdateTitle(up, upw);
   } else if (eventAtom == up->atoms.WM_PROTOCOLS) {
      UPWindowUpdateProtocols(up, upw);
   } else if (eventAtom == up->atoms._NET_WM_ALLOWED_ACTIONS) {
      UPWindowUpdateActions(up, upw);
   } else if (eventAtom == up->atoms._NET_WM_WINDOW_TYPE) {
      UPWindowUpdateType(up, upw);
   } else if (eventAtom == up->atoms._NET_WM_ICON
              || eventAtom == up->atoms.WM_ICON) {
      UPWindowUpdateIcon(up, upw);
   } else if (eventAtom == up->atoms._NET_WM_DESKTOP) {
      UPWindowUpdateDesktop(up, upw);
   } else if (eventAtom == up->atoms._NET_FRAME_EXTENTS) {
      UPWindowUpdateFrameExtents(up, upw);
   }
}


/*
 *-----------------------------------------------------------------------------
 *
 * UPWindowProcessConfigureEvent --
 *
 *      Processes an notification that the window configuration has changed.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

static void
UPWindowProcessConfigureEvent(UnityPlatform *up,        // IN
                              UnityPlatformWindow *upw, // IN
                              const XEvent *xevent)     // IN
{
   if (xevent->xconfigure.window == upw->toplevelWindow) {
      const int border_width = xevent->xconfigure.border_width;
      int x = xevent->xconfigure.x;
      int y = xevent->xconfigure.y;
      int xprime;
      int yprime;

      xprime = x + xevent->xconfigure.width + border_width;
      yprime = y + xevent->xconfigure.height + border_width;
      x -= border_width;
      y -= border_width;

#ifdef VMX86_DEVEL
      Debug("Moving window %#lx/%#lx to (%d, %d) +(%d, %d)\n",
            upw->toplevelWindow, upw->clientWindow,
            x, y, xprime - x, yprime - y);
#endif

      /*
       * If these are the same, then the window hasn't been reparented by
       * the window manager, and its window decorations are accounted for
       * by the values of the _NET_FRAME_EXTENTS property.
       */
      if (upw->toplevelWindow == upw->clientWindow) {
         x -= upw->frameExtents[0];             // left
         y -= upw->frameExtents[2];             // top
         xprime += upw->frameExtents[1];        // right
         yprime += upw->frameExtents[3];        // bottom
      }

      UnityWindowTracker_MoveWindow(up->tracker, upw->toplevelWindow,
                                    x, y, xprime, yprime);

      if ((xevent->xconfigure.above != None && !upw->lowerWindow)
	  || (xevent->xconfigure.above == None && upw->lowerWindow)
	  || (upw->lowerWindow && xevent->xconfigure.above
              != upw->lowerWindow->toplevelWindow)) {
         Debug("Marking window %#lx/%#lx for restacking\n",
               upw->toplevelWindow, upw->clientWindow);
         UPWindow_Restack(up, upw, xevent->xconfigure.above);
      }
   } else {
      Debug("ProcessConfigureEvent skipped event on window %#lx (upw was %#lx/%#lx)\n",
            xevent->xconfigure.window, upw->toplevelWindow, upw->clientWindow);
   }

#ifdef VMX86_DEVEL
   CompareStackingOrder(up, upw->rootWindow, __func__);
#endif
}


#if defined(VM_HAVE_X11_SHAPE_EXT)


/*
 *-----------------------------------------------------------------------------
 *
 * UPWindowUpdateShape --
 *
 *      Updates the window shape.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Notification to the window tracker
 *
 *-----------------------------------------------------------------------------
 */

static void
UPWindowUpdateShape(UnityPlatform *up,        // IN
                    UnityPlatformWindow *upw) // IN
{
   RegionPtr clipRegion = NULL;
   RegionPtr boundingRegion = NULL;
   RegionPtr region = NULL;
   XRectangle *rects = NULL;
   int rectCount;
   int rectOrdering;

   /*
    * Retrieve the X11 'clipping shape' (the window shape including its border) and turn
    * it into a region.
    */
   UnityPlatformResetErrorCount(up);
   rects = XShapeGetRectangles(up->display, upw->toplevelWindow, ShapeClip,
                               &rectCount, &rectOrdering);
   if (!UnityPlatformGetErrorCount(up) && rects && rectCount) {
      xRectangle *vmRects;
      int i;

      vmRects = alloca(rectCount * (sizeof *vmRects));
      memset(vmRects, 0, rectCount * (sizeof *vmRects));
      for (i = 0; i < rectCount; i++) {
         ASSERT(rects[i].width);
         ASSERT(rects[i].height);
         vmRects[i].x = rects[i].x;
         vmRects[i].y = rects[i].y;
         vmRects[i].width = rects[i].width;
         vmRects[i].height = rects[i].height;
         vmRects[i].info.type = UpdateRect;
      }

      clipRegion = miRectsToRegion(rectCount, vmRects, 0);
   }
   XFree(rects); rects = NULL;
   rectCount = 0;

   /*
    * The X Shape Extension operates on unshaped windows by using default bounding
    * and clipping regions.  I.e., XShapeGetRectangles will return a single rectangle
    * for an unshaped window.  Without the following test, we'd end up informing the
    * Unity client that this window can be described by a single rectangle region,
    * and it'd expect further region updates when the window's geometry changes.
    *
    * This wouldn't be a problem, except we don't receive XShapeEvents on these
    * windows when they're resized.  To work around this, we make sure that the UWT
    * knows that unshaped windows are exactly that.
    */
   {
      int bShaped;
      int cShaped;
      int dummy;

      XShapeQueryExtents(up->display, upw->toplevelWindow,
                         &bShaped, &dummy, &dummy, &dummy, &dummy,
                         &cShaped, &dummy, &dummy, &dummy, &dummy);
      if (!bShaped && !cShaped) {
         UnityWindowTracker_ChangeWindowRegion(up->tracker, upw->toplevelWindow, 0);
         return;
      }
   }

   UnityPlatformResetErrorCount(up);

   /*
    * Retrieve the X11 'clipping shape' (the window shape of the window without its
    * border) and turn it into a region.
    */
   rects = XShapeGetRectangles(up->display, upw->toplevelWindow, ShapeBounding,
                               &rectCount, &rectOrdering);
   if (!UnityPlatformGetErrorCount(up)
       && rects && rectCount) {
      xRectangle *vmRects;
      int i;

      vmRects = alloca(rectCount * (sizeof *vmRects));
      memset(vmRects, 0, rectCount * (sizeof *vmRects));
      for (i = 0; i < rectCount; i++) {
         ASSERT(rects[i].width);
         ASSERT(rects[i].height);
         vmRects[i].x = rects[i].x;
         vmRects[i].y = rects[i].y;
         vmRects[i].width = rects[i].width;
         vmRects[i].height = rects[i].height;
         vmRects[i].info.type = UpdateRect;
      }

      boundingRegion = miRectsToRegion(rectCount, vmRects, 0);
   }
   XFree(rects);

   if (boundingRegion && clipRegion) {
      region = miRegionCreate(NULL, 2);
      miIntersect(region, clipRegion, boundingRegion);
   } else if (clipRegion) {
      region = clipRegion; clipRegion = NULL;
   } else if (boundingRegion) {
      region = boundingRegion; boundingRegion = NULL;
   }

   UnityWindowTracker_ChangeWindowRegion(up->tracker, upw->toplevelWindow, region);
   if (clipRegion) {
      miRegionDestroy(clipRegion);
   }
   if (boundingRegion) {
      miRegionDestroy(boundingRegion);
   }
   if (region) {
      miRegionDestroy(region);
   }
}


/*
 *-----------------------------------------------------------------------------
 *
 * UPWindowProcessShapeEvent --
 *
 *      Processes an notification that the non-rectangular window shape has changed.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

static void
UPWindowProcessShapeEvent(UnityPlatform *up,        // IN
                          UnityPlatformWindow *upw, // IN
                          const XEvent *xevent)     // IN
{
   XShapeEvent *sev;

   ASSERT(up);
   ASSERT(upw);
   ASSERT(xevent->type == (up->shapeEventBase + ShapeNotify));

   sev = (XShapeEvent *)xevent;
   ASSERT (sev->window == upw->toplevelWindow ||
           sev->window == upw->clientWindow);

   if (sev->shaped) {
      UPWindowUpdateShape(up, upw);
   } else {
      UnityWindowTracker_ChangeWindowRegion(up->tracker, upw->toplevelWindow, NULL);
   }
}
#endif


/*
 *-----------------------------------------------------------------------------
 *
 * UnityPlatformWindowProcessEvent --
 *
 *      Handle an event on a typical window.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Many.
 *
 *-----------------------------------------------------------------------------
 */

void
UPWindow_ProcessEvent(UnityPlatform *up,        // IN
                      UnityPlatformWindow *upw, // IN
                      Window realEventWindow,   // IN
                      const XEvent *xevent)     // IN
{
   Bool eventHandled = TRUE;

   ASSERT(up);
   ASSERT(upw);
   ASSERT(xevent);

   UPWindow_CheckRelevance(up, upw, xevent);

   switch (xevent->type) {
   case KeyPress:
   case KeyRelease:
   case ButtonPress:
   case ButtonRelease:
   case MotionNotify:
   case EnterNotify:
   case LeaveNotify:
   case KeymapNotify:
   case Expose:
   case GraphicsExpose:
   case NoExpose:
   case MapRequest:
   case ResizeRequest:
   case CirculateRequest:
   case SelectionClear:
   case SelectionRequest:
   case SelectionNotify:
   case ColormapNotify:
   case ClientMessage:
   case GravityNotify:
   case VisibilityNotify:
   case MappingNotify:
   case ReparentNotify:
   case ConfigureRequest:
      break; // No extra processing on these for now

   case CreateNotify:
      /* Do nothing. The UPWindow has already been created. */
      break;

   case FocusIn:
      if (upw->isRelevant) {
         UnityWindowInfo *info;
         info = UnityWindowTracker_LookupWindow(up->tracker, upw->toplevelWindow);

         UnityWindowTracker_ChangeWindowState(up->tracker,
                                              upw->toplevelWindow,
                                              info->state | UNITY_WINDOW_STATE_IN_FOCUS);
      }
      break;

   case FocusOut:
      if (upw->isRelevant) {
         UnityWindowInfo *info;
         info = UnityWindowTracker_LookupWindow(up->tracker, upw->toplevelWindow);

         UnityWindowTracker_ChangeWindowState(up->tracker,
                                              upw->toplevelWindow,
                                              (info->state
                                               & ~UNITY_WINDOW_STATE_IN_FOCUS));
      }
      break;

   case DestroyNotify:
      Debug("Destroying window (%p) %#lx/%#lx\n",
            upw, upw->toplevelWindow, upw->clientWindow);

      /*
       * Release the UnityPlatform object's reference to this UnityPlatformWindow,
       */
      upw->windowType = UNITY_WINDOW_TYPE_NONE;
      upw->deleteWhenSafe = TRUE;
#ifdef VMX86_DEVEL
   CompareStackingOrder(up, upw->rootWindow, __func__);
#endif
      break;

   case UnmapNotify:
      upw->wantInputFocus = FALSE;
      upw->isViewable = FALSE;
      break;

   case MapNotify:
      /*
       * This is here because we want to set input focus as part of UnminimizeWindow, but
       * can't call XSetInputFocus until the window has actually been shown.
       */
      if (upw->wantInputFocus && upw->clientWindow) {
         XSetInputFocus(up->display, upw->clientWindow, RevertToParent,
                        UnityPlatformGetServerTime(up));
         upw->wantInputFocus = FALSE;
      }

      upw->isViewable = TRUE;
      break;

   case CirculateNotify:
      if (upw->isRelevant) {
         UPWindow_Restack(up, upw,
                          (up->topWindow && xevent->xcirculate.place == PlaceOnTop)
                          ? up->topWindow->toplevelWindow : None);
      }
      break;

   case PropertyNotify:
      UPWindowProcessPropertyEvent(up, upw, xevent);
      break;

   case ConfigureNotify:
      UPWindowProcessConfigureEvent(up, upw, xevent);
      break;

   default:
      eventHandled = FALSE; // Unknown "regular" event
      break;
   }

   if (!eventHandled) { // Handle extension events here
#if defined(VM_HAVE_X11_SHAPE_EXT)
      if (up->shapeEventBase &&
          xevent->type == (up->shapeEventBase + ShapeNotify)) {
         UPWindowProcessShapeEvent(up, upw, xevent);
         eventHandled = TRUE;
      }
#endif

      ASSERT(eventHandled);
   }
}


/*
 *-----------------------------------------------------------------------------
 *
 * UPWindowUpdateTitle --
 *
 *      Tells the window tracker about the window's latest title
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Notification to the window tracker
 *
 *-----------------------------------------------------------------------------
 */

static void
UPWindowUpdateTitle(UnityPlatform *up,        // IN
                    UnityPlatformWindow *upw) // IN
{
   Atom propertyType;
   int propertyFormat;
   unsigned long itemsReturned;
   unsigned long bytesRemaining;
   unsigned char *valueReturned = NULL;
   DynBuf titleBuf;

   if (!upw->clientWindow) {
      return;
   }

   if (XGetWindowProperty(up->display, upw->clientWindow, up->atoms.WM_NAME, 0,
                          1024, False, AnyPropertyType,
                          &propertyType, &propertyFormat, &itemsReturned,
                          &bytesRemaining, &valueReturned)
       != Success) {
      /*
       * Some random error occurred - perhaps the window disappeared
       */
      return;
   }

   if (propertyType != XA_STRING || propertyFormat != 8) {
      return;
   }

   DynBuf_Init(&titleBuf);
   DynBuf_Append(&titleBuf, valueReturned, itemsReturned);
   if (!itemsReturned || valueReturned[itemsReturned-1] != '\0') {
      DynBuf_AppendString(&titleBuf, "");
   }
   XFree(valueReturned);
   Debug("Set title of window %#lx to %s\n",
         upw->clientWindow, (char *)DynBuf_Get(&titleBuf));
   UnityWindowTracker_SetWindowTitle(up->tracker, (UnityWindowId) upw->toplevelWindow,
                                     &titleBuf);
   DynBuf_Destroy(&titleBuf);
}


/*
 *-----------------------------------------------------------------------------
 *
 * UPWindowUpdateType --
 *
 *      Tells the window tracker about the window's latest type
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Notification to the window tracker
 *
 *-----------------------------------------------------------------------------
 */

static void
UPWindowUpdateType(UnityPlatform *up,        // IN
                   UnityPlatformWindow *upw) // IN
{
   ASSERT(up);
   ASSERT(upw);

   /*
    * upw->windowType was previously updated by the CheckRelevance method.
    */
   UnityWindowTracker_ChangeWindowType(up->tracker,
                                       upw->toplevelWindow,
                                       upw->windowType);
}


/*
 *-----------------------------------------------------------------------------
 *
 * UPWindowUpdateProtocols --
 *
 *      Updates the list of protocols supported by the window.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Notification to the window tracker
 *
 *-----------------------------------------------------------------------------
 */

static void
UPWindowUpdateProtocols(UnityPlatform *up,        // IN
                        UnityPlatformWindow *upw) // IN
{
   Atom propertyType;
   int propertyFormat;
   unsigned long itemsReturned;
   unsigned long bytesRemaining;
   Atom *valueReturned = NULL;
   int i;

   if (!upw->clientWindow) {
      return;
   }

   if (XGetWindowProperty(up->display, upw->clientWindow, up->atoms.WM_STATE, 0,
                          1024, False, AnyPropertyType,
                          &propertyType, &propertyFormat, &itemsReturned,
                          &bytesRemaining, (unsigned char **) &valueReturned)
       != Success) {
      /*
       * Some random error occurred - perhaps the window disappeared.
       */
      return;
   }

   if (propertyType != up->atoms.WM_STATE
       || propertyFormat != 32) {
      itemsReturned = 0;
   }

   memset(upw->windowProtocols, 0, sizeof upw->windowProtocols);
   for (i = 0; i < itemsReturned; i++) {
      UnityX11WinProtocol proto;

      if (valueReturned[i] == up->atoms.WM_DELETE_WINDOW) {
         proto = UNITY_X11_WIN_WM_DELETE_WINDOW;
      } else {
         continue;
      }

      upw->windowProtocols[proto] = TRUE;
   }
   XFree(valueReturned);
}


/*
 *-----------------------------------------------------------------------------
 *
 * UPWindowUpdateActions --
 *
 *      Updates the window attributes based on a new _NET_WM_ALLOWED_ACTIONS attribute.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Notification to the window tracker
 *
 *-----------------------------------------------------------------------------
 */

static void
UPWindowUpdateActions(UnityPlatform *up,        // IN
                      UnityPlatformWindow *upw) // IN
{
   Atom propertyType;
   int propertyFormat;
   unsigned long itemsReturned = 0;
   unsigned long bytesRemaining;
   Atom *valueReturned = NULL;
   int i;
   Bool curAttrValues[UNITY_MAX_ATTRIBUTES];
   Bool attrsAreSet[UNITY_MAX_ATTRIBUTES];
   Bool haveHorizMax;
   Bool haveVertMax;

   if (!upw->clientWindow) {
      return;
   }

   memset(curAttrValues, 0, sizeof curAttrValues);
   memset(attrsAreSet, 0, sizeof attrsAreSet);
   haveHorizMax = haveVertMax = FALSE;

   /*
    * List of attributes that we know how to process from the ALLOWED_ACTIONS list. If we
    * don't find these in the ALLOWED_ACTIONS list, and they are supported by the window
    * manager, then we report that they're FALSE (set by the first memset above).
    */
   attrsAreSet[UNITY_WINDOW_ATTR_MINIMIZABLE] =
      UnityPlatformWMProtocolSupported(up, UNITY_X11_WM__NET_WM_ACTION_MINIMIZE);
   attrsAreSet[UNITY_WINDOW_ATTR_MAXIMIZABLE] =
      UnityPlatformWMProtocolSupported(up, UNITY_X11_WM__NET_WM_ACTION_MAXIMIZE_HORZ) &&
      UnityPlatformWMProtocolSupported(up, UNITY_X11_WM__NET_WM_ACTION_MAXIMIZE_VERT);
   attrsAreSet[UNITY_WINDOW_ATTR_CLOSABLE] =
      UnityPlatformWMProtocolSupported(up, UNITY_X11_WM__NET_WM_ACTION_CLOSE);
   attrsAreSet[UNITY_WINDOW_ATTR_FULLSCREENABLE] =
      UnityPlatformWMProtocolSupported(up, UNITY_X11_WM__NET_WM_ACTION_FULLSCREEN);
   attrsAreSet[UNITY_WINDOW_ATTR_SHADEABLE] =
      UnityPlatformWMProtocolSupported(up, UNITY_X11_WM__NET_WM_ACTION_SHADE);
   attrsAreSet[UNITY_WINDOW_ATTR_STICKABLE] =
      UnityPlatformWMProtocolSupported(up, UNITY_X11_WM__NET_WM_ACTION_STICK);

   if (XGetWindowProperty(up->display, upw->clientWindow,
                          up->atoms._NET_WM_ALLOWED_ACTIONS, 0,
                          1024, False, XA_ATOM,
                          &propertyType, &propertyFormat, &itemsReturned,
                          &bytesRemaining, (unsigned char **) &valueReturned)
       == Success
      && propertyFormat == 32) {
      for (i = 0; i < itemsReturned; i++) {
         UnityWindowAttribute attr;
         Bool attrValue = TRUE;

         if (valueReturned[i] == up->atoms._NET_WM_ACTION_MINIMIZE) {
            attr = UNITY_WINDOW_ATTR_MINIMIZABLE;
         } else if (valueReturned[i] == up->atoms._NET_WM_ACTION_MAXIMIZE_HORZ) {
            haveHorizMax = TRUE;
            continue;
         } else if (valueReturned[i] == up->atoms._NET_WM_ACTION_MAXIMIZE_VERT) {
            haveVertMax = TRUE;
            continue;
         } else if (valueReturned[i] == up->atoms._NET_WM_ACTION_CLOSE) {
            attr = UNITY_WINDOW_ATTR_CLOSABLE;
         } else if (valueReturned[i] == up->atoms._NET_WM_ACTION_FULLSCREEN) {
            attr = UNITY_WINDOW_ATTR_FULLSCREENABLE;
         } else if (valueReturned[i] == up->atoms._NET_WM_ACTION_SHADE) {
            attr = UNITY_WINDOW_ATTR_SHADEABLE;
         } else if (valueReturned[i] == up->atoms._NET_WM_ACTION_STICK) {
            attr = UNITY_WINDOW_ATTR_STICKABLE;
         } else {
            continue;
         }

         curAttrValues[attr] = attrValue;
         attrsAreSet[attr] = TRUE;
      }
      XFree(valueReturned);
   } else {
      curAttrValues[UNITY_WINDOW_ATTR_MINIMIZABLE] = TRUE;
      attrsAreSet[UNITY_WINDOW_ATTR_MINIMIZABLE] = TRUE;
   }

   curAttrValues[UNITY_WINDOW_ATTR_MAXIMIZABLE] = (haveHorizMax && haveVertMax);
   attrsAreSet[UNITY_WINDOW_ATTR_MAXIMIZABLE] = TRUE;

   for (i = 0; i < UNITY_MAX_ATTRIBUTES; i++) {
      if (attrsAreSet[i]) {
         UnityWindowTracker_ChangeWindowAttribute(up->tracker, upw->toplevelWindow,
                                                  i, curAttrValues[i]);
      }
   }
}


/*
 *-----------------------------------------------------------------------------
 *
 * UPWindowGetDesktop --
 *
 *      Retrieve's the current X11 virtual desktop of a window.
 *
 * Results:
 *      Virtual desktop number
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

static Bool
UPWindowGetDesktop(UnityPlatform *up,        // IN
                   UnityPlatformWindow *upw, // IN
                   int *guestDesktop)        // IN/OUT
{
   Atom propertyType;
   int propertyFormat;
   unsigned long itemsReturned = 0;
   unsigned long bytesRemaining;
   Atom *valueReturned = NULL;
   Bool retval = FALSE;

   if (!upw->clientWindow) {
      return FALSE;
   }

   if (XGetWindowProperty(up->display, upw->clientWindow,
                          up->atoms._NET_WM_DESKTOP, 0,
                          1024, False, AnyPropertyType,
                          &propertyType, &propertyFormat, &itemsReturned,
                          &bytesRemaining, (unsigned char **) &valueReturned)
       == Success
       && propertyType == XA_CARDINAL
       && propertyFormat == 32
       && itemsReturned) {

      *guestDesktop = *valueReturned;
      retval = TRUE;
   }

   XFree(valueReturned);

   return retval;
}


/*
 *-----------------------------------------------------------------------------
 *
 * UPWindowUpdateDesktop --
 *
 *      Updates the window's virtual desktop based on a new _NET_WM_DESKTOP attribute.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Notification to the window tracker.
 *
 *-----------------------------------------------------------------------------
 */

static void
UPWindowUpdateDesktop(UnityPlatform *up,        // IN
                      UnityPlatformWindow *upw) // IN
{
   int guestDesktop = -1;

   if (!upw->clientWindow) {
      return;
   }

   if (!UPWindowGetDesktop(up, upw, &guestDesktop)) {
      Debug("Window %#lx has a clientWindow, but its "
            "virtual desktop could not be retrieved\n",
            upw->clientWindow);
      return;
   }

   if (guestDesktop < ((int)up->desktopInfo.numDesktops)) {
      UnityDesktopId desktopId = -1;
      Bool isSticky;

      isSticky = (guestDesktop < 0);
      if (!isSticky) {
         desktopId = up->desktopInfo.guestDesktopToUnity[guestDesktop];
      }

      Debug("Window %#lx is now on desktop %d\n", upw->toplevelWindow, desktopId);
      UnityWindowTracker_ChangeWindowDesktop(up->tracker,
                                             upw->toplevelWindow,
                                             desktopId);

      UnityWindowTracker_ChangeWindowAttribute(up->tracker,
                                               upw->toplevelWindow,
                                               UNITY_WINDOW_ATTR_STICKY,
                                               isSticky);
   } else {
      Debug("Guest's virtual desktop config may not match host's (yet?)"
            " (window is on desktop %d, guest is supposed to have %"FMTSZ"u desktops)\n",
            guestDesktop, up->desktopInfo.numDesktops);
   }
}


/*
 *-----------------------------------------------------------------------------
 *
 * UPWindowUpdateIcon --
 *
 *      Updates the window's virtual desktop based on a new _NET_WM_DESKTOP attribute.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Notification to the window tracker.
 *
 *-----------------------------------------------------------------------------
 */

static void
UPWindowUpdateIcon(UnityPlatform *up,        // IN
                   UnityPlatformWindow *upw) // IN
{
   UnityWindowTracker_NotifyIconChanged(up->tracker, upw->toplevelWindow,
                                        UNITY_ICON_TYPE_MAIN);

   if (DynBuf_GetSize(&upw->iconPng.data)) {
      DynBuf_SetSize(&upw->iconPng.data, 0);
   }
}


/*
 *-----------------------------------------------------------------------------
 *
 * UPWindowIsNowWithdrawn  --
 *
 *      In response to an update to a window's WM_STATE property, properties, test
 *      whether or not the window has been withdrawn.
 *
 * Results:
 *      TRUE if we believe the window was withdrawn, FALSE otherwise.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

static Bool
UPWindowIsNowWithdrawn(UnityPlatform *up,            // IN
                       UnityPlatformWindow *upw,     // IN
                       const XPropertyEvent *xevent) // IN
{
   Window mainWindow;
   Bool isWithdrawn = FALSE;

   Atom actual_type;
   int actual_format;
   unsigned long nitems;
   unsigned long bytes_remaining;
   unsigned char *properties = NULL;

   mainWindow = upw->clientWindow ? upw->clientWindow : upw->toplevelWindow;

   /*
    * Per ICCCM §4.1.3.1, WM_STATE.state will either be set to WithdrawnState
    * or WM_STATE removed from a window when it is withdrawn.
    */
   if (xevent->state == PropertyDelete) {
      return TRUE;
   }

   if (XGetWindowProperty(up->display, mainWindow, up->atoms.WM_STATE,
                      0,                // offset
                      1,                // length (in 32-bit chunks)
                      False,            // delete
                      AnyPropertyType,  // requested property type
                      &actual_type,     // returned type
                      &actual_format,   // returned format
                      &nitems,          // # of items returned
                      &bytes_remaining, // # of bytes remaining
                      &properties) == Success) {
      uint32 *state = (uint32 *)properties;

      if (actual_type == None ||
          (nitems > 0 && *state == WithdrawnState)) {
         isWithdrawn = TRUE;
      }

      XFree(properties);
   }

   return isWithdrawn;
}


/*
 *-----------------------------------------------------------------------------
 *
 * UPWindowUpdateState --
 *
 *      Tells the window tracker about the window's changes to the _NET_WM_STATE and
 *      WM_STATE properties.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Notification to the window tracker
 *
 *-----------------------------------------------------------------------------
 */

static void
UPWindowUpdateState(UnityPlatform *up,            // IN
                    UnityPlatformWindow *upw,     // IN
                    const XPropertyEvent *xevent) // IN
{
   Atom propertyType;
   int propertyFormat;
   unsigned long itemsReturned;
   unsigned long bytesRemaining;
   Atom *valueReturned = NULL;
   int i;
   Bool curAttrValues[UNITY_MAX_ATTRIBUTES];
   Bool attrsAreSet[UNITY_MAX_ATTRIBUTES];
   Bool isMinimized = FALSE;
   Bool haveHorizMax = FALSE;
   Bool haveVertMax = FALSE;
   Bool doSkipTaskbar = FALSE;
   Bool doSkipPager = FALSE;
   Window mainWindow;

   mainWindow = upw->clientWindow ? upw->clientWindow : upw->toplevelWindow;

   /*
    * If a change to WM_STATE indicates this window was withdrawn/unmapped, simply
    * invalidate it from the window tracker and return.
    */
   if (xevent->atom == up->atoms.WM_STATE &&
       UPWindowIsNowWithdrawn(up, upw, xevent)) {
      UPWindowSetRelevance(up, upw, FALSE);
      return;
   }

   memset(curAttrValues, 0, sizeof curAttrValues);
   memset(attrsAreSet, 0, sizeof attrsAreSet);

   curAttrValues[UNITY_WINDOW_ATTR_VISIBLE] = TRUE;
   attrsAreSet[UNITY_WINDOW_ATTR_VISIBLE] =
      attrsAreSet[UNITY_WINDOW_ATTR_MAXIMIZED] =
      attrsAreSet[UNITY_WINDOW_ATTR_STICKY] =
      attrsAreSet[UNITY_WINDOW_ATTR_ALWAYS_ABOVE] =
      attrsAreSet[UNITY_WINDOW_ATTR_ALWAYS_BELOW] =
      attrsAreSet[UNITY_WINDOW_ATTR_MODAL] =
      attrsAreSet[UNITY_WINDOW_ATTR_SHADED] =
      attrsAreSet[UNITY_WINDOW_ATTR_FULLSCREENED] =
      attrsAreSet[UNITY_WINDOW_ATTR_ATTN_WANTED] = TRUE;

   if (!UnityPlatformWMProtocolSupported(up, UNITY_X11_WM__NET_WM_STATE_HIDDEN)) {
      if (XGetWindowProperty(up->display, mainWindow, up->atoms.WM_STATE, 0,
                             1024, False, AnyPropertyType,
                             &propertyType, &propertyFormat, &itemsReturned,
                             &bytesRemaining, (unsigned char **) &valueReturned)
          != Success) {
         /*
          * Some random error occurred - perhaps the window disappeared
          */
         return;
      }

      if (propertyType == up->atoms.WM_STATE
          && propertyFormat == 32
          && itemsReturned
          && valueReturned[0] == IconicState) {
         isMinimized = TRUE;
      }
      XFree(valueReturned);
   }

   if (XGetWindowProperty(up->display, mainWindow, up->atoms._NET_WM_STATE, 0,
                          1024, False, AnyPropertyType,
                          &propertyType, &propertyFormat, &itemsReturned,
                          &bytesRemaining, (unsigned char **) &valueReturned)
       != Success) {
      /*
       * Some random error occurred - perhaps the window disappeared
       */
      return;
   }

   if (propertyType != XA_ATOM
       || propertyFormat != 32) {
      itemsReturned = 0;
   }

   for (i = 0; i < itemsReturned; i++) {
      UnityWindowAttribute attr;
      Bool attrValue = TRUE;

      if (valueReturned[i] == up->atoms._NET_WM_STATE_MINIMIZED
          || valueReturned[i] == up->atoms._NET_WM_STATE_HIDDEN) {
         isMinimized = TRUE;
         continue;
      } else if (valueReturned[i] == up->atoms._NET_WM_STATE_MAXIMIZED_HORZ) {
         haveHorizMax = TRUE;
         continue;
      } else if (valueReturned[i] == up->atoms._NET_WM_STATE_MAXIMIZED_VERT) {
         haveVertMax = TRUE;
         continue;
      } else if (valueReturned[i] == up->atoms._NET_WM_STATE_STICKY) {
         attr = UNITY_WINDOW_ATTR_STICKY;
      } else if (valueReturned[i] == up->atoms._NET_WM_STATE_ABOVE) {
         attr = UNITY_WINDOW_ATTR_ALWAYS_ABOVE;
      } else if (valueReturned[i] == up->atoms._NET_WM_STATE_BELOW) {
         attr = UNITY_WINDOW_ATTR_ALWAYS_BELOW;
      } else if (valueReturned[i] == up->atoms._NET_WM_STATE_MODAL) {
         attr = UNITY_WINDOW_ATTR_MODAL;
      } else if (valueReturned[i] == up->atoms._NET_WM_STATE_SHADED) {
         attr = UNITY_WINDOW_ATTR_SHADED;
      } else if (valueReturned[i] == up->atoms._NET_WM_STATE_FULLSCREEN) {
         attr = UNITY_WINDOW_ATTR_FULLSCREENED;
      } else if (valueReturned[i] == up->atoms._NET_WM_STATE_DEMANDS_ATTENTION) {
         attr = UNITY_WINDOW_ATTR_ATTN_WANTED;
      } else if (valueReturned[i] == up->atoms._NET_WM_STATE_SKIP_TASKBAR) {
         attr = UNITY_WINDOW_ATTR_TOOLWINDOW;
         doSkipTaskbar = TRUE;
      } else if (valueReturned[i] == up->atoms._NET_WM_STATE_SKIP_PAGER) {
         doSkipPager = TRUE;
         continue;
      } else {
         continue;
      }

      curAttrValues[attr] = attrValue;
      attrsAreSet[attr] = TRUE;
   }
   XFree(valueReturned);

   curAttrValues[UNITY_WINDOW_ATTR_MAXIMIZED] = (haveHorizMax && haveVertMax);
   attrsAreSet[UNITY_WINDOW_ATTR_MAXIMIZED] = TRUE;
   curAttrValues[UNITY_WINDOW_ATTR_APPWINDOW] = (!doSkipPager && !doSkipTaskbar)
      && (upw->windowType == UNITY_WINDOW_TYPE_NORMAL);
   attrsAreSet[UNITY_WINDOW_ATTR_APPWINDOW] = TRUE;

   if (upw->isRelevant) {
      UnityWindowInfo *info;
      uint32 newState;
      uint32 cDesk = -1;
      uint32 gDesk;

      info = UnityWindowTracker_LookupWindow(up->tracker, upw->toplevelWindow);
      ASSERT(info);

      newState = info->state;

      /*
       * Only push minimize state for windows on the same desktop (inc. sticky
       * windows).
       */
      if (UPWindowGetDesktop(up, upw, &gDesk)) {
         cDesk = UnityX11GetCurrentDesktop(up);
         if (cDesk == gDesk || gDesk == -1) {
            if (isMinimized) {
               if (! (newState & UNITY_WINDOW_STATE_MINIMIZED)) {
                  Debug("Enabling minimized attribute for window %#lx/%#lx\n",
                        upw->toplevelWindow, upw->clientWindow);
                  newState |= UNITY_WINDOW_STATE_MINIMIZED;
               }
            } else {
               if ((newState & UNITY_WINDOW_STATE_MINIMIZED)) {
                  Debug("Disabling minimized attribute for window %#lx/%#lx\n",
                        upw->toplevelWindow, upw->clientWindow);
                  newState &= ~UNITY_WINDOW_STATE_MINIMIZED;
               }
            }
         }
      } else {
         Debug("%s: Unable to get window desktop\n", __FUNCTION__);
      }

      if (newState != info->state) {
         UnityWindowTracker_ChangeWindowState(up->tracker,
                                              upw->toplevelWindow,
                                              newState);
      }

      upw->isMinimized = isMinimized;
      upw->isMaximized = (haveHorizMax && haveVertMax);

      for (i = 0; i < UNITY_MAX_ATTRIBUTES; i++) {
         if (attrsAreSet[i]) {
            UnityWindowTracker_ChangeWindowAttribute(up->tracker, upw->toplevelWindow,
                                                     i, curAttrValues[i]);
         }
      }
   }
}


/*
 *-----------------------------------------------------------------------------
 *
 * UPWindowPushFullUpdate --
 *
 *      Pushes a full update for the given window.
 *
 * Results:
 *      TRUE if we pushed the updates for this window, FALSE otherwise.
 *
 * Side effects:
 *      UnityWindowTracker contains latest info on this window.
 *
 *-----------------------------------------------------------------------------
 */

static Bool
UPWindowPushFullUpdate(UnityPlatform *up,            // IN
                       UnityPlatformWindow *upw)     // IN
{
   XWindowAttributes winAttr;
   Atom *props;
   int propCount;
   int i;
   int x, y, xprime, yprime;
   int border_width;

   XGetWindowAttributes(up->display, upw->toplevelWindow, &winAttr);
   UPWindowUpdateFrameExtents(up, upw);

   x = winAttr.x;
   y = winAttr.y;
   border_width = winAttr.border_width;

   xprime = x + winAttr.width + border_width;
   yprime = y + winAttr.height + border_width;
   x -= border_width;
   y -= border_width;

   /*
    * If these are the same, then the window hasn't been reparented by
    * the window manager, and its window decorations are accounted for
    * by the values of the _NET_FRAME_EXTENTS property.
    */
   if (upw->toplevelWindow == upw->clientWindow) {
      x -= upw->frameExtents[0];             // left
      y -= upw->frameExtents[2];             // top
      xprime += upw->frameExtents[1];        // right
      yprime += upw->frameExtents[3];        // bottom
   }

   UnityWindowTracker_MoveWindow(up->tracker, upw->toplevelWindow,
                                 x, y, xprime, yprime);

#if defined(VM_HAVE_X11_SHAPE_EXT)
   UPWindowUpdateShape(up, upw);
#endif
   UPWindowUpdateType(up, upw);

   propCount = 0;
   UnityPlatformResetErrorCount(up);
   props = XListProperties(up->display,
                           upw->clientWindow ? upw->clientWindow : upw->toplevelWindow,
                           &propCount);
   if (!UnityPlatformGetErrorCount(up)) {
      for (i = 0; i < propCount; i++) {
         XEvent fakeEvent;

         fakeEvent.xproperty.atom = props[i];
         UPWindowProcessPropertyEvent(up, upw, &fakeEvent);
      }
      XFree(props);
   }

   return TRUE;
}


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

Bool
UPWindow_ProtocolSupported(const UnityPlatform *up,        // IN
                           const UnityPlatformWindow *upw, // IN
                           UnityX11WinProtocol proto)      // IN
{
   ASSERT(up);
   ASSERT(upw);
   ASSERT(proto < UNITY_X11_MAX_WIN_PROTOCOLS);

   return upw->windowProtocols[proto];
}


/*
 *----------------------------------------------------------------------------
 *
 * UnityPlatformShowWindow --
 *
 *      Makes hidden Window visible. If the Window is already visible, it stays
 *      visible. Window reappears at its original location. A minimized window
 *      reappears as minimized.
 *
 * Results:
 *
 *      FALSE if the Window handle is invalid.
 *      TRUE otherwise.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */

Bool
UnityPlatformShowWindow(UnityPlatform *up,    // IN
                        UnityWindowId window) // IN
{
   UnityPlatformWindow *upw;

   ASSERT(up);

   upw = UPWindow_Lookup(up, window);

   if (!upw || !upw->clientWindow) {
      Debug("Hiding FAILED!\n");
      return FALSE;
   }

   if (upw->isHidden) {
      Atom data[5] = {0, 0, 0, 0, 0};

      /*
       * Unfortunately the _NET_WM_STATE messages only work for windows that are already
       * mapped, i.e. not iconified or withdrawn.
       */
      if (!upw->isMinimized) {
         XMapRaised(up->display, upw->clientWindow);
      }

      data[0] = _NET_WM_STATE_REMOVE;
      data[1] = up->atoms._NET_WM_STATE_HIDDEN;
      data[3] = 2; // Message is from the pager/taskbar
      UnityPlatformSendClientMessage(up, upw->rootWindow, upw->clientWindow,
                                     up->atoms._NET_WM_STATE, 32, 4, data);

      upw->wantInputFocus = TRUE;
      upw->isHidden = FALSE;
   }

   return TRUE;
}


/*
 *----------------------------------------------------------------------------
 *
 * UnityPlatformHideWindow --
 *
 *      Hides window. If the window is already hidden it stays hidden. Hides
 *      maximized and minimized windows too.
 *
 * Results:
 *      FALSE if the Window handle is invalid.
 *      TRUE otherwise.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */

Bool
UnityPlatformHideWindow(UnityPlatform *up,    // IN
                        UnityWindowId window) // IN
{
   UnityPlatformWindow *upw;

   ASSERT(up);

   upw = UPWindow_Lookup(up, window);

   if (!upw
      || !upw->clientWindow) {
      Debug("Hiding FAILED!\n");
      return FALSE;
   }

   if (!upw->isHidden) {
      Atom data[5] = {0, 0, 0, 0, 0};

      upw->isHidden = TRUE;

      data[0] = _NET_WM_STATE_ADD;
      data[1] = up->atoms._NET_WM_STATE_HIDDEN;
      data[3] = 2; // Message is from a pager/taskbar/etc.
      UnityPlatformSendClientMessage(up, upw->rootWindow, upw->clientWindow,
                                     up->atoms._NET_WM_STATE, 32, 4, data);
   }

   return TRUE;
}


/*
 *----------------------------------------------------------------------------
 *
 * UnityPlatformMinimizeWindow --
 *
 *      Mimimizes window. If the window is already mimimized it stays minimized.
 *
 * Results:
 *      FALSE if the Window handle is invalid.
 *      TRUE otherwise.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */

Bool
UnityPlatformMinimizeWindow(UnityPlatform *up,    // IN
                            UnityWindowId window) // IN
{
   UnityPlatformWindow *upw;

   ASSERT(up);

   upw = UPWindow_Lookup(up, window);

   if (!upw
      || !upw->clientWindow) {
      Debug("Minimizing FAILED!\n");
      return FALSE;
   }

   Debug("UnityPlatformMinimizeWindow(%#lx)\n", upw->toplevelWindow);
   upw->wantInputFocus = FALSE;
   if (!upw->isMinimized) {
      Atom data[5] = {0, 0, 0, 0, 0};

      Debug("Minimizing window %#x\n", window);
      upw->isMinimized = TRUE;
      data[0] = _NET_WM_STATE_ADD;
      if (UnityPlatformWMProtocolSupported(up, UNITY_X11_WM__NET_WM_STATE_MINIMIZED)) {
         data[1] = up->atoms._NET_WM_STATE_MINIMIZED;
      } else {
         data[1] = up->atoms._NET_WM_STATE_HIDDEN;
      }
      data[3] = 2; // Message is from a pager/taskbar/etc.
      UnityPlatformSendClientMessage(up, upw->rootWindow, upw->clientWindow,
                                     up->atoms._NET_WM_STATE, 32, 4, data);

      XIconifyWindow(up->display, upw->clientWindow, 0);
   } else {
      Debug("Window %#x is already minimized\n", window);
   }


   return TRUE;
}


/*
 *----------------------------------------------------------------------------
 *
 * UnityPlatformMaximizeWindow --
 *
 *      Maximizes window. If the window is already maximized it will stay so.
 *
 * Results:
 *      FALSE if the Window handle is invalid.
 *      TRUE otherwise.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */

Bool
UnityPlatformMaximizeWindow(UnityPlatform *up,    // IN
                            UnityWindowId window) // IN
{
   UnityPlatformWindow *upw;

   ASSERT(up);

   upw = UPWindow_Lookup(up, window);

   if (!upw
      || !upw->clientWindow) {
      Debug("Maximizing FAILED!\n");
      return FALSE;
   }

   if (!upw->isMaximized) {
      Atom data[5] = {0, 0, 0, 0, 0};

      upw->isMaximized = TRUE;
      data[0] = _NET_WM_STATE_ADD;
      data[1] = up->atoms._NET_WM_STATE_MAXIMIZED_HORZ;
      data[2] = up->atoms._NET_WM_STATE_MAXIMIZED_VERT;
      data[3] = 2; // Message is from a pager/taskbar/etc.
      UnityPlatformSendClientMessage(up, upw->rootWindow, upw->clientWindow,
                                     up->atoms._NET_WM_STATE, 32, 4, data);
   }

   return TRUE;
}


/*
 *----------------------------------------------------------------------------
 *
 * UnityPlatformUnmaximizeWindow --
 *
 *      Unmaximizes window. If the window is already unmaximized, it will stay
 *      that way.
 *
 * Results:
 *      FALSE if the Window handle is invalid.
 *      TRUE otherwise.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */

Bool
UnityPlatformUnmaximizeWindow(UnityPlatform *up,    // IN
                              UnityWindowId window) // IN
{
   UnityPlatformWindow *upw;

   ASSERT(up);

   upw = UPWindow_Lookup(up, window);

   if (!upw
      || !upw->clientWindow) {
      Debug("Maximizing FAILED!\n");
      return FALSE;
   }

   if (upw->isMaximized) {
      Atom data[5] = {0, 0, 0, 0, 0};

      data[0] = _NET_WM_STATE_REMOVE;
      data[1] = up->atoms._NET_WM_STATE_MAXIMIZED_HORZ;
      data[2] = up->atoms._NET_WM_STATE_MAXIMIZED_VERT;
      data[3] = 2; // Message is from a pager/taskbar/etc.
      UnityPlatformSendClientMessage(up, upw->rootWindow, upw->clientWindow,
                                     up->atoms._NET_WM_STATE, 32, 4, data);

      upw->isMaximized = FALSE;
   }

   return TRUE;
}


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

Bool
UnityPlatformSetWindowDesktop(UnityPlatform *up,         // IN
                              UnityWindowId windowId,    // IN
                              UnityDesktopId desktopId)  // IN
{
   UnityPlatformWindow *upw;
   uint32 guestDesktopId;

   ASSERT(up);

   upw = UPWindow_Lookup(up, windowId);

   if (!upw
      || !upw->clientWindow) {
      Debug("Desktop change FAILED on %#lx (perhaps it has no clientWindow)!\n",
            upw ? upw->toplevelWindow : 0);
      return FALSE;
   }

   /*
    * XXX I wrote this code assuming that UnityWindowTracker on the
    * guest side will be updated with the latest settings as they come
    * from the host, but that is not currently the case. unity.c needs
    * fixing.
    */

   ASSERT(desktopId < up->desktopInfo.numDesktops);
   guestDesktopId = up->desktopInfo.unityDesktopToGuest[desktopId];

   UPWindow_SetEWMHDesktop(up, upw, guestDesktopId);

   return TRUE;
}


/*
 *------------------------------------------------------------------------------
 *
 * UPWindow_SetEWMHDesktop --
 *
 *     Move the window to the specified desktop.  ewmhDesktopId corresponds
 *     to a desktop index to be used with _NET_WM_DESKTOP.
 *
 * Results:
 *     This will directly change _NET_WM_DESKTOP of an unmapped window,
 *     and will instead request the window manager to update that property
 *     for a mapped window.
 *
 * Side effects:
 *     None.
 *
 *------------------------------------------------------------------------------
 */


void
UPWindow_SetEWMHDesktop(UnityPlatform *up,               // IN
                        UnityPlatformWindow *upw,        // IN
                        uint32 ewmhDesktopId)            // IN
{
   Atom data[5] = {0, 0, 0, 0, 0};

   ASSERT(up);
   ASSERT(upw);

   if (!upw->isViewable || upw->wantSetDesktopNumberOnUnmap) {
     Atom currentDesktop = ewmhDesktopId; // Cast for 64-bit correctness.

     /*
      * Sending the _NET_WM_DESKTOP client message only works if the
      * window is mapped. We should still send that message to
      * eliminate race conditions, but if the window is not mapped, we
      * also need to set the property on the window so that it shows
      * up on the correct desktop when it is re-mapped.
      *
      * wantSetDesktopNumberOnUnmap implies that we unmapped the window
      * in question.  We evaluate this here, in addition to isViewable,
      * because it's totally possible that the window server processed
      * our unmap request, but we just haven't received the notification
      * yet.  (In other words, if that's the case, isViewable may still
      * be TRUE.)
      */

     XChangeProperty(up->display, (Window)upw->clientWindow, up->atoms._NET_WM_DESKTOP,
		     XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&currentDesktop, 1);
   }

   data[0] = ewmhDesktopId;
   data[1] = 2; // Indicates that this was requested by the pager/taskbar/etc.
   UnityPlatformSendClientMessage(up,
				  upw->rootWindow,
				  upw->clientWindow,
				  up->atoms._NET_WM_DESKTOP,
				  32, 5, data);
}


/*
 *-----------------------------------------------------------------------------
 *
 * UPWindowLookupClientLeader --
 *
 *      Given a UnityPlatformWindow, look up the associated "client leader"
 *      window, identified by the WM_CLIENT_LEADER property, if it exists.
 *
 * Results:
 *      A valid window ID if found, otherwise None.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

static Window
UPWindowLookupClientLeader(UnityPlatform *up,           // IN
                           UnityPlatformWindow *upw)    // IN
{
   Atom propertyType;
   int propertyFormat;
   unsigned long itemsReturned;
   unsigned long bytesRemaining;
   unsigned char *valueReturned = NULL;

   Window checkWindow;
   Window leaderWindow = None;

   ASSERT(up);
   ASSERT(upw);

   checkWindow = upw->clientWindow ? upw->clientWindow : upw->toplevelWindow;

   UnityPlatformResetErrorCount(up);
   XGetWindowProperty(up->display, checkWindow, up->atoms.WM_CLIENT_LEADER, 0,
                      4, False, XA_WINDOW, &propertyType, &propertyFormat,
                      &itemsReturned, &bytesRemaining, &valueReturned);

   if (UnityPlatformGetErrorCount(up) == 0 && propertyFormat == 32 &&
       itemsReturned == 1) {
      leaderWindow = *(XID *)valueReturned;
   }

   XFree(valueReturned);

   return leaderWindow;
}


/*
 *-----------------------------------------------------------------------------
 *
 * UPWindowUpdateFrameExtents --
 *
 *      Lookup and record (cache) the _NET_FRAME_EXTENTS property.
 *
 * Results:
 *      If _NET_FRAME_EXTENTS is set, upw->frameExtents may be updated.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

static void
UPWindowUpdateFrameExtents(UnityPlatform *up,
                           UnityPlatformWindow *upw)
{
   Atom propertyType;
   int propertyFormat = 0;
   unsigned long itemsReturned = 0;
   unsigned long bytesRemaining;
   unsigned char *valueReturned = NULL;
   Window w = upw->clientWindow ? upw->clientWindow : upw->toplevelWindow;

   ASSERT(up);
   ASSERT(upw);

   if (UnityPlatformWMProtocolSupported(up, UNITY_X11_WM__NET_FRAME_EXTENTS)
       && XGetWindowProperty(up->display, w, up->atoms._NET_FRAME_EXTENTS, 0,
                             1024, False, XA_CARDINAL,
                             &propertyType, &propertyFormat, &itemsReturned,
                             &bytesRemaining, &valueReturned) == Success
       && propertyFormat == 32
       && itemsReturned >= 4) {
      Atom *atomValue = (Atom *)valueReturned;

      upw->frameExtents[0] = atomValue[0];
      upw->frameExtents[1] = atomValue[1];
      upw->frameExtents[2] = atomValue[2];
      upw->frameExtents[3] = atomValue[3];

      XFree(valueReturned);
   }
}