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

#include <unistd.h>

#include "X.h"
#include "Xproto.h"
#include "gcstruct.h"
#include "../../include/window.h"
#include "windowstr.h"
#include "pixmapstr.h"
#include "colormapst.h"
#include "scrnintstr.h"
#include "region.h"
#include "dixstruct.h"
#include "selection.h"
#include "mi.h"
#include "fb.h"
#include "mibstorest.h"

#include "Agent.h"
#include "Display.h"
#include "Screen.h"
#include "GCs.h"
#include "GCOps.h"
#include "Drawable.h"
#include "Colormap.h"
#include "Cursor.h"
#include "Visual.h"
#include "Events.h"
#include "Clipboard.h"
#include "Args.h"
#include "Trap.h"
#include "Rootless.h"
#include "Atoms.h"
#include "Client.h"
#include "Reconnect.h"
#include "Dialog.h"
#include "Splash.h"
#include "Init.h"
#include "Composite.h"
#include "Events.h"
#include "Utils.h"

#include <nx/NX.h>
#include "compext/Compext.h"

#include "Xatom.h"

/*
 * Used to register the window's privates.
 */

int nxagentWindowPrivateIndex;

/*
 * Number of windows which need synchronization.
 */

int nxagentCorruptedWindows;

/*
 * Used to track nxagent window's visibility.
 */

int nxagentVisibility = VisibilityUnobscured;
unsigned long nxagentVisibilityTimeout = 0;
Bool nxagentVisibilityStop = False;

/*
 * Set here the required log level.
 */

#define PANIC
#define WARNING
#undef  TEST
#undef  DEBUG

/*
 * Useful to test the window configuration
 * failures.
 */

#ifdef TEST
#define MAKE_SYNC_CONFIGURE_WINDOW  XSync(nxagentDisplay, 0)
#else
#define MAKE_SYNC_CONFIGURE_WINDOW
#endif

extern WindowPtr nxagentViewportFrameLeft;
extern WindowPtr nxagentViewportFrameRight;
extern WindowPtr nxagentViewportFrameAbove;
extern WindowPtr nxagentViewportFrameBelow;

extern WindowPtr nxagentRootTileWindow;

extern Bool nxagentReportPrivateWindowIds;

#define RECTLIMIT 25
#define BSPIXMAPLIMIT 128

Bool nxagentExposeArrayIsInitialized = False;
Window nxagentConfiguredSynchroWindow;
static int nxagentExposeSerial = 0;

StoringPixmapPtr nxagentBSPixmapList[BSPIXMAPLIMIT];

/*
 * Used to walk through the window hierarchy
 * to find a window
 */

typedef struct _WindowMatch
{
  WindowPtr pWin;
  Window    id;
} WindowMatchRec;

Bool nxagentReconnectAllWindows(void *);
Bool nxagentDisconnectAllWindows(void);
Bool nxagentIsIconic(WindowPtr);

/*
 * From NXproperty.c.
 */

int GetWindowProperty(WindowPtr, Atom, long, long, Bool, Atom, Atom*, int*,
                                 unsigned long*, unsigned long*, unsigned char**);

/*
 * Other local functions.
 */

static Bool nxagentSomeWindowsAreMapped(void);
static void nxagentFrameBufferPaintWindow(WindowPtr pWin, RegionPtr pRegion, int what);
static void nxagentTraverseWindow(WindowPtr, void(*)(void *, XID, void *), void *);
static void nxagentDisconnectWindow(void *, XID, void *);
static Bool nxagentLoopOverWindows(void(*)(void *, XID, void *));
static void nxagentReconfigureWindowCursor(void *, XID, void *);
static void nxagentReconnectWindow(void *, XID, void *);
static void nxagentReconfigureWindow(void *, XID, void *);
static int nxagentForceExposure(WindowPtr pWin, void * ptr);

/* by dimbor */
typedef struct
{
  CARD32 state;
  Window icon;
}
nxagentWMStateRec;

/*
 * This is currently unused.
 */

#ifdef TEST
static Bool nxagentCheckWindowIntegrity(WindowPtr pWin);
#endif

WindowPtr nxagentGetWindowFromID(Window id)
{
  WindowPtr pWin = screenInfo.screens[0]->root;

  while (pWin && nxagentWindowPriv(pWin))
  {
    if (nxagentWindow(pWin) == id)
    {
      return pWin;
    }

    if (pWin -> nextSib)
    {
      pWin = pWin -> nextSib;
    }
    else
    {
      pWin = pWin -> firstChild;
    }
  }

  return NULL;
}

static int nxagentFindWindowMatch(WindowPtr pWin, void * ptr)
{
  WindowMatchRec *match = (WindowMatchRec *) ptr;

  if (match -> id == nxagentWindow(pWin))
  {
    match -> pWin = pWin;
    return WT_STOPWALKING;
  }
  else
  {
    return WT_WALKCHILDREN;
  }
}

WindowPtr nxagentWindowPtr(Window window)
{
  WindowMatchRec match = {.pWin = NullWindow, .id   = window};

  for (int i = 0; i < nxagentNumScreens; i++)
  {
    WalkTree(screenInfo.screens[i], nxagentFindWindowMatch, (void *) &match);

    if (match.pWin)
    {
      break;
    }
  }

  return match.pWin;
}

/*
 * from "Definition of the Porting Layer for X v11 Sample Server":
 *
 * This routine is a hook for when DIX creates a window. It should
 * fill in the "Window Procedures in the WindowRec" below and also
 * allocate the devPrivate block for it.
 *
 * See Xserver/fb/fbwindow.c for the sample server implementation.
 */
Bool nxagentCreateWindow(WindowPtr pWin)
{
  unsigned long mask;
  XSetWindowAttributes attributes;
  Visual *visual;
  ColormapPtr pCmap;

  if (nxagentScreenTrap)
  {
    return True;
  }

  if (pWin->drawable.class == InputOnly)
  {
    mask = CWEventMask;
    visual = CopyFromParent;
  }
  else
  {
    mask = CWEventMask | CWBackingStore;

    if (pWin->optional)
    {
      mask |= CWBackingPlanes | CWBackingPixel;
      attributes.backing_planes = pWin->optional->backingBitPlanes;
      attributes.backing_pixel = pWin->optional->backingPixel;
    }

    attributes.backing_store = NotUseful;

    #ifdef TEST
    fprintf(stderr, "nxagentCreateWindow: Backing store on window at [%p] is [%d].\n",
                (void*)pWin, attributes.backing_store);
    #endif

    /*
      FIXME: We need to set save under on the real display?
    */
    if (nxagentSaveUnder)
    {
      mask |= CWSaveUnder;
      attributes.save_under = False;
    }

    if (pWin->parent)
    {
      if (pWin->optional && pWin->optional->visual != wVisual(pWin->parent))
      {
        visual = nxagentVisualFromID(pWin->drawable.pScreen, wVisual(pWin));
        mask |= CWColormap;
        if (pWin->optional->colormap)
        {
          pCmap = (ColormapPtr)LookupIDByType(wColormap(pWin), RT_COLORMAP);
          attributes.colormap = nxagentColormap(pCmap);
        }
        else
        {
          attributes.colormap = nxagentDefaultVisualColormap(visual);
        }
      }
      else if (pWin->optional)
      {
        visual = CopyFromParent;
      }
      else
      {
        visual = nxagentVisualFromID(pWin->drawable.pScreen, wVisual(pWin));
        mask |= CWColormap;
        attributes.colormap = nxagentDefaultVisualColormap(visual);
      }
    }
    else
    {
      /* root windows have their own colormaps at creation time */
      visual = nxagentVisualFromID(pWin->drawable.pScreen, wVisual(pWin));
      pCmap = (ColormapPtr)LookupIDByType(wColormap(pWin), RT_COLORMAP);
      mask |= CWColormap;
      attributes.colormap = nxagentColormap(pCmap);
    }
  }

  if (mask & CWEventMask)
  {
    attributes.event_mask = nxagentGetEventMask(pWin);
  }
  #ifdef WARNING
  else
  {
    attributes.event_mask = NoEventMask;
  }
  #endif

  /*
   * Select the event mask if window is a top level
   * window. This at least makes the keyboard barely
   * work.
   */

  #ifdef TEST
  fprintf(stderr, "nxagentCreateWindow: Going to create new window.\n");
  #endif

  #ifdef TEST
  fprintf(stderr, "nxagentCreateWindow: Creating %swindow at %p current event mask = %lX mask & CWEventMask = %ld "
              "event_mask = %lX\n",
                  nxagentWindowTopLevel(pWin) ? "toplevel " : "", (void*)pWin, pWin -> eventMask,
                      mask & CWEventMask, attributes.event_mask);

  fprintf(stderr, "nxagentCreateWindow: position [%d,%d] size [%d,%d] depth [%d] border [%d] class [%d].\n",
              pWin->origin.x - wBorderWidth(pWin), pWin->origin.y - wBorderWidth(pWin),
                  pWin->drawable.width, pWin->drawable.height, pWin->drawable.depth, pWin->borderWidth,
                      pWin->drawable.class);
  #endif

  nxagentWindowPriv(pWin)->window = XCreateWindow(nxagentDisplay,
                                                  nxagentWindowParent(pWin),
                                                  pWin->origin.x -
                                                  wBorderWidth(pWin),
                                                  pWin->origin.y -
                                                  wBorderWidth(pWin),
                                                  pWin->drawable.width,
                                                  pWin->drawable.height,
                                                  pWin->borderWidth,
                                                  pWin->drawable.depth,
                                                  pWin->drawable.class,
                                                  visual,
                                                  mask, &attributes);

  nxagentWindowPriv(pWin) -> isMapped = 0;
  nxagentWindowPriv(pWin) -> isRedirected = 0;
  nxagentWindowPriv(pWin) -> visibilityState = VisibilityUnobscured;
  nxagentWindowPriv(pWin) -> corruptedRegion = RegionCreate(NULL, 1);
  nxagentWindowPriv(pWin) -> hasTransparentChildren = 0;
  nxagentWindowPriv(pWin) -> containGlyphs = 0;
  nxagentWindowPriv(pWin) -> corruptedId = 0;
  nxagentWindowPriv(pWin) -> deferredBackgroundExpose = 0;
  nxagentWindowPriv(pWin) -> synchronizationBitmap = NullPixmap;
  nxagentWindowPriv(pWin) -> corruptedTimestamp = 0;
  nxagentWindowPriv(pWin) -> splitResource = NULL;

  if (nxagentOption(Rootless) == 1)
  {
    if (pWin != nxagentRootlessWindow)
    {
      WindowPtr pParent = pWin -> parent;

      if (pParent && nxagentWindowPriv(pParent) -> isMapped == 1)
      {
        nxagentWindowPriv(pWin) -> isMapped = 1;
      }
      else
      {
        nxagentWindowPriv(pWin) -> isMapped = 0;
      }
    }
    else
    {
      nxagentWindowPriv(pWin) -> isMapped = 0;
    }
  }

  if (nxagentReportPrivateWindowIds)
  {
    fprintf (stderr, "NXAGENT_WINDOW_ID: PRIVATE_WINDOW,WID:[0x%x]\n", nxagentWindowPriv(pWin)->window);
  }
  #ifdef TEST
  fprintf(stderr, "nxagentCreateWindow: Created new window with id [0x%x].\n",
              nxagentWindowPriv(pWin)->window);
  #endif

  /*
   * Set the WM_DELETE_WINDOW protocols on every
   * top level window. Also redirect the window
   * if it is a top level.
   */

  if (nxagentOption(Rootless) && nxagentWindowTopLevel(pWin))
  {
    Atom prop = nxagentMakeAtom("WM_PROTOCOLS", strlen("WM_PROTOCOLS"), True);
    XlibAtom atom = nxagentMakeAtom("WM_DELETE_WINDOW", strlen("WM_DELETE_WINDOW"), True);

    XSetWMProtocols(nxagentDisplay, nxagentWindowPriv(pWin)->window, &atom, 1);

    nxagentAddPropertyToList(prop, pWin);

    /*
     * Redirect the window to the off-screen
     * memory, if the composite extension is
     * supported on the display.
     */
    /*
      FIXME: Do all the windows for which nxagentWindowTopLevel(pWin)
             returns true need to be redirected?
    */
    nxagentRedirectWindow(pWin);
  }

  if ((nxagentRealWindowProp) && (!nxagentWindowTopLevel(pWin)))
  {
    Atom prop = MakeAtom("NX_REAL_WINDOW", strlen("NX_REAL_WINDOW"), True);

    if (ChangeWindowProperty(pWin, prop, XA_WINDOW, 32, PropModeReplace, 1, nxagentWindowPriv(pWin), 1) != Success)
    {
      fprintf(stderr, "nxagentCreateWindow: Adding NX_REAL_WINDOW failed.\n");
    }
    #ifdef DEBUG
    else
    {
      fprintf(stderr, "nxagentCreateWindow: Added NX_REAL_WINDOW for Window ID [%x].\n", nxagentWindowPriv(pWin)->window);
    }
    #endif
  }

  nxagentWindowPriv(pWin)->x = pWin->origin.x - wBorderWidth(pWin);
  nxagentWindowPriv(pWin)->y = pWin->origin.y - wBorderWidth(pWin);
  nxagentWindowPriv(pWin)->width = pWin->drawable.width;
  nxagentWindowPriv(pWin)->height = pWin->drawable.height;
  nxagentWindowPriv(pWin)->borderWidth = pWin->borderWidth;
  nxagentWindowPriv(pWin)->siblingAbove = None;
  nxagentWindowPriv(pWin)->pPicture = NULL;

  if (pWin->nextSib)
  {
    nxagentWindowPriv(pWin->nextSib)->siblingAbove = nxagentWindow(pWin);
  }

  #ifdef SHAPE
    #ifdef NXAGENT_SHAPE2
      nxagentWindowPriv(pWin)->boundingShape = NULL;
      nxagentWindowPriv(pWin)->clipShape = NULL;
    #else
      nxagentWindowPriv(pWin)->boundingShape = RegionCreate(NULL, 1);
      nxagentWindowPriv(pWin)->clipShape = RegionCreate(NULL, 1);
    #endif
  #endif /* SHAPE */

  fbCreateWindow(pWin);

  /*
   * Only the root window will have
   * the right colormap.
   */

  if (!pWin->parent)
  {
    nxagentSetInstalledColormapWindows(pWin->drawable.pScreen);
  }

  return True;
}

/* set the NX_AGENT_VERSION property for the given window (normally
   the root window) */
void nxagentSetVersionProperty(WindowPtr pWin)
{
  char *name = "NX_AGENT_VERSION";
  Atom prop = MakeAtom(name, strlen(name), True);

  if (ChangeWindowProperty(pWin, prop, XA_STRING, 8, PropModeReplace, strlen(NX_VERSION_CURRENT_STRING), NX_VERSION_CURRENT_STRING, True) != Success)
  {
    fprintf(stderr, "%s: Adding property [%s], value [%s] failed.\n", __func__, name, NX_VERSION_CURRENT_STRING);
  }
  #ifdef DEBUG
  else
  {
    fprintf(stderr, "%s: Added property [%s], value [%s] for root window [%x].\n", __func__, name, NX_VERSION_CURRENT_STRING, pWin);
  }
  #endif
}

Bool nxagentSomeWindowsAreMapped(void)
{
  WindowPtr pWin = screenInfo.screens[0]->root -> firstChild;

  while (pWin)
  {
    if ((pWin -> mapped || nxagentIsIconic(pWin)) &&
            pWin -> drawable.class == InputOutput)
    {
      return True;
    }

    pWin = pWin -> nextSib;
  }

  return False;
}

/*
 * from "Definition of the Porting Layer for X v11 Sample Server":
 *
 * This routine is a hook for when DIX destroys a window. It should
 * deallocate the devPrivate block for it and any other blocks that
 * need to be freed, besides doing other cleanup actions.
 *
 * See Xserver/fb/fbwindow.c for the sample server implementation.
 */
Bool nxagentDestroyWindow(WindowPtr pWin)
{
  nxagentPrivWindowPtr pWindowPriv;

  if (nxagentScreenTrap == 1)
  {
    return 1;
  }

  nxagentClearClipboard(NULL, pWin);

  for (int j = 0; j < nxagentExposeQueue.length; j++)
  {
    int i = (nxagentExposeQueue.start + j) % EXPOSED_SIZE;

    if (nxagentExposeQueue.exposures[i].pWindow == pWin)
    {
      if (nxagentExposeQueue.exposures[i].localRegion != NullRegion)
      {
        RegionDestroy(nxagentExposeQueue.exposures[i].localRegion);
      }

      nxagentExposeQueue.exposures[i].localRegion = NullRegion;

      if (nxagentExposeQueue.exposures[i].remoteRegion != NullRegion)
      {
        RegionDestroy(nxagentExposeQueue.exposures[i].remoteRegion);
      }

      nxagentExposeQueue.exposures[i].remoteRegion = NullRegion;
    }
  }

  nxagentDeleteConfiguredWindow(pWin);

  pWindowPriv = nxagentWindowPriv(pWin);

  if (pWin->nextSib)
  {
    nxagentWindowPriv(pWin->nextSib)->siblingAbove =
           pWindowPriv->siblingAbove;
  }

  #ifdef NXAGENT_SHAPE2
    #ifdef SHAPE
    if (pWindowPriv->boundingShape)
    {
      RegionDestroy(pWindowPriv->boundingShape);
    }

    if (pWindowPriv->clipShape)
    {
      RegionDestroy(pWindowPriv->clipShape);
    }
    #endif
  #else
    RegionDestroy(pWindowPriv->boundingShape);
    RegionDestroy(pWindowPriv->clipShape);
  #endif

  if (pWindowPriv -> corruptedRegion)
  {
    RegionDestroy(pWindowPriv -> corruptedRegion);
    pWindowPriv -> corruptedRegion = NULL;
  }

  if (nxagentSynchronization.pDrawable == (DrawablePtr) pWin)
  {
    nxagentSynchronization.pDrawable = NULL;

    #ifdef TEST
    fprintf(stderr, "nxagentDestroyWindow: Synchronization drawable [%p] removed from resources.\n",
                (void *) pWin);
    #endif
  }

  nxagentDestroyCorruptedResource((DrawablePtr) pWin, RT_NX_CORR_WINDOW);
  nxagentDestroyDrawableBitmap((DrawablePtr) pWin);

  if (pWindowPriv -> splitResource != NULL)
  {
    nxagentReleaseSplit((DrawablePtr) pWin);
  }

  XDestroyWindow(nxagentDisplay, nxagentWindow(pWin));

  if (nxagentOption(Rootless))
  {
    nxagentRootlessDelTopLevelWindow(pWin);
  }

  pWindowPriv->window = None;

  if (pWin -> optional)
  {
    pWin -> optional -> userProps = NULL;
  }

  if (nxagentOption(Rootless) && nxagentRootlessDialogPid == 0 &&
          nxagentLastWindowDestroyed == False && nxagentSomeWindowsAreMapped() == False)
  {
    #ifdef TEST
    fprintf(stderr, "nxagentDestroyWindow: Last mapped window as been destroyed.\n");
    #endif

    nxagentLastWindowDestroyed     = True;
    nxagentLastWindowDestroyedTime = GetTimeInMillis();
  }

  return True;
}

/*
 * from "Definition of the Porting Layer for X v11 Sample Server":
 *
 * This routine is a hook for when DIX moves or resizes a window. It
 * should do whatever private operations need to be done when a window
 * is moved or resized. For instance, if DDX keeps a pixmap tile used
 * for drawing the background or border, and it keeps the tile rotated
 * such that it is longword aligned to longword locations in the frame
 * buffer, then you should rotate your tiles here. The actual graphics
 * involved in moving the pixels on the screen and drawing the border
 * are handled by CopyWindow(), below.
 *
 * See Xserver/fb/fbwindow.c for the sample server implementation.
 */
Bool nxagentPositionWindow(WindowPtr pWin, int x, int y)
{
  if (nxagentScreenTrap == 1)
  {
    return True;
  }

  #ifdef TEST
  fprintf(stderr, "nxagentPositionWindow: Changing position of window [%p][%ld] to [%d,%d].\n",
              (void *) pWin, nxagentWindow(pWin), x, y);
  #endif

  nxagentAddConfiguredWindow(pWin, CWSibling | CWX | CWY | CWWidth |
                                 CWHeight | CWBorderWidth);

  return True;
}

void nxagentRestackWindow(WindowPtr pWin, WindowPtr pOldNextSib)
{
  if (nxagentScreenTrap == 1)
  {
    return;
  }

  nxagentAddConfiguredWindow(pWin, CW_RootlessRestack);
}

void nxagentSwitchFullscreen(ScreenPtr pScreen, Bool switchOn)
{
  if (nxagentOption(Rootless) == 1)
  {
    return;
  }

  if (!switchOn)
  {
    nxagentWMDetect();

    /*
     * The smart scheduler could be stopped while
     * waiting for the reply. In this case we need
     * to yield explicitly to avoid to be stuck in
     * the dispatch loop forever.
     */

    isItTimeToYield = 1;

    if (!nxagentWMIsRunning)
    {
      #ifdef WARNING
      fprintf(stderr, "Warning: Can't switch to window mode, no window manager "
                  "has been detected.\n");
      #endif

      return;
    }
  }

  #ifdef TEST
  fprintf(stderr, "nxagentSwitchFullscreen: Switching to %s mode.\n",
              switchOn ? "fullscreen" : "windowed");
  #endif

  nxagentChangeOption(Fullscreen, switchOn);

  XEvent e = {
    .xclient.type = ClientMessage,
    .xclient.message_type = nxagentAtoms[13], /* _NET_WM_STATE */
    .xclient.display = nxagentDisplay,
    .xclient.window = nxagentDefaultWindows[pScreen -> myNum],
    .xclient.format = 32,
    .xclient.data.l[0] = nxagentOption(Fullscreen) ? 1 : 0,
    .xclient.data.l[1] = nxagentAtoms[14] /* _NET_WM_STATE_FULLSCREEN */
  };
  XSendEvent(nxagentDisplay, DefaultRootWindow(nxagentDisplay), False,
                 SubstructureRedirectMask, &e);

  if (switchOn)
  {
    nxagentFullscreenWindow = nxagentDefaultWindows[pScreen -> myNum];
    nxagentGrabPointerAndKeyboard(NULL);
  }
  else
  {
    nxagentFullscreenWindow = None;

    /* if we had AutoGrab before entering fullscreen reactivate it now */
    if (nxagentOption(AutoGrab))
      nxagentGrabPointerAndKeyboard(NULL);
    else
      nxagentUngrabPointerAndKeyboard(NULL);
  }
}

void nxagentSwitchAllScreens(ScreenPtr pScreen, Bool switchOn)
{
  Window w;
  XSetWindowAttributes attributes;
  unsigned long valuemask;

  if (nxagentOption(Rootless))
  {
    return;
  }

  if (!switchOn)
  {
    nxagentWMDetect();

    if (!nxagentWMIsRunning)
    {
      #ifdef WARNING
      fprintf(stderr, "Warning: Can't switch to window mode, no window manager has been detected.\n");
      #endif

      return;
    }
  }

  w = nxagentDefaultWindows[pScreen -> myNum];

  /*
   * override_redirect makes the window manager ignore the window and
   * not add decorations, see ICCCM)
   */
  attributes.override_redirect = switchOn;
  valuemask = CWOverrideRedirect;
  XUnmapWindow(nxagentDisplay, w);
  XChangeWindowAttributes(nxagentDisplay, w, valuemask, &attributes);

  XReparentWindow(nxagentDisplay, w, DefaultRootWindow(nxagentDisplay), 0, 0);

  if (switchOn)
  {
    /*
     * Change to fullscreen mode.
     */

    int i;
    XEvent e;

    /*
     * Wait for window manager reparenting the default window.
     */

    for (i = 0; i < 100 && nxagentWMIsRunning; i++)
    {
      #ifdef TEST
      fprintf(stderr, "nxagentSwitchAllScreens: WARNING! Going to wait for the ReparentNotify event.\n");
      #endif

      if (XCheckTypedWindowEvent(nxagentDisplay, w, ReparentNotify, &e))
      {
        break;
      }

      /*
       * This should also flush the NX link for us.
       */

      XSync(nxagentDisplay, 0);

      nxagentWaitEvents(nxagentDisplay, 50);
    }

    if (i < 100)
    {
      /*
       * The window manager has done with the reparent
       * operation. We can resize and map the window.
       */

      nxagentChangeOption(Fullscreen, True);
      nxagentChangeOption(AllScreens, True);

      /*
       * Save the window-mode configuration.
       */

      nxagentChangeOption(SavedX, nxagentOption(X));
      nxagentChangeOption(SavedY, nxagentOption(Y));
      nxagentChangeOption(SavedWidth, nxagentOption(Width));
      nxagentChangeOption(SavedHeight, nxagentOption(Height));
      nxagentChangeOption(SavedRootWidth, nxagentOption(RootWidth));
      nxagentChangeOption(SavedRootHeight, nxagentOption(RootHeight));

      /*
       * Reconf the Default window.
       */

      nxagentChangeOption(X, 0);
      nxagentChangeOption(Y, 0);
      nxagentChangeOption(Width, WidthOfScreen(DefaultScreenOfDisplay(nxagentDisplay)));
      nxagentChangeOption(Height, HeightOfScreen(DefaultScreenOfDisplay(nxagentDisplay)));

      /*
       * Move the root window.
       */

      nxagentChangeOption(RootX, (nxagentOption(Width) - nxagentOption(RootWidth)) / 2);
      nxagentChangeOption(RootY, (nxagentOption(Height) - nxagentOption(RootHeight)) / 2);
      nxagentChangeOption(ViewportXSpan, nxagentOption(Width) - nxagentOption(RootWidth));
      nxagentChangeOption(ViewportYSpan, nxagentOption(Height) - nxagentOption(RootHeight));

      XMoveResizeWindow(nxagentDisplay, w, nxagentOption(X), nxagentOption(Y),
                            nxagentOption(Width), nxagentOption(Height));

      nxagentUpdateViewportFrame(0, 0, nxagentOption(RootWidth), nxagentOption(RootHeight));

      XMoveWindow(nxagentDisplay, nxagentWindow(pScreen->root),
                      nxagentOption(RootX), nxagentOption(RootY));

      /*
       * We disable the screensaver when changing
       * mode to fullscreen. Is it really needed?
       */

      XSetScreenSaver(nxagentDisplay, 0, 0, DefaultExposures, DefaultBlanking);

      if (nxagentIconWindow == None)
      {
        nxagentIconWindow = nxagentCreateIconWindow();
        XMapWindow(nxagentDisplay, nxagentIconWindow);
      }

      XMapRaised(nxagentDisplay, w);
      XSetInputFocus(nxagentDisplay, w, RevertToParent, CurrentTime);
      XCheckTypedWindowEvent(nxagentDisplay, w, LeaveNotify, &e);
      nxagentFullscreenWindow = w;

      if (nxagentOption(DesktopResize) == 1)
      {
        if (nxagentOption(Shadow) == 0)
        {
          nxagentChangeScreenConfig(0, WidthOfScreen(DefaultScreenOfDisplay(nxagentDisplay)),
                                        HeightOfScreen(DefaultScreenOfDisplay(nxagentDisplay)));
        }
        else
        {
          nxagentShadowAdaptToRatio();
        }
      }
    }
    else
    {
      /*
       * We have waited for a reparent event unsuccessfully.
       * Something happened to the window manager.
       */

      #ifdef WARNING
      fprintf(stderr, "nxagentSwitchAllScreens: WARNING! Expected ReparentNotify event missing.\n");
      #endif

      nxagentWMIsRunning = False;
      attributes.override_redirect = False;
      XChangeWindowAttributes(nxagentDisplay, w, valuemask, &attributes);
      XMapWindow(nxagentDisplay, w);
    }
  }
  else
  {
    /*
     * FIXME:
     * It could be necessary:
     * - To restore screensaver.
     * - To set or reset nxagentForceBackingStore flag.
     * - To propagate device settings to the X server if no WM is running.
     */

    /*
     * Change to windowed mode.
     */

    nxagentChangeOption(Fullscreen, False);
    nxagentChangeOption(AllScreens, False);

    XDestroyWindow(nxagentDisplay, nxagentIconWindow);

    nxagentIconWindow = nxagentFullscreenWindow = None;

    if (nxagentOption(DesktopResize) == 1)
    {
      nxagentChangeOption(RootWidth, nxagentOption(SavedRootWidth));
      nxagentChangeOption(RootHeight, nxagentOption(SavedRootHeight));

      if (nxagentOption(Shadow) == 0)
      {
        nxagentChangeScreenConfig(0, nxagentOption(RootWidth),
                                      nxagentOption(RootHeight));
      }
    }

    /*
     * FIXME: These are 0 most of the time nowadays. The effect is,
     * that the window is moving a bit to right/bottom every time
     * fullscreen mode is left. To fix this query the frame extents
     * from the window manager via _NET_REQUEST_FRAME_EXTENTS
     */

    if (nxagentOption(WMBorderWidth) > 0)
    {
      nxagentChangeOption(X, nxagentOption(SavedX) - nxagentOption(WMBorderWidth));
    }
    else
    {
      nxagentChangeOption(X, nxagentOption(SavedX));
    }

    if (nxagentOption(WMTitleHeight) > 0)
    {
      nxagentChangeOption(Y, nxagentOption(SavedY) - nxagentOption(WMTitleHeight));
    }
    else
    {
      nxagentChangeOption(Y, nxagentOption(SavedY));
    }

    nxagentChangeOption(Width, nxagentOption(SavedWidth));
    nxagentChangeOption(Height, nxagentOption(SavedHeight));

    if (nxagentOption(Shadow) == 1 && nxagentOption(DesktopResize) == 1)
    {
      nxagentShadowAdaptToRatio();
    }

    XMoveResizeWindow(nxagentDisplay, w, nxagentOption(X), nxagentOption(Y),
                          nxagentOption(Width), nxagentOption(Height));

    nxagentUpdateViewportFrame(0, 0, nxagentOption(Width), nxagentOption(Height));

    XMoveWindow(nxagentDisplay, nxagentWindow(pScreen->root), 0, 0);
    XMapWindow(nxagentDisplay, w);

    nxagentChangeOption(RootX, 0);
    nxagentChangeOption(RootY, 0);
  }

  XMoveResizeWindow(nxagentDisplay, nxagentInputWindows[0], 0, 0,
                        nxagentOption(Width), nxagentOption(Height));

  /* if we had AutoGrab before entering fullscreen reactivate it now */
  if (nxagentOption(AutoGrab))
    nxagentGrabPointerAndKeyboard(NULL);

  nxagentSetPrintGeometry(pScreen -> myNum);
}

#ifdef VIEWPORT_FRAME

void nxagentUpdateViewportFrame(int x, int y, int w, int h)
{
  /*
   * Four virtual windows make a frame around the viewport. We move the frame
   * with the viewport together. The areas going into the viewport were covered by
   * the frame and become exposed. This make the agent send expose events to his
   * clients.
   */

  XID values[3];
  Mask mask;

  /*
   * nxagentScreenTrap = True;
   */

  values[2] = Above;

  values[1] = nxagentOption(RootHeight);

  mask = CWX | CWHeight | CWStackMode;
  values[0] = x - NXAGENT_FRAME_WIDTH;
  ConfigureWindow(nxagentViewportFrameLeft, mask, (XID *) &values, serverClient);

  values[0] = x + w;
  ConfigureWindow(nxagentViewportFrameRight, mask, (XID *) &values, serverClient);

  values[1] = nxagentOption(RootWidth);

  mask = CWY | CWWidth | CWStackMode;
  values[0] = y - NXAGENT_FRAME_WIDTH;
  ConfigureWindow(nxagentViewportFrameAbove, mask, (XID *) &values, serverClient);

  values[0] = y + h;
  ConfigureWindow(nxagentViewportFrameBelow, mask, (XID *) &values, serverClient);

  /*
   * nxagentScreenTrap = False;
   */
}

#endif /* #ifdef VIEWPORT_FRAME */

void nxagentMoveViewport(ScreenPtr pScreen, int hShift, int vShift)
{
  int newX, newY, oldX = 0, oldY = 0;
  Bool doMove = False;

  if (nxagentOption(Rootless))
  {
    return;
  }

  /*
   * We must keep x coordinate between viewportXSpan and zero, if viewportXSpan
   * is less then zero. If viewportXSpan is greater or equal to zero, it means
   * the agent root window has a size smaller than the agent default window.
   * In this case we keep the old coordinate.
   */

  #ifdef DEBUG
  fprintf(stderr, "nxagentMoveViewport: RootX[%i] RootY[%i], hShift[%i] vShift[%i].\n",
          nxagentOption(RootX), nxagentOption(RootY), hShift, vShift);
  #endif

  nxagentChangeOption(ViewportXSpan, nxagentOption(Width) - nxagentOption(RootWidth));
  nxagentChangeOption(ViewportYSpan, nxagentOption(Height) - nxagentOption(RootHeight));

  if (nxagentOption(ViewportXSpan) < 0)
  {
    newX = nxagentOption(RootX) - hShift;

    if (newX > 0)
    {
      newX = 0;
    }
    else if (newX < nxagentOption(ViewportXSpan))
    {
      newX = nxagentOption(ViewportXSpan);
    }
  }
  else if (nxagentOption(ViewportXSpan) == 0)
  {
    newX = 0;
  }
  else
  {
    newX = nxagentOption(RootX);
  }

  if (nxagentOption(ViewportYSpan) < 0)
  {
    newY = nxagentOption(RootY) - vShift;

    if (newY > 0)
    {
      newY = 0;
    }
    else if (newY < nxagentOption(ViewportYSpan))
    {
      newY = nxagentOption(ViewportYSpan);
    }
  }
  else if (nxagentOption(ViewportYSpan) == 0)
  {
    newY = 0;
  }
  else
  {
    newY = nxagentOption(RootY);
  }

  oldX = nxagentOption(RootX);

  if (newX != nxagentOption(RootX))
  {
    nxagentChangeOption(RootX, newX);

    doMove = True;
  }

  oldY = nxagentOption(RootY);

  if (newY != nxagentOption(RootY))
  {
    nxagentChangeOption(RootY, newY);

    doMove = True;
  }

  if (doMove)
  {
    #ifdef TEST
    fprintf(stderr, "nxagentMoveViewport: New viewport geometry: (%d, %d)-"
                "(%d, %d)\n", -nxagentOption(RootX), -nxagentOption(RootY),
                    -nxagentOption(RootX) + nxagentOption(Width),
                        -nxagentOption(RootY) + nxagentOption(Height));

    fprintf(stderr, "nxagentMoveViewport: Root geometry x=[%d] y=[%d]\n",
                pScreen->root -> drawable.x,
                    pScreen->root -> drawable.y );
    #endif

    XMoveWindow(nxagentDisplay, nxagentWindow(pScreen->root),
                    nxagentOption(RootX), nxagentOption(RootY));

    if (nxagentOption(ClientOs) == ClientOsWinnt)
    {
      /*
       * If doMove is True we add exposed rectangles
       * to the remote expose region. This is done to
       * refresh the areas showed newly in the viewport.
       * We create two rectangles, one for horizontal
       * pan and one for vertical pan.
       */

      BoxRec hRect = {.x1 = -newX, .y1 = -newY};

      if (hShift < 0)
      {
        hRect.x2 = -oldX;
        hRect.y2 = -newY + nxagentOption(Height);
      }
      else if (hShift > 0)
      {
        hRect.x1 = -oldX + nxagentOption(Width);
        hRect.x2 = -newX + nxagentOption(Width);
        hRect.y2 = -newY + nxagentOption(Height);
      }

      #ifdef DEBUG
      fprintf(stderr, "nxagentMoveViewport: hRect p1[%i, %i] - p2[%i, %i].\n", hRect.x1, hRect.y1, hRect.x2, hRect.y2);
      #endif

      BoxRec vRect = {.x1 = -newX, .y1 = -newY};

      if (vShift < 0)
      {
        vRect.x2 = -newX + nxagentOption(Width);
        vRect.y2 = -oldY;
      }
      else if (vShift > 0)
      {
        vRect.y1 = -oldY + nxagentOption(Height);
        vRect.x2 = -newX + nxagentOption(Width);
        vRect.y2 = -newY + nxagentOption(Height);
      }

      #ifdef DEBUG
      fprintf(stderr, "nxagentMoveViewport: vRect p1[%i, %i] - p2[%i, %i].\n", vRect.x1, vRect.y1, vRect.x2, vRect.y2);
      #endif

      if (oldX != newX && hRect.x1 != hRect.x2 && hRect.y1 != hRect.y2)
      {
        nxagentAddRectToRemoteExposeRegion(&hRect);
      }

      if (oldY != newY && vRect.x1 != vRect.x2 && vRect.y1 != vRect.y2)
      {
        nxagentAddRectToRemoteExposeRegion(&vRect);
      }
    }
  }

  nxagentUpdateViewportFrame(-nxagentOption(RootX), -nxagentOption(RootY),
                                 nxagentOption(Width), nxagentOption(Height));
}

/*
 * This will update the window on the real X server by calling
 * XConfigureWindow()/XMapWindow()/XLowerWindow()/XRaiseWindow()
 * mask definesthe values that need to be updated, see e.g
 * man XConfigureWindow.
 *
 * In addition to the bit flags known to Xorg it uses these
 * self-defined ones: CW_Update, CW_Shape, CW_Map, CW_RootlessRestack.
 */
void nxagentConfigureWindow(WindowPtr pWin, unsigned int mask)
{
  unsigned int valuemask;
  XWindowChanges values;
  int offX = nxagentWindowPriv(pWin)->x - pWin->origin.x;
  int offY = nxagentWindowPriv(pWin)->y - pWin->origin.y;

  if (nxagentScreenTrap == 1)
  {
    #ifdef TEST
    fprintf(stderr, "nxagentConfigureWindow: WARNING: Called with the screen trap set.\n");
    #endif

    return;
  }

  if (nxagentOption(Rootless) == 1 &&
          nxagentWindowTopLevel(pWin) == 1)
  {
    mask &= ~(CWSibling | CWStackMode);
  }
  else
  {
    if (mask & CW_RootlessRestack)
    {
      mask = CWStackMode;
    }
  }

  #ifdef TEST
  fprintf(stderr, "nxagentConfigureWindow: Called with window [%p][%ld] and mask [%x].\n",
              (void *) pWin, nxagentWindow(pWin), mask);
  #endif

  nxagentMoveCorruptedRegion(pWin, mask);

  valuemask = 0;

  if (mask & CW_Update)
  {
    mask |= CWX | CWY | CWWidth | CWHeight | CWBorderWidth | CWStackMode;
  }

  if (mask & CWX)
  {
    valuemask |= CWX;

    values.x = nxagentWindowPriv(pWin)->x = pWin->origin.x - wBorderWidth(pWin);
  }

  if (mask & CWY)
  {
    valuemask |= CWY;

    values.y = nxagentWindowPriv(pWin)->y = pWin->origin.y - wBorderWidth(pWin);
  }

  if (mask & CWWidth)
  {
    valuemask |= CWWidth;

    values.width = nxagentWindowPriv(pWin)->width = pWin->drawable.width;
  }

  if (mask & CWHeight)
  {
    valuemask |= CWHeight;

    values.height = nxagentWindowPriv(pWin)->height = pWin->drawable.height;
  }

  if (mask & CWBorderWidth)
  {
    valuemask |= CWBorderWidth;

    values.border_width = nxagentWindowPriv(pWin)->borderWidth =
        pWin->borderWidth;
  }

  if (mask & CW_Update)
  {
    valuemask = 0;
  }

  if (valuemask)
  {
    #ifdef TEST
    fprintf(stderr, "nxagentConfigureWindow: Going to configure window [%p][%ld] with mask [%x].\n",
                (void *) pWin, nxagentWindow(pWin), valuemask);
    #endif

    if (pWin->bitGravity == StaticGravity &&
            ((mask & CWX) || (mask & CWY)) &&
                ((mask & CWWidth) || (mask & CWHeight)))
    {
      #ifdef TEST
      fprintf(stderr, "nxagentConfigureWindow: Window has StaticGravity. Going to translate Expose events by offset [%d, %d].\n",
                  offX, offY);
      #endif

      nxagentAddStaticResizedWindow(pWin, XNextRequest(nxagentDisplay), offX, offY);

      for (int j = 0; j < nxagentExposeQueue.length; j++)
      {
        int i = (nxagentExposeQueue.start + j) % EXPOSED_SIZE;

        if (nxagentExposeQueue.exposures[i].pWindow == pWin &&
                nxagentExposeQueue.exposures[i].remoteRegion != NullRegion)
        {
          RegionTranslate(nxagentExposeQueue.exposures[i].remoteRegion, offX, offY);
        }
      }
    }

    XConfigureWindow(nxagentDisplay, nxagentWindow(pWin), valuemask, &values);

    MAKE_SYNC_CONFIGURE_WINDOW;
  }

  if (mask & CWStackMode &&
          nxagentWindowPriv(pWin)->siblingAbove != nxagentWindowSiblingAbove(pWin))
  {
    WindowPtr pSib;

    /*
     * Find the top sibling.
     */

    for (pSib = pWin; pSib->prevSib != NullWindow; pSib = pSib->prevSib);

    /*
     * Configure the top sibling.
     */

    valuemask = CWStackMode;

    values.stack_mode = Above;

    #ifdef TEST
    fprintf(stderr, "nxagentConfigureWindow: Going to configure top sibling [%ld] "
                "with mask [%x] and parent [%ld].\n", nxagentWindow(pSib),
                    valuemask, nxagentWindowParent(pWin));
    #endif

    XConfigureWindow(nxagentDisplay, nxagentWindow(pSib), valuemask, &values);

    MAKE_SYNC_CONFIGURE_WINDOW;

    nxagentWindowPriv(pSib)->siblingAbove = None;

    /*
     * Configure the rest of siblings.
     */

    valuemask = CWSibling | CWStackMode;

    values.stack_mode = Below;

    for (pSib = pSib->nextSib; pSib != NullWindow; pSib = pSib->nextSib)
    {
      values.sibling = nxagentWindowSiblingAbove(pSib);

      #ifdef TEST
      fprintf(stderr, "nxagentConfigureWindow: Going to configure other sibling [%ld] "
                  "with mask [%x] and parent [%ld] below [%ld].\n", nxagentWindow(pSib),
                      valuemask, nxagentWindowParent(pWin), nxagentWindowSiblingAbove(pSib));
      #endif

      XConfigureWindow(nxagentDisplay, nxagentWindow(pSib), valuemask, &values);

      MAKE_SYNC_CONFIGURE_WINDOW;

      nxagentWindowPriv(pSib)->siblingAbove = nxagentWindowSiblingAbove(pSib);
    }

    #ifdef TEST
    {
      Window root_return;
      Window parent_return;
      Window *children_return = NULL;
      unsigned int nchildren_return;
      Status result;

      result = XQueryTree(nxagentDisplay, DefaultRootWindow(nxagentDisplay),
                              &root_return, &parent_return, &children_return, &nchildren_return);

      if (result)
      {
        fprintf(stderr, "nxagentConfigureWindow: Children of the root: ");
        while(nchildren_return > 0)
        {
          pSib = nxagentWindowPtr(children_return[--nchildren_return]);
          if (pSib)
          {
            fprintf(stderr, "%lu  ", children_return[nchildren_return]);
          }
        }
        fprintf(stderr, "\n");
      }
      else
      {
        fprintf(stderr, "nxagentConfigureWindow: Failed QueryTree request.\n ");
      }

      SAFE_XFree(children_return);
    }
    #endif
  }

  /*
   * This should bring again the splash window
   * on top, so why the else clause? Is this
   * really needed?
   *
   *
   *  else if (mask & CWStackMode)
   *  {
   *    if (nxagentSplashWindow)
   *    {
   *      valuemask = CWStackMode;
   *
   *      values.stack_mode = Above;
   *
   *      #ifdef TEST
   *      fprintf(stderr, "nxagentConfigureWindow: Going to configure splash window [%ld].\n",
   *                  nxagentSplashWindow);
   *      #endif
   *
   *      XConfigureWindow(nxagentDisplay, nxagentSplashWindow, valuemask, &values);
   *
   *      MAKE_SYNC_CONFIGURE_WINDOW;
   *    }
   *  }
   */

  if (mask & CW_RootlessRestack)
  {
    if (!pWin -> prevSib)
    {
      #ifdef TEST
      fprintf(stderr, "nxagentConfigureWindow: Raising window [%p][%ld].\n",
                  (void *) pWin, nxagentWindow(pWin));
      #endif

      XRaiseWindow(nxagentDisplay, nxagentWindow(pWin));
    }
    else if (!pWin -> nextSib)
    {
      #ifdef TEST
      fprintf(stderr, "nxagentConfigureWindow: Lowering window [%p][%ld].\n",
                  (void *) pWin, nxagentWindow(pWin));
      #endif

      XLowerWindow(nxagentDisplay, nxagentWindow(pWin));
    }
    else
    {
      XlibWindow windowList[2];

      #ifdef TEST
      fprintf(stderr, "nxagentConfigureWindow: Putting window [%p][%ld] in the middle.\n",
                  (void *) pWin, nxagentWindow(pWin));
      #endif

      windowList[0] = nxagentWindow(pWin->prevSib);
      windowList[1] = nxagentWindow(pWin);

      XRestackWindows(nxagentDisplay, windowList, 2);
    }
  }

  #ifdef SHAPE
  if (mask & CW_Shape)
  {
    nxagentShapeWindow(pWin);
  }
  #endif

  if (mask & CW_Map &&
         (!nxagentOption(Rootless) ||
             nxagentRootlessWindow != pWin))
  {
    XMapWindow(nxagentDisplay, nxagentWindow(pWin));
    return;
  }
}

/*
 * from "Definition of the Porting Layer for X v11 Sample Server":
 *
 * This function will be called when a window is reparented. At the
 * time of the call, pWin will already be spliced into its new
 * position in the window tree, and pPriorParent is its previous
 * parent. This function can be NULL.
 *
 * We simply pass this pver to the real X server.
 */
void nxagentReparentWindow(WindowPtr pWin, WindowPtr pOldParent)
{
  if (nxagentScreenTrap)
  {
    return;
  }

  #ifdef TEST
  fprintf(stderr, "nxagentReparentWindow:  window at %p [%lx] previous parent at %p [%lx].\n",
              (void*)pWin, nxagentWindow(pWin),
                  (void*)pOldParent, nxagentWindow(pOldParent));
  #endif

  XReparentWindow(nxagentDisplay, nxagentWindow(pWin),
                      nxagentWindowParent(pWin),
                          pWin->origin.x - wBorderWidth(pWin),
                              pWin->origin.y - wBorderWidth(pWin));
}

/*
 * from "Definition of the Porting Layer for X v11 Sample Server":
 *
 * ChangeWindowAttributes is called whenever DIX changes window
 * attributes, such as the size, front-to-back ordering, title, or
 * anything of lesser severity that affects the window itself. The
 * sample server implements this routine. It computes accelerators for
 * quickly putting up background and border tiles. (See description of
 * the set of routines stored in the WindowRec.)
 */
Bool nxagentChangeWindowAttributes(WindowPtr pWin, unsigned long mask)
{
  XSetWindowAttributes attributes;

  #ifdef TEST
  fprintf(stderr, "nxagentChangeWindowAttributes: Changing attributes for window at [%p] with mask [%lu].\n",
              (void *) pWin, mask);
  #endif

  if (nxagentScreenTrap)
  {
    return True;
  }

  if (mask & CWBackPixmap)
  {
    switch (pWin->backgroundState)
    {
      case None:
      {
        attributes.background_pixmap = None;
        attributes.background_pixel = nxagentWhitePixel;

        /*
         * One of problems faced during the implementation of lazy
         * encoding policies was due to the presence of windows with
         * transparent background, usually created by X clients to
         * cover some sensible areas (i.e. checkboxes used by
         * Konqueror 3.5). The sequence of operations consists in
         * drawing the underneath part before covering it with the
         * transparent window, so when we synchronize the deferred
         * drawing operation we have to bear in mind that the dest-
         * ination area is covered by a window. By using the Inclu-
         * deInferiors GC's property and by clipping the region to
         * synchronize to the borderClip instead of clipList (to
         * include the areas covered by children) we can easily take
         * care of this situation, but there is a drawback: if the
         * children are not transparent, we are going to synchronize
         * invisible areas. To avoid this we have added the 'has-
         * TransparentChildren' flag, which is set when a window has
         * at least one child with background None. The problem is
         * that we don't know when to reset the flag. This solution,
         * also, doesn't take care of transparent windows which don't
         * have childhood relationships with underneath windows.
         * We tried to mark the whole windows as dirty when they are
         * created to force the synchronization of transparent windows
         * with the content of underneath windows, but, of course,
         * this works only with the first synchronization because the
         * transparent windows will be never marked again as dirty.
         */

        if (pWin -> parent != NULL)
        {
          nxagentWindowPriv(pWin -> parent) -> hasTransparentChildren = 1;

          #ifdef DEBUG
          fprintf(stderr, "nxagentChangeWindowAttributes: WARNING! Window at [%p] got the "
                      "hasTransparentChildren flag.\n", (void *) pWin);
          #endif
        }

        break;
      }
      case ParentRelative:
      {
        attributes.background_pixmap = ParentRelative;

        break;
      }
      case BackgroundPixmap:
      {
        /*
         * If a window background is corrupted, we grant
         * its usability by clearing it with a solid co-
         * lor. When the pixmap will be fully synchroni-
         * zed, an expose will be sent to the window's
         * hierarchy.
         */

        if (nxagentDrawableStatus((DrawablePtr) pWin -> background.pixmap) == NotSynchronized)
        {
          #ifdef TEST
          fprintf(stderr, "nxagentChangeWindowAttributes: The window at [%p] has the background at [%p] "
                      "not synchronized.\n", (void *) pWin, (void *) pWin -> background.pixmap);
          #endif

          if (nxagentIsCorruptedBackground(pWin -> background.pixmap) == 0)
          {
            nxagentIsCorruptedBackground(pWin -> background.pixmap) = 1;

            nxagentAllocateCorruptedResource((DrawablePtr) pWin -> background.pixmap, RT_NX_CORR_BACKGROUND);

            /*
             * Clearing the remote background to
             * make it usable.
             */

            nxagentFillRemoteRegion((DrawablePtr) pWin -> background.pixmap,
                                        nxagentCorruptedRegion((DrawablePtr) pWin -> background.pixmap));
          }
        }

        attributes.background_pixmap = nxagentPixmap(pWin -> background.pixmap);

        break;
      }
      case BackgroundPixel:
      {
        mask &= ~CWBackPixmap;

        break;
      }
    }
  }

  if (mask & CWBackPixel)
  {
    if (pWin -> backgroundState == BackgroundPixel)
    {
      attributes.background_pixel = nxagentPixel(pWin -> background.pixel);
    }
    else
    {
      mask &= ~CWBackPixel;
    }
  }

  if (mask & CWBorderPixmap)
  {
    if (pWin -> borderIsPixel != 0)
    {
      mask &= ~CWBorderPixmap;
    }
    else
    {
      attributes.border_pixmap = nxagentPixmap(pWin -> border.pixmap);
    }
  }

  if (mask & CWBorderPixel)
  {
    if (pWin -> borderIsPixel != 0)
    {
      attributes.border_pixel = nxagentPixel(pWin -> border.pixel);
    }
    else
    {
      mask &= ~CWBorderPixel;
    }
  }

  if (mask & CWBitGravity)
  {
    attributes.bit_gravity = pWin -> bitGravity;
  }

  /*
   * As we set this bit, we must change dix in
   * order not to perform PositionWindow and let
   * X move children windows for us.
   */

  if (mask & CWWinGravity)
  {
    attributes.win_gravity = pWin -> winGravity;
  }

  /*
    FIXME: Do we need to set the attribute on the
           remote display?
  */
  if (mask & CWBackingStore)
  {
    attributes.backing_store = pWin -> backingStore;

    #ifdef TEST
    fprintf(stderr, "nxagentChangeWindowAttributes: Changing backing store value to %d"
                " for window at %p.\n", pWin -> backingStore, (void*)pWin);
    #endif
  }

  if (mask & CWBackingPlanes)
  {
    if ((nxagentBackingStore == NotUseful) || (pWin -> optional == NULL))
    {
      mask &= ~CWBackingPlanes;
    }
    else
    {
      attributes.backing_planes = pWin -> optional -> backingBitPlanes;
    }
  }

  if (mask & CWBackingPixel)
  {
    if ((nxagentBackingStore == NotUseful) || (pWin -> optional == NULL))
    {
      mask &= ~CWBackingPixel;
    }
    else
    {
      attributes.backing_pixel = pWin -> optional -> backingPixel;
    }
  }

  if (mask & CWOverrideRedirect)
  {
    attributes.override_redirect = pWin -> overrideRedirect;
  }

  /*
    FIXME: Do we need to set the attribute on the
           remote display?
  */
  if (mask & CWSaveUnder)
  {
    attributes.save_under = pWin -> saveUnder;
  }

  /*
   * Events are handled elsewhere.
   */

  if (mask & CWEventMask)
  {
    mask &= ~CWEventMask;
  }

  if (mask & CWDontPropagate)
  {
    mask &= ~CWDontPropagate;
  }

  if (mask & CWColormap)
  {
    ColormapPtr pCmap = (ColormapPtr) LookupIDByType(wColormap(pWin), RT_COLORMAP);

    /*
      FIXME: When the caller is nxagentReconfigureWindow
             sometimes wColormap(pWin) is 0. Could a window
             have no colormap?
    */
    if (pCmap != NULL)
    {
      attributes.colormap = nxagentColormap(pCmap);

      nxagentSetInstalledColormapWindows(pWin -> drawable.pScreen);
    }
    else
    {
      #ifdef WARNING
      fprintf(stderr, "nxagentChangeWindowAttributes: WARNING! Bad colormap "
                  "[%lu] for window at [%p].\n", wColormap(pWin), (void *) pWin);
      #endif

      mask &= ~CWColormap;
    }
  }

  if (mask & CWCursor)
  {
    if (nxagentOption(Rootless))
    {
      if (pWin->cursorIsNone == 0 && pWin->optional != NULL &&
              pWin->optional->cursor != NULL && nxagentCursorPriv(pWin ->
                  optional -> cursor, pWin -> drawable.pScreen) != NULL)
      {
        attributes.cursor = nxagentCursor(pWin -> optional -> cursor,
                                              pWin -> drawable.pScreen);
      }
      else
      {
        attributes.cursor = None;
      }
    }
    else
    {
      /*
       * This is handled in cursor code
       */

      mask &= ~CWCursor;
    }
  }

  if (mask != 0)
  {
    XChangeWindowAttributes(nxagentDisplay, nxagentWindow(pWin), mask, &attributes);
  }

  return 1;
}

/* Set the WM_STATE property of pWin to the desired value */
void nxagentSetWMState(WindowPtr pWin, CARD32 desired)
{
  Atom prop = MakeAtom("WM_STATE", strlen("WM_STATE"), True);
  nxagentWMStateRec wmState = {.state = desired, .icon = None};
  if (ChangeWindowProperty(pWin, prop, prop, 32, 0, 2, &wmState, 1) != Success)
  {
    #ifdef WARNING
    fprintf(stderr, "%s: Changing WM_STATE failed.\n", __func__);
    #endif
  }
}

/*
 * from "Definition of the Porting Layer for X v11 Sample Server":
 *
 * RealizeWindow/UnRealizeWindow:
 * These routines are hooks for when DIX maps (makes visible) and
 * unmaps (makes invisible) a window. It should do whatever private
 * operations need to be done when these happen, such as allocating or
 * deallocating structures that are only needed for visible
 * windows. RealizeWindow does NOT draw the window border, background
 * or contents; UnrealizeWindow does NOT erase the window or generate
 * exposure events for underlying windows; this is taken care of by
 * DIX. DIX does, however, call PaintWindowBackground() and
 * PaintWindowBorder() to perform some of these.
-+ */
Bool nxagentRealizeWindow(WindowPtr pWin)
{
  if (nxagentScreenTrap == 1)
  {
    return True;
  }

  /*
   * Not needed.
   *
   * nxagentConfigureWindow(pWin, CWStackMode);
   *
   * nxagentFlushConfigureWindow();
   */

  nxagentAddConfiguredWindow(pWin, CWStackMode);
  nxagentAddConfiguredWindow(pWin, CW_Shape);

  /* add by dimbor */
  if (nxagentOption(Rootless) && nxagentWindowTopLevel(pWin))
  {
    nxagentSetWMState(pWin, NormalState);
  }

  /*
   * Not needed.
   *
    #ifdef SHAPE
    nxagentShapeWindow(pWin);
    #endif
   */

  #ifdef TEST
  if (nxagentOption(Rootless) && nxagentLastWindowDestroyed)
  {
    fprintf(stderr, "%s: Window realized. Stopped termination for rootless session.\n", __func__);
  }
  #endif

  nxagentAddConfiguredWindow(pWin, CW_Map);

  nxagentLastWindowDestroyed = False;

  return True;
}

/* See nxagentRealizeWindow for a description */
Bool nxagentUnrealizeWindow(WindowPtr pWin)
{
  if (nxagentScreenTrap)
  {
    return True;
  }

  /* add by dimbor */
  if (nxagentOption(Rootless) && nxagentWindowTopLevel(pWin))
  {
    /*
     * The original _comment_ was WithdrawnState, while the _value_
     * was 3, which is IconicState.
     */
    nxagentSetWMState(pWin, IconicState);
  }

  XUnmapWindow(nxagentDisplay, nxagentWindow(pWin));

  return True;
}

void nxagentFrameBufferPaintWindow(WindowPtr pWin, RegionPtr pRegion, int what)
{
  if (pWin->backgroundState == BackgroundPixmap)
  {
    pWin->background.pixmap = nxagentVirtualPixmap(pWin->background.pixmap);
  }

  if (pWin->borderIsPixel == False)
  {
    pWin->border.pixmap = nxagentVirtualPixmap(pWin->border.pixmap);
  }

  /*
   * Call fbPaintWindow(). We need to temporarily replace
   * PaintWindowBackground() by ourself because fbPaintWindow() is
   * recursively calling it for parent windows, too.
   */
  {
    void (*PaintWindowBackgroundBackup)(WindowPtr, RegionPtr, int);

    PaintWindowBackgroundBackup = pWin->drawable.pScreen -> PaintWindowBackground;

    pWin->drawable.pScreen -> PaintWindowBackground = nxagentFrameBufferPaintWindow;

    fbPaintWindow(pWin, pRegion, what);

    pWin->drawable.pScreen -> PaintWindowBackground = PaintWindowBackgroundBackup;
  }

  if (pWin->backgroundState == BackgroundPixmap)
  {
    pWin->background.pixmap = nxagentRealPixmap(pWin->background.pixmap);
  }

  if (pWin->borderIsPixel == False)
  {
    pWin->border.pixmap = nxagentRealPixmap(pWin->border.pixmap);
  }
}

void nxagentPaintWindowBackground(WindowPtr pWin, RegionPtr pRegion, int what)
{
  RegionRec temp;

  if (pWin -> realized)
  {
    BoxPtr pBox = RegionRects(pRegion);

    for (int i = 0; i < RegionNumRects(pRegion); i++)
    {
      XClearArea(nxagentDisplay, nxagentWindow(pWin),
                 pBox[i].x1 - pWin->drawable.x,
                 pBox[i].y1 - pWin->drawable.y,
                 pBox[i].x2 - pBox[i].x1,
                 pBox[i].y2 - pBox[i].y1,
                 False);
    }
  }
  #ifdef TEST
  else
  {
    fprintf(stderr, "nxagentPaintWindowBackground: Saving the operation with window "
                "at [%p] not realized.\n", (void *) pWin);
  }
  #endif

  /*
   * The framebuffer operations don't take care of
   * clipping to the actual area of the framebuffer
   * so we need to clip ourselves.
   */

  RegionInit(&temp, NullBox, 1);
  RegionIntersect(&temp, pRegion, &pWin -> clipList);
  nxagentFrameBufferPaintWindow(pWin, &temp, what);
  RegionUninit(&temp);
}

void nxagentPaintWindowBorder(WindowPtr pWin, RegionPtr pRegion, int what)
{
  RegionRec temp;

  /*
   * The framebuffer operations don't take care of
   * clipping to the actual area of the framebuffer
   * so we need to clip ourselves.
   */

  RegionInit(&temp, NullBox, 1);
  RegionIntersect(&temp, pRegion, &pWin -> borderClip);
  nxagentFrameBufferPaintWindow(pWin, &temp, what);
  RegionUninit(&temp);
}

/*
 * from "Definition of the Porting Layer for X v11 Sample Server":
 *
 * CopyWindow is called when a window is moved, and graphically moves
 * to pixels of a window on the screen. It should not change any other
 * state within DDX (see PositionWindow(), above).
 *
 * oldpt is the old location of the upper-left corner. oldRegion is
 * the old region it is coming from. The new location and new region
 * is stored in the WindowRec. oldRegion might modified in place by
 * this routine (the sample implementation does this).
 *
 * CopyArea could be used, except that this operation has more
 * complications. First of all, you do not want to copy a rectangle
 * onto a rectangle. The original window may be obscured by other
 * windows, and the new window location may be similarly
 * obscured. Second, some hardware supports multiple windows with
 * multiple depths, and your routine needs to take care of that.
 *
 * The pixels in oldRegion (with reference point oldpt) are copied to
 * the window's new region (pWin->borderClip). pWin->borderClip is
 * gotten directly from the window, rather than passing it as a
 * parameter.
 *
 * The sample server implementation is in Xserver/fb/fbwindow.c.
 */
void nxagentCopyWindow(WindowPtr pWin, xPoint oldOrigin, RegionPtr oldRegion)
{
  fbCopyWindow(pWin, oldOrigin, oldRegion);
}

/*
 * from "Definition of the Porting Layer for X v11 Sample Server":
 *
 * Whenever the cliplist for a window is changed, this function is
 * called to perform whatever hardware manipulations might be
 * necessary. When called, the clip list and border clip regions in
 * the window are set to the new values. dx,dy are the distance that
 * the window has been moved (if at all).
 */
void nxagentClipNotify(WindowPtr pWin, int dx, int dy)
{
  /*
   * nxagentConfigureWindow(pWin, CWStackMode);
   */

  nxagentAddConfiguredWindow(pWin, CWStackMode);
  nxagentAddConfiguredWindow(pWin, CW_Shape);

  #ifndef NXAGENT_SHAPE
    #ifdef SHAPE
    /*
     * nxagentShapeWindow(pWin);
     */
    #endif /* SHAPE */
  #endif /* NXAGENT_SHAPE */
}

/*
 * from "Definition of the Porting Layer for X v11 Sample Server":
 *
 * The WindowExposures() routine paints the border and generates
 * exposure events for the window. pRegion is an unoccluded region of
 * the window, and pBSRegion is an occluded region that has backing
 * store. Since exposure events include a rectangle describing what
 * was exposed, this routine may have to send back a series of
 * exposure events, one for each rectangle of the region. The count
 * field in the expose event is a hint to the client as to the number
 * of regions that are after this one. This routine must be
 * provided. The sample server has a machine-independent version in
 * Xserver/mi/miexpose.c.
 */
void nxagentWindowExposures(WindowPtr pWin, RegionPtr pRgn, RegionPtr other_exposed)
{
  /*
   * The problem: we want to synthetize the expose events internally, so
   * that we reduce the time between a window operation and the corresp-
   * onding graphical output, but at the same time we need to take care
   * of the remote exposures, as we need to handle those cases where our
   * windows are covered by the windows on the real display. Handling
   * both the local and the remote exposures we would generate the same
   * redraws twice, something we call "double refreshes", so we must be
   * able to identify which events have been already sent to our clients.
   *
   * Here is how the algorithm is working:
   *
   * - We collect the exposures that the agent sent to its clients in a
   *   region (the "local-region") and store the region for a given win-
   *   dow in a vector.
   *
   * - Another region collects the expose that were received from the
   *   real X server (the "remote-region") for the same window.
   *
   * - We create a "fake" off-screen window. For every generated region
   *   we send a ConfigureWindow request for that window to synchronize
   *   ourselves with both the remote X server and/or the window manager.
   *
   * - When the ConfigureNotify is received, we calculate the difference
   *   between the "remote-region" and the "local-region" for the window
   *   that had collected exposures.
   *
   * - Finally we send the resulting exposures to our clients.
   *
   * As you may have guessed, the windows are synchronized per-region,
   * that is there is a single region for a set of exposures. The regions
   * are handled in order. This means that we can always calculate the
   * final region by referring to the first element of the vector.
   */

  RegionRec temp;
  BoxRec box;

  if (nxagentSessionState != SESSION_DOWN)
  {
    if (nxagentExposeArrayIsInitialized == 0)
    {
      #ifdef TEST
      fprintf(stderr, "nxagentWindowExposures: Initializing expose queue.\n");
      #endif

      for (int i = 0; i < EXPOSED_SIZE; i++)
      {
        nxagentExposeQueue.exposures[i].pWindow = NULL;
        nxagentExposeQueue.exposures[i].localRegion = NullRegion;
        nxagentExposeQueue.exposures[i].remoteRegion = NullRegion;
        nxagentExposeQueue.exposures[i].remoteRegionIsCompleted = False;
        nxagentExposeQueue.exposures[i].serial = 0;
      }

      nxagentExposeQueue.start = 0;
      nxagentExposeQueue.length = 0;
      nxagentExposeSerial = 0;

      XSetWindowAttributes attributes = {.event_mask = StructureNotifyMask};
      nxagentConfiguredSynchroWindow = XCreateWindow(nxagentDisplay, DefaultRootWindow(nxagentDisplay), 0, 0,
                                                           1, 1, 0, 0, InputOutput, 0, CWEventMask, &attributes);

      nxagentInitRemoteExposeRegion();

      nxagentExposeArrayIsInitialized = 1;
    }

    RegionInit(&temp, (BoxRec *) NULL, 1);

    if (pRgn != NULL)
    {
      if (RegionNumRects(pRgn) > RECTLIMIT)
      {
        box = *RegionExtents(pRgn);

        RegionEmpty(pRgn);
        RegionInit(pRgn, &box, 1);
      }

      RegionUnion(&temp, &temp, pRgn);
    }

    if (other_exposed != NULL)
    {
      RegionUnion(&temp, &temp, other_exposed);
    }

    if (RegionNil(&temp) == 0)
    {
      RegionTranslate(&temp,
                           -(pWin -> drawable.x), -(pWin -> drawable.y));

      if (nxagentExposeQueue.length < EXPOSED_SIZE)
      {
        int index = (nxagentExposeQueue.start + nxagentExposeQueue.length) % EXPOSED_SIZE;

        nxagentExposeQueue.exposures[index].pWindow = pWin;
        nxagentExposeQueue.exposures[index].localRegion = RegionCreate(NULL, 1);

        if (nxagentOption(Rootless) && nxagentWindowPriv(pWin) &&
                (nxagentWindowPriv(pWin) -> isMapped == 0 ||
                     nxagentWindowPriv(pWin) -> visibilityState != VisibilityUnobscured))
        {
          nxagentExposeQueue.exposures[index].remoteRegion = RegionCreate(NULL, 1);

          RegionUnion(nxagentExposeQueue.exposures[index].remoteRegion,
                           nxagentExposeQueue.exposures[index].remoteRegion, &temp);

          #ifdef TEST
          fprintf(stderr, "nxagentWindowExposures: Added region to remoteRegion for window [%ld] to position [%d].\n",
                      nxagentWindow(pWin), nxagentExposeQueue.length);
          #endif
        }
        else
        {
          RegionUnion(nxagentExposeQueue.exposures[index].localRegion,
                           nxagentExposeQueue.exposures[index].localRegion, &temp);

          #ifdef TEST
          fprintf(stderr, "nxagentWindowExposures: Added region to localRegion for window [%ld] to position [%d].\n",
                      nxagentWindow(pWin), nxagentExposeQueue.length);
          #endif
        }

        nxagentExposeSerial = (nxagentExposeSerial - 1) % EXPOSED_SIZE;

        nxagentExposeQueue.exposures[index].serial = nxagentExposeSerial;

        #ifdef TEST
        fprintf(stderr, "nxagentWindowExposures: Added region to queue with serial [%d].\n", nxagentExposeSerial);
        #endif

        /*
         * Mark this region for sending a synchro,
         * in nxagentFlushConfigureWindow().
         */

        nxagentExposeQueue.exposures[index].synchronize = 1;
        nxagentExposeQueue.length++;

        if (nxagentOption(Rootless) && nxagentWindowPriv(pWin) &&
                (nxagentWindowPriv(pWin) -> isMapped == 0 ||
                     nxagentWindowPriv(pWin) -> visibilityState != VisibilityUnobscured))
        {
          RegionUninit(&temp);

          return;
        }
      }
      else
      {
        RegionUninit(&temp);

        #ifdef TEST
        fprintf(stderr, "nxagentWindowExposures: WARNING! Reached maximum size of collect exposures vector.\n");
        #endif

        if ((pRgn != NULL && RegionNotEmpty(pRgn) != 0) ||
               (other_exposed != NULL && RegionNotEmpty(other_exposed) != 0))
        {
          nxagentUnmarkExposedRegion(pWin, pRgn, other_exposed);

          miWindowExposures(pWin, pRgn, other_exposed);
        }

        return;
      }
    }

    RegionUninit(&temp);
  }

  if ((pRgn != NULL && RegionNotEmpty(pRgn) != 0) ||
         (other_exposed != NULL && RegionNotEmpty(other_exposed) != 0))
  {
    nxagentUnmarkExposedRegion(pWin, pRgn, other_exposed);

    miWindowExposures(pWin, pRgn, other_exposed);
  }

  return;
}

#ifdef SHAPE
static Bool nxagentRegionEqual(RegionPtr pReg1, RegionPtr pReg2)
{
  BoxPtr pBox1, pBox2;
  unsigned int n1, n2;

  if (pReg1 == pReg2)
  {
    return True;
  }

  if (pReg1 == NullRegion || pReg2 == NullRegion)
  {
    return False;
  }

  pBox1 = RegionRects(pReg1);
  n1 = RegionNumRects(pReg1);

  pBox2 = RegionRects(pReg2);
  n2 = RegionNumRects(pReg2);

  if (n1 != n2)
  {
    return False;
  }

  if (pBox1 == pBox2)
  {
    return True;
  }

  if (memcmp(pBox1, pBox2, n1 * sizeof(BoxRec)))
  {
    return False;
  }

  return True;
}

void nxagentShapeWindow(WindowPtr pWin)
{
  Region reg;
  BoxPtr pBox;

  if (NXDisplayError(nxagentDisplay) == 1)
  {
    return;
  }

  #ifdef DEBUG
  fprintf(stderr, "nxagentShapeWindow: Window at [%p][%ld].\n",
              (void *) pWin, nxagentWindow(pWin));
  #endif

  /*
    FIXME: this is the same code as below, just with another shape. Maybe move
    this code to a helper function?
   */
  if (!nxagentRegionEqual(nxagentWindowPriv(pWin)->boundingShape,
                        wBoundingShape(pWin)))
  {
    #ifdef DEBUG
    fprintf(stderr, "nxagentShapeWindow: Bounding shape differs.\n");
    #endif

    if (wBoundingShape(pWin))
    {
      #ifdef DEBUG
      fprintf(stderr, "nxagentShapeWindow: wBounding shape has [%ld] rects.\n",
                  RegionNumRects(wBoundingShape(pWin)));
      #endif

      #ifdef NXAGENT_SHAPE2
      if (!nxagentWindowPriv(pWin)->boundingShape)
      {
        nxagentWindowPriv(pWin)->boundingShape = RegionCreate(NULL, 1);
      }
      #endif

      RegionCopy(nxagentWindowPriv(pWin)->boundingShape, wBoundingShape(pWin));

      reg = XCreateRegion();
      pBox = RegionRects(nxagentWindowPriv(pWin)->boundingShape);
      for (int i = 0;
           i < RegionNumRects(nxagentWindowPriv(pWin)->boundingShape);
           i++)
      {
        XRectangle rect = {
          .x = pBox[i].x1,
          .y = pBox[i].y1,
          .width = pBox[i].x2 - pBox[i].x1,
          .height = pBox[i].y2 - pBox[i].y1
        };
        XUnionRectWithRegion(&rect, reg, reg);
      }

      #ifndef NXAGENT_SHAPE
      XShapeCombineRegion(nxagentDisplay, nxagentWindow(pWin),
                              ShapeBounding, 0, 0, reg, ShapeSet);
      #endif

      XDestroyRegion(reg);
    }
    else
    {
      #ifdef DEBUG
      fprintf(stderr, "nxagentShapeWindow: wBounding shape does not exist. Removing the shape.\n");
      #endif

      RegionEmpty(nxagentWindowPriv(pWin)->boundingShape);

      #ifndef NXAGENT_SHAPE
      XShapeCombineMask(nxagentDisplay, nxagentWindow(pWin),
                            ShapeBounding, 0, 0, None, ShapeSet);
      #endif
    }
  }

  if (!nxagentRegionEqual(nxagentWindowPriv(pWin)->clipShape, wClipShape(pWin)))
  {
    #ifdef DEBUG
    fprintf(stderr, "nxagentShapeWindow: Clip shape differs.\n");
    #endif

    if (wClipShape(pWin))
    {
      #ifdef DEBUG
      fprintf(stderr, "nxagentShapeWindow: wClip shape has [%ld] rects.\n",
                  RegionNumRects(wClipShape(pWin)));
      #endif

      #ifdef NXAGENT_SHAPE2
      if (!nxagentWindowPriv(pWin)->clipShape)
      {
        nxagentWindowPriv(pWin)->clipShape = RegionCreate(NULL, 1);
      }
      #endif

      RegionCopy(nxagentWindowPriv(pWin)->clipShape, wClipShape(pWin));

      reg = XCreateRegion();
      pBox = RegionRects(nxagentWindowPriv(pWin)->clipShape);
      for (int i = 0;
           i < RegionNumRects(nxagentWindowPriv(pWin)->clipShape);
           i++)
      {
        XRectangle rect = {
          .x = pBox[i].x1,
          .y = pBox[i].y1,
          .width = pBox[i].x2 - pBox[i].x1,
          .height = pBox[i].y2 - pBox[i].y1
        };
        XUnionRectWithRegion(&rect, reg, reg);
      }

      #ifndef NXAGENT_SHAPE
      XShapeCombineRegion(nxagentDisplay, nxagentWindow(pWin),
                              ShapeClip, 0, 0, reg, ShapeSet);
      #endif

      XDestroyRegion(reg);
    }
    else
    {
      #ifdef DEBUG
      fprintf(stderr, "nxagentShapeWindow: wClip shape does not exist. Removing the shape.\n");
      #endif

      RegionEmpty(nxagentWindowPriv(pWin)->clipShape);

      #ifndef NXAGENT_SHAPE
      XShapeCombineMask(nxagentDisplay, nxagentWindow(pWin),
                            ShapeClip, 0, 0, None, ShapeSet);
      #endif
    }
  }
}
#endif /* SHAPE */

static int nxagentForceExposure(WindowPtr pWin, void * ptr)
{
  if (pWin -> drawable.class != InputOnly)
  {
    WindowPtr pRoot = pWin->drawable.pScreen->root;
    BoxRec Box = {
      .x1 = pWin->drawable.x,
      .y1 = pWin->drawable.y,
      .x2 = Box.x1 + pWin->drawable.width,
      .y2 = Box.y1 + pWin->drawable.height,
    };
    RegionPtr exposedRgn = RegionCreate(&Box, 1);

    RegionIntersect(exposedRgn, exposedRgn, &pRoot->winSize);

    if (exposedRgn != NULL && RegionNotEmpty(exposedRgn) != 0)
    {
      miWindowExposures(pWin, exposedRgn, NullRegion);
    }

    RegionDestroy(exposedRgn);
  }

  return WT_WALKCHILDREN;
}

void nxagentRefreshWindows(WindowPtr pWin)
{
  int action = 1;

  TraverseTree(pWin, nxagentForceExposure, &action);
}

void nxagentUnmapWindows(void)
{
  if (nxagentOption(Fullscreen) == 1)
  {
    for (int i = 0; i < screenInfo.numScreens; i++)
    {
      if (nxagentDefaultWindows[i])
      {
        XUnmapWindow(nxagentDisplay, nxagentDefaultWindows[i]);
      }
    }
  }

  NXFlushDisplay(nxagentDisplay, NXFlushLink);
}

void nxagentMapDefaultWindows(void)
{
  for (int i = 0; i < screenInfo.numScreens; i++)
  {
    WindowPtr pWin = screenInfo.screens[i]->root;
    ScreenPtr pScreen = pWin -> drawable.pScreen;

    MapWindow(pWin, serverClient);

    if (nxagentOption(Rootless) == 0)
    {
      /*
       * Show the NX splash screen.
       */

      #ifdef TEST
      fprintf(stderr, "nxagentMapDefaultWindows: Showing the splash window.\n");
      #endif

      nxagentShowSplashWindow(nxagentDefaultWindows[pScreen->myNum]);

      /*
       * Map the default window. Defer the mapping if the session is
       * of shadow type. If no WM is running on the remote display,
       * map the window soon anyway: this avoids a flickering effect
       * on the !M logo if the shadow session is displayed from a
       * Windows client.
       */

      if (nxagentOption(Shadow) == 0 || !nxagentWMIsRunning)
      {
        #ifdef TEST
        fprintf(stderr, "nxagentMapDefaultWindows: Mapping default window id [%ld].\n",
                    nxagentDefaultWindows[pScreen->myNum]);
        #endif

        XMapWindow(nxagentDisplay, nxagentDefaultWindows[pScreen->myNum]);

        if (nxagentOption(Fullscreen) == 1 && nxagentWMIsRunning)
        {
          nxagentMaximizeToFullScreen(pScreen);
        }
      }

      /*
       * Map and raise the input window.
       */

      XMapWindow(nxagentDisplay, nxagentInputWindows[pScreen->myNum]);

      /*
       * At reconnection the Input Window is
       * raised in nxagentReconnectAllWindows,
       * after the Root Window is mapped.
       */

      if (nxagentReconnectTrap == 0)
      {
        XRaiseWindow(nxagentDisplay, nxagentInputWindows[pScreen->myNum]);
      }
    }

    /*
     * Send a SetSelectionOwner request
     * to notify of the agent start.
     */

    XSetSelectionOwner(nxagentDisplay, serverCutProperty,
                           nxagentDefaultWindows[i], CurrentTime);
  }

  /*
   * Map the icon window.
   */

  if (nxagentIconWindow != None)
  {
    #ifdef TEST
    fprintf(stderr, "nxagentMapDefaultWindows: Mapping icon window id [%ld].\n",
                nxagentIconWindow);
    #endif

    XMapWindow(nxagentDisplay, nxagentIconWindow);
  }

  /*
   * Ensure that the fullscreen window gets the focus.
   */

  if (nxagentFullscreenWindow != 0)
  {
    XSetInputFocus(nxagentDisplay, nxagentFullscreenWindow,
                       RevertToParent, CurrentTime);
  }

  #ifdef TEST
  fprintf(stderr, "nxagentMapDefaultWindows: Completed mapping of default windows.\n");
  #endif
}

Bool nxagentDisconnectAllWindows(void)
{
  Bool succeeded = True;

  #if defined(NXAGENT_RECONNECT_DEBUG) || defined(NXAGENT_RECONNECT_WINDOW_DEBUG)
  fprintf(stderr, "nxagentDisconnectAllWindows\n");
  #endif

  for (int i = 0; i < screenInfo.numScreens; i++)
  {
    WindowPtr pWin = screenInfo.screens[i]->root;
    nxagentTraverseWindow( pWin, nxagentDisconnectWindow, &succeeded);
    nxagentDefaultWindows[i] = None;
  }

  #ifdef NXAGENT_RECONNECT_WINDOW_DEBUG
  fprintf(stderr, "nxagentDisconnectAllWindows: all windows disconnected\n");
  #endif

  return succeeded;
}

/*
 * FIXME: We are giving up reconnecting those void *
 * that are not resource, and we are just disconnecting them.
 * Perhaps we could do better and reconnect them.
 */

void nxagentDisconnectWindow(void * p0, XID x1, void * p2)
{
  WindowPtr pWin = (WindowPtr)p0;
  Bool*     pBool = (Bool*)p2;
  CursorPtr pCursor = wCursor(pWin);
  ScreenPtr pScreen = pWin -> drawable.pScreen;

  if ((pCursor = wCursor(pWin)) &&
         nxagentCursorPriv(pCursor, pScreen) &&
           nxagentCursor(pCursor, pScreen))
  {
    #ifdef NXAGENT_RECONNECT_CURSOR_DEBUG
    char msg[] = "nxagentDisconnectWindow:";

    nxagentPrintCursorInfo(pCursor, msg);
    #endif

    #ifdef NXAGENT_RECONNECT_CURSOR_DEBUG
    fprintf(stderr, "nxagentDisconnectWindow: window %p - disconnecting cursor %p ID %lx\n",
                pWin, pCursor, nxagentCursor(pCursor, pScreen));
    #endif

    nxagentDisconnectCursor(pCursor, (XID)0, pBool);

    if (!*pBool)
    {
      #ifdef WARNING
      fprintf(stderr, "nxagentDisconnectWindow: WARNING failed disconnection of cursor at [%p]"
                  " for window at [%p]: ignoring it.\n", (void*)pCursor, (void*)pWin);
      #endif

      *pBool = True;
    }
  }
  #ifdef NXAGENT_RECONNECT_CURSOR_DEBUG
  else if (pCursor)
  {
    fprintf(stderr, "nxagentDisconnectWindow: window %p - cursor %p already disconnected\n",
                pWin, pCursor);
  }
  #endif

  if ((nxagentRealWindowProp) && (!nxagentWindowTopLevel(pWin)))
  {
    Atom prop = MakeAtom("NX_REAL_WINDOW", strlen("NX_REAL_WINDOW"), True);

    if (DeleteProperty(pWin, prop) != Success)
    {
        fprintf(stderr, "nxagentDisconnectWindow: Deleting NX_REAL_WINDOW failed.\n");
    }
    #ifdef DEBUG
    else
    {
      fprintf(stderr, "nxagentDisconnectWindow: Deleting NX_REAL_WINDOW from Window ID [%x].\n", nxagentWindowPriv(pWin)->window);
    }
    #endif
  }

  nxagentWindow(pWin) = None;

  if (nxagentDrawableStatus((DrawablePtr) pWin) == NotSynchronized)
  {
    nxagentDestroyCorruptedResource((DrawablePtr) pWin, RT_NX_CORR_WINDOW);
  }
}

Bool nxagentReconnectAllWindows(void *p0)
{
  /*
    access the parameter like this if this function needs it in future:
    int flexibility = *(int *) p0;
  */

  #if defined(NXAGENT_RECONNECT_DEBUG) || defined(NXAGENT_RECONNECT_WINDOW_DEBUG)
  fprintf(stderr, "nxagentReconnectAllWindows\n");
  #endif

  if (screenInfo.screens[0]->root -> backgroundState == BackgroundPixmap &&
          screenInfo.screens[0]->root -> background.pixmap == NULL)
  {
    FatalError("nxagentReconnectAllWindows: correct the FIXME\n");
  }

  if (nxagentOption(Fullscreen))
  {
    screenInfo.screens[0]->root -> origin.x = nxagentOption(RootX);
    screenInfo.screens[0]->root -> origin.y = nxagentOption(RootY);
  }

  if (!nxagentLoopOverWindows(nxagentReconnectWindow))
  {
    #ifdef WARNING
    fprintf(stderr, "nxagentReconnectAllWindows: couldn't recreate windows\n");
    #endif

    return False;
  }

  #ifdef NXAGENT_RECONNECT_WINDOW_DEBUG
  XSync(nxagentDisplay, 0);
  fprintf(stderr, "nxagentReconnectAllWindows: all windows recreated\n");
  #endif

  if (!nxagentLoopOverWindows(nxagentReconfigureWindow))
  {
    #ifdef WARNING
    fprintf(stderr, "nxagentReconnectAllWindows: couldn't reconfigure windows\n");
    #endif

    return False;
  }

  /*
   * After the Root Window has
   * been mapped, the Input
   * Windows is raised.
   */

  if (nxagentOption(Rootless) == 0)
  {
    for (int i = 0; i < screenInfo.numScreens; i++)
    {
      XRaiseWindow(nxagentDisplay, nxagentInputWindows[i]);
    }
  }

  nxagentFlushConfigureWindow();

  if (nxagentOption(Fullscreen))
  {
    screenInfo.screens[0]->root -> origin.x = 0;
    screenInfo.screens[0]->root -> origin.y = 0;
  }

  #ifdef NXAGENT_RECONNECT_WINDOW_DEBUG
  XSync(nxagentDisplay, 0);
  fprintf(stderr, "nxagentReconnectAllWindows: All windows reconfigured.\n");
  #endif

  if (nxagentInitClipboard(screenInfo.screens[0]->root) == -1)
  {
    #ifdef WARNING
    fprintf(stderr, "nxagentReconnectAllWindows: WARNING! Couldn't initialize the clipboard.\n");
    #endif

    return False;
  }

  #ifdef NXAGENT_RECONNECT_WINDOW_DEBUG
  XSync(nxagentDisplay, 0);
  fprintf(stderr, "nxagentReconnectAllWindows: Clipboard initialized.\n");
  #endif

  #ifdef VIEWPORT_FRAME
  /*
   * We move the viewport frames out of the way on the X server side.
   */

  if (nxagentViewportFrameLeft &&
          nxagentViewportFrameRight &&
              nxagentViewportFrameAbove &&
                  nxagentViewportFrameBelow)
  {
    XMoveWindow(nxagentDisplay, nxagentWindow(nxagentViewportFrameLeft),
                    -NXAGENT_FRAME_WIDTH, 0);
    XMoveWindow(nxagentDisplay, nxagentWindow(nxagentViewportFrameRight),
                    nxagentOption(RootWidth), 0);
    XMoveWindow(nxagentDisplay, nxagentWindow(nxagentViewportFrameAbove),
                    0, -NXAGENT_FRAME_WIDTH);
    XMoveWindow(nxagentDisplay, nxagentWindow(nxagentViewportFrameBelow),
                    0, nxagentOption(RootHeight));
  }
  #endif /* #ifdef VIEWPORT_FRAME */

  return True;
}

Bool nxagentSetWindowCursors(void *p0)
{
  /*
    access the parameter like this if this function needs it in future:
    int flexibility = *(int *) p0;
   */

  #if defined(NXAGENT_RECONNECT_DEBUG) || defined(NXAGENT_RECONNECT_WINDOW_DEBUG)
  fprintf(stderr, "nxagentSetWindowCursors: Going to loop over the windows.\n");
  #endif

  if (!nxagentLoopOverWindows(nxagentReconfigureWindowCursor))
  {
    #ifdef WARNING
    fprintf(stderr, "nxagentSetWindowCursors: WARNING! Couldn't configure all windows' cursors.\n");
    #endif

    return False;
  }

  #ifdef NXAGENT_RECONNECT_WINDOW_DEBUG
  fprintf(stderr, "nxagentSetWindowCursors: All cursors configured.\n");
  #endif

  nxagentReDisplayCurrentCursor();

  return True;
}

static void nxagentTraverseWindow(
  WindowPtr pWin,
  void (*pF)(void *, XID, void *),
  void * p)
{
  pF(pWin, 0, p);

  if (pWin -> nextSib)
  {
    nxagentTraverseWindow(pWin -> nextSib, pF, p);
  }

  if (pWin -> firstChild)
  {
    nxagentTraverseWindow(pWin -> firstChild, pF, p);
  }
}

static Bool nxagentLoopOverWindows(void (*pF)(void *, XID, void *))
{
  Bool windowSuccess = True;

  for (int i = 0; i < screenInfo.numScreens; i++)
  {
    nxagentTraverseWindow(screenInfo.screens[i]->root, pF, &windowSuccess);
  }

  return windowSuccess;
}

static void nxagentReconnectWindow(void * param0, XID param1, void * data_buffer)
{
  WindowPtr pWin = (WindowPtr)param0;
  Bool *pBool = (Bool*)data_buffer;
  Visual *visual;
  unsigned long mask;
  XSetWindowAttributes attributes;
  ColormapPtr pCmap;

  if (!pWin || !*pBool)
  {
    return;
  }

  #ifdef NXAGENT_RECONNECT_WINDOW_DEBUG
  fprintf(stderr, "nxagentReconnectWindow: %p - ID %lx\n", pWin, nxagentWindow(pWin));
  #endif

  if (pWin->drawable.class == InputOnly)
  {
    mask = CWEventMask;
    visual = CopyFromParent;
  }
  else
  {
    mask = CWEventMask | CWBackingStore;

    attributes.backing_store = NotUseful;

    if (pWin->optional)
    {
      mask |= CWBackingPlanes | CWBackingPixel;
      attributes.backing_planes = pWin->optional->backingBitPlanes;
      attributes.backing_pixel = pWin->optional->backingPixel;
    }

    /*
      FIXME: Do we need to set save unders attribute here?
    */
    if (nxagentSaveUnder)
    {
      mask |= CWSaveUnder;
      attributes.save_under = pWin->saveUnder;
    }

    if (pWin->parent)
    {
      if (pWin->optional && pWin->optional->visual != wVisual(pWin->parent))
      {
        visual = nxagentVisualFromID(pWin->drawable.pScreen, wVisual(pWin));
        mask |= CWColormap;
        if (pWin->optional->colormap)
        {
          pCmap = (ColormapPtr)LookupIDByType(wColormap(pWin), RT_COLORMAP);
          attributes.colormap = nxagentColormap(pCmap);
        }
        else
        {
          attributes.colormap = nxagentDefaultVisualColormap(visual);
        }
      }
      else
      {
        visual = CopyFromParent;
      }
    }
    else
    {
      /* root windows have their own colormaps at creation time */
      visual = nxagentVisualFromID(pWin->drawable.pScreen, wVisual(pWin));
      pCmap = (ColormapPtr)LookupIDByType(wColormap(pWin), RT_COLORMAP);
      mask |= CWColormap;
      attributes.colormap = nxagentColormap(pCmap);
    }
  }

  if (mask & CWEventMask)
  {
    attributes.event_mask = nxagentGetEventMask(pWin);
  }
  #ifdef WARNING
  else
  {
    attributes.event_mask = NoEventMask;
  }
  #endif

  #ifdef TEST
  fprintf(stderr, "nxagentReconnectWindow: Going to create new window.\n");
  fprintf(stderr, "nxagentReconnectWindow: Recreating %swindow at %p current event mask = %lX mask & CWEventMask = %ld "
              "event_mask = %lX\n",
                  nxagentWindowTopLevel(pWin) ? "toplevel " : "", (void*)pWin, pWin -> eventMask,
                      mask & CWEventMask, attributes.event_mask);
  #endif

  /*
   * FIXME: This quick hack is intended to solve a
   *        problem of NXWin X server for windows.
   *        The NXWin minimize the windows moving them
   *        out of the screen area, this behaviour
   *        can cause problem when a rootless session
   *        is disconnected and an apps is minimized.
   *        It will be solved with new Xorg version of
   *        the NXWin server.
   */

  if (nxagentOption(Rootless))
  {
    if (pWin -> drawable.x == -32000 && pWin -> drawable.y == -32000)
    {
      pWin -> drawable.x = (pWin -> drawable.pScreen -> width - pWin -> drawable.width) / 2;
      pWin -> drawable.y = (pWin -> drawable.pScreen -> height - pWin -> drawable.height) /2;
    }

    if (pWin -> origin.x == -32000 && pWin -> origin.y == -32000)
    {
      pWin -> origin.x = (pWin -> drawable.pScreen -> width - pWin -> drawable.width) / 2;
      pWin -> origin.y = (pWin -> drawable.pScreen -> height - pWin -> drawable.height) / 2;
    }
  }

  nxagentWindow(pWin) = XCreateWindow(nxagentDisplay,
                                      nxagentWindowParent(pWin),
                                      pWin->origin.x -
                                      wBorderWidth(pWin),
                                      pWin->origin.y -
                                      wBorderWidth(pWin),
                                      pWin->drawable.width,
                                      pWin->drawable.height,
                                      pWin->borderWidth,
                                      pWin->drawable.depth,
                                      pWin->drawable.class,
                                      visual,
                                      mask,
                                      &attributes);

  if (nxagentReportPrivateWindowIds)
  {
    fprintf (stderr, "NXAGENT_WINDOW_ID: PRIVATE_WINDOW,WID:[0x%x]\n", nxagentWindowPriv(pWin)->window);
  }
  #ifdef TEST
  fprintf(stderr, "nxagentReconnectWindow: Created new window with id [0x%x].\n",
              nxagentWindowPriv(pWin)->window);
  #endif

  /*
   * We have to set the WM_DELETE_WINDOW protocols
   * on every top level window, because we don't know
   * if a client handles this.
   */

  if (nxagentOption(Rootless) && (pWin != screenInfo.screens[0]->root))
  {
    if (nxagentWindowTopLevel(pWin))
    {
      Atom prop = nxagentMakeAtom("WM_PROTOCOLS", strlen("WM_PROTOCOLS"), True);

      XlibAtom atom = nxagentMakeAtom("WM_DELETE_WINDOW", strlen("WM_DELETE_WINDOW"), True);

      XSetWMProtocols(nxagentDisplay, nxagentWindow(pWin), &atom, 1);

      nxagentAddPropertyToList(prop, pWin);
    }

    nxagentExportAllProperty(pWin);

    if (nxagentWindowTopLevel(pWin))
    {
      int ret;
      Atom type;
      int format;
      unsigned long nItems, bytesLeft;
      XSizeHints hints = {0};
      unsigned char *data = NULL;
      #ifdef _XSERVER64
      unsigned char *data64 = NULL;
      #endif

      ret = GetWindowProperty(pWin,
                                  XA_WM_NORMAL_HINTS,
                                      0, sizeof(XSizeHints),
                                          False, XA_WM_SIZE_HINTS,
                                              &type, &format, &nItems, &bytesLeft, &data);

      /*
       * 72 is the number of bytes returned by
       * sizeof(XSizeHints) on 32 bit platforms.
       */

      if (ret == Success &&
              ((format >> 3) * nItems) == 72 &&
                  bytesLeft == 0 &&
                      type == XA_WM_SIZE_HINTS)
      {
        XSizeHints *props;
        #ifdef TEST
        fprintf(stderr, "nxagentReconnectWindow: setting WMSizeHints on window %p [%lx - %lx].\n",
                    (void*)pWin, pWin -> drawable.id, nxagentWindow(pWin));
        #endif

        #ifdef _XSERVER64
        data64 = (unsigned char *) malloc(sizeof(XSizeHints) + 4);

        for (int i = 0; i < 4; i++)
        {
          *(data64 + i) = *(data + i);
        }

        *(((int *) data64) + 1) = 0;

        for (int i = 8; i < sizeof(XSizeHints) + 4; i++)
        {
          *(data64 + i) = *(data + i - 4);
        }

        props = (XSizeHints *) data64;
        #else
        props = (XSizeHints *) data;
        #endif   /* _XSERVER64 */

        hints = *props;
      }
      else
      {
        #ifdef WARNING
        fprintf(stderr, "nxagentReconnectWindow: Failed to get property WM_NORMAL_HINTS on window %p\n",
                    (void*)pWin);
        #endif
      }

      hints.flags |= (USPosition | PWinGravity);
      hints.x = pWin -> drawable.x;
      hints.y = pWin -> drawable.y;
      hints.win_gravity = StaticGravity;

      XSetWMNormalHints(nxagentDisplay,
                           nxagentWindow(pWin),
                              &hints);

      #ifdef _XSERVER64
      SAFE_free(data64);
      #endif
    }
  }

  if ((nxagentRealWindowProp) && (!nxagentWindowTopLevel(pWin)))
  {
    Atom prop = MakeAtom("NX_REAL_WINDOW", strlen("NX_REAL_WINDOW"), True);

    if (ChangeWindowProperty(pWin, prop, XA_WINDOW, 32, PropModeReplace, 1, nxagentWindowPriv(pWin), 1) != Success)
    {
      fprintf(stderr, "nxagentReconnectWindow: Updating NX_REAL_WINDOW failed.\n");
    }
    #ifdef DEBUG
    else
    {
      fprintf(stderr, "nxagentReconnectWindow: Updated NX_REAL_WINDOW for Window ID [%x].\n", nxagentWindowPriv(pWin)->window);
    }
    #endif
  }

  if (nxagentDrawableStatus((DrawablePtr) pWin) == NotSynchronized)
  {
    nxagentAllocateCorruptedResource((DrawablePtr) pWin, RT_NX_CORR_WINDOW);
  }
}

static void nxagentReconfigureWindowCursor(void * param0, XID param1, void * data_buffer)
{
  WindowPtr pWin = (WindowPtr)param0;
  Bool *pBool = (Bool*)data_buffer;
  CursorPtr   pCursor;
  ScreenPtr   pScreen;

  if (!pWin || !*pBool || !(pCursor = wCursor(pWin)))
  {
    return;
  }

  pScreen = pWin -> drawable.pScreen;

  if (!(nxagentCursorPriv(pCursor, pScreen)))
  {
    return;
  }

  #ifdef DEBUG
  fprintf(stderr, "nxagentReconfigureWindowCursor: %p - ID %lx geometry (%d,%d,%d,%d) "
                  "cursor %p - ID %lx\n",
                  pWin, nxagentWindow(pWin),
                  pWin -> drawable.x,
                  pWin -> drawable.y,
                  pWin -> drawable.width,
                  pWin -> drawable.height,
                  pCursor, nxagentCursor(pCursor, pScreen));
  #endif

  if (nxagentCursor(pCursor, pScreen) == None)
  {
    #ifdef NXAGENT_RECONNECT_WINDOW_DEBUG
    fprintf(stderr, "nxagentReconfigureWindowCursor: reconnecting valid cursor %lx\n",
                (void*)pCursor);
    #endif

    nxagentReconnectCursor(pCursor, 0, pBool);

    if (!*pBool)
    {
      #ifdef WARNING
      fprintf(stderr, "nxagentReconfigureWindowCursor: WARNING "
                  "failed reconnection of cursor at [%p] for window at [%p]: ignoring it.\n",
                      (void*)pCursor, (void*)pWin);
      #endif

      *pBool = True;
    }
  }

  if (nxagentOption(Rootless))
  {
    XDefineCursor(nxagentDisplay,nxagentWindow(pWin),nxagentCursor(pCursor,pScreen));
  }
}

static void nxagentReconfigureWindow(void * param0, XID param1, void * data_buffer)
{
  WindowPtr pWin = (WindowPtr)param0;
  unsigned long mask = 0;

  #ifdef DEBUG
  fprintf(stderr, "nxagentReconfigureWindow: pWin %p - ID %lx\n", pWin, nxagentWindow(pWin));
  #endif

  if (pWin -> drawable.class == InputOnly)
  {
    mask = CWWinGravity | CWEventMask | CWDontPropagate | CWOverrideRedirect | CWCursor;
  }
  else
  {
    mask = CWBackPixmap | CWBackPixel | CWBorderPixmap | CWBorderPixel |
         CWBitGravity | CWWinGravity | CWBackingStore | CWBackingPlanes |
         CWBackingPixel | CWOverrideRedirect | CWSaveUnder | CWEventMask |
         CWDontPropagate | CWColormap | CWCursor;
  }
  nxagentChangeWindowAttributes(pWin, mask);

  #ifdef SHAPE
  if (nxagentWindowPriv(pWin) -> boundingShape)
  {
    RegionDestroy(nxagentWindowPriv(pWin) -> boundingShape);
    nxagentWindowPriv(pWin) -> boundingShape = NULL;
  }

  if (nxagentWindowPriv(pWin) -> clipShape)
  {
    RegionDestroy(nxagentWindowPriv(pWin) -> clipShape);
    nxagentWindowPriv(pWin) -> clipShape = NULL;
  }
  nxagentShapeWindow(pWin);
  #endif

  if (pWin != screenInfo.screens[0]->root)
  {
    if (pWin->realized)
    {
        nxagentRealizeWindow (pWin);
    }
/*
XXX: This would break Motif menus.
     If pWin is mapped but not realized, a following UnmapWindow() wouldn't
     do anything, leaving this mapped window around. XMapWindow()
     is called in nxagentRealizeWindow() and there it is enough.

    else if (pWin->mapped)
    {
      XMapWindow(nxagentDisplay, nxagentWindow(pWin));
    }
*/
    else if (nxagentOption(Rootless) && pWin -> overrideRedirect == 0 &&
                 nxagentWindowTopLevel(pWin) && nxagentIsIconic(pWin))
    {
      MapWindow(pWin, serverClient);
      XIconifyWindow(nxagentDisplay, nxagentWindow(pWin), pWin -> drawable.pScreen -> myNum);
    }
  }
  else if (nxagentOption(Rootless) == 0)
  {
    /*
     * Map the root window.
     */

    XMoveWindow(nxagentDisplay, nxagentWindow(pWin),
                    nxagentOption(RootX), nxagentOption(RootY));
    XMapWindow(nxagentDisplay, nxagentWindow(pWin));
  }
}

Bool nxagentCheckIllegalRootMonitoring(WindowPtr pWin, Mask mask)
{
  Mask invalidMask = SubstructureRedirectMask | ResizeRedirectMask | ButtonPressMask;

  if (nxagentOption(Rootless) &&
        pWin == screenInfo.screens[0]->root &&
          (mask & invalidMask))
  {
    return True;
  }

  return False;
}

#ifdef TEST
Bool nxagentCheckWindowIntegrity(WindowPtr pWin)
{
  Bool integrity = True;
  XImage *image;
  char *data;
  int format;
  unsigned long plane_mask = AllPlanes;
  unsigned int width, height, length, depth;

  width = pWin -> drawable.width;
  height = pWin -> drawable.height;
  depth = pWin -> drawable.depth;
  format = (depth == 1) ? XYPixmap : ZPixmap;

  if (width && height)
  {
     length = nxagentImageLength(width, height, format, 0, depth);
     data = calloc(1, length);
     if (data == NULL)
     {
       FatalError("nxagentCheckWindowIntegrity: Failed to allocate a buffer of size %d.\n", length);
     }

     image = XGetImage(nxagentDisplay, nxagentWindow(pWin), 0, 0,
                                   width, height, plane_mask, format);
     if (image == NULL)
     {
       fprintf(stderr, "XGetImage: Failed.\n");
       return False;
     }

     fbGetImage((DrawablePtr)pWin, 0, 0, width, height, format, plane_mask, data);

     if (image && memcmp(image->data, data, length) != 0)
     {
       integrity = False;

       #ifdef TEST
       char *p = image->data, *q = data;

       for (int i = 0; i < length; i++)
       {
         if (p[i] != q[i])
         {
           fprintf(stderr, "[%d] %d - %d !!!!!!!!!!!!!!!!!!! **************** !!!!!!!!!!!!!!!!!\n", i, p[i], q[i]);
         }
         else
         {
           fprintf(stderr, "[%d] %d - %d\n", i, p[i], q[i]);
         }
       }
       #endif

       #ifdef WARNING
       fprintf(stderr, "nxagentCheckWindowIntegrity: Window %p width %d, height %d, has been realized "
                 "but the data buffer still differs.\n", (void*) pWin, width, height);
       fprintf(stderr, "nxagentCheckWindowIntegrity: bytes_per_line = %d byte pad %d format %d.\n",
                 image -> bytes_per_line, nxagentImagePad(width, height, 0, depth), image->format);

       fprintf(stderr, "nxagentCheckWindowIntegrity: image is corrupted!!\n");
       #endif
     }
     else
     {
       #ifdef WARNING
       fprintf(stderr, "nxagentCheckWindowIntegrity: Window %p has been realized "
                   "now remote and framebuffer data are synchronized.\n", (void*) pWin);
       #endif
     }

     if (image)
     {
       XDestroyImage(image);
     }

     SAFE_free(data);
  }
  else
  {
    #ifdef WARNING
    fprintf(stderr, "nxagentCheckWindowIntegrity: ignored window %p with geometry (%d,%d).\n",
                (void*) pWin, width, height);
    #endif
  }

  return integrity;
}
#endif /* TEST */

Bool nxagentIsIconic(WindowPtr pWin)
{
  int           iReturn;
  unsigned long ulReturnItems;
  unsigned long ulReturnBytesLeft;
  Atom          atomReturnType;
  int           iReturnFormat;
  unsigned char *pszReturnData = NULL;

  if (!wUserProps (pWin))
  {
    return 0;
  }

  iReturn = GetWindowProperty(pWin, MakeAtom("WM_STATE", 8, False), 0, sizeof(CARD32), False,
                              AnyPropertyType, &atomReturnType, &iReturnFormat,
                              &ulReturnItems, &ulReturnBytesLeft, &pszReturnData);

  if (iReturn == Success)
  {
    return (((CARD32 *)pszReturnData)[0] == IconicState);
  }
  else
  {
    return 0;
  }
}

/* pass Eventmask to the real X server (for the rootless toplevel window only) */
void nxagentSetTopLevelEventMask(WindowPtr pWin)
{
  if (nxagentOption(Rootless) && nxagentWindowTopLevel(pWin))
  {
    XSetWindowAttributes attributes = {.event_mask = nxagentGetEventMask(pWin)};
    XChangeWindowAttributes(nxagentDisplay, nxagentWindow(pWin), CWEventMask, &attributes);
  }
}

/*
 * Run nxagentConfigureWindow() on all windows in
 * nxagentConfiguredWindowList and move them from the list
 * afterwards. The list will be empty then.
 *
 * This is also taking care of entries in nxagentExposeQueue that need
 * to be synchronized with the real X server.
 */
void nxagentFlushConfigureWindow(void)
{
  ConfiguredWindowStruct *index;
  XWindowChanges changes;

  index = nxagentConfiguredWindowList;

  while (index)
  {
    if (index -> next == NULL)
    {
      break;
    }

    index = index -> next;
  }

  while (index)
  {
    WindowPtr pWin = index -> pWin;
    unsigned int valuemask = index -> valuemask;

    if (pWin && valuemask)
    {
      nxagentConfigureWindow(pWin, valuemask);
    }

    if (index == nxagentConfiguredWindowList)
    {
      SAFE_free(index);
      break;
    }
    else
    {
      ConfiguredWindowStruct *tmp = index;
      index = index -> prev;
      SAFE_free(tmp);
    }
  }

  nxagentConfiguredWindowList = NULL;

  for (int j = 0; j < nxagentExposeQueue.length; j++)
  {
    int i = (nxagentExposeQueue.start + j) % EXPOSED_SIZE;

    if (nxagentExposeQueue.exposures[i].synchronize == 1)
    {
      changes.x = nxagentExposeQueue.exposures[i].serial;
      changes.y = -2;

      #ifdef DEBUG
      fprintf(stderr, "nxagentFlushConfigureWindow: Sending synch ConfigureWindow for "
                  "index [%d] serial [%d].\n", i, nxagentExposeQueue.exposures[i].serial);
      #endif

      XConfigureWindow(nxagentDisplay, nxagentConfiguredSynchroWindow,
                           CWX | CWY, &changes);

      nxagentExposeQueue.exposures[i].synchronize = 0;
    }
  }

  nxagentSendDeferredBackgroundExposures();

  return;
}

/*
 * from "Definition of the Porting Layer for X v11 Sample Server":
 *
 * If this routine is not NULL, DIX calls it shortly after calling
 * ValidateTree, passing it the same arguments. This is useful for
 * managing multi-layered framebuffers. The sample server sets this to
 * NULL.
 */
void nxagentPostValidateTree(WindowPtr pParent, WindowPtr pChild, VTKind kind)
{
  /*
    FIXME: Do we need this here?

  nxagentFlushConfigureWindow();
  */

  return;
}

/*
 * Add the given window to the beginning of
 * nxagentconfiguredWindowList. This list collects all windows that
 * need to be reconfigured on the real X server. valuemask defines
 * what changes need to be done. The required values (like position,
 * size, ...) are already stored in pWin).
 *
 * Note that we just add the window to the list here. The actual work
 * will be done by nxagentFlushConfigureWindow() later.
 */
void nxagentAddConfiguredWindow(WindowPtr pWin, unsigned int valuemask)
{
  unsigned int mask;

  mask = valuemask & (CWSibling | CWX | CWY | CWWidth | CWHeight |
                   CWBorderWidth | CWStackMode | CW_Map | CW_Update | CW_Shape);

  valuemask &= ~(CWSibling | CWX | CWY | CWWidth | CWHeight | CWBorderWidth | CWStackMode);

  if (mask & CWX &&
          nxagentWindowPriv(pWin)->x !=
              pWin->origin.x - wBorderWidth(pWin))
  {
    valuemask |= CWX;
  }

  if (mask & CWY &&
          nxagentWindowPriv(pWin)->y !=
              pWin->origin.y - wBorderWidth(pWin))
  {
    valuemask |= CWY;
  }

  if (mask & CWWidth &&
          nxagentWindowPriv(pWin)->width !=
              pWin->drawable.width)
  {
    valuemask |= CWWidth;
  }

  if (mask & CWHeight &&
          nxagentWindowPriv(pWin)->height !=
              pWin->drawable.height)
  {
    valuemask |= CWHeight;
  }

  if (mask & CWBorderWidth &&
          nxagentWindowPriv(pWin)->borderWidth !=
              pWin->borderWidth)
  {
    valuemask |= CWBorderWidth;
  }

  if (mask & CWStackMode &&
          nxagentWindowPriv(pWin)->siblingAbove !=
              nxagentWindowSiblingAbove(pWin))
  {
    valuemask |= CWStackMode;
  }

  {
    ConfiguredWindowStruct *tmp = nxagentConfiguredWindowList;

    nxagentConfiguredWindowList = malloc(sizeof(ConfiguredWindowStruct));
    nxagentConfiguredWindowList -> next = tmp; /* can be NULL */
    nxagentConfiguredWindowList -> prev = NULL;
    nxagentConfiguredWindowList -> pWin = pWin;
    nxagentConfiguredWindowList -> valuemask = valuemask;

    if (tmp)
    {
      tmp -> prev = nxagentConfiguredWindowList;
    }
  }

  return;
}

/*
 * remove pWin from nxgentConfigureWindowList
 *
 * This is just updating the linked list and freeing the
 * given entry. It will not perform any X stuff
 */
void nxagentDeleteConfiguredWindow(WindowPtr pWin)
{
  ConfiguredWindowStruct *index, *previous, *tmp;

  index = nxagentConfiguredWindowList;

  while (index)
  {
    WindowPtr pDel = index -> pWin;

    if (pDel == pWin)
    {
      if (index -> prev == NULL && index -> next == NULL)
      {
        SAFE_free(nxagentConfiguredWindowList);
        return;
      }
      else if (index -> prev == NULL)
      {
        tmp = nxagentConfiguredWindowList;
        index = nxagentConfiguredWindowList = tmp -> next;
        SAFE_free(tmp);
        nxagentConfiguredWindowList -> prev = NULL;

        continue;
      }
      else if (index -> next == NULL)
      {
        tmp = index;
        index = index -> prev;
        SAFE_free(tmp);
        index -> next = NULL;

        return;
      }

      previous = index -> prev;
      tmp = index;
      index = index -> next;
      previous -> next = index;
      index -> prev = previous;
      SAFE_free(tmp);

      continue;
    }

    index = index -> next;
  }

  return;
}

void nxagentAddStaticResizedWindow(WindowPtr pWin, unsigned long sequence, int offX, int offY)
{
  StaticResizedWindowStruct *tmp = nxagentStaticResizedWindowList;

  nxagentStaticResizedWindowList = malloc(sizeof(StaticResizedWindowStruct));
  nxagentStaticResizedWindowList -> next = tmp;
  nxagentStaticResizedWindowList -> prev = NULL;

  if (tmp)
  {
    tmp -> prev = nxagentStaticResizedWindowList;
  }

  nxagentStaticResizedWindowList -> pWin = pWin;
  nxagentStaticResizedWindowList -> sequence = sequence;
  nxagentStaticResizedWindowList -> offX = offX;
  nxagentStaticResizedWindowList -> offY = offY;
}

void nxagentDeleteStaticResizedWindow(unsigned long sequence)
{
  StaticResizedWindowStruct *index, *previous, *tmp;

  index = nxagentStaticResizedWindowList;

  while (index)
  {
    if (index -> sequence <= sequence)
    {
      if (index -> prev == NULL && index -> next == NULL)
      {
        SAFE_free(nxagentStaticResizedWindowList);
        return;
      }
      else if (index -> prev == NULL)
      {
        tmp = nxagentStaticResizedWindowList;
        index = nxagentStaticResizedWindowList = tmp -> next;
        SAFE_free(tmp);
        nxagentStaticResizedWindowList -> prev = NULL;

        continue;
      }
      else if (index -> next == NULL)
      {
        tmp = index;
        index = index -> prev;
        SAFE_free(tmp);
        index -> next = NULL;

        return;
      }

      previous = index -> prev;
      tmp = index;
      index = index -> next;
      previous -> next = index;
      index -> prev = previous;
      SAFE_free(tmp);

      continue;
    }

    index = index -> next;
  }

  return;
}

StaticResizedWindowStruct *nxagentFindStaticResizedWindow(unsigned long sequence)
{
  StaticResizedWindowStruct *index;
  StaticResizedWindowStruct *ret = NULL;

  if (nxagentStaticResizedWindowList == NULL)
  {
    return NULL;
  }

  index = nxagentStaticResizedWindowList;

  while (index && index -> sequence > sequence)
  {
    ret = index;
    index = index -> next;
  }

  return ret;
}

void nxagentEmptyBackingStoreRegion(void * param0, XID param1, void * data_buffer)
{
  WindowPtr pWin = (WindowPtr) param0;

  miBSWindowPtr pBackingStore = (miBSWindowPtr)pWin->backStorage;

  if (pBackingStore != NULL)
  {
    RegionEmpty(&pBackingStore->SavedRegion);

    #ifdef TEST
    fprintf(stderr, "nxagentEmptyBackingStoreRegion: Emptying saved region for window at [%p].\n", (void*) pWin);
    #endif

    if (pBackingStore -> pBackingPixmap != NULL)
    {
      #ifdef TEST
      fprintf(stderr, "nxagentEmptyBackingStoreRegion: Emptying corrupted region for drawable at [%p].\n",
                  (void*) pBackingStore -> pBackingPixmap);
      #endif

      nxagentUnmarkCorruptedRegion((DrawablePtr) pBackingStore -> pBackingPixmap, NullRegion);
    }
  }
}

void nxagentEmptyAllBackingStoreRegions(void)
{
  if (nxagentLoopOverWindows(nxagentEmptyBackingStoreRegion) == 0)
  {
    #ifdef WARNING
    fprintf(stderr, "nxagentEmptyAllSavedRegions: Failed to empty backing store saved regions.\n");
    #endif
  }
}

void nxagentInitBSPixmapList(void)
{
  memset(nxagentBSPixmapList, 0, BSPIXMAPLIMIT * sizeof( StoringPixmapPtr));
}

int nxagentAddItemBSPixmapList(unsigned long id, PixmapPtr pPixmap, WindowPtr pWin, int bsx, int bsy)
{
  for (int i = 0; i < BSPIXMAPLIMIT; i++)
  {
    if (nxagentBSPixmapList[i] == NULL)
    {
      nxagentBSPixmapList[i] = malloc(sizeof(StoringPixmapRec));

      if (nxagentBSPixmapList[i] == NULL)
      {
        FatalError("nxagentAddItemBSPixmapList: Failed to allocate memory for nxagentBSPixmapList.\n");
      }

      nxagentBSPixmapList[i] -> storingPixmapId = id;
      nxagentBSPixmapList[i] -> pStoringPixmap = pPixmap;
      nxagentBSPixmapList[i] -> pSavedWindow = pWin;
      nxagentBSPixmapList[i] -> backingStoreX = bsx;
      nxagentBSPixmapList[i] -> backingStoreY = bsy;

      #ifdef TEST
      fprintf(stderr, "nxagentAddItemBSPixmapList: Added Pixmap with id [%lu] to nxagentBSPixmapList.\n", id);
      #endif

      return 1;
    }

    if (nxagentBSPixmapList[i] -> storingPixmapId == id)
    {
      nxagentBSPixmapList[i] -> pStoringPixmap = pPixmap;
      nxagentBSPixmapList[i] -> pSavedWindow = pWin;
      nxagentBSPixmapList[i] -> backingStoreX = bsx;
      nxagentBSPixmapList[i] -> backingStoreY = bsy;

      #ifdef TEST
      fprintf(stderr, "nxagentAddItemBSPixmapList: Updated existing item for id [%lu].\n", id);
      #endif

      return 1;
    }
  }

  #ifdef TEST
  fprintf(stderr, "nxagentAddItemBSPixmapList: WARNING! List item full.\n");
  #endif

  return 0;
}

int nxagentRemoveItemBSPixmapList(unsigned long pixmapId)
{
  if (pixmapId == 0 || nxagentBSPixmapList[0] == NULL)
  {
    return 0;
  }

  for (int i = 0; i < BSPIXMAPLIMIT; i++)
  {
    if ((nxagentBSPixmapList[i] != NULL) &&
            (nxagentBSPixmapList[i] -> storingPixmapId == pixmapId))
    {
      SAFE_free(nxagentBSPixmapList[i]);

      if (i < BSPIXMAPLIMIT - 1)
      {
        int j;

        for (j = i; j < BSPIXMAPLIMIT -1; j++)
        {
          nxagentBSPixmapList[j] = nxagentBSPixmapList[j + 1];
        }

        if (nxagentBSPixmapList[j] == nxagentBSPixmapList[j - 1])
        {
          nxagentBSPixmapList[j] = NULL;
        }
      }

      #ifdef TEST
      fprintf(stderr, "nxagentRemoveItemBSPixmapList: Removed Pixmap with id [%lu] from list.\n",
                  pixmapId);
      #endif

      return 1;
    }
  }

  #ifdef TEST
  fprintf(stderr, "nxagentRemoveItemBSPixmapList: WARNING! Can't remove item [%lu]: item not found.\n",
              pixmapId);
  #endif

  return 0;
}

int nxagentEmptyBSPixmapList(void)
{
  for (int i = 0; i < BSPIXMAPLIMIT; i++)
  {
    SAFE_free(nxagentBSPixmapList[i]);
  }

  return 1;
}

StoringPixmapPtr nxagentFindItemBSPixmapList(unsigned long pixmapId)
{
  for (int i = 0; i < BSPIXMAPLIMIT; i++)
  {
    if ((nxagentBSPixmapList[i] != NULL) &&
            (nxagentBSPixmapList[i] -> storingPixmapId == pixmapId))
    {
      #ifdef TEST
      fprintf(stderr, "%s: pixmapId [%lu].\n", __func__, pixmapId);
      fprintf(stderr, "%s: nxagentBSPixmapList[%d] = [%p].\n", __func__,
                  i, (void *) nxagentBSPixmapList[i]);
      fprintf(stderr, "%s: nxagentBSPixmapList[%d] -> storingPixmapId [%lu].\n", __func__,
                  i, nxagentBSPixmapList[i] -> storingPixmapId);
      #endif

      return nxagentBSPixmapList[i];
    }
  }

  #ifdef WARNING
  fprintf(stderr, "%s: WARNING! Item not found.\n", __func__);
  #endif

  #ifdef TEST
  fprintf(stderr, "%s: Pixmap with id [%lu] not found.\n", __func__,
              pixmapId);
  #endif

  return NULL;
}