aboutsummaryrefslogtreecommitdiff
path: root/nx-X11/programs/Xserver/hw/nxagent/Clipboard.c
blob: 2881a403182192570931e246116ab2736914d146 (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
/**************************************************************************/
/*                                                                        */
/* Copyright (c) 2001, 2011 NoMachine (http://www.nomachine.com)          */
/* Copyright (c) 2008-2017 Oleksandr Shneyder <o.shneyder@phoca-gmbh.de>  */
/* Copyright (c) 2011-2022 Mike Gabriel <mike.gabriel@das-netzwerkteam.de>*/
/* Copyright (c) 2014-2019 Mihai Moldovan <ionic@ionic.de>                */
/* Copyright (c) 2014-2022 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 "X.h"
#include "Xproto.h"
#include "Xatom.h"
#include "selection.h"
#include "windowstr.h"
#include "scrnintstr.h"

#include "Agent.h"
#include "Windows.h"
#include "Atoms.h"
#include "Args.h"
#include "Trap.h"
#include "Rootless.h"
#include "Clipboard.h"
#include "Utils.h"
#include "Client.h"

#include "gcstruct.h"
#include "xfixeswire.h"
#include "X11/include/Xfixes_nxagent.h"

/*
 * Use asynchronous get property replies.
 */

#include "compext/Compext.h"

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

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

/*
 * Define this to see the clipboard content in the debug output. As
 * this can lead to information leaking it must be activated
 * explicitly!
 */
#undef PRINT_CLIPBOARD_CONTENT_ON_DEBUG

/*
 * Define these to also support special targets TEXT and COMPOUND_TEXT
 * in text-only mode. We do not have a special handling for these. See
 * https://www.x.org/releases/X11R7.6/doc/xorg-docs/specs/ICCCM/icccm.html#text_properties
 * for details.
 */
#undef SUPPORT_TEXT_TARGET
#undef SUPPORT_COMPOUND_TEXT_TARGET

/*
 * These are defined in the dispatcher.
 */

extern int NumCurrentSelections;
extern Selection *CurrentSelections;

static int agentClipboardInitialized = False;
static int clientAccum;

XlibAtom serverTransToAgentProperty;
Atom clientCutProperty;
static XlibWindow serverWindow;

const int nxagentPrimarySelection = 0;
const int nxagentClipboardSelection = 1;
const int nxagentMaxSelections = 2;

/* store the remote atom for all selections */
static XlibAtom *remoteSelectionAtoms = NULL;
static Atom *localSelectionAtoms = NULL;

/*
 * The real owner window (inside nxagent) is stored in
 * lastSelectionOwner[index].window.
 * lastSelectionOwner[index].windowPtr points to the struct that
 * contains all information about the owner window.
 * lastTimeChanged is always a local time.
 */
typedef struct _SelectionOwner
{
  ClientPtr  client;           /* local client */
  Window     window;           /* local window id */
  WindowPtr  windowPtr;        /* local window struct */
  TimeStamp  lastTimeChanged;  /* local time (server time) */
} SelectionOwner;

/*
 * This contains the last selection owner for each selection. If
 * .client is NULL the owner is outside nxagent or there is no owner.
 */

static SelectionOwner *lastSelectionOwner = NULL;

/*
 * Cache for targets the current selection owner
 * has to offer. We are storing the targets
 * after they have been converted.
*/
typedef struct _Targets
{
  Bool          type;        /* EMPTY, FOR_LOCAL, FOR_REMOTE */
  unsigned int  numTargets;
  Atom         *forLocal;    /* Atoms converted for local  -> type Atom, not XlibAtom */
  XlibAtom     *forRemote;   /* Atoms converted for remote -> type XlibAtom, not Atom */
} Targets;

#define EMPTY 0
#define FOR_REMOTE 1
#define FOR_LOCAL 2

static Targets *targetCache = NULL;

/* FIXME: can this also be stored per selection? */
static XlibAtom serverLastRequestedSelection = -1;

#define IS_LOCAL_OWNER(lsoindex) (lastSelectionOwner[lsoindex].client != NullClient)

typedef enum
{
  SelectionStageNone,
  SelectionStageQuerySize,
  SelectionStageWaitSize,
  SelectionStageQueryData,
  SelectionStageWaitData
} ClientSelectionStage;

/*
 * Needed to handle the notify selection event to be sent to the
 * waiting client once the selection property has been retrieved from
 * the real X server.
 */

typedef struct _lastClient
{
  WindowPtr     windowPtr;
  ClientPtr     clientPtr;
  Window        requestor;
  Atom          property;
  Atom          target;
  Time          time;
  Time          reqTime;
  unsigned long propertySize;
  ClientSelectionStage stage;
  int           resource;       /* nxcompext resource where collected property data is stored */
} lastClient;

static lastClient *lastClients;

typedef struct _lastServer {
  XlibWindow    requestor;
  XlibAtom      property;
  XlibAtom      target;
  Time          time;
} lastServer;

static lastServer *lastServers;

/*
 * FIXME: use (additional) Atoms.c helpers to get rid of all these
 * Atoms and strings
 */
static XlibAtom serverTARGETS;
static XlibAtom serverTIMESTAMP;
static XlibAtom serverINCR;
static XlibAtom serverMULTIPLE;
static XlibAtom serverDELETE;
static XlibAtom serverINSERT_SELECTION;
static XlibAtom serverINSERT_PROPERTY;
static XlibAtom serverSAVE_TARGETS;
static XlibAtom serverTARGET_SIZES;
#ifdef SUPPORT_TEXT_TARGET
static XlibAtom serverTEXT;
#endif
#ifdef SUPPORT_COMPOUND_TEXT_TARGET
static XlibAtom serverCOMPOUND_TEXT;
#endif
static XlibAtom serverUTF8_STRING;
static XlibAtom serverTransFromAgentProperty;
static Atom clientTARGETS;
static Atom clientTIMESTAMP;
static Atom clientINCR;
static Atom clientMULTIPLE;
static Atom clientDELETE;
static Atom clientINSERT_SELECTION;
static Atom clientINSERT_PROPERTY;
static Atom clientSAVE_TARGETS;
static Atom clientTARGET_SIZES;
#ifdef SUPPORT_TEXT_TARGET
static Atom clientTEXT;
#endif
#ifdef SUPPORT_COMPOUND_TEXT_TARGET
static Atom clientCOMPOUND_TEXT;
#endif
static Atom clientUTF8_STRING;

static char szAgentTARGETS[] = "TARGETS";
#ifdef SUPPORT_TEXT_TARGET
static char szAgentTEXT[] = "TEXT";
#endif
#ifdef SUPPORT_COMPOUND_TEXT_TARGET
static char szAgentCOMPOUND_TEXT[] = "COMPOUND_TEXT";
#endif
static char szAgentTIMESTAMP[] = "TIMESTAMP";
static char szAgentINCR[] = "INCR";
static char szAgentMULTIPLE[] = "MULTIPLE";
static char szAgentDELETE[] = "DELETE";
static char szAgentINSERT_SELECTION[] = "INSERT_SELECTION";
static char szAgentINSERT_PROPERTY[] = "INSERT_PROPERTY";
static char szAgentSAVE_TARGETS[] = "SAVE_TARGETS";
static char szAgentTARGET_SIZES[] = "TARGET_SIZES";
static char szAgentUTF8_STRING[] = "UTF8_STRING";
static char szAgentNX_CUT_BUFFER_CLIENT[] = "NX_CUT_BUFFER_CLIENT";
static char szAgentCLIPBOARD[] = "CLIPBOARD";

/* Number of milliseconds to wait for a conversion from the real X server. */
#define CONVERSION_TIMEOUT 5000

/*
 * Time window (milliseconds) within to detect multiple conversion
 * calls of the same client.
 */
#define ACCUM_TIME 5000

/*
 * Some helpers for debugging output
 */

static const char * getClientSelectionStageString(int stage)
{
  switch(stage)
  {
    case SelectionStageNone:      return("None"); break;;
    case SelectionStageQuerySize: return("QuerySize"); break;;
    case SelectionStageWaitSize:  return("WaitSize"); break;;
    case SelectionStageQueryData: return("QueryData"); break;;
    case SelectionStageWaitData:  return("WaitData"); break;;
    default:                      return("UNKNOWN!"); break;;
  }
}

#ifdef DEBUG
#define printClientSelectionStage(_index) do {fprintf(stderr, "%s: Current selection stage for selection [%d] is [%s]\n", __func__, _index, getClientSelectionStageString(lastClients[_index].stage));} while (0)
#else
#define printClientSelectionStage(_index)
#endif

#define WINDOWID(ptr) (ptr) ? (ptr->drawable.id) : 0
#define CLINDEX(clientptr) (clientptr) ? (clientptr->index) : -1

#ifdef DEBUG
/*
 * See also nx-X11/lib/src/ErrDes.c
 *
 * We use our own version to avoid Xlib doing expensive calls.
 * FIXME: Must check if XGetErrorText() is really causing traffic over the wire.
 * FIXME: move this to a Utils.c or similar
 */
const char * getXErrorString(int code)
{
  switch(code)
  {
    case Success:           return("Success"); break;;
    case BadRequest:        return("BadRequest"); break;;
    case BadValue:          return("BadValue"); break;;
    case BadWindow:         return("BadWindow"); break;;
    case BadPixmap:         return("BadPixmap"); break;;
    case BadAtom:           return("BadAtom"); break;;
    case BadCursor:         return("BadCursor"); break;;
    case BadFont:           return("BadFont"); break;;
    case BadMatch:          return("BadMatch"); break;;
    case BadDrawable:       return("BadDrawable"); break;;
    case BadAccess:         return("BadAccess"); break;;
    case BadAlloc:          return("BadAlloc"); break;;
    case BadColor:          return("BadColor"); break;;
    case BadGC:             return("BadGC"); break;;
    case BadIDChoice:       return("BadIDChoice"); break;;
    case BadName:           return("BadName"); break;;
    case BadLength:         return("BadLength"); break;;
    case BadImplementation: return("BadImplementation"); break;;
    default:                return("UNKNOWN!"); break;;
  }
}
#endif

/*
 * Save the values queried from X server.
 */

XFixesAgentInfoRec nxagentXFixesInfo = { -1, -1, -1, False };

extern Display *nxagentDisplay;

static Bool isTextTarget(XlibAtom target);
static void setClientSelectionStage(int index, int stage);
static void endTransfer(int index, Bool success);
#define SELECTION_SUCCESS True
#define SELECTION_FAULT False
static void transferSelectionFromXServer(int index, int resource);
#if 0
static void resetSelectionOwnerOnXServer(void);
#endif
static void initSelectionOwnerData(int index);
static void clearSelectionOwnerData(int index);
static Bool matchSelectionOwner(int index, ClientPtr pClient, WindowPtr pWindow);
#ifdef NXAGENT_CLIPBOARD
static void setSelectionOwnerOnXServer(Selection *pSelection);
static void storeSelectionOwnerData(int index, Selection *sel);
#endif
static int sendEventToClient(ClientPtr client, xEvent *pEvents);
static void sendSelectionNotifyEventToClient(ClientPtr client,
                                             Time time,
                                             Window requestor,
                                             Atom selection,
                                             Atom target,
                                             Atom property);
static Status sendSelectionNotifyEventToXServer(XSelectionEvent *event_to_send);
static void replyPendingRequestSelectionToXServer(int index, Bool success);
#ifdef DEBUG
static void printSelectionStat(int sel);
#endif
static void replyRequestSelectionToXServer(XEvent *X, Bool success);
void handlePropertyTransferFromAgentToXserver(int index, XlibAtom property);

void nxagentPrintClipboardStat(char *);

XlibAtom translateLocalToRemoteSelection(Atom local);
XlibAtom translateLocalToRemoteTarget(Atom local);

#ifdef NXAGENT_TIMESTAMP
extern unsigned long startTime;
#endif

static void printSelectionStat(int index)
{
  SelectionOwner lOwner = lastSelectionOwner[index];
  Selection curSel = CurrentSelections[index];

  fprintf(stderr, "selection [%d]:\n", index);

  fprintf(stderr, "  selection Atom                         local [%d][%s]  remote [%ld][%s]\n",
              localSelectionAtoms[index], NameForLocalAtom(localSelectionAtoms[index]),
                  remoteSelectionAtoms[index], NameForRemoteAtom(remoteSelectionAtoms[index]));
  fprintf(stderr, "  owner side                             %s\n", IS_LOCAL_OWNER(index) ? "nxagent" : "real X server/none");
  fprintf(stderr, "  lastSelectionOwner[].client            %s\n", nxagentClientInfoString(lOwner.client));
  fprintf(stderr, "  lastSelectionOwner[].window            [0x%x]\n", lOwner.window);
  if (lOwner.windowPtr)
    fprintf(stderr, "  lastSelectionOwner[].windowPtr         [%p] (-> [0x%x])\n", (void *)lOwner.windowPtr, WINDOWID(lOwner.windowPtr));
  else
    fprintf(stderr, "  lastSelectionOwner[].windowPtr         -\n");
  fprintf(stderr, "  lastSelectionOwner[].lastTimeChanged   [%u]\n", lOwner.lastTimeChanged.milliseconds);

  fprintf(stderr, "  CurrentSelections[].client             %s\n", nxagentClientInfoString(curSel.client));
  fprintf(stderr, "  CurrentSelections[].window             [0x%x]\n", curSel.window);
  if (curSel.pWin)
    fprintf(stderr, "  CurrentSelections[].pWin               [%p] (-> [0x%x])\n", (void *)curSel.pWin, WINDOWID(curSel.pWin));
  else
    fprintf(stderr, "  CurrentSelections[].pWin               -\n");
  fprintf(stderr, "  CurrentSelections[].lastTimeChanged    [%u]\n", curSel.lastTimeChanged.milliseconds);
  return;
}

static void printLastClientStat(int index)
{
  lastClient lc = lastClients[index];
  if (lc.windowPtr)
    fprintf(stderr, "  lastClients[].windowPtr    (WindowPtr) [%p] ([0x%x])\n", (void *)lc.windowPtr, WINDOWID(lc.windowPtr));
  else
    fprintf(stderr, "  lastClients[].windowPtr    (WindowPtr) -\n");
  fprintf(stderr, "  lastClients[].clientPtr    (ClientPtr) %s\n", nxagentClientInfoString(lc.clientPtr));
  fprintf(stderr, "  lastClients[].requestor       (Window) [0x%x]\n", lc.requestor);
  fprintf(stderr, "  lastClients[].property          (Atom) [% 4d][%s]\n", lc.property, NameForLocalAtom(lc.property));
  fprintf(stderr, "  lastClients[].target            (Atom) [% 4d][%s]\n", lc.target, NameForLocalAtom(lc.target));
  if (lc.time > 0)
    fprintf(stderr, "  lastClients[].time              (Time) [%u] ([%u]ms ago)\n", lc.time, GetTimeInMillis() - lc.time);
  else
    fprintf(stderr, "  lastClients[].time              (Time) [%u]\n", lc.time);
  if (lc.reqTime > 0)
    fprintf(stderr, "  lastClients[].reqTime           (Time) [%u] ([%u]ms ago)\n", lc.reqTime, GetTimeInMillis() - lc.reqTime);
  else
    fprintf(stderr, "  lastClients[].reqTime           (Time) [%u]\n", lc.reqTime);
  fprintf(stderr, "  lastClients[].propertySize     (ulong) [%lu]\n", lc.propertySize);
  fprintf(stderr, "  lastClients[].stage   (ClientSelStage) [%d][%s]\n", lc.stage, getClientSelectionStageString(lc.stage));
  fprintf(stderr, "  lastClients[].resource           (int) [%d]\n", lc.resource);
}

static void printLastServerStat(int index)
{
  lastServer ls = lastServers[index];
  fprintf(stderr, "  lastServer[].requestor    (XlibWindow) [0x%lx]\n", ls.requestor);
  fprintf(stderr, "  lastServer[].property       (XlibAtom) [% 4ld][%s]\n", ls.property, NameForRemoteAtom(ls.property));
  fprintf(stderr, "  lastServer[].target         (XlibAtom) [% 4ld][%s]\n", ls.target, NameForRemoteAtom(ls.target));
  fprintf(stderr, "  lastServer[].time               (Time) [%u]\n", ls.time);
}

static void printTargetCacheStat(int index)
{
  fprintf(stderr, "  targetCache[].type               (int) [%d]\n", targetCache[index].type);
  fprintf(stderr, "  targetCache[].forLocal        (Atom *) [%p]\n", (void *)targetCache[index].forLocal);
  fprintf(stderr, "  targetCache[].forRemote   (XlibAtom *) [%p]\n", (void *)targetCache[index].forRemote);
  fprintf(stderr, "  targetCache[].numTargets         (int) [%d]\n", targetCache[index].numTargets);
}

void nxagentDumpClipboardStat(void)
{
  fprintf(stderr, "/----- Clipboard internal status -----\n");

  fprintf(stderr, "  current time                    (Time) [%u]\n", GetTimeInMillis());
  fprintf(stderr, "  agentClipboardInitialized       (Bool) [%s]\n", agentClipboardInitialized ? "True" : "False");
  fprintf(stderr, "  clientAccum                      (int) [%d]\n", clientAccum);
  fprintf(stderr, "  nxagentMaxSelections             (int) [%d]\n", nxagentMaxSelections);
  fprintf(stderr, "  NumCurrentSelections             (int) [%d]\n", NumCurrentSelections);
  fprintf(stderr, "  serverWindow              (XlibWindow) [0x%lx]\n", serverWindow);

  fprintf(stderr, "  Clipboard mode                         ");
  switch(nxagentOption(Clipboard))
  {
    case ClipboardBoth:    fprintf(stderr, "[Both]"); break;;
    case ClipboardClient:  fprintf(stderr, "[Client]"); break;;
    case ClipboardServer:  fprintf(stderr, "[Server]"); break;;
    case ClipboardNone:    fprintf(stderr, "[None]"); break;;
    default:               fprintf(stderr, "[UNKNOWN] (FAIL!)"); break;;
  }
  fprintf(stderr, "\n");

  if (serverLastRequestedSelection == -1)
      fprintf(stderr, "  serverLastRequestedSelection           [-1](uninitialized)\n");
  else
      fprintf(stderr, "  serverLastRequestedSelection           [% 4ld][%s]\n", serverLastRequestedSelection, NameForRemoteAtom(serverLastRequestedSelection));

  fprintf(stderr, "Compile time settings\n");
#ifdef PRINT_CLIPBOARD_CONTENT_ON_DEBUG
  fprintf(stderr, "  PRINT_CLIPBOARD_CONTENT_ON_DEBUG       [enabled]\n");
#else
  fprintf(stderr, "  PRINT_CLIPBOARD_CONTENT_ON_DEBUG       [disabled]\n");
#endif
#ifdef SUPPORT_TEXT_TARGET
  fprintf(stderr, "  SUPPORT_TEXT_TARGET                    [enabled]\n");
#else
  fprintf(stderr, "  SUPPORT_TEXT_TARGET                    [disabled]\n");
#endif
#ifdef SUPPORT_COMPOUND_TEXT_TARGET
  fprintf(stderr, "  SUPPORT_COMPOUND_TEXT_TARGET           [enabled]\n");
#else
  fprintf(stderr, "  SUPPORT_COMPOUND_TEXT_TARGET           [disabled]\n");
#endif

#define WIDTH 32
  Atom cl = 0;
  XlibAtom sv = 0;
  int len = WIDTH;

  fprintf(stderr, "Atoms                                    local%*sremote\n", WIDTH - 5, "");
  cl = clientTARGETS; sv = serverTARGETS; len = (int)(WIDTH - 9 - strlen(NameForLocalAtom(cl)));
  fprintf(stderr, "  TARGETS                                [% 4d][%s]%*s [% 4ld][%s]\n", cl, NameForLocalAtom(cl), len, "", sv, NameForRemoteAtom(sv));

  cl = clientTIMESTAMP; sv = serverTIMESTAMP; len = (int)(WIDTH - 9 - strlen(NameForLocalAtom(cl)));
  fprintf(stderr, "  TIMESTAMP                              [% 4d][%s]%*s [% 4ld][%s]\n", cl, NameForLocalAtom(cl), len, "", sv, NameForRemoteAtom(sv));

#ifdef SUPPORT_TEXT_TARGET
  cl = clientTEXT; sv = serverTEXT; len = (int)(WIDTH - 9 - strlen(NameForLocalAtom(cl)));
  fprintf(stderr, "  TEXT                                   [% 4d][%s]%*s [% 4ld][%s]\n", cl, NameForLocalAtom(cl), len, "", sv, NameForRemoteAtom(sv));
#endif
#ifdef SUPPORT_COMPOUND_TEXT_TARGET
  cl = clientCOMPOUND_TEXT; sv = serverCOMPOUND_TEXT; len = (int)(WIDTH - 9 - strlen(NameForLocalAtom(cl)));
  fprintf(stderr, "  COMPOUND_TEXT                          [% 4d][%s]%*s [% 4ld][%s]\n", cl, NameForLocalAtom(cl), len, "", sv, NameForRemoteAtom(sv));
#endif

  cl = clientUTF8_STRING; sv = serverUTF8_STRING; len = (int)(WIDTH - 9 - strlen(NameForLocalAtom(cl)));
  fprintf(stderr, "  UTF8_STRING                            [% 4d][%s]%*s [% 4ld][%s]\n", cl, NameForLocalAtom(cl), len, "", sv, NameForRemoteAtom(sv));

  sv = serverTransToAgentProperty;
  fprintf(stderr, "  serverTransToAgentProperty             - %*s[% 4ld][%s]\n", WIDTH - 2, "", sv, NameForRemoteAtom(sv));

  sv = serverTransFromAgentProperty;
  fprintf(stderr, "  serverTransFromAgentProperty           - %*s[% 4ld][%s]\n", WIDTH - 2, "", sv, NameForRemoteAtom(sv));

  cl = clientCutProperty; len = (int)(WIDTH - 9 - strlen(NameForLocalAtom(cl)));
  fprintf(stderr, "  clientCutProperty                      [% 4d][%s]%*s\n", cl, NameForLocalAtom(cl), len + 2, "-" );

  for (int index = 0; index < nxagentMaxSelections; index++)
  {
    printSelectionStat(index);
    printLastClientStat(index);
    printLastServerStat(index);
    printTargetCacheStat(index);
  }

  fprintf(stderr, "\\------------------------------------------------------------------------------\n");
}

/*
 * Helper to handle data transfer
 */
static void resetClientSelectionStage(int index)
{
  #ifdef DEBUG
  fprintf(stderr, "%s: Resetting selection stage for [%d]\n", __func__, index);
  #endif

  lastClients[index].stage = SelectionStageNone;
  lastClients[index].windowPtr = NULL;
  lastClients[index].clientPtr = NULL;
  lastClients[index].requestor = 0;
  lastClients[index].property = 0;
  lastClients[index].target = 0;
  lastClients[index].time = 0;
  lastClients[index].reqTime = 0;
  lastClients[index].propertySize = 0;
  lastClients[index].resource = -1;
}

static void setClientSelectionStage(int index, int stage)
{
  if (stage == SelectionStageNone)
  {
    resetClientSelectionStage(index);
  }
  else
  {
    #ifdef DEBUG
    fprintf(stderr, "%s: Changing selection stage for [%d] from [%s] to [%s]\n", __func__, index,
                getClientSelectionStageString(lastClients[index].stage), getClientSelectionStageString(stage));
    #endif
    lastClients[index].stage = stage;
  }
}

/*
 * This is from NXproperty.c.
 */

int GetWindowProperty(WindowPtr pWin, Atom property, long longOffset, long longLength,
                          Bool delete, Atom type, Atom *actualType, int *format,
                              unsigned long *nItems, unsigned long *bytesAfter,
                                  unsigned char **propData);

/*
 * Send a SelectionNotify event to the real X server and do some error
 * handling (in DEBUG mode).
 */
static Status sendSelectionNotifyEventToXServer(XSelectionEvent *event_to_send)
{
  XlibWindow w = event_to_send->requestor;

  event_to_send->type = SelectionNotify;
  event_to_send->send_event = True;
  event_to_send->display = nxagentDisplay;

  Status result = XSendEvent(nxagentDisplay, w, False, 0L, (XEvent *)event_to_send);

  #ifdef DEBUG
  /*
   * man XSendEvent: XSendEvent returns zero if the conversion to wire
   * protocol format failed and returns nonzero otherwise.  XSendEvent
   * can generate BadValue and BadWindow errors.
   */
  if (result == 0)
  {
    fprintf(stderr, "%s: XSendEvent to [0x%lx] failed.\n", __func__, w);
  }
  else
  {
    if (result == BadValue || result == BadWindow)
    {
      fprintf(stderr, "%s: WARNING! XSendEvent to [0x%lx] failed: %s\n", __func__, w, getXErrorString(result));
    }
    else
    {
      fprintf(stderr, "%s: XSendEvent() successfully sent to [0x%lx]\n", __func__, w);
    }
  }
  #endif

  NXFlushDisplay(nxagentDisplay, NXFlushLink);

  return result;
}

static int sendEventToClient(ClientPtr client, xEvent *pEvents)
{
  return TryClientEvents(client, pEvents, 1, NoEventMask, NoEventMask, NullGrab);
}

static void sendSelectionNotifyEventToClient(ClientPtr client,
                                             Time time,
                                             Window requestor,
                                             Atom selection,
                                             Atom target,
                                             Atom property)
{
  /*
   * Check if the client is still valid.
   */
  if (clients[client -> index] != client)
  {
    #ifdef WARNING
    fprintf(stderr, "%s: WARNING! Invalid client pointer.", __func__);
    #endif

    return;
  }

  xEvent x = {0};
  x.u.u.type = SelectionNotify;
  x.u.selectionNotify.time = time;
  x.u.selectionNotify.requestor = requestor;
  x.u.selectionNotify.selection = selection;
  x.u.selectionNotify.target = target;
  x.u.selectionNotify.property = property;

  #ifdef DEBUG
  if (property == None)
    fprintf(stderr, "%s: Denying request to client %s - event time [%u].\n", __func__,
            nxagentClientInfoString(client), time);
  else
    fprintf(stderr, "%s: Sending event to client %s - event time [%u].\n", __func__,
            nxagentClientInfoString(client), time);
  #endif

  sendEventToClient(client, &x);
}

/*
 * Check if target is a valid text content type target sent by the real X
 * server, like .e.g XA_STRING or UTF8_STRING.
 */
static Bool isTextTarget(XlibAtom target)
{
  if (target == XA_STRING)
  {
    #ifdef DEBUG
    fprintf(stderr, "%s: valid target [XA_STRING].\n", __func__);
    #endif
    return True;
  }
#ifdef SUPPORT_TEXT_TARGET
  else if (target == serverTEXT)
  {
    #ifdef DEBUG
    fprintf(stderr, "%s: valid target [TEXT].\n", __func__);
    #endif
    return True;
  }
#endif
#ifdef SUPPORT_COMPOUND_TEXT_TARGET
  else if (target == serverCOMPOUND_TEXT)
  {
    #ifdef DEBUG
    fprintf(stderr, "%s: valid target [COMPOUND_TEXT].\n", __func__);
    #endif
    return True;
  }
#endif
  else if (target == serverUTF8_STRING)
  {
    #ifdef DEBUG
    fprintf(stderr, "%s: valid target [UTF8_STRING].\n", __func__);
    #endif
    return True;
  }
  /* FIXME: add text/plain */

  #ifdef DEBUG
  fprintf(stderr, "%s: not a text target [%lu].\n", __func__, target);
  #endif
  return False;
}

static void initSelectionOwnerData(int index)
{
  lastSelectionOwner[index].client = NullClient;
  lastSelectionOwner[index].window = screenInfo.screens[0]->root->drawable.id;
  lastSelectionOwner[index].windowPtr = NULL;
  lastSelectionOwner[index].lastTimeChanged = ClientTimeToServerTime(CurrentTime);
}

/* there's no owner on nxagent side anymore */
static void clearSelectionOwnerData(int index)
{
  lastSelectionOwner[index].client = NullClient;
  lastSelectionOwner[index].window = None;
  lastSelectionOwner[index].windowPtr = NULL;
  lastSelectionOwner[index].lastTimeChanged = ClientTimeToServerTime(CurrentTime);
}

#ifdef NXAGENT_CLIPBOARD
static void storeSelectionOwnerData(int index, Selection *sel)
{
  lastSelectionOwner[index].client = sel->client;
  lastSelectionOwner[index].window = sel->window;
  lastSelectionOwner[index].windowPtr = sel->pWin;
  lastSelectionOwner[index].lastTimeChanged = ClientTimeToServerTime(CurrentTime);
}
#endif

static Bool matchSelectionOwner(int index, ClientPtr pClient, WindowPtr pWindow)
{
  return ((pClient && lastSelectionOwner[index].client == pClient) ||
          (pWindow && lastSelectionOwner[index].windowPtr == pWindow));
}

/*
 * Clear relevant clipboard states if a client or window is closing.
 * Attention: does not work properly when both client AND window
 * are passed as setClientSelectionStage(None) will also clear
 * the lastClientWindowPtr!
 * This is only called from Client.c and Window.c
 */
void nxagentClearClipboard(ClientPtr pClient, WindowPtr pWindow)
{
  #ifdef DEBUG
  fprintf(stderr, "%s: Called with client [%p] index [%d] window [%p] ([0x%x]).\n", __func__,
              (void *) pClient, CLINDEX(pClient), (void *) pWindow, WINDOWID(pWindow));
  #endif

  /* FIXME: there's almost identical code in nxagentClipboardInit */
  for (int index = 0; index < nxagentMaxSelections; index++)
  {
    if (matchSelectionOwner(index, pClient, pWindow))
    {
      #ifdef TEST
      fprintf(stderr, "%s: Resetting state [%d] with client [%p] window [%p].\n", __func__,
                  index, (void *) pClient, (void *) pWindow);
      #endif

      clearSelectionOwnerData(index);

      setClientSelectionStage(index, SelectionStageNone);

      replyPendingRequestSelectionToXServer(index, False);
    }

    if (pWindow && pWindow == lastClients[index].windowPtr)
    {
      setClientSelectionStage(index, SelectionStageNone);
    }
  }
}

/*
 * Find the index of the lastSelectionOwner with the selection
 * sel. sel is an atom on the real X server. If the index cannot be
 * determined it will return -1.
 */
int nxagentFindRemoteSelectionIndex(XlibAtom sel)
{
  for (int index = 0; index < nxagentMaxSelections; index++)
  {
    if (remoteSelectionAtoms[index] == sel)
    {
      #ifdef DEBUG
      fprintf(stderr, "%s: remote selection [%ld][%s] belongs to index [%d]\n", __func__, sel, NameForRemoteAtom(sel), index);
      #endif
      return index;
    }
  }
  #ifdef DEBUG
  fprintf(stderr, "%s: remote selection [%ld][%s] does not belong to any index!\n", __func__, sel, NameForRemoteAtom(sel));
  #endif
  return -1;
}

/*
 * Find the index of CurrentSelection with the selection
 * sel. sel is a local atom. If the index cannot be
 * determined it will return -1.
 */
int nxagentFindCurrentSelectionIndex(Atom sel)
{
  /*
   * Normally you'd expect the loop going up to
   * NumCurrentSelections. But the dix code will increase that number
   * (but not nxagentMaxSelections) when drag and drop comes into
   * play. In that case this helper will report a match for other
   * selections than the ones the clipboard code knows about. The
   * subsequent code will then use a higher index which will be used
   * by the clipboard code and will lead to out of range data reads
   * (and writes!). Therefore we take nxagentMaxSelections here. The
   * startup code ensures that both arrays will refer to the same
   * selection for the first nxagentMaxSelections selection atoms.
   */

  /*  for (int index = 0; index < NumCurrentSelections; index++) */
  for (int index = 0; index < nxagentMaxSelections; index++)
  {
    if (CurrentSelections[index].selection == sel)
    {
      #ifdef DEBUG
      fprintf(stderr, "%s: selection [%d][%s] belongs to index [%d]\n", __func__, sel, NameForLocalAtom(sel), index);
      #endif
      return index;
    }
  }
  #ifdef DEBUG
  fprintf(stderr, "%s: selection [%d][%s] does not belong to any index!\n", __func__, sel, NameForLocalAtom(sel));
  #endif
  return -1;
}

void cacheTargetsForLocal(int index, Atom* targets, int numTargets)
{
  #ifdef DEBUG
  fprintf(stderr, "%s: caching [%d] targets for local requests\n", __func__, numTargets);
  #endif

  SAFE_free(targetCache[index].forLocal);
  SAFE_free(targetCache[index].forRemote);
  targetCache[index].type = FOR_LOCAL;
  targetCache[index].forLocal = targets;
  targetCache[index].numTargets = numTargets;
}

void cacheTargetsForRemote(int index, XlibAtom* targets, int numTargets)
{
  #ifdef DEBUG
  fprintf(stderr, "%s: caching [%d] targets for remote requests\n", __func__, numTargets);
  #endif

  SAFE_free(targetCache[index].forLocal);
  SAFE_free(targetCache[index].forRemote);
  targetCache[index].type = FOR_REMOTE;
  targetCache[index].forRemote = targets;
  targetCache[index].numTargets = numTargets;
}

/* This is called on init, reconnect and SelectionClear. */
void invalidateTargetCache(int index)
{
  #ifdef DEBUG
  fprintf(stderr, "%s: invalidating target cache [%d]\n", __func__, index);
  #endif

  SAFE_free(targetCache[index].forLocal);
  SAFE_free(targetCache[index].forRemote);
  targetCache[index].type = EMPTY;
  targetCache[index].numTargets = 0;
}

void invalidateTargetCaches(void)
{
  #ifdef DEBUG
  fprintf(stderr, "%s: invalidating all target caches\n", __func__);
  #endif

  for (int index = 0; index < nxagentMaxSelections; index++)
  {
    SAFE_free(targetCache[index].forLocal);
    SAFE_free(targetCache[index].forRemote);
    targetCache[index].type = EMPTY;
    targetCache[index].numTargets = 0;
  }
}

/*
 * This is called from Events.c dispatch loop on reception of a
 * SelectionClear or XFixes selection event from the real X
 * server. We receive this event if someone on the real X server
 * claims the selection ownership we have/had.
 * Three versions of this routine with different parameter types.
 */
void nxagentHandleSelectionClearFromXServerByIndex(int index)
{
  #ifdef DEBUG
  fprintf(stderr, "%s: SelectionClear event for selection index [%u].\n", __func__, index);
  #endif

  if (index == -1)
  {
    #ifdef DEBUG
    fprintf(stderr, "%s: ignoring index -1 - doing nothing.\n", __func__);
    #endif
    return;
  }

  if (!agentClipboardInitialized)
  {
    #ifdef DEBUG
    fprintf(stderr, "%s: clipboard not initialized - doing nothing.\n", __func__);
    #endif
    return;
  }

  if (nxagentOption(Clipboard) == ClipboardServer)
  {
    #ifdef DEBUG
    fprintf(stderr, "%s: clipboard mode 'server' - doing nothing.\n", __func__);
    #endif
    return;
  }

  UpdateCurrentTime();
  TimeStamp time = ClientTimeToServerTime(CurrentTime);

  if (IS_LOCAL_OWNER(index))
  {
    /* Send a SelectionClear event to (our) previous owner. */
    xEvent x = {0};
    x.u.u.type = SelectionClear;
    x.u.selectionClear.time = time.milliseconds;
    x.u.selectionClear.window = lastSelectionOwner[index].window;
    x.u.selectionClear.atom = CurrentSelections[index].selection;

    sendEventToClient(lastSelectionOwner[index].client, &x);

    /*
     * Set the root window with the NullClient as selection owner. Our
     * clients asking for the owner via XGetSelectionOwner() will get
     * this for an answer.
     * Set the CurrentSelection data just as ProcSetSelectionOwner does.
     */
    CurrentSelections[index].lastTimeChanged = time;
    CurrentSelections[index].window = screenInfo.screens[0]->root->drawable.id;
    CurrentSelections[index].pWin = NULL;
    CurrentSelections[index].client = NullClient;

    clearSelectionOwnerData(index);

    setClientSelectionStage(index, SelectionStageNone);

    invalidateTargetCache(index);

    /*
     * Now call the callbacks. This is important, especially for
     * XFixes events to work properly. Keep in mind that this will
     * also call our own callback so we must be prepared there to not
     * communicate back to the real X server about this SelectionClear
     * event. It already knows about that...
     */
    if (SelectionCallback)
    {
        SelectionInfoRec info = {0};

        info.selection = &CurrentSelections[index];
        info.kind = SelectionSetOwner;
        CallCallbacks(&SelectionCallback, &info);
    }
  }
  else
  {
    #ifdef DEBUG
    fprintf(stderr, "%s: selection already cleared - doing nothing.\n", __func__);
    #endif
  }
}

void nxagentHandleSelectionClearFromXServerByAtom(XlibAtom sel)
{
  #ifdef DEBUG
  fprintf(stderr, "---------\n%s: SelectionClear event for remote selection atom [%lu][%s].\n", __func__, sel, NameForRemoteAtom(sel));
  #endif

  nxagentHandleSelectionClearFromXServerByIndex(nxagentFindRemoteSelectionIndex(sel));
}

void nxagentHandleSelectionClearFromXServer(XEvent *X)
{
  #ifdef DEBUG
  fprintf(stderr, "---------\n%s: SelectionClear event for selection [%lu][%s] window [0x%lx] time [%lu].\n",
              __func__, X->xselectionclear.selection, NameForRemoteAtom(X->xselectionclear.selection),
                  X->xselectionclear.window, X->xselectionclear.time);
  #endif
  nxagentHandleSelectionClearFromXServerByAtom(X->xselectionclear.selection);
}

/*
 * Send a SelectionNotify event as reply to the RequestSelection
 * event X. If success is True take the property from the event, else
 * take None (which reports "failed/denied" to the requestor).
 */
static void replyRequestSelectionToXServer(XEvent *X, Bool success)
{
  XSelectionEvent eventSelection = {
    .requestor = X->xselectionrequest.requestor,
    .selection = X->xselectionrequest.selection,
    .target    = X->xselectionrequest.target,
    .time      = X->xselectionrequest.time,
    .property  = X->xselectionrequest.property
  };

  if (!success)
  {
    #ifdef DEBUG
    fprintf(stderr, "%s: denying request\n", __func__);
    #endif
    eventSelection.property = None;
  }

  sendSelectionNotifyEventToXServer(&eventSelection);
}

/*
 * This is called from Events.c dispatch loop on reception of a
 * SelectionRequest event, meaning a client of the real X server wants
 * to have the selection content. The real X server knows the nxagent
 * as selection owner. But in reality one of our windows is the owner,
 * so we must pass the request on to the real owner.
 */
void nxagentHandleSelectionRequestFromXServer(XEvent *X)
{
  XlibAtom target = X->xselectionrequest.target;

  #ifdef DEBUG
  fprintf(stderr, "---------\n%s: Received SelectionRequestEvent from real server: selection [%ld][%s] " \
          "target [%ld][%s] requestor [display[%s]/0x%lx] destination [%ld][%s] time [%lu]\n",
          __func__,
          X->xselectionrequest.selection, NameForRemoteAtom(X->xselectionrequest.selection),
          target, NameForRemoteAtom(target),
          DisplayString(nxagentDisplay), X->xselectionrequest.requestor,
          X->xselectionrequest.property,  NameForRemoteAtom(X->xselectionrequest.property),
          X->xselectionrequest.time);
  if (X->xselectionrequest.requestor == serverWindow)
  {
    fprintf(stderr, "%s: this event has been sent by nxagent!\n", __func__);;
  }
  #endif

  if (!agentClipboardInitialized)
  {
    #ifdef DEBUG
    fprintf(stderr, "%s: clipboard not initialized - doing nothing.\n", __func__);
    #endif
    return;
  }

  /* The selection in this request is none we own. */
  int index = nxagentFindRemoteSelectionIndex(X->xselectionrequest.selection);
  if (index == -1)
  {
    #ifdef DEBUG
    fprintf(stderr, "%s: not owning selection [%ld] - denying request.\n", __func__, X->xselectionrequest.selection);
    #endif

    replyRequestSelectionToXServer(X, False);
    return;
  }

  if (!IS_LOCAL_OWNER(index))
  {
    #ifdef DEBUG
    fprintf(stderr, "%s: no local owner for selection [%ld] - denying request.\n", __func__, X->xselectionrequest.selection);
    #endif
    replyRequestSelectionToXServer(X, False);
    return;
  }

  #ifdef DEBUG
  fprintf(stderr, "%s: lastServers[%d].requestor [0x%lx].\n", __func__, index, lastServers[index].requestor);
  #endif

  /* lastServers[index].requestor is non-NULL (= we are currently in the transfer phase) */
  if (lastServers[index].requestor != None)
  {
    #ifdef DEBUG
    fprintf(stderr, "%s: denying additional request during transfer phase.\n", __func__);
    #endif

    replyRequestSelectionToXServer(X, False);
    return;
  }

  if (target == serverTARGETS)
  {
    /*
     * In TextClipboard mode answer with a predefined list of
     * targets. This is just the previous implementation of handling
     * the clipboard.
     */
    if (nxagentOption(TextClipboard))
    {
      /*
       * The selection request target is TARGETS. The requestor is
       * asking for a list of supported data formats.
       *
       * The selection does not matter here, we will return this for
       * PRIMARY and CLIPBOARD.
       *
       * The list is aligned with the one in nxagentConvertSelection()
       * and in isTextTarget().
       */

      XlibAtom targets[] = {XA_STRING,
                            serverUTF8_STRING,
#ifdef SUPPORT_TEXT_TARGET
                            serverTEXT,
#endif
#ifdef SUPPORT_COMPOUND_TEXT_TARGET
                            serverCOMPOUND_TEXT,
#endif
                            serverTARGETS,
                            serverTIMESTAMP};
      int numTargets = sizeof(targets) / sizeof(targets[0]);

      #ifdef DEBUG
      fprintf(stderr, "%s: Sending %d available targets:\n", __func__, numTargets);
      for (int i = 0; i < numTargets; i++)
      {
        fprintf(stderr, "%s: %ld %s\n", __func__, targets[i], NameForRemoteAtom(targets[i]));
      }
      #endif

      /*
       * Pass on the requested list by setting the property provided
       * by the requestor accordingly.
       */
      XChangeProperty(nxagentDisplay,
                      X->xselectionrequest.requestor,
                      X->xselectionrequest.property,
                      XInternAtom(nxagentDisplay, "ATOM", 0),
                      32,
                      PropModeReplace,
                      (unsigned char*)targets,
                      numTargets);

      replyRequestSelectionToXServer(X, True);
      return;
    }
    else
    {
      /*
       * Shortcut: Some applications tend to post multiple
       * SelectionRequests. Further it can happen that multiple
       * clients are interested in clipboard content. If we already
       * know the answer and no intermediate SelectionOwner event
       * occurred we can answer with the cached list of targets.
       */

      if (targetCache[index].type == FOR_REMOTE && targetCache[index].forRemote)
      {
        XlibAtom *targets = targetCache[index].forRemote;
        unsigned int numTargets = targetCache[index].numTargets;

        #ifdef DEBUG
        fprintf(stderr, "%s: Sending %d cached targets to remote requestor:\n", __func__, numTargets);
        for (int i = 0; i < numTargets; i++)
        {
          fprintf(stderr, "%s: %ld %s\n", __func__, targets[i], NameForRemoteAtom(targets[i]));
        }
        #endif

        XChangeProperty(nxagentDisplay,
                        X->xselectionrequest.requestor,
                        X->xselectionrequest.property,
                        XInternAtom(nxagentDisplay, "ATOM", 0),
                        32,
                        PropModeReplace,
                        (unsigned char *)targets,
                        numTargets);

        replyRequestSelectionToXServer(X, True);
        return;
      }
    }
  }
  else if (target == serverTIMESTAMP)
  {
    /*
     * Section 2.6.2 of the ICCCM states:
     * TIMESTAMP - To avoid some race conditions, it is important
     * that requestors be able to discover the timestamp the owner
     * used to acquire ownership. Until and unless the protocol is
     * changed so that a GetSelectionOwner request returns the
     * timestamp used to acquire ownership, selection owners must
     * support conversion to TIMESTAMP, returning the timestamp they
     * used to obtain the selection.
     *
     * FIXME: ensure we are reporting an _external_ timestamp
     * FIXME: for a 32 bit property list we need to pass a "long" array, not "char"!
     */

    XChangeProperty(nxagentDisplay,
                    X->xselectionrequest.requestor,
                    X->xselectionrequest.property,
                    XA_INTEGER,
                    32,
                    PropModeReplace,
                    (unsigned char *) &lastSelectionOwner[index].lastTimeChanged,
                    1);
    replyRequestSelectionToXServer(X, True);
    return;
  }
  else if (target == serverMULTIPLE)
  {
    #ifdef DEBUG
    fprintf(stderr, "%s: (currently) unsupported target [MULTIPLE] - denying request.\n", __func__);
    #endif
    replyRequestSelectionToXServer(X, False);
    return;
  }
  else if (target == serverDELETE)
  {
    #ifdef DEBUG
    fprintf(stderr, "%s: (currently) unsupported target [DELETE] - denying request.\n", __func__);
    #endif
    replyRequestSelectionToXServer(X, False);
    return;
  }
  else if (target == serverINSERT_SELECTION)
  {
    #ifdef DEBUG
    fprintf(stderr, "%s: (currently) unsupported target [INSERT_SELECTION] - denying request.\n", __func__);
    #endif
    replyRequestSelectionToXServer(X, False);
    return;
  }
  else if (target == serverINSERT_PROPERTY)
  {
    #ifdef DEBUG
    fprintf(stderr, "%s: (currently) unsupported target [INSERT_PROPERTY] - denying request.\n", __func__);
    #endif
    replyRequestSelectionToXServer(X, False);
    return;
  }
  else if (target == serverSAVE_TARGETS)
  {
    #ifdef DEBUG
    fprintf(stderr, "%s: (currently) unsupported target [SAVE_TARGETS] - denying request.\n", __func__);
    #endif
    replyRequestSelectionToXServer(X, False);
    return;
  }
  else if (target == serverTARGET_SIZES)
  {
    #ifdef DEBUG
    fprintf(stderr, "%s: (currently) unsupported target [TARGET_SIZES] - denying request.\n", __func__);
    #endif
    replyRequestSelectionToXServer(X, False);
    return;
  }

  if (nxagentOption(TextClipboard))
  {
    if (!isTextTarget(target))
    {
      #ifdef DEBUG
      fprintf(stderr, "%s: denying request for non-text target [%ld][%s].\n", __func__,
                  target, NameForRemoteAtom(target));
      #endif

      replyRequestSelectionToXServer(X, False);

      return;
    }
    /* go on, target is acceptable */
  }

  #ifdef DEBUG
  fprintf(stderr, "%s: target [%ld][%s].\n", __func__, target,
              NameForRemoteAtom(target));
  #endif

  /*
   * Reaching this line means the request is a normal, valid
   * request. We can process it now.
   */

  if (!nxagentOption(TextClipboard))
  {
    /*
     * Optimization: if we have a current target cache check if the
     * requested target is supported by the owner. If not we can take
     * a shortcut and deny the request immediately without doing any
     * further communication.
     */
    if (targetCache[index].type == FOR_REMOTE && targetCache[index].forRemote)
    {
      XlibAtom *targets = targetCache[index].forRemote;

      #ifdef DEBUG
      fprintf(stderr, "%s: Checking target validity\n", __func__);
      #endif
      Bool match = False;
      for (int i = 0; i < targetCache[index].numTargets; i++)
      {
        if (targets[i] == target)
        {
          match = True;
          break;
        }
      }
      if (!match)
      {
        #ifdef DEBUG
        fprintf(stderr, "%s: target [%ld][%s] is not supported by the owner - denying request.\n",
                    __func__, X->xselectionrequest.target, NameForRemoteAtom(X->xselectionrequest.target));
        #endif
        replyRequestSelectionToXServer(X, False);
        return;
      }
    }
    else
    {
      /*
       * At this stage we know a remote client has requested a
       * selection target without having retrieved the list of
       * supported targets first.
       */
      #ifdef DEBUG
      if (target != serverTARGETS)
      {
         fprintf(stderr, "%s: WARNING: remote client has not retrieved TARGETS before asking for selection!\n",
                   __func__);
      }
      #endif
    }
  }

  /*
   * This is required for nxagentGetClipboardWindow.
   */
  serverLastRequestedSelection = X->xselectionrequest.selection;

  if (!(nxagentOption(Clipboard) == ClipboardServer ||
        nxagentOption(Clipboard) == ClipboardBoth))
  {
    #ifdef DEBUG
    fprintf (stderr, "%s: clipboard (partly) disabled - denying request.\n", __func__);
    #endif

    /* deny the request */
    replyRequestSelectionToXServer(X, False);
    return;
  }

  /*
   * If one of our clients owns the selection we ask it to copy
   * the selection to the clientCutProperty on nxagent's root
   * window in the first step. We then later push that property's
   * content to the real X server.
   */
  if (IS_LOCAL_OWNER(index))
  {
    /*
     * Store who on the real X server requested the data and how
     * and where it wants to have it.
     */
    lastServers[index].property = X->xselectionrequest.property;
    lastServers[index].requestor = X->xselectionrequest.requestor;
    lastServers[index].target = target;
    lastServers[index].time = X->xselectionrequest.time;

    /* Prepare the request (like XConvertSelection, but locally). */
    xEvent x = {0};
    x.u.u.type = SelectionRequest;
    x.u.selectionRequest.time = GetTimeInMillis();
    x.u.selectionRequest.owner = lastSelectionOwner[index].window;
    x.u.selectionRequest.selection = CurrentSelections[index].selection;
    x.u.selectionRequest.property = clientCutProperty;
    x.u.selectionRequest.requestor = screenInfo.screens[0]->root->drawable.id; /* Fictitious window.*/

    /*
     * Don't send the same window, some programs are clever and
     * verify cut and paste operations inside the same window and
     * don't notify at all.
     *
     * x.u.selectionRequest.requestor = lastSelectionOwner[index].window;
     */

    /*
     * In TextClipboard mode simply use the previous clipboard
     * handling code.
     */
    if (nxagentOption(TextClipboard))
    {
      /* by dimbor */
      if (target != XA_STRING)
      {
        lastServers[index].target = serverUTF8_STRING;
        /* by dimbor (idea from zahvatov) */
        x.u.selectionRequest.target = clientUTF8_STRING;
      }
      else
      {
        x.u.selectionRequest.target = XA_STRING;
      }
    }
    else
    {
      x.u.selectionRequest.target = nxagentRemoteToLocalAtom(target);
    }

    /*
     * Delete property before sending the request to the client as
     * required by ICCCM.
     */
    DeleteProperty(lastSelectionOwner[index].windowPtr, clientCutProperty);

    sendEventToClient(lastSelectionOwner[index].client, &x);

    #ifdef DEBUG
    fprintf(stderr, "%s: sent SelectionRequest event to client %s property [%d][%s] " \
            "target [%d][%s] requestor [0x%x] selection [%d][%s].\n", __func__,
            nxagentClientInfoString(lastSelectionOwner[index].client),
            x.u.selectionRequest.property, NameForLocalAtom(x.u.selectionRequest.property),
            x.u.selectionRequest.target, NameForLocalAtom(x.u.selectionRequest.target),
            x.u.selectionRequest.requestor,
            x.u.selectionRequest.selection, NameForLocalAtom(x.u.selectionRequest.selection));
    #endif
    /*
     * No reply to the Xserver yet - we will do that once the answer
     * of the above sendEventToClient arrives.
     */
  }
  else
  {
    #ifdef DEBUG
    fprintf(stderr, "%s: no local owner for selection [%ld][%s] - denying request.\n", __func__,
                X->xselectionrequest.selection, NameForRemoteAtom(X->xselectionrequest.selection));
    #endif

    /* deny the request */
    replyRequestSelectionToXServer(X, False);
  }
}

/*
 * End the current selection transfer by sending a notification to the
 * client and resetting the corresponding variables and the state
 * machine. If success is False send a None reply, meaning "request
 * denied/failed".
 * Use SELECTION_SUCCESS and SELECTION_FAULT macros for the success
 * value.
 */
static void endTransfer(int index, Bool success)
{
  if (lastClients[index].clientPtr == NULL)
  {
    #ifdef DEBUG
    fprintf(stderr, "%s: lastClients[%d].clientPtr is NULL - doing nothing.\n", __func__, index);
    #endif
  }
  else
  {
    #ifdef DEBUG
    if (success == SELECTION_SUCCESS)
      fprintf(stderr, "%s: sending notification to client %s, property [%d][%s]\n", __func__,
                  nxagentClientInfoString(lastClients[index].clientPtr), lastClients[index].property, NameForLocalAtom(lastClients[index].property));
    else
      fprintf(stderr, "%s: sending negative notification to client %s\n", __func__,
                  nxagentClientInfoString(lastClients[index].clientPtr));
    #endif

    sendSelectionNotifyEventToClient(lastClients[index].clientPtr,
                                     lastClients[index].time,
                                     lastClients[index].requestor,
                                     localSelectionAtoms[index],
                                     lastClients[index].target,
                                     success == SELECTION_SUCCESS ? lastClients[index].property : None);
  }

  /*
   * Enable further requests from clients.
   */
  setClientSelectionStage(index, SelectionStageNone);
}

static void transferSelectionFromXServer(int index, int resource)
{
  #ifdef DEBUG
  fprintf(stderr, "%s: resource [%d] lastClients[%d].clientPtr->index [%d].\n", __func__,
              resource, index, lastClients[index].clientPtr -> index);
  #endif
  /* FIXME: can we use this instead of lastClients[index].resource? */
  if (lastClients[index].clientPtr -> index != resource)
  {
    #ifdef DEBUG
    fprintf (stderr, "%s: WARNING! Inconsistent resource [%d] with current client %s.\n", __func__,
                 resource, nxagentClientInfoString(lastClients[index].clientPtr));
    #endif

    endTransfer(index, SELECTION_FAULT);

    return;
  }

  switch (lastClients[index].stage)
  {
    case SelectionStageQuerySize:
    {
      int result;

      printClientSelectionStage(index);

      /*
       * Don't get data yet, just get size. We skip this stage in
       * current implementation and go straight to the data.
       */

      /* Get next free resource slot. */
      int free_resource = NXGetCollectPropertyResource(nxagentDisplay);

      lastClients[index].resource = free_resource;

      if (free_resource == -1)
      {
        #ifdef WARNING
        fprintf(stderr, "%s: WARNING! Asynchronous GetProperty queue full.\n", __func__);
        #endif

        result = -1;
      }
      else
      {
        /* Collect the property and store it with index "free_resource" */
        result = NXCollectProperty(nxagentDisplay,
                                   free_resource,
                                   serverWindow,
                                   serverTransToAgentProperty,
                                   0,
                                   0,
                                   False,
                                   AnyPropertyType);
      }

      if (result == -1)
      {
        #ifdef DEBUG
        fprintf (stderr, "%s: Aborting selection notify procedure for client %s.\n", __func__,
                     nxagentClientInfoString(lastClients[index].clientPtr));
        #endif

        endTransfer(index, SELECTION_FAULT);

        return;
      }

      setClientSelectionStage(index, SelectionStageWaitSize);

      NXFlushDisplay(nxagentDisplay, NXFlushLink);

      break;
    }
    case SelectionStageQueryData:
    {
      int result;

      printClientSelectionStage(index);

      /*
       * Request the selection data now.
       */

      #ifdef DEBUG
      fprintf(stderr, "%s: Getting property content from remote server.\n", __func__);
      #endif

      /* Get next free resource slot. */
      resource = NXGetCollectPropertyResource(nxagentDisplay);

      lastClients[index].resource = resource;

      if (resource == -1)
      {
        #ifdef WARNING
        fprintf(stderr, "%s: WARNING! Asynchronous GetProperty queue full.\n", __func__);
        #endif

        result = -1;
      }
      else
      {
        /*
         * Now initiate kind of an asynchronuos GetProperty()
         * call. Once the property has been retrieved we will
         * receive an NXCollectPropertyNotify event which will then
         * be handled in
         * nxagentCollectPropertyEventFromXServer().
         */
        result = NXCollectProperty(nxagentDisplay,
                                   resource,
                                   serverWindow,
                                   serverTransToAgentProperty,
                                   0,
                                   lastClients[index].propertySize,
                                   False,
                                   AnyPropertyType);
      }

      if (result == -1)
      {
        #ifdef DEBUG
        fprintf (stderr, "%s: Aborting selection notify procedure for client %s.\n", __func__,
                     nxagentClientInfoString(lastClients[index].clientPtr));
        #endif

        endTransfer(index, SELECTION_FAULT);

        return;
      }

      setClientSelectionStage(index, SelectionStageWaitData);

      /*
       * We've seen situations where you had to move the mouse or press a
       * key to let the transfer complete. Flushing here fixed it
       */
      NXFlushDisplay(nxagentDisplay, NXFlushLink);

      break;
    }
    default:
    {
      #ifdef DEBUG
      fprintf (stderr, "%s: WARNING! Inconsistent state [%s] for selection [%d] for client %s.\n", __func__,
                   getClientSelectionStageString(lastClients[index].stage), index,
                       nxagentClientInfoString(lastClients[index].clientPtr));
      #endif

      break;
    }
  }
}

/*
   Called from Events.c/nxagentHandleCollectPropertyEvent
   This event is generated after XChangeProperty(), XDeleteProperty() or
   XGetWindowProperty(delete=True).

   Returncode:
   True: processed
   False: not processed, resource is not ours
*/
Bool nxagentCollectPropertyEventFromXServer(int resource)
{
  XlibAtom              atomReturnType;
  int                   resultFormat;
  unsigned long         ulReturnItems;
  unsigned long         ulReturnBytesLeft;
  unsigned char         *pszReturnData = NULL;

  int index = 0;

  if (resource < 0)
  {
    #ifdef DEBUG
    fprintf (stderr, "%s: resource [%d] is invalid.\n", __func__, resource);
    #endif
    return False;
  }

  /* Determine the selection we are talking about here. */
  for (index = 0; index < nxagentMaxSelections; index++)
  {
    /*
    #ifdef DEBUG
    fprintf(stderr, "%s: lastClients[%d].resource [%d] resource [%d]\n", __func__, index, lastClients[index].resource, resource);
    #endif
    */
    if (lastClients[index].resource == resource)
    {
      #ifdef DEBUG
      fprintf (stderr, "%s: resource [%d] belongs to selection [%d].\n", __func__, resource, index);
      #endif
      break;
    }
  }

  if (index == nxagentMaxSelections)
  {
    /*
    #ifdef DEBUG
    fprintf (stderr, "%s: resource [%d] does not belong to any selection we handle.\n", __func__, resource);
    #endif
    */
    return False;
  }

  /*
   * We have received the notification so we can safely retrieve data
   * from the client structure.
   */

  int result = NXGetCollectedProperty(nxagentDisplay,
                                      resource,
                                      &atomReturnType,
                                      &resultFormat,
                                      &ulReturnItems,
                                      &ulReturnBytesLeft,
                                      &pszReturnData);

  #ifdef DEBUG
  fprintf(stderr, "%s: NXGetCollectedProperty: result [%d]\n", __func__, result);
  fprintf(stderr, "%s:   atomReturnType [%ld]\n", __func__, atomReturnType);
  fprintf(stderr, "%s:   resultFormat [%d]\n", __func__, resultFormat);
  fprintf(stderr, "%s:   ulReturnItems [%lu]\n", __func__, ulReturnItems);
  fprintf(stderr, "%s:   ulReturnBytesLeft [%lu]\n", __func__, ulReturnBytesLeft);
  #endif

  lastClients[index].resource = -1;

  /*
   * ICCCM states: "The requestor must delete the property named in
   * the SelectionNotify once all the data has been retrieved. The
   * requestor should invoke either DeleteProperty or GetProperty
   * (delete==True) after it has successfully retrieved all the data
   * in the selection."
   * FIXME: this uses serverTransToAgentProperty which is shared between
   * all the selections. Could be a problem with simultaneous transfers.
   * FIXME: NXGetCollectedProperty can return 0 and True. Some other
   * functions in this field return False as well. Clean up that
   * mess...
   */
  if (result == True && ulReturnBytesLeft == 0)
  {
    #ifdef DEBUG
    fprintf (stderr, "%s: Retrieved property data - deleting property [%ld][%s] "
             "for ICCCM conformity.\n", __func__, serverTransToAgentProperty,
             NameForRemoteAtom(serverTransToAgentProperty));
    #endif
    XDeleteProperty(nxagentDisplay, serverWindow, serverTransToAgentProperty);
  }

  if (result == 0)
  {
    #ifdef DEBUG
    fprintf (stderr, "%s: Failed to get reply data.\n", __func__);
    #endif

    endTransfer(index, SELECTION_FAULT);
  }
  else if (resultFormat != 8 && resultFormat != 16 && resultFormat != 32)
  {
    #ifdef DEBUG
    fprintf(stderr, "%s: WARNING! Invalid property format [%d].\n", __func__, resultFormat);
    #endif

    endTransfer(index, SELECTION_FAULT);
  }
  else
  {
    switch (lastClients[index].stage)
    {
      case SelectionStageWaitSize:
      {
        printClientSelectionStage(index);
        #ifdef DEBUG
        fprintf (stderr, "%s: Got size notify event for client %s.\n", __func__,
                     nxagentClientInfoString(lastClients[index].clientPtr));
        #endif

        if (ulReturnBytesLeft == 0)
        {
          #ifdef DEBUG
          fprintf (stderr, "%s: data size is [0] - aborting selection notify procedure.\n", __func__);
          #endif

          endTransfer(index, SELECTION_FAULT);
        }
        else
        {
          #ifdef DEBUG
          fprintf(stderr, "%s: Got property size [%lu] from remote server.\n", __func__, ulReturnBytesLeft);
          #endif

          /*
           * Request the selection data now.
           */
          lastClients[index].propertySize = ulReturnBytesLeft;
          setClientSelectionStage(index, SelectionStageQueryData);

          transferSelectionFromXServer(index, resource);
        }
        break;
      }
      case SelectionStageWaitData:
      {
        printClientSelectionStage(index);
        #ifdef DEBUG
        fprintf (stderr, "%s: Got data notify event for waiting client %s.\n", __func__,
                     nxagentClientInfoString(lastClients[index].clientPtr));
        #endif

        if (ulReturnBytesLeft != 0)
        {
          #ifdef DEBUG
          fprintf (stderr, "%s: not all content could be retrieved - [%lu] bytes left - aborting selection notify procedure.\n", __func__, ulReturnBytesLeft);
          #endif

          endTransfer(index, SELECTION_FAULT);
        }
        else
        {
          #ifdef DEBUG
          fprintf(stderr, "%s: Got property content from remote server. [%lu] items with format [%d] = [%lu] bytes.\n", __func__, ulReturnItems, resultFormat, (ulReturnItems * resultFormat/8));
          #endif

          if (lastClients[index].target == clientTARGETS)
          {
            Atom * targets = calloc(sizeof(Atom), ulReturnItems);
            if (targets == NULL)
            {
              #ifdef WARNING
              fprintf(stderr, "%s: WARNING! Could not alloc memory for clipboard targets transmission.\n", __func__);
              #endif

              /* operation failed */
              endTransfer(index, SELECTION_FAULT);
            }
            else
            {
              /* fprintf(stderr, "sizeof(Atom) [%lu], sizeof(XlibAtom) [%lu], sizeof(long) [%lu], sizeof(CARD32) [%lu] sizeof(INT32) [%lu]\n", sizeof(Atom), sizeof(XlibAtom), sizeof(long), sizeof(CARD32), sizeof(INT32)); */

              Atom *addr = targets;
              unsigned int numTargets = ulReturnItems;

              for (int i = 0; i < numTargets; i++)
              {
                XlibAtom remote = *((XlibAtom*)(pszReturnData + i*resultFormat/8));
                Atom local = nxagentRemoteToLocalAtom(remote);
                *(addr++) = local;

                #ifdef DEBUG
                fprintf(stderr, "%s: converting atom: remote [%u][%s] -> local [%u][%s]\n", __func__,
                            (unsigned int)remote, NameForRemoteAtom(remote), local, NameForLocalAtom(local));
                #endif
              }
              ChangeWindowProperty(lastClients[index].windowPtr,
                                   lastClients[index].property,
                                   MakeAtom("ATOM", 4, 1),
                                   32, PropModeReplace,
                                   ulReturnItems, (unsigned char*)targets, 1);

              cacheTargetsForLocal(index, targets, numTargets);

              endTransfer(index, SELECTION_SUCCESS);
            }
          }
          else
          {
            ChangeWindowProperty(lastClients[index].windowPtr,
                                 lastClients[index].property,
                                 nxagentRemoteToLocalAtom(atomReturnType),
                                 resultFormat, PropModeReplace,
                                 ulReturnItems, pszReturnData, 1);

            #ifdef DEBUG
            fprintf(stderr, "%s: Selection property [%d][%s] changed to resultFormat [%d] returnType [%ld][%s] len [%d]"
                    #ifdef PRINT_CLIPBOARD_CONTENT_ON_DEBUG
                    /* FIXME: only print the string if the resultFormat is 8 */
                    " value [\"%*.*s\"...] hex [0x%2.2x%2.2x%2.2x%2.2x]"
                    #endif
                    "\n", __func__,
                    lastClients[index].property,
                    validateString(NameForLocalAtom(lastClients[index].property)),
                    resultFormat,
                    atomReturnType, NameForRemoteAtom(atomReturnType),
                    (int)ulReturnItems * resultFormat / 8
                    #ifdef PRINT_CLIPBOARD_CONTENT_ON_DEBUG
                    ,(int)(min(20, ulReturnItems * resultFormat / 8)),
                    (int)(min(20, ulReturnItems * resultFormat / 8)),
                    pszReturnData,
                    pszReturnData[0], pszReturnData[1], pszReturnData[2], pszReturnData[3]
                    #endif
                   );
            #endif

            endTransfer(index, SELECTION_SUCCESS);
          }
        }
        break;
      }
      default:
      {
        #ifdef DEBUG
        fprintf(stderr, "%s: WARNING! Inconsistent state [%s] for client %s.\n", __func__,
                    getClientSelectionStageString(lastClients[index].stage),
                        nxagentClientInfoString(lastClients[index].clientPtr));
        #endif
        break;
      }
    }
  }
  SAFE_XFree(pszReturnData);

  return True;
}

/*
 * This is _only_ called from Events.c dispatch loop on reception of a
 * SelectionNotify event from the real X server. These events are
 * sent out by nxagent itself!
 */
void nxagentHandleSelectionNotifyFromXServer(XEvent *X)
{
  if (!agentClipboardInitialized)
  {
    #ifdef DEBUG
    fprintf(stderr, "%s: clipboard not initialized - doing nothing.\n", __func__);
    #endif
    return;
  }

  XSelectionEvent *E = (XSelectionEvent *)X;
  #ifdef DEBUG
  fprintf(stderr, "---------\n%s: Received SelectionNotify event from real X server, property " \
              "[%ld][%s] requestor [0x%lx] selection [%s] target [%ld][%s] time [%lu] send_event [%d].\n",
                  __func__, E->property, NameForRemoteAtom(E->property), E->requestor,
                      NameForRemoteAtom(E->selection), E->target,
                          NameForRemoteAtom(E->target), E->time, E->send_event);

  /* this has not been SENT by nxagent but is the answer to a request of nxagent */
  if (E->requestor == serverWindow)
  {
    fprintf(stderr, "%s: requestor is nxagent's serverWindow!\n", __func__);;
  }
  #endif

  /* determine the selection we are talking about here */
  int index = nxagentFindRemoteSelectionIndex(E->selection);
  if (index == -1)
  {
    #ifdef DEBUG
    fprintf (stderr, "%s: unknown selection [%ld] .\n", __func__, E->selection);
    #endif
    return;
  }

  printClientSelectionStage(index);

  /*
   * If the property is serverTransFromAgentProperty this means we are
   * transferring data FROM the agent TO the server.
   */

  if (X->xselection.property != serverTransFromAgentProperty && lastClients[index].windowPtr != NULL)
  {
    /*
     * We reach here after a paste inside the nxagent, triggered by
     * the XConvertSelection call in nxagentConvertSelection(). This
     * means that data we need has been transferred to the
     * serverTransToAgentProperty of the serverWindow (our window on
     * the real X server). We now need to transfer it to the original
     * requestor, which is stored in the lastClients[index].* variables.
     */

    #ifdef DEBUG
    nxagentDumpClipboardStat();
    #endif
    if (lastClients[index].stage == SelectionStageNone)
    {
      if (X->xselection.property == serverTransToAgentProperty)
      {
        #ifdef DEBUG
        fprintf(stderr, "%s: Starting selection transferral for client %s.\n", __func__,
                nxagentClientInfoString(lastClients[index].clientPtr));
        #endif

        /*
         * The state machine is able to work in two phases. In the first
         * phase we get the size of property data, in the second we get
         * the actual data. We save a round-trip by requesting a prede-
         * termined amount of data in a single GetProperty and by discar-
         * ding the remaining part. This is not the optimal solution (we
         * could get the remaining part if it doesn't fit in a single
         * reply) but, at least with text, it should work in most situa-
         * tions.
         */

        setClientSelectionStage(index, SelectionStageQueryData);
        lastClients[index].propertySize = 262144;

        transferSelectionFromXServer(index, lastClients[index].clientPtr -> index);
      }
      else if (X->xselection.property == 0)
      {
        #ifdef DEBUG
        fprintf(stderr, "%s: WARNING! Resetting selection transferral for client [%d] because of failure notification from real X server.\n", __func__,
                    CLINDEX(lastClients[index].clientPtr));
        #endif
        endTransfer(index, SELECTION_FAULT);
      }
      else
      {
        #ifdef DEBUG
        fprintf(stderr, "%s: Unexpected property [%ld][%s] - reporting conversion failure.\n",
                    __func__, X->xselection.property, NameForRemoteAtom(X->xselection.property));
        #endif
        endTransfer(index, SELECTION_FAULT);
      }
    }
    else
    {
      #ifdef DEBUG
      fprintf(stderr, "%s: WARNING! Resetting selection transferral for client [%d] because of unexpected stage.\n", __func__,
                  CLINDEX(lastClients[index].clientPtr));
      #endif

      endTransfer(index, SELECTION_FAULT);
    }
  }
  else
  {
    handlePropertyTransferFromAgentToXserver(index, X->xselection.property);
  }
}

void handlePropertyTransferFromAgentToXserver(int index, XlibAtom property)
{
  /*
   * If the last owner was a local one, read the
   * clientCutProperty and push the contents to the
   * lastServers[index].requestor on the real X server.
   */
  if (IS_LOCAL_OWNER(index) &&
         lastSelectionOwner[index].windowPtr != NULL &&
             property == serverTransFromAgentProperty)
  {
    Atom            atomReturnType;
    int             resultFormat;
    unsigned long   ulReturnItems;
    unsigned long   ulReturnBytesLeft;
    unsigned char   *pszReturnData = NULL;

    /* First get size values ... */
    int result = GetWindowProperty(lastSelectionOwner[index].windowPtr, clientCutProperty, 0, 0, False,
                                       AnyPropertyType, &atomReturnType, &resultFormat,
                                           &ulReturnItems, &ulReturnBytesLeft, &pszReturnData);

    #ifdef DEBUG
    fprintf(stderr, "%s: GetWindowProperty() window [0x%x] property [%d][%s] returned [%s]\n", __func__,
                lastSelectionOwner[index].window, clientCutProperty, NameForLocalAtom(clientCutProperty),
                    getXErrorString(result));
    #endif
    if (result == BadAlloc || result == BadAtom ||
            result == BadWindow || result == BadValue)
    {
      lastServers[index].property = None;
    }
    else
    {
      /* ... then use the size values for the actual request data. */
      result = GetWindowProperty(lastSelectionOwner[index].windowPtr, clientCutProperty, 0,
                                     ulReturnBytesLeft, False, AnyPropertyType, &atomReturnType,
                                         &resultFormat, &ulReturnItems, &ulReturnBytesLeft,
                                             &pszReturnData);
      #ifdef DEBUG
      fprintf(stderr, "%s: GetWindowProperty() window [0x%x] property [%d][%s] returned [%s]\n", __func__,
                  lastSelectionOwner[index].window, clientCutProperty, NameForLocalAtom(clientCutProperty),
                      getXErrorString(result));
      #endif

      if (result == BadAlloc || result == BadAtom ||
              result == BadWindow || result == BadValue)
      {
        lastServers[index].property = None;
      }
      else
      {
        if (lastServers[index].target == serverTARGETS)
        {
          #ifdef DEBUG
          fprintf(stderr, "%s: ulReturnItems [%ld]\n", __func__, ulReturnItems);
          fprintf(stderr, "%s: resultformat [%d]\n", __func__, resultFormat);
          #endif

          XlibAtom * targets = calloc(sizeof(XlibAtom), ulReturnItems);
          if (targets == NULL)
          {
            #ifdef WARNING
            fprintf(stderr, "%s: WARNING! Could not alloc memory for clipboard targets transmission.\n", __func__);
            #endif
            /* This will effectively lead to the request being answered as failed. */
            lastServers[index].property = None;
          }
          else
          {
            /* Convert the targets to remote atoms. */
            XlibAtom *addr = targets;
            unsigned int numTargets = ulReturnItems;

            for (int i = 0; i < numTargets; i++)
            {
              Atom local = *((Atom*)(pszReturnData + i*resultFormat/8));
              XlibAtom remote = nxagentLocalToRemoteAtom(local);
              *(addr++) = remote;

              #ifdef DEBUG
              fprintf(stderr, "%s: converting atom: local [%d][%s] -> remote [%ld][%s]\n", __func__,
                          local, NameForLocalAtom(local), remote, NameForRemoteAtom(remote));
              #endif
            }

            /* FIXME: do we need to take care of swapping byte order here? */
            XChangeProperty(nxagentDisplay,
                            lastServers[index].requestor,
                            lastServers[index].property,
                            XInternAtom(nxagentDisplay, "ATOM", 0),
                            32,
                            PropModeReplace,
                            (unsigned char*)targets,
                            numTargets);

            cacheTargetsForRemote(index, targets, numTargets);
          }
        }
        else
        {
          /* Fill the property on the requestor with the requested data. */
          /* The XChangeProperty source code reveals it will always
             return 1, no matter what, so no need to check the result */
          XChangeProperty(nxagentDisplay,
                          lastServers[index].requestor,
                          lastServers[index].property,
                          nxagentLocalToRemoteAtom(atomReturnType),
                          resultFormat,
                          PropModeReplace,
                          pszReturnData,
                          ulReturnItems);
          #ifdef DEBUG
          {
            fprintf(stderr, "%s: XChangeProperty sent to window [0x%lx] for property [%ld][%s] resultFormat [%d] returnType [%ld][%s] len [%d]"
                    #ifdef PRINT_CLIPBOARD_CONTENT_ON_DEBUG
                    /* FIXME: only print the string if the resultFormat is 8 */
                    " value [\"%*.*s\"...] hex [0x%2.2x%2.2x%2.2x%2.2x]"
                    #endif
                    "\n",
                    __func__,
                    lastServers[index].requestor,
                    lastServers[index].property,
                    NameForRemoteAtom(lastServers[index].property),
                    resultFormat,
                    nxagentLocalToRemoteAtom(atomReturnType), NameForLocalAtom(atomReturnType),
                    (int)ulReturnItems * resultFormat / 8
                    #ifdef PRINT_CLIPBOARD_CONTENT_ON_DEBUG
                    ,(int)(min(20, ulReturnItems * 8 / 8)),
                    (int)(min(20, ulReturnItems * 8 / 8)),
                    pszReturnData,
                    pszReturnData[0], pszReturnData[1], pszReturnData[2], pszReturnData[3]
                    #endif
                    );
          }
          #endif
        }

        /* FIXME: free it or not? */
        /*
         * SAFE_XFree(pszReturnData);
         */
      }
    }

    /*
     * Inform the initial requestor that the requested data has
     * arrived in the desired property. If we have been unable to
     * get the data from the owner XChangeProperty will not have
     * been called and lastServers[index].property will be None which
     * effectively will send a "Request denied" to the initial
     * requestor.
     */
    replyPendingRequestSelectionToXServer(index, True);
  }
}

/*
 * This is similar to replyRequestSelectionToXServer(), but gets the
 * required values from a stored request instead of an XEvent
 * structure.
 */
void replyPendingRequestSelectionToXServer(int index, Bool success)
{
  if (lastServers[index].requestor == None)
  {
    #ifdef DEBUG
    fprintf(stderr, "%s: no pending request for index [%d] - doing nothing\n", __func__, index);
    #endif
  }
  else
  {
    XSelectionEvent eventSelection = {
      .requestor = lastServers[index].requestor,
      .selection = remoteSelectionAtoms[index],
      .target    = lastServers[index].target,
      .time      = lastServers[index].time,
      .property  = success ? lastServers[index].property : None,
    };

    #ifdef DEBUG
    fprintf(stderr, "%s: Sending %s SelectionNotify event to requestor [%p].\n", __func__,
                success ? "positive" : "negative", (void *)eventSelection.requestor);
    #endif

    sendSelectionNotifyEventToXServer(&eventSelection);

    lastServers[index].requestor = None; /* allow further request */
    lastServers[index].property = 0;
    lastServers[index].target = 0;
    lastServers[index].time = 0;
  }
}

#if 0
/* FIXME: currently unused */
/*
 * Let nxagent's serverWindow acquire the selection. All requests from
 * the real X server (or its clients) will be sent to this window. The
 * real X server never communicates with our windows directly.
 */
static void resetSelectionOwnerOnXServer(void)
{
  if (lastServers[index].requestor != None)
  {
    /*
     * We are in the process of communicating back and forth between
     * real X server and nxagent's clients - let's not disturb.
     */
    #if defined(TEST) || defined(DEBUG)
    fprintf(stderr, "%s: WARNING! Requestor window [0x%x] already set.\n", __func__,
                lastServers[index].requestor);
    #endif

    /* FIXME: maybe we should put back the event that lead us here. */
    return;
  }

  for (int index = 0; index < nxagentMaxSelections; index++)
  {
    XSetSelectionOwner(nxagentDisplay, remoteSelectionAtoms[index], serverWindow, CurrentTime);

    #ifdef DEBUG
    fprintf(stderr, "%s: Reset selection state for selection [%d].\n", __func__, index);
    #endif

    clearSelectionOwnerData(index);

    setClientSelectionStage(index, SelectionStageNone);

    invalidateTargetCache(index);

    /* Hmm, this is already None when reaching here. */
    lastServers[index].requestor = None;
  }
}
#endif

#ifdef NXAGENT_CLIPBOARD

/*
 * The callback is called from dix.
 */
void nxagentSetSelectionCallback(CallbackListPtr *callbacks, void *data,
                                   void *args)
{
  SelectionInfoRec *info = (SelectionInfoRec *)args;

  #ifdef DEBUG
  fprintf(stderr, "---------\n");
  if (info->kind == SelectionSetOwner)
  {
    fprintf(stderr, "%s: SelectionCallbackKind [SelectionSetOwner]\n", __func__);
  }
  else if (info->kind == SelectionWindowDestroy)
  {
    fprintf(stderr, "%s: SelectionCallbackKind [SelectionWindowDestroy]\n", __func__);
  }
  else if (info->kind == SelectionClientClose)
  {
    fprintf(stderr, "%s: SelectionCallbackKind [SelectionClientClose]\n", __func__);
  }
  else
  {
    fprintf(stderr, "%s: SelectionCallbackKind [unknown]\n", __func__);
  }
  #endif

  Selection * pCurSel = (Selection *)info->selection;

  int index = nxagentFindCurrentSelectionIndex(pCurSel->selection);
  if (index == -1)
  {
    #ifdef DEBUG
    fprintf(stderr, "%s: selection [%s] can/will not be handled by the clipboard code\n", __func__, NameForLocalAtom(pCurSel->selection));
    #endif
    return;
  }

  #ifdef DEBUG
  printSelectionStat(index);
  #endif

  if (CurrentSelections[index].client == NullClient &&
      CurrentSelections[index].pWin == (WindowPtr)None &&
      CurrentSelections[index].window == screenInfo.screens[0]->root->drawable.id &&
      lastSelectionOwner[index].client == NullClient &&
      lastSelectionOwner[index].window == None &&
      lastSelectionOwner[index].windowPtr == NULL)
  {
    /*
     * No need to propagate anything to the real X server because this
     * callback was triggered by a SelectionClear from the real X
     * server. See nxagentHandleSelectionClearFromXServer
     */
    #ifdef DEBUG
    fprintf(stderr, "%s: aborting callback because it was triggered by nxagent\n", __func__);
    #endif
    return;
  }

  /*
   * Always invalidate the target cache for the relevant selection.
   * This ensures not having invalid data in the cache.
   */
  invalidateTargetCache(index);

  if (nxagentOption(Clipboard) != ClipboardNone) /* FIXME: shouldn't we also check for != ClipboardClient? */
  {
    Selection *pSel = NULL;
    Selection nullSel = {
                         .client = NullClient,
                         .window = None,
                         .pWin = NULL,
                         .selection = pCurSel->selection,
                         .lastTimeChanged = pCurSel->lastTimeChanged
    };

    if (info->kind == SelectionSetOwner)
    {
      pSel = pCurSel;
    }
    else if (info->kind == SelectionWindowDestroy)
    {
      if (pCurSel->window == lastSelectionOwner[index].window)
      {
        pSel = &nullSel;
      }
    }
    else if (info->kind == SelectionClientClose)
    {
      if (pCurSel->client == lastSelectionOwner[index].client)
      {
        pSel = &nullSel;
      }
    }
    else
    {
      #ifdef WARNING
      fprintf(stderr, "%s: WARNING: unknown kind [%d] - data corruption?\n", __func__, info->kind);
      #endif
    }

    if (pSel)
    {
      #ifdef DEBUG
      fprintf(stderr, "%s: calling setSelectionOwnerOnXServer\n", __func__);
      #endif
      setSelectionOwnerOnXServer(pSel);
    }
  }
}

/*
 * This is called from the nxagentSetSelectionCallback, so it is using
 * local Atoms.
 */
static void setSelectionOwnerOnXServer(Selection *pSelection)
{
  if (!agentClipboardInitialized)
  {
    #ifdef DEBUG
    fprintf(stderr, "%s: clipboard not initialized - doing nothing.\n", __func__);
    #endif
    return;
  }

  int index = nxagentFindCurrentSelectionIndex(pSelection->selection);
  if (index == -1)
  {
    #ifdef DEBUG
    fprintf(stderr, "%s: selection [%s] can/will not be handled by the clipboard code\n", __func__, NameForLocalAtom(pSelection->selection));
    #endif
    return;
  }

  #ifdef DEBUG
  printSelectionStat(index);
  #endif


  /*
   * There's an X client on the real X server waiting for a
   * reply. That reply will never come because now we are the
   * owner so let's be fair and cancel that request.
   */
  replyPendingRequestSelectionToXServer(index, False);

  /*
   * Inform the real X server that our serverWindow is the
   * clipboard owner.
   * https://www.freedesktop.org/wiki/ClipboardManager/ states
   * "In order to support peers who use the XFIXES extension to
   * watch clipboard ownership changes, clipboard owners should
   * reacquire the clipboard whenever the content or metadata (e.g
   * the list of supported targets) changes."
   * If pWin is NULL this is a SelectionClear.
   */
  #ifdef DEBUG
  if (pSelection->pWin)
  {
    fprintf(stderr, "%s: Setting selection owner to serverwindow ([0x%lx]).\n", __func__,
                serverWindow);
  }
  #endif
  XSetSelectionOwner(nxagentDisplay, remoteSelectionAtoms[index], pSelection->pWin ? serverWindow : 0, CurrentTime);

  /*
   * The real owner window (inside nxagent) is stored in
   * lastSelectionOwner[index].window.
   * lastSelectionOwner[index].windowPtr points to the struct that
   * contains all information about the owner window.
   */
  storeSelectionOwnerData(index, pSelection);

  setClientSelectionStage(index, SelectionStageNone);

  /*
   * This will be repeated on reception of the SelectionOwner
   * callback but we cannot be sure if there are any intermediate
   * requests in the queue already so better do it here, too.
   */
  invalidateTargetCache(index);

/*
FIXME

FIXME2: instead of XGetSelectionOwner we could check if the Xfixes
        SetSelectionOwner event has arrived in the event queue;
        possibly saving one roundtrip.

  if (XGetSelectionOwner(nxagentDisplay, pSelection->selection) == serverWindow)
  {
    fprintf (stderr, "%s: SetSelectionOwner OK\n", __func__);

    lastSelectionOwnerSelection = pSelection;
    lastSelectionOwnerClient = pSelection->client;
    lastSelectionOwnerWindow = pSelection->window;
    lastSelectionOwnerWindowPtr = pSelection->pWin;

    setClientSelectionStage(index, SelectionStageNone);

    lastServers[index].requestor = None;
  }
  else
  {
     fprintf (stderr, "%s: SetSelectionOwner failed\n", __func__);
  }
*/
}
#endif

/*
 * This is called from dix (ProcConvertSelection) if an nxagent client
 * issues a ConvertSelection request. So all the Atoms are local.
 * return codes:
 * 0: let dix process the request
 * 1: don't let dix process the request
 */
int nxagentConvertSelection(ClientPtr client, WindowPtr pWin, Atom selection,
                                Window requestor, Atom property, Atom target, Time time)
{
  #ifdef DEBUG
  fprintf(stderr, "---------\n%s: client %s requests sel [%s] "
              "on window [0x%x] prop [%d][%s] target [%d][%s] time [%u].\n", __func__,
                  nxagentClientInfoString(client), NameForLocalAtom(selection), requestor,
                      property, NameForLocalAtom(property),
                          target, NameForLocalAtom(target), time);
  #endif

  /* We cannot use NameForLocalAtom() here! FIXME: Why not? */
  if (NameForAtom(target) == NULL)
  {
    #ifdef DEBUG
    fprintf(stderr, "%s: cannot find name for target Atom [%d] - returning\n", __func__, target);
    #endif
    return 1;
  }

  if (!agentClipboardInitialized)
  {
    #ifdef DEBUG
    fprintf(stderr, "%s: clipboard not initialized - doing nothing.\n", __func__);
    #endif
    return 0;
  }

  if (nxagentOption(Clipboard) == ClipboardServer)
  {
    #ifdef DEBUG
    fprintf(stderr, "%s: clipboard mode 'server' - doing nothing.\n", __func__);
    #endif
    return 0;
  }

  int index = nxagentFindCurrentSelectionIndex(selection);
  if (index == -1)
  {
    #ifdef DEBUG
    fprintf(stderr, "%s: cannot find index for selection [%u]\n", __func__, selection);
    #endif
    return 0;
  }

  if (IS_LOCAL_OWNER(index))
  {
    /*
     * There is a client owner on the agent side, let normal dix stuff happen.
     */
    #ifdef DEBUG
    fprintf(stderr, "%s: clipboard is owned by local client - let dix process the request\n", __func__);
    #endif
    return 0;
  }

  /*
   * If lastClients[index].windowPtr is set we are waiting for an
   * answer from the real X server. If that answer takes more than 5
   * seconds we consider the conversion failed and tell our client
   * about that. The new request that lead us here is then processed.
   */
  #ifdef TEST
  fprintf(stderr, "%s: lastClients[%d].windowPtr [0x%lx].\n", __func__, index, (unsigned long)lastClients[index].windowPtr);
  #endif

  if (lastClients[index].windowPtr != NULL)
  {
    #ifdef TEST
    fprintf(stderr, "%s: lastClients[%d].windowPtr != NULL.\n", __func__, index);
    #endif

    #ifdef DEBUG
    fprintf(stderr, "%s: localSelectionAtoms[%d] [%d] - selection [%d]\n", __func__, index, localSelectionAtoms[index], selection);
    #endif

    if ((GetTimeInMillis() - lastClients[index].reqTime) >= CONVERSION_TIMEOUT)
    {
      #ifdef DEBUG
      fprintf(stderr, "%s: timeout expired on previous request - "
                  "notifying failure to waiting client\n", __func__);
      #endif

      /* Notify the waiting client of the failure. */
      endTransfer(index, SELECTION_FAULT);

      /* Do NOT return here but process the new request instead! */
    }
    else
    {
      /*
       * We got another convert request while already waiting for an
       * answer from the real X server to a previous convert request
       * for this selection, which we cannot handle (yet). So return
       * an error for the new request.
       */
      #ifdef DEBUG
      fprintf(stderr, "%s: got new request "
                  "before timeout expired on previous request, notifying failure to client %s\n",
                      __func__, nxagentClientInfoString(client));
      #endif

      /* Notify the sender of the new request of the failure. */
      sendSelectionNotifyEventToClient(client, time, requestor, selection, target, None);

      return 1;
    }
  }

  /*
   * The selection request target is TARGETS. The requestor is asking
   * for a list of supported data formats.
   */

  if (target == clientTARGETS)
  {
    /*
     * In TextClipboard mode answer with a predefined list that was used
     * in previous versions.
     */
    if (nxagentOption(TextClipboard))
    {
      /*
       * The list is aligned with the one in
       * nxagentHandleSelectionRequestFromXServer.
       */
      Atom targets[] = {XA_STRING,
                        clientUTF8_STRING,
#ifdef SUPPORT_TEXT_TARGET
                        clientTEXT,
#endif
#ifdef SUPPORT_COMPOUND_TEXT_TARGET
                        clientCOMPOUND_TEXT,
#endif
                        clientTARGETS,
                        clientTIMESTAMP};
      int numTargets = sizeof(targets) / sizeof(targets[0]);

      #ifdef DEBUG
      fprintf(stderr, "%s: Sending %d available targets:\n", __func__, numTargets);
      for (int i = 0; i < numTargets; i++)
      {
        fprintf(stderr, "%s: %d %s\n", __func__, targets[i], NameForLocalAtom(targets[i]));
      }
      #endif

      ChangeWindowProperty(pWin,
                           property,
                           MakeAtom("ATOM", 4, 1),
                           sizeof(Atom)*8,
                           PropModeReplace,
                           numTargets,
                           targets,
                           1);

      sendSelectionNotifyEventToClient(client, time, requestor, selection,
                                           target, property);

      return 1;
    }
    else
    {
      /*
       * Shortcut: Some applications tend to post multiple
       * SelectionRequests. Further it can happen that multiple
       * clients are interested in clipboard content. If we already
       * know the answer and no intermediate SelectionOwner event
       * occurred we can answer with the cached list of targets.
       */

      if (targetCache[index].type == FOR_LOCAL && targetCache[index].forLocal)
      {
        Atom *targets = targetCache[index].forLocal;
        int numTargets = targetCache[index].numTargets;

        #ifdef DEBUG
        fprintf(stderr, "%s: Sending %d cached targets to local client:\n", __func__, numTargets);
        for (int i = 0; i < numTargets; i++)
        {
          fprintf(stderr, "%s: %d %s\n", __func__, targets[i], NameForLocalAtom(targets[i]));
        }
        #endif

        ChangeWindowProperty(pWin,
                             property,
                             MakeAtom("ATOM", 4, 1),
                             sizeof(Atom)*8,
                             PropModeReplace,
                             numTargets,
                             targets,
                             1);

        sendSelectionNotifyEventToClient(client, time, requestor, selection,
                                             target, property);

        return 1;
      }

      /*
       * Do nothing - TARGETS will be handled like any other target
       * and passed on to the owner on the remote side.
       */
    }
  }

  /*
   * Section 2.6.2 of the ICCCM states:
   * "TIMESTAMP - To avoid some race conditions, it is important
   * that requestors be able to discover the timestamp the owner
   * used to acquire ownership. Until and unless the protocol is
   * changed so that a GetSelectionOwner request returns the
   * timestamp used to acquire ownership, selection owners must
   * support conversion to TIMESTAMP, returning the timestamp they
   * used to obtain the selection."
   */
  else if (target == clientTIMESTAMP)
  {
    /*
     * From ICCCM:
     * "If the specified property is not None, the owner should place
     * the data resulting from converting the selection into the
     * specified property on the requestor window and should set the
     * property's type to some appropriate value, which need not be
     * the same as the specified target."
     */
    ChangeWindowProperty(pWin,
                         property,
                         XA_INTEGER,
                         32,
                         PropModeReplace,
                         1,
                         (unsigned char *) &lastSelectionOwner[index].lastTimeChanged,
                         1);
    sendSelectionNotifyEventToClient(client, time, requestor, selection, target, property);
    return 1;
  }
  else if (target == clientMULTIPLE)
  {
    #ifdef DEBUG
    fprintf(stderr, "%s: (currently) unsupported target [MULTIPLE] - denying request.\n", __func__);
    #endif
    sendSelectionNotifyEventToClient(client, time, requestor, selection, target, None);
    return 1;
  }
  else if (target == clientDELETE)
  {
    #ifdef DEBUG
    fprintf(stderr, "%s: (currently) unsupported target [DELETE] - denying request.\n", __func__);
    #endif
    sendSelectionNotifyEventToClient(client, time, requestor, selection, target, None);
    return 1;
  }
  else if (target == clientINSERT_SELECTION)
  {
    #ifdef DEBUG
    fprintf(stderr, "%s: (currently) unsupported target [INSERT_SELECTION] - denying request.\n", __func__);
    #endif
    sendSelectionNotifyEventToClient(client, time, requestor, selection, target, None);
    return 1;
  }
  else if (target == clientINSERT_PROPERTY)
  {
    #ifdef DEBUG
    fprintf(stderr, "%s: (currently) unsupported target [INSERT_PROPERTY] - denying request.\n", __func__);
    #endif
    sendSelectionNotifyEventToClient(client, time, requestor, selection, target, None);
    return 1;
  }
  else if (target == clientSAVE_TARGETS)
  {
    #ifdef DEBUG
    fprintf(stderr, "%s: (currently) unsupported target [SAVE_TARGETS] - denying request.\n", __func__);
    #endif
    sendSelectionNotifyEventToClient(client, time, requestor, selection, target, None);
    return 1;
  }
  else if (target == clientTARGET_SIZES)
  {
    #ifdef DEBUG
    fprintf(stderr, "%s: (currently) unsupported target [TARGET_SIZES] - denying request.\n", __func__);
    #endif
    sendSelectionNotifyEventToClient(client, time, requestor, selection, target, None);
    return 1;
  }

  /* In TextClipboard mode we reject all non-text targets. */
  if (nxagentOption(TextClipboard))
  {
    if (!isTextTarget(translateLocalToRemoteTarget(target)))
    {
      #ifdef DEBUG
      fprintf(stderr, "%s: denying request for non-text target [%d][%s].\n", __func__,
                  target, NameForLocalAtom(target));
      #endif

      sendSelectionNotifyEventToClient(client, time, requestor, selection, target, None);
      return 1;
    }
    /* Go on, target is acceptable! */
  }

  #ifdef DEBUG
  fprintf(stderr, "%s: target [%d][%s].\n", __func__, target,
              NameForLocalAtom(target));
  #endif

  if (!nxagentOption(TextClipboard))
  {
    /*
     * Optimization: if we have a current target cache check if the
     * requested target is supported by the owner. If not we can take
     * a shortcut and deny the request immediately without doing any
     * further communication
     */
    if (targetCache[index].type == FOR_LOCAL && targetCache[index].forLocal)
    {
      Atom *targets = targetCache[index].forLocal;

      #ifdef DEBUG
      fprintf(stderr, "%s: Checking target validity\n", __func__);
      #endif
      Bool match = False;
      for (int i = 0; i < targetCache[index].numTargets; i++)
      {
        if (targets[i] == target)
        {
          match = True;
          break;
        }
      }
      if (!match)
      {
        #ifdef DEBUG
        fprintf(stderr, "%s: target [%d][%s] is not supported by the owner - denying request.\n",
                    __func__, target, NameForLocalAtom(target));
        #endif
        sendSelectionNotifyEventToClient(client, time, requestor, selection, target, None);
        return 1;
      }
    }
    else
    {
      /*
       * At this stage we know a client has asked for a selection
       * target without having retrieved the list of supported targets
       * first.
       */
      #ifdef DEBUG
      if (target != clientTARGETS)
      {
         fprintf(stderr, "%s: WARNING: client has not retrieved TARGETS before asking for selection!\n",
                   __func__);
      }
      #endif
    }
  }

  if (lastClients[index].clientPtr == client)
  {
    #ifdef DEBUG
    fprintf(stderr, "%s: same client as previous request\n", __func__);
    #endif

    if (GetTimeInMillis() - lastClients[index].reqTime < ACCUM_TIME)
    {
      /*
       * The same client made consecutive requests of clipboard content
       * with less than 5 seconds time interval between them.
       */
       #ifdef DEBUG
       fprintf(stderr, "%s: Consecutives request from client %s selection [%u] "
                  "elapsed time [%u] clientAccum [%d]\n", __func__,
                      nxagentClientInfoString(client),
                          selection, GetTimeInMillis() - lastClients[index].reqTime,
                              clientAccum);
       #endif

       clientAccum++;
    }
  }
  else
  {
    /*
     * Reset clientAccum as now another client requested the clipboard
     * content.
     */
    clientAccum = 0;
  }

  setClientSelectionStage(index, SelectionStageNone);

  /*
   * Store the original requestor, we need that later after
   * serverTransToAgentProperty has been filled with the desired
   * selection content.
   */
  lastClients[index].requestor = requestor;
  lastClients[index].windowPtr = pWin;
  lastClients[index].clientPtr = client;
  lastClients[index].time = time;
  lastClients[index].property = property;
  lastClients[index].target = target;
  /* If the last client request time is more than 5s ago update it. Why? */
  if ((GetTimeInMillis() - lastClients[index].reqTime) >= CONVERSION_TIMEOUT)
    lastClients[index].reqTime = GetTimeInMillis();

  XlibAtom remSelection = translateLocalToRemoteSelection(selection);
  XlibAtom remTarget = translateLocalToRemoteTarget(target);
  XlibAtom remProperty = serverTransToAgentProperty;

  #ifdef DEBUG
  fprintf(stderr, "%s: replacing local by remote property: [%d][%s] -> [%ld][%s]\n",
              __func__, property, NameForLocalAtom(property),
                  remProperty, "NX_CUT_BUFFER_SERVER");
  #endif

  #ifdef DEBUG
  fprintf(stderr, "%s: Sending XConvertSelection to real X server: requestor [0x%lx] target [%ld][%s] property [%ld][%s] selection [%ld][%s] time [0][CurrentTime]\n", __func__,
          serverWindow, remTarget, NameForRemoteAtom(remTarget),
              remProperty, NameForRemoteAtom(remProperty),
                  remSelection, NameForRemoteAtom(remSelection));
  #endif

  /*
   * ICCCM: "It is necessary for requestors to delete the property
   * before issuing the request so that the target can later be
   * extended to take parameters without introducing an
   * incompatibility. Also note that the requestor of a selection need
   * not know the client that owns the selection nor the window on
   * which the selection was acquired."
   */

  XDeleteProperty(nxagentDisplay, serverWindow, remProperty);

  /*
   * FIXME: ICCCM states: "Clients should not use CurrentTime for the
   * time argument of a ConvertSelection request. Instead, they should
   * use the timestamp of the event that caused the request to be
   * made."  Well, the event that that caused this came from an
   * nxagent _client_ but we are a client to the real X server, which
   * has an own time., we cannot use its time there. So what time
   * would be correct here?
   */

  UpdateCurrentTime();

  XConvertSelection(nxagentDisplay, remSelection, remTarget, remProperty,
                        serverWindow, CurrentTime);

  NXFlushDisplay(nxagentDisplay, NXFlushLink);

  /* XConvertSelection will always return 1 (check the source!), so no
     need to check the return code. */

  #ifdef DEBUG
  fprintf(stderr, "%s: Sent XConvertSelection\n", __func__);
  #endif

  return 1;
}

/*
 * FIXME: do we still need this special treatment? Can't we just
 * call nxagentLocalToRemoteAtom() everywhere?
 */
XlibAtom translateLocalToRemoteSelection(Atom local)
{
  /*
   * On the real server, the right CLIPBOARD atom is
   * XInternAtom(nxagentDisplay, "CLIPBOARD", 1), which is stored in
   * remoteSelectionAtoms[nxagentClipboardSelection]. For
   * PRIMARY there's nothing to map because that is identical on all
   * X servers (defined in Xatom.h). We do it anyway so we do not
   * require a special treatment.
   */

  XlibAtom remote = -1;

  for (int index = 0; index < nxagentMaxSelections; index++)
  {
    if (local == localSelectionAtoms[index])
    {
      remote = remoteSelectionAtoms[index];
      break;
    }
  }

  if (remote == -1)
  {
    remote = nxagentLocalToRemoteAtom(local);
  }

  #ifdef DEBUG
  fprintf(stderr, "%s: mapping local to remote selection: [%d][%s] -> [%ld][%s]\n", __func__,
              local, NameForLocalAtom(local), remote, NameForRemoteAtom(remote));
  #endif

  return remote;
}

/* FIXME: do we still need this special treatment? Can't we just
   call nxagentLocalToRemoteAtom() everywhere? */
XlibAtom translateLocalToRemoteTarget(Atom local)
{
  /*
   * .target must be translated, too, as a client on the real
   * server is requested to fill our property and it needs to know
   * the format.
   */

  XlibAtom remote;

  /*
   * we only convert to either UTF8 or XA_STRING
#ifdef SUPPORT_TEXT_TARGET
   * despite accepting TEXT
#endif
#ifdef SUPPORT_COMPOUND_TEXT_TARGET
   * and COMPOUND_TEXT.
#endif
   */

  if (local == clientUTF8_STRING)
  {
    remote = serverUTF8_STRING;
  }
#ifdef SUPPORT_TEXT_TARGET
  else if (local == clientTEXT)
  {
    remote = serverTEXT;
  }
#endif
#ifdef SUPPORT_COMPOUND_TEXT_TARGET
  else if (local == clientCOMPOUND_TEXT)
  {
    remote = serverCOMPOUND_TEXT;
  }
#endif
  else if (local == clientTARGETS)
  {
    remote = serverTARGETS;
  }
  else
  {
    remote = nxagentLocalToRemoteAtom(local);
  }

  #ifdef DEBUG
  fprintf(stderr, "%s: mapping local to remote target: [%d][%s] -> [%ld][%s]\n", __func__,
              local, NameForLocalAtom(local), remote, NameForRemoteAtom(remote));
  #endif

  return remote;
}

/*
 * This is _only_ called from ProcSendEvent in NXevents.c. It is used
 * to send a SelectionNotify event to our server window which will
 * trigger the dispatch loop in Events.c to run
 * nxagentHandleSelectionNotifyFromXServer which in turn will take
 * care of transferring the selection content from the owning client
 * to a property of the server window.
 *
 * Returning 1 here means the client request will not be further
 * handled by dix. Returning 0 means a SelectionNotify event being
 * pushed out to our clients.
 *
 * From https://tronche.com/gui/x/xlib/events/client-communication/selection.html:
 * "This event is generated by the X server in response to a
 * ConvertSelection protocol request when there is no owner for the
 * selection. When there is an owner, it should be generated by the
 * owner of the selection by using XSendEvent()."
 */
int nxagentSendNotificationToSelfViaXServer(xEvent *event)
{
  if (!agentClipboardInitialized)
  {
    #ifdef DEBUG
    fprintf(stderr, "%s: clipboard not initialized - doing nothing.\n", __func__);
    #endif
    return 0;
  }

  #ifdef DEBUG
  fprintf(stderr, "---------\n%s: Received SendNotify from client: property [%d][%s] target [%d][%s] selection [%d][%s] requestor [0x%x] time [%u].\n", __func__,
          event->u.selectionNotify.property, NameForLocalAtom(event->u.selectionNotify.property),
          event->u.selectionNotify.target, NameForLocalAtom(event->u.selectionNotify.target),
          event->u.selectionNotify.selection, NameForLocalAtom(event->u.selectionNotify.selection),
          event->u.selectionNotify.requestor, event->u.selectionNotify.time);
  #endif

  int index = nxagentFindCurrentSelectionIndex(event->u.selectionNotify.selection);
  if (index == -1)
  {
    #ifdef DEBUG
    fprintf(stderr, "%s: unknown selection [%d]\n", __func__,
                event->u.selectionNotify.selection);
    #endif
    return 0;
  }

  #ifdef DEBUG
  fprintf(stderr, "%s: lastServers[index].requestor is [0x%lx].\n", __func__, lastServers[index].requestor);
  #endif

  /*
   * If we have nested sessions there are situations where we do not
   * need to send out anything to the real X server because
   * communication happens completely between our own clients (some of
   * which can be nxagents themselves). In that case we return 0 (tell
   * dix to go on) and do nothing!
   * Be sure to not let this trigger for the failure answer (property 0).
   */
  if (!(event->u.selectionNotify.property == clientCutProperty || event->u.selectionNotify.property == 0) || lastServers[index].requestor == None)
  {
    #ifdef DEBUG
    fprintf(stderr, "%s: sent nothing - message to real X server is not required.\n", __func__);
    #endif
    return 0;
  }
  else
  {
    /*
     * If the property is 0 (reporting failure) we can directly
     * answer to the lastServer about the failure!
     */
    if (lastServers[index].requestor != None && event->u.selectionNotify.property == 0)
    {
      replyPendingRequestSelectionToXServer(index, False);
      return 1;
    }
    else
    {
      /*
       * Setup selection notify event to real server.
       *
       * .property must be a server-side Atom. As this property is only
       * set on our serverWindow and normally there are few other
       * properties except serverTransToAgentProperty, the only thing
       * we need to ensure is that the local Atom clientCutProperty
       * differs from the server-side serverTransToAgentProperty
       * Atom. The actual name is not important. To be clean here we use
       * a separate serverTransFromAgentProperty.
       */

      XSelectionEvent eventSelection = {
        .requestor = serverWindow,
        .selection = translateLocalToRemoteSelection(event->u.selectionNotify.selection),
        .target    = translateLocalToRemoteTarget(event->u.selectionNotify.target),
        .property  = serverTransFromAgentProperty,
        .time      = CurrentTime,
      };

      #ifdef DEBUG
      fprintf(stderr, "%s: remote property [%ld][%s].\n", __func__,
                  serverTransFromAgentProperty, NameForRemoteAtom(serverTransFromAgentProperty));
      #endif
      sendSelectionNotifyEventToXServer(&eventSelection);
      return 1;
    }
  }
}

/*
 * This is called from NXproperty.c to determine if a client sets the
 * property we are waiting for.
 * FIXME: in addition we should check if the client is the one we expect.
 */
WindowPtr nxagentGetClipboardWindow(Atom property)
{
  if (serverLastRequestedSelection == -1)
  {
    return NULL;
  }

  int index = nxagentFindRemoteSelectionIndex(serverLastRequestedSelection);
  if (index != -1 &&
          property == clientCutProperty &&
              lastSelectionOwner[index].windowPtr != NULL)
  {
    #ifdef DEBUG
    fprintf(stderr, "%s: Returning last [%d] selection owner window [%p] (0x%x).\n", __func__,
            localSelectionAtoms[index],
            (void *)lastSelectionOwner[index].windowPtr, WINDOWID(lastSelectionOwner[index].windowPtr));
    #endif

    return lastSelectionOwner[index].windowPtr;
  }
  else
  {
    return NULL;
  }
}

/*
 * Initialize the clipboard.
 * Returns: True for success else False
 */
Bool nxagentInitClipboard(WindowPtr pWin)
{
  #ifdef DEBUG
  fprintf(stderr, "%s: Got called.\n", __func__);
  #endif

  #ifdef NXAGENT_TIMESTAMP
  {
    fprintf(stderr, "%s: Clipboard init starts at [%lu] ms.\n", __func__,
            GetTimeInMillis() - startTime);
  }
  #endif

  agentClipboardInitialized = False;
  serverWindow = nxagentWindow(pWin);

  if (!nxagentReconnectTrap)
  {
    /* Cannot move that down to others - we need it for
     * initSelectionOwnerData! */
    /* FIXME: it is probably better to re-use the strings from Atoms.c here */
    clientTARGETS = MakeAtom(szAgentTARGETS, strlen(szAgentTARGETS), True);
#ifdef SUPPORT_TEXT_TARGET
    clientTEXT = MakeAtom(szAgentTEXT, strlen(szAgentTEXT), True);
#endif
#ifdef SUPPORT_COMPOUND_TEXT_TARGET
    clientCOMPOUND_TEXT = MakeAtom(szAgentCOMPOUND_TEXT, strlen(szAgentCOMPOUND_TEXT), True);
#endif
    clientUTF8_STRING = MakeAtom(szAgentUTF8_STRING, strlen(szAgentUTF8_STRING), True);
    clientTIMESTAMP = MakeAtom(szAgentTIMESTAMP, strlen(szAgentTIMESTAMP), True);
    clientINCR = MakeAtom(szAgentINCR, strlen(szAgentINCR), True);
    clientMULTIPLE = MakeAtom(szAgentMULTIPLE, strlen(szAgentMULTIPLE), True);
    clientDELETE = MakeAtom(szAgentDELETE, strlen(szAgentDELETE), True);
    clientINSERT_SELECTION = MakeAtom(szAgentINSERT_SELECTION, strlen(szAgentINSERT_SELECTION), True);
    clientINSERT_PROPERTY = MakeAtom(szAgentINSERT_PROPERTY, strlen(szAgentINSERT_PROPERTY), True);
    clientSAVE_TARGETS = MakeAtom(szAgentSAVE_TARGETS, strlen(szAgentSAVE_TARGETS), True);
    clientTARGET_SIZES = MakeAtom(szAgentTARGET_SIZES, strlen(szAgentTARGET_SIZES), True);

    SAFE_free(lastSelectionOwner);
    lastSelectionOwner = (SelectionOwner *) malloc(nxagentMaxSelections * sizeof(SelectionOwner));

    if (lastSelectionOwner == NULL)
    {
      FatalError("nxagentInitClipboard: Failed to allocate memory for the clipboard selections.\n");
    }
    initSelectionOwnerData(nxagentPrimarySelection);
    initSelectionOwnerData(nxagentClipboardSelection);

    SAFE_free(lastClients);
    lastClients = (lastClient *) calloc(nxagentMaxSelections, sizeof(lastClient));
    if (lastClients == NULL)
    {
      FatalError("nxagentInitClipboard: Failed to allocate memory for the last clients array.\n");
    }

    SAFE_free(lastServers);
    lastServers = (lastServer *) calloc(nxagentMaxSelections, sizeof(lastServer));
    if (lastServers == NULL)
    {
      FatalError("nxagentInitClipboard: Failed to allocate memory for the last servers array.\n");
    }

    SAFE_free(localSelectionAtoms);
    localSelectionAtoms = (Atom *) calloc(nxagentMaxSelections, sizeof(Atom));
    if (localSelectionAtoms == NULL)
    {
      FatalError("nxagentInitClipboard: Failed to allocate memory for the local selection Atoms array.\n");
    }
    localSelectionAtoms[nxagentPrimarySelection] = XA_PRIMARY;
    localSelectionAtoms[nxagentClipboardSelection] = MakeAtom(szAgentCLIPBOARD, strlen(szAgentCLIPBOARD), True);

    SAFE_free(remoteSelectionAtoms);
    remoteSelectionAtoms = (XlibAtom *) calloc(nxagentMaxSelections, sizeof(XlibAtom));
    if (remoteSelectionAtoms == NULL)
    {
      FatalError("nxagentInitClipboard: Failed to allocate memory for the remote selection Atoms array.\n");
    }

    SAFE_free(targetCache);
    targetCache = (Targets *) calloc(nxagentMaxSelections, sizeof(Targets));
    if (targetCache == NULL)
    {
      FatalError("nxagentInitClipboard: Failed to allocate memory for target cache.\n");
    }
  }

  /*
   * The clipboard selection atom can change with a new X
   * server while Primary is constant.
   */
  remoteSelectionAtoms[nxagentPrimarySelection] = XA_PRIMARY;
  remoteSelectionAtoms[nxagentClipboardSelection] = nxagentAtoms[10];   /* CLIPBOARD */

  serverTARGETS = nxagentAtoms[6];  /* TARGETS */
#ifdef SUPPORT_TEXT_TARGET
  serverTEXT = nxagentAtoms[7];  /* TEXT */
#endif
#ifdef SUPPORT_COMPOUND_TEXT_TARGET
  serverCOMPOUND_TEXT = nxagentAtoms[16]; /* COMPOUND_TEXT */
#endif
  serverUTF8_STRING = nxagentAtoms[12]; /* UTF8_STRING */
  serverTIMESTAMP = nxagentAtoms[11];   /* TIMESTAMP */
  serverINCR = nxagentAtoms[17];   /* INCR */
  serverMULTIPLE = nxagentAtoms[18];   /* MULTIPLE */
  serverDELETE = nxagentAtoms[19];   /* DELETE */
  serverINSERT_SELECTION = nxagentAtoms[20];   /* INSERT_SELECTION */
  serverINSERT_PROPERTY = nxagentAtoms[21];   /* INSERT_PROPERTY */
  serverSAVE_TARGETS = nxagentAtoms[22];   /* SAVE_TARGETS */
  serverTARGET_SIZES = nxagentAtoms[23];   /* TARGET_SIZES */

  /*
   * Server side properties to hold pasted data.
   * See nxagentSendNotificationToSelfViaXServer for an explanation
   */
  serverTransFromAgentProperty = nxagentAtoms[15]; /* NX_SELTRANS_FROM_AGENT */
  serverTransToAgentProperty = nxagentAtoms[5];  /* NX_CUT_BUFFER_SERVER */

  if (serverTransToAgentProperty == None)
  {
    #ifdef PANIC
    fprintf(stderr, "%s: PANIC! Could not create %s atom\n", __func__, "NX_CUT_BUFFER_SERVER");
    #endif

    return False;
  }

#ifdef NXAGENT_ONSTART
  /* This is probably to communicate with nomachine nxclient. */
  #ifdef TEST
  fprintf(stderr, "%s: Setting owner of selection [%d][%s] to serverWindow [0x%lx]\n", __func__,
              (int) serverTransToAgentProperty, "NX_CUT_BUFFER_SERVER", serverWindow);
  #endif

  XSetSelectionOwner(nxagentDisplay, serverTransToAgentProperty, serverWindow, CurrentTime);
#endif

  if (XQueryExtension(nxagentDisplay,
                      "XFIXES",
                      &nxagentXFixesInfo.Opcode,
                      &nxagentXFixesInfo.EventBase,
                      &nxagentXFixesInfo.ErrorBase) == 0)
  {
    ErrorF("Unable to initialize XFixes extension.\n");
  }
  else
  {
    #ifdef TEST
    fprintf(stderr, "%s: Registering for XFixesSelectionNotify events.\n", __func__);
    #endif

    for (int index = 0; index < nxagentMaxSelections; index++)
    {
      XFixesSelectSelectionInput(nxagentDisplay, serverWindow,
                                 remoteSelectionAtoms[index],
                                 XFixesSetSelectionOwnerNotifyMask |
                                 XFixesSelectionWindowDestroyNotifyMask |
                                 XFixesSelectionClientCloseNotifyMask);
    }

    nxagentXFixesInfo.Initialized = True;
  }

#ifdef NXAGENT_ONSTART
  /*
     The first paste from CLIPBOARD did not work directly after
     session start. Removing this code makes it work. It is unsure why
     it was introduced in the first place so it is possible that we
     see other effects by leaving out this code.

     Fixes X2Go bug #952, see https://bugs.x2go.org/952 for details .

  if (nxagentSessionId[0])
  {
    #ifdef TEST
    fprintf(stderr, "%s: setting the ownership of %s to %lx"
                " and registering for PropertyChangeMask events\n", __func__,
                    validateString(NameForRemoteAtom(nxagentAtoms[10])), serverWindow);
    #endif

    XSetSelectionOwner(nxagentDisplay, nxagentAtoms[10], serverWindow, CurrentTime);    // nxagentAtoms[10] is the CLIPBOARD atom
    pWin -> eventMask |= PropertyChangeMask;
    nxagentChangeWindowAttributes(pWin, CWEventMask);
  }
  */
#endif

  if (nxagentReconnectTrap)
  {
    if (nxagentOption(Clipboard) == ClipboardServer ||
        nxagentOption(Clipboard) == ClipboardBoth)
    {
      for (int index = 0; index < nxagentMaxSelections; index++)
      {
        /*
         * If we have a selection inform the (new) real Xserver and
         * claim the ownership. Note that we report our serverWindow as
         * owner, not the real window!
         */
        if (IS_LOCAL_OWNER(index) && lastSelectionOwner[index].window)
        {
          /* remoteSelectionAtoms have already been adjusted above */
          XSetSelectionOwner(nxagentDisplay, remoteSelectionAtoms[index], serverWindow, CurrentTime);
        }

        /*
         * On reconnect there cannot be any external requestor
         * waiting for a reply so clean this.
         */
        lastServers[index].requestor = None;

        /*
         * FIXME: We should reset lastClients[index].* here! Problem
         * is that local clients might still be waiting for
         * answers. Should reply with failure then.
         */

        invalidateTargetCache(index);
      }
    }
  }
  else
  {
    for (int index = 0; index < nxagentMaxSelections; index++)
    {
      clearSelectionOwnerData(index);
      resetClientSelectionStage(index);
      /* FIXME: required? move to setSelectionStage? */
      lastClients[index].reqTime = GetTimeInMillis();
      lastServers[index].requestor = None;
      invalidateTargetCache(index);
    }

    clientCutProperty = MakeAtom(szAgentNX_CUT_BUFFER_CLIENT,
                                    strlen(szAgentNX_CUT_BUFFER_CLIENT), True);
    if (clientCutProperty == None)
    {
      #ifdef PANIC
      fprintf(stderr, "%s: PANIC! "
              "Could not create %s atom.\n", __func__, szAgentNX_CUT_BUFFER_CLIENT);
      #endif

      return False;
    }
  }

  agentClipboardInitialized = True;

  #ifdef DEBUG
  fprintf(stderr, "%s: Clipboard initialization completed.\n", __func__);
  #endif

  #ifdef NXAGENT_TIMESTAMP
  {
    fprintf(stderr, "%s: Clipboard init ends at [%lu] ms.\n", __func__,
                GetTimeInMillis() - startTime);
  }
  #endif

  return True;
}