1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
|
/*
* Copyright 1996-2007 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
Copyright (C) 2002, 2004-2009 Jeroen Frijters
Copyright (C) 2006 Active Endpoints, Inc.
Copyright (C) 2006-2010 Volker Berlin (i-net software)
Copyright (C) 2010 Karsten Heinrich (i-net software)
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
Jeroen Frijters
jeroen@frijters.net
*/
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using System.ComponentModel;
using System.Reflection;
using java.net;
using java.util;
using ikvm.awt.printing;
using ikvm.runtime;
using sun.awt;
using System.Runtime.InteropServices;
using System.Drawing.Drawing2D;
namespace ikvm.awt
{
internal delegate TResult Func<TResult>();
internal delegate void Action<T>(T t);
class UndecoratedForm : Form
{
private bool focusableWindow = true;
private bool alwaysOnTop;
public UndecoratedForm()
{
setBorderStyle();
SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw, true);
}
protected virtual void setBorderStyle()
{
this.FormBorderStyle = FormBorderStyle.None;
this.ShowInTaskbar = false;
}
internal void SetWindowState(bool focusableWindow, bool alwaysOnTop)
{
this.focusableWindow = focusableWindow;
this.alwaysOnTop = alwaysOnTop;
}
protected override bool ShowWithoutActivation {
// This work not like in Java. In Java it is not possible to click on a not focusable Window
// But now the windows is not stealing the focus on showing
get
{
return !focusableWindow;
}
}
private const int WS_EX_TOPMOST = 0x00000008;
private const int WS_EX_NOACTIVATE = 0x08000000;
private const int WS_DISABLED = 0x08000000;
protected override CreateParams CreateParams {
get {
CreateParams baseParams = base.CreateParams;
int exStyle = baseParams.ExStyle;
// This work not like in Java. In Java it is not possible to click on a not focusable Window
// But now the windows is not stealing the focus on showing
exStyle = focusableWindow ? exStyle & ~WS_EX_NOACTIVATE : exStyle | WS_EX_NOACTIVATE;
// we need to set TOPMOST here because the property TopMost does not work with ShowWithoutActivation
baseParams.ExStyle = alwaysOnTop ? exStyle | WS_EX_TOPMOST : exStyle & ~WS_EX_TOPMOST;
// the Enabled on Forms has no effect. In Java a window beep if ot is disabled
// the same effect have we with this flag
baseParams.Style = Enabled ? baseParams.Style & ~WS_DISABLED : baseParams.Style | WS_DISABLED;
return baseParams;
}
}
protected override void OnPaintBackground(PaintEventArgs e)
{
NetComponentPeer peer = NetComponentPeer.FromControl(this);
if (peer.eraseBackground)
{
base.OnPaintBackground(e);
}
}
}
class MyForm : UndecoratedForm
{
/// <summary>
/// Original MaximizedBounds
/// </summary>
private Rectangle maxBounds;
private bool maxBoundsSet;
public java.awt.Insets peerInsets;
/// <summary>
/// Creates the native form
/// </summary>
/// <param name="peerInsets">the insets instance of the peer instance</param>
public MyForm( java.awt.Insets peerInsets )
{
this.peerInsets = peerInsets;
}
protected override void setBorderStyle()
{
//nothing, default behaviour
}
public void setMaximizedBounds(java.awt.Rectangle rect)
{
if (rect == null)
{
// null means reset to the original system setting
if (maxBoundsSet)
{
SetMaximizedBoundsImpl(maxBounds);
}
}
else
{
if (!maxBoundsSet)
{
maxBounds = MaximizedBounds;
maxBoundsSet = true;
}
SetMaximizedBoundsImpl(J2C.ConvertRect(rect));
}
}
private void SetMaximizedBoundsImpl(Rectangle rect)
{
NetToolkit.Invoke(delegate { MaximizedBounds = rect; });
}
}
sealed class EventQueueSynchronizationContext : SynchronizationContext
{
public override SynchronizationContext CreateCopy()
{
return new EventQueueSynchronizationContext();
}
public override void Post(SendOrPostCallback d, object state)
{
java.awt.EventQueue.invokeLater(Delegates.toRunnable(delegate { d(state); }));
}
public override void Send(SendOrPostCallback d, object state)
{
java.awt.EventQueue.invokeAndWait(Delegates.toRunnable(delegate { d(state); }));
}
[System.Security.SecuritySafeCritical]
internal static void Install()
{
SynchronizationContext.SetSynchronizationContext(new EventQueueSynchronizationContext());
}
}
public sealed class NetToolkit : sun.awt.SunToolkit, ikvm.awt.IkvmToolkit
{
public static readonly String DATA_TRANSFERER_CLASS_NAME = typeof(NetDataTransferer).AssemblyQualifiedName;
private static volatile Form bogusForm;
private int resolution;
private NetClipboard clipboard;
private bool eventQueueSynchronizationContext;
protected override java.awt.EventQueue getSystemEventQueueImpl()
{
java.awt.EventQueue eq = base.getSystemEventQueueImpl();
if (!eventQueueSynchronizationContext)
{
InstallEventQueueSynchronizationContext(eq);
}
return eq;
}
private void InstallEventQueueSynchronizationContext(java.awt.EventQueue eq)
{
bool install;
lock (this)
{
install = !eventQueueSynchronizationContext;
eventQueueSynchronizationContext = true;
}
if (install)
{
eq.postEvent(new java.awt.@event.InvocationEvent(this, Delegates.toRunnable(EventQueueSynchronizationContext.Install), null, true));
}
}
private static void MessageLoop()
{
using (Form form = new Form())
{
CreateNative(form);
bogusForm = form;
Application.Run();
}
}
internal static void CreateNative(Control control)
{
control.CreateControl();
// HACK I have no idea why this line is necessary...
IntPtr p = control.Handle;
if (p == IntPtr.Zero)
{
// shut up compiler warning
}
}
public NetToolkit()
{
lock (typeof(NetToolkit))
{
System.Diagnostics.Debug.Assert(bogusForm == null);
setDataTransfererClassName(DATA_TRANSFERER_CLASS_NAME);
Thread thread = new Thread(new ThreadStart(MessageLoop));
thread.SetApartmentState(ApartmentState.STA);
thread.Name = "IKVM AWT WinForms Message Loop";
thread.IsBackground = true;
thread.Start();
// TODO don't use polling...
while (bogusForm == null && thread.IsAlive)
{
Thread.Sleep(1);
}
}
}
/// <summary>
/// Run on a win 32 system
/// </summary>
/// <returns></returns>
internal static bool isWin32()
{
return Environment.OSVersion.Platform == PlatformID.Win32NT || Environment.OSVersion.Platform == PlatformID.Win32Windows;
}
protected override void loadSystemColors(int[] systemColors)
{
// initialize all colors to purple to make the ones we might have missed stand out
for (int i = 0; i < systemColors.Length; i++)
{
systemColors[i] = Color.Purple.ToArgb();
}
systemColors[java.awt.SystemColor.DESKTOP] = SystemColors.Desktop.ToArgb();
systemColors[java.awt.SystemColor.ACTIVE_CAPTION] = SystemColors.ActiveCaption.ToArgb();
systemColors[java.awt.SystemColor.ACTIVE_CAPTION_TEXT] = SystemColors.ActiveCaptionText.ToArgb();
systemColors[java.awt.SystemColor.ACTIVE_CAPTION_BORDER] = SystemColors.ActiveBorder.ToArgb();
systemColors[java.awt.SystemColor.INACTIVE_CAPTION] = SystemColors.InactiveCaption.ToArgb();
systemColors[java.awt.SystemColor.INACTIVE_CAPTION_TEXT] = SystemColors.InactiveCaptionText.ToArgb();
systemColors[java.awt.SystemColor.INACTIVE_CAPTION_BORDER] = SystemColors.InactiveBorder.ToArgb();
systemColors[java.awt.SystemColor.WINDOW] = SystemColors.Window.ToArgb();
systemColors[java.awt.SystemColor.WINDOW_BORDER] = SystemColors.WindowFrame.ToArgb();
systemColors[java.awt.SystemColor.WINDOW_TEXT] = SystemColors.WindowText.ToArgb();
systemColors[java.awt.SystemColor.MENU] = SystemColors.Menu.ToArgb();
systemColors[java.awt.SystemColor.MENU_TEXT] = SystemColors.MenuText.ToArgb();
systemColors[java.awt.SystemColor.TEXT] = SystemColors.Window.ToArgb();
systemColors[java.awt.SystemColor.TEXT_TEXT] = SystemColors.WindowText.ToArgb();
systemColors[java.awt.SystemColor.TEXT_HIGHLIGHT] = SystemColors.Highlight.ToArgb();
systemColors[java.awt.SystemColor.TEXT_HIGHLIGHT_TEXT] = SystemColors.HighlightText.ToArgb();
systemColors[java.awt.SystemColor.TEXT_INACTIVE_TEXT] = SystemColors.GrayText.ToArgb();
systemColors[java.awt.SystemColor.CONTROL] = SystemColors.Control.ToArgb();
systemColors[java.awt.SystemColor.CONTROL_TEXT] = SystemColors.ControlText.ToArgb();
systemColors[java.awt.SystemColor.CONTROL_HIGHLIGHT] = SystemColors.ControlLight.ToArgb();
systemColors[java.awt.SystemColor.CONTROL_LT_HIGHLIGHT] = SystemColors.ControlLightLight.ToArgb();
systemColors[java.awt.SystemColor.CONTROL_SHADOW] = SystemColors.ControlDark.ToArgb();
systemColors[java.awt.SystemColor.CONTROL_DK_SHADOW] = SystemColors.ControlDarkDark.ToArgb();
systemColors[java.awt.SystemColor.SCROLLBAR] = SystemColors.ScrollBar.ToArgb();
systemColors[java.awt.SystemColor.INFO] = SystemColors.Info.ToArgb();
systemColors[java.awt.SystemColor.INFO_TEXT] = SystemColors.InfoText.ToArgb();
}
public override java.awt.peer.ButtonPeer createButton(java.awt.Button target)
{
java.awt.peer.ButtonPeer peer = Invoke<NetButtonPeer>(delegate { return new NetButtonPeer(target); });
targetCreatedPeer(target, peer);
return peer;
}
public override java.awt.peer.TextFieldPeer createTextField(java.awt.TextField target)
{
java.awt.peer.TextFieldPeer peer = Invoke<NetTextFieldPeer>(delegate { return new NetTextFieldPeer(target); });
targetCreatedPeer(target, peer);
return peer;
}
public override java.awt.peer.LabelPeer createLabel(java.awt.Label target)
{
java.awt.peer.LabelPeer peer = Invoke<NetLabelPeer>(delegate { return new NetLabelPeer(target); });
targetCreatedPeer(target, peer);
return peer;
}
public override java.awt.peer.ListPeer createList(java.awt.List target)
{
java.awt.peer.ListPeer peer = Invoke<NetListPeer>(delegate { return new NetListPeer(target); });
targetCreatedPeer(target, peer);
return peer;
}
public override java.awt.peer.CheckboxPeer createCheckbox(java.awt.Checkbox target)
{
java.awt.peer.CheckboxPeer peer = Invoke<NetCheckboxPeer>(delegate { return new NetCheckboxPeer(target); });
targetCreatedPeer(target, peer);
return peer;
}
public override java.awt.peer.ScrollbarPeer createScrollbar(java.awt.Scrollbar target)
{
java.awt.peer.ScrollbarPeer peer = Invoke<NetScrollbarPeer>(delegate { return new NetScrollbarPeer(target); });
targetCreatedPeer(target, peer);
return peer;
}
public override java.awt.peer.ScrollPanePeer createScrollPane(java.awt.ScrollPane target)
{
java.awt.peer.ScrollPanePeer peer = Invoke<NetScrollPanePeer>(delegate { return new NetScrollPanePeer(target); });
targetCreatedPeer(target, peer);
return peer;
}
public override java.awt.peer.TextAreaPeer createTextArea(java.awt.TextArea target)
{
java.awt.peer.TextAreaPeer peer = Invoke<NetTextAreaPeer>(delegate { return new NetTextAreaPeer(target); });
targetCreatedPeer(target, peer);
return peer;
}
public override java.awt.peer.ChoicePeer createChoice(java.awt.Choice target)
{
java.awt.peer.ChoicePeer peer = Invoke<NetChoicePeer>(delegate { return new NetChoicePeer(target); });
targetCreatedPeer(target, peer);
return peer;
}
public override java.awt.peer.FramePeer createFrame(java.awt.Frame target)
{
java.awt.peer.FramePeer peer = Invoke<NetFramePeer>(delegate { return new NetFramePeer(target); });
targetCreatedPeer(target, peer);
return peer;
}
public override java.awt.peer.WindowPeer createWindow(java.awt.Window target)
{
java.awt.peer.WindowPeer peer = Invoke<NetWindowPeer>(delegate { return new NetWindowPeer(target); });
targetCreatedPeer(target, peer);
return peer;
}
public override java.awt.peer.DialogPeer createDialog(java.awt.Dialog target)
{
java.awt.peer.DialogPeer peer = Invoke<NetDialogPeer>(delegate { return new NetDialogPeer(target); });
targetCreatedPeer(target, peer);
return peer;
}
public override java.awt.peer.MenuBarPeer createMenuBar(java.awt.MenuBar target)
{
// we need to force peer creation of the sub menus here, because we're
// transitioning to the UI thread to do the rest of the work and there
// we cannot acquire the AWT tree lock (because it is owned by the current thread)
for (int i = 0; i < target.getMenuCount(); i++)
{
target.getMenu(i).addNotify();
}
java.awt.Menu help = target.getHelpMenu();
if (help != null)
{
help.addNotify();
}
java.awt.peer.MenuBarPeer peer = Invoke<NetMenuBarPeer>(delegate { return new NetMenuBarPeer(target); });
targetCreatedPeer(target, peer);
return peer;
}
public override java.awt.peer.MenuPeer createMenu(java.awt.Menu target)
{
for (int i = 0; i < target.getItemCount(); i++)
{
target.getItem(i).addNotify();
}
java.awt.peer.MenuPeer peer = Invoke<NetMenuPeer>(delegate { return new NetMenuPeer(target); });
targetCreatedPeer(target, peer);
return peer;
}
public override java.awt.peer.PopupMenuPeer createPopupMenu(java.awt.PopupMenu target)
{
for (int i = 0; i < target.getItemCount(); i++)
{
target.getItem(i).addNotify();
}
java.awt.peer.PopupMenuPeer peer = Invoke<NetPopupMenuPeer>(delegate { return new NetPopupMenuPeer(target); });
targetCreatedPeer(target, peer);
return peer;
}
public override java.awt.peer.MenuItemPeer createMenuItem(java.awt.MenuItem target)
{
java.awt.peer.MenuItemPeer peer = Invoke<NetMenuItemPeer>(delegate { return new NetMenuItemPeer(target); });
targetCreatedPeer(target, peer);
return peer;
}
public override java.awt.peer.FileDialogPeer createFileDialog(java.awt.FileDialog target)
{
return new NetFileDialogPeer(target);
}
public override java.awt.peer.CheckboxMenuItemPeer createCheckboxMenuItem(java.awt.CheckboxMenuItem target)
{
return new NetCheckboxMenuItemPeer(target);
}
public override java.awt.peer.FontPeer getFontPeer(string name, int style)
{
throw new NotImplementedException();
}
public override java.awt.peer.KeyboardFocusManagerPeer createKeyboardFocusManagerPeer(java.awt.KeyboardFocusManager manager)
{
return new NetKeyboardFocusManagerPeer(manager);
}
public override java.awt.Dimension getScreenSize()
{
return new java.awt.Dimension(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
}
public override int getScreenResolution()
{
if (resolution == 0)
{
using (Graphics g = bogusForm.CreateGraphics())
{
resolution = (int)Math.Round(g.DpiY);
}
}
return resolution;
}
public override java.awt.image.ColorModel getColorModel()
{
//we return the default ColorModel because this produce the fewest problems with convertions
return java.awt.image.ColorModel.getRGBdefault();
}
[Obsolete]
public override string[] getFontList()
{
// This method is deprecated and Sun's JDK only returns these fonts as well
return new string[] { "Dialog", "SansSerif", "Serif", "Monospaced", "DialogInput" };
}
[Obsolete]
public override java.awt.FontMetrics getFontMetrics(java.awt.Font font)
{
return new NetFontMetrics(font);
}
public override void sync()
{
}
public override java.awt.Image getImage(string filename)
{
try
{
filename = new java.io.File(filename).getPath(); //convert a Java file name to .NET filename (slahes, backslasches, etc)
using (System.IO.FileStream stream = new System.IO.FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
return new java.awt.image.BufferedImage(new Bitmap(Image.FromStream(stream)));
}
}
catch (Exception)
{
return new NoImage();
}
}
public override java.awt.Image getImage(URL url)
{
// TODO extremely lame...
System.IO.MemoryStream mem = new System.IO.MemoryStream();
java.io.InputStream inS = url.openStream();
int b;
while ((b = inS.read()) >= 0)
{
mem.WriteByte((byte)b);
}
try
{
mem.Position = 0;
return new java.awt.image.BufferedImage(new Bitmap(Image.FromStream(mem)));
}
catch
{
return new NoImage();
}
}
public override java.awt.Image createImage(string filename)
{
return getImage(filename);
}
public override java.awt.Image createImage(URL url)
{
return getImage(url);
}
const int ERROR = java.awt.image.ImageObserver.__Fields.ERROR;
const int ABORT = java.awt.image.ImageObserver.__Fields.ABORT;
const int WIDTH = java.awt.image.ImageObserver.__Fields.WIDTH;
const int HEIGHT = java.awt.image.ImageObserver.__Fields.HEIGHT;
const int FRAMEBITS = java.awt.image.ImageObserver.__Fields.FRAMEBITS;
const int ALLBITS = java.awt.image.ImageObserver.__Fields.ALLBITS;
public override bool prepareImage(java.awt.Image image, int width, int height, java.awt.image.ImageObserver observer)
{
// HACK for now we call checkImage to obtain the status and fire the observer
return (checkImage(image, width, height, observer) & (ALLBITS | ERROR | ABORT)) != 0;
}
public override int checkImage(java.awt.Image image, int width, int height, java.awt.image.ImageObserver observer)
{
if (image.getWidth(null) == -1)
{
if (observer != null)
{
observer.imageUpdate(image, ERROR | ABORT, 0, 0, -1, -1);
}
return ERROR | ABORT;
}
if (observer != null)
{
observer.imageUpdate(image, WIDTH + HEIGHT + FRAMEBITS + ALLBITS, 0, 0, image.getWidth(null), image.getHeight(null));
}
return WIDTH + HEIGHT + FRAMEBITS + ALLBITS;
}
public override java.awt.Image createImage(java.awt.image.ImageProducer producer)
{
NetProducerImage img = new NetProducerImage(producer);
if (producer != null)
{
producer.startProduction(img);
}
return img;
}
public override java.awt.Image createImage(byte[] imagedata, int imageoffset, int imagelength)
{
try
{
return new java.awt.image.BufferedImage(new Bitmap(new MemoryStream(imagedata, imageoffset, imagelength, false)));
}
catch (Exception)
{
return new NoImage();//TODO should throw the exception unstead of NoImage()
}
}
public override java.awt.PrintJob getPrintJob(java.awt.Frame frame, string jobtitle, Properties props)
{
throw new NotImplementedException();
}
public override void beep()
{
Console.Beep();
}
public override java.awt.datatransfer.Clipboard getSystemClipboard()
{
lock(this)
{
if (clipboard==null)
{
clipboard = new NetClipboard();
}
}
return clipboard;
}
public override java.awt.dnd.DragGestureRecognizer createDragGestureRecognizer(java.lang.Class abstractRecognizerClass, java.awt.dnd.DragSource ds, java.awt.Component c, int srcActions, java.awt.dnd.DragGestureListener dgl)
{
java.lang.Class clazz = typeof(java.awt.dnd.MouseDragGestureRecognizer);
if (abstractRecognizerClass == clazz)
return new NetMouseDragGestureRecognizer(ds, c, srcActions, dgl);
else
return null;
}
public override java.awt.dnd.peer.DragSourceContextPeer createDragSourceContextPeer(java.awt.dnd.DragGestureEvent dge)
{
return NetDragSourceContextPeer.createDragSourceContextPeer(dge);
}
public override Map mapInputMethodHighlight(java.awt.im.InputMethodHighlight highlight)
{
throw new NotImplementedException();
}
#if false
protected override java.awt.peer.LightweightPeer createComponent(java.awt.Component target)
{
if(target is java.awt.Container)
{
return new NetLightweightContainerPeer((java.awt.Container)target);
}
return new NetLightweightComponentPeer(target);
}
#endif
/* public override java.awt.Font createFont(int format, java.io.InputStream stream)
{
throw new NotImplementedException();
}
public override gnu.java.awt.peer.ClasspathFontPeer getClasspathFontPeer(string name, java.util.Map attrs)
{
return new NetFontPeer(name, attrs);
}
public override java.awt.GraphicsEnvironment getLocalGraphicsEnvironment()
{
return new NetGraphicsEnvironment();
}
public override RobotPeer createRobot(java.awt.GraphicsDevice screen)
{
if (Environment.OSVersion.Platform == PlatformID.Win32NT || Environment.OSVersion.Platform == PlatformID.Win32Windows)
{
return new WindowsRobot(screen);
}
throw new java.awt.AWTException("Robot not supported for this OS");
}
public override gnu.java.awt.peer.EmbeddedWindowPeer createEmbeddedWindow(gnu.java.awt.EmbeddedWindow ew)
{
throw new NotImplementedException();
}
*/
protected override java.awt.peer.DesktopPeer createDesktopPeer(java.awt.Desktop target)
{
return new NetDesktopPeer();
}
public override java.awt.Dimension getBestCursorSize(int preferredWidth, int preferredHeight)
{
// TODO
return new java.awt.Dimension(preferredWidth, preferredHeight);
}
public override java.awt.Cursor createCustomCursor(java.awt.Image cursor, java.awt.Point hotSpot, string name)
{
return new NetCustomCursor(cursor, hotSpot, name);
}
private object getRegistry(string subKey, string valueName)
{
using (Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(subKey, false))
{
return key == null ? null : key.GetValue(valueName);
}
}
protected override void initializeDesktopProperties()
{
//copied from WToolkit.java
desktopProperties.put("DnD.Autoscroll.initialDelay", java.lang.Integer.valueOf(50));
desktopProperties.put("DnD.Autoscroll.interval", java.lang.Integer.valueOf(50));
try
{
if (isWin32())
{
desktopProperties.put("Shell.shellFolderManager", java.lang.Class.forName("sun.awt.shell.Win32ShellFolderManager2"));
object themeActive = getRegistry("Software\\Microsoft\\Windows\\CurrentVersion\\ThemeManager", "ThemeActive");
// string dllName = (string)getRegistry("Software\\Microsoft\\Windows\\CurrentVersion\\ThemeManager", "DllName");
// string sizeName = (string)getRegistry("Software\\Microsoft\\Windows\\CurrentVersion\\ThemeManager", "SizeName");
// string colorName = (string)getRegistry("Software\\Microsoft\\Windows\\CurrentVersion\\ThemeManager", "ColorName");
desktopProperties.put("win.xpstyle.themeActive", java.lang.Boolean.valueOf("1".Equals(themeActive)));
// desktopProperties.put("win.xpstyle.dllName", dllName);
// desktopProperties.put("win.xpstyle.sizeName", sizeName);
// desktopProperties.put("win.xpstyle.colorName", colorName);
}
}
catch (java.lang.ClassNotFoundException)
{
}
}
protected override Object lazilyLoadDesktopProperty(String name)
{
if ("win.defaultGUI.font".Equals(name))
{
Font font = Control.DefaultFont;
return C2J.ConvertFont(font);
}
return null;
}
protected override java.awt.peer.MouseInfoPeer getMouseInfoPeer() {
return new NetMouseInfoPeer();
}
/*===============================
* Implementations of interface IkvmToolkit
*/
public java.awt.Graphics2D createGraphics(System.Drawing.Bitmap bitmap)
{
return new BitmapGraphics(bitmap);
}
/// <summary>
/// Get a helper class for implementing the print API
/// </summary>
/// <returns></returns>
public sun.print.PrintPeer getPrintPeer()
{
if (isWin32())
{
return new Win32PrintPeer();
}
else
{
return new LinuxPrintPeer();
}
}
/// <summary>
/// Create a outline from the given text and font parameter
/// </summary>
/// <param name="javaFont">the font</param>
/// <param name="frc">font render context</param>
/// <param name="text">the text</param>
/// <param name="x">x - position</param>
/// <param name="y">y - position</param>
/// <returns></returns>
public java.awt.Shape outline(java.awt.Font javaFont, java.awt.font.FontRenderContext frc, string text, float x, float y) {
GraphicsPath path = new GraphicsPath(FillMode.Winding);
Font netFont = javaFont.getNetFont();
FontFamily family = netFont.FontFamily;
FontStyle style = netFont.Style;
float factor = netFont.Size / family.GetEmHeight(style);
float ascent = family.GetCellAscent(style) * factor;
y -= ascent;
StringFormat format = new StringFormat(StringFormat.GenericTypographic);
format.FormatFlags = StringFormatFlags.MeasureTrailingSpaces | StringFormatFlags.NoWrap | StringFormatFlags.FitBlackBox;
format.Trimming = StringTrimming.None;
path.AddString(text, family, (int)style, netFont.Size, new PointF(x, y), format);
return C2J.ConvertShape(path);
}
/*===============================
* Implementations of interface SunToolkit
*/
public override bool isModalExclusionTypeSupported(java.awt.Dialog.ModalExclusionType dmet)
{
throw new NotImplementedException();
}
public override bool isModalityTypeSupported(java.awt.Dialog.ModalityType type)
{
return type.ordinal() == java.awt.Dialog.ModalityType.MODELESS.ordinal() ||
type.ordinal() == java.awt.Dialog.ModalityType.APPLICATION_MODAL.ordinal();
}
public override java.awt.Window createInputMethodWindow(string __p1, sun.awt.im.InputContext __p2)
{
throw new NotImplementedException();
}
public override java.awt.peer.RobotPeer createRobot(java.awt.Robot r, java.awt.GraphicsDevice screen)
{
if (isWin32())
{
return new WindowsRobot(screen);
}
throw new java.awt.AWTException("Robot not supported for this OS");
}
public override java.awt.peer.SystemTrayPeer createSystemTray(java.awt.SystemTray target)
{
NetSystemTrayPeer peer = new NetSystemTrayPeer(target);
targetCreatedPeer(target, peer);
return peer;
}
public override java.awt.peer.TrayIconPeer createTrayIcon(java.awt.TrayIcon target)
{
NetTrayIconPeer peer = new NetTrayIconPeer(target);
targetCreatedPeer(target, peer);
return peer;
}
public override java.awt.im.spi.InputMethodDescriptor getInputMethodAdapterDescriptor()
{
return null;
}
protected override int getScreenHeight()
{
return Screen.PrimaryScreen.Bounds.Height;
}
protected override int getScreenWidth()
{
return Screen.PrimaryScreen.Bounds.Width;
}
public override java.awt.Insets getScreenInsets(java.awt.GraphicsConfiguration gc)
{
NetGraphicsConfiguration ngc = gc as NetGraphicsConfiguration;
if (ngc != null)
{
Rectangle rectWorkingArea = ngc.screen.WorkingArea;
Rectangle rectBounds = ngc.screen.Bounds;
return new java.awt.Insets(
rectWorkingArea.Top - rectBounds.Top,
rectWorkingArea.Left - rectBounds.Left,
rectBounds.Bottom - rectWorkingArea.Bottom,
rectBounds.Right - rectWorkingArea.Right);
}
else
{
return base.getScreenInsets(gc);
}
}
public override void grab(java.awt.Window window)
{
NetWindowPeer peer = (NetWindowPeer)window.getPeer();
if (peer != null)
{
peer.Grab();
}
}
public override bool isDesktopSupported()
{
return true;
}
public override bool isTraySupported()
{
return true;
}
public override bool isFrameStateSupported(int state)
{
switch (state)
{
case java.awt.Frame.NORMAL:
case java.awt.Frame.ICONIFIED:
case java.awt.Frame.MAXIMIZED_BOTH:
return true;
default:
return false;
}
}
protected override bool syncNativeQueue(long l)
{
throw new NotImplementedException();
}
public override void ungrab(java.awt.Window window)
{
NetWindowPeer peer = (NetWindowPeer)window.getPeer();
if (peer != null)
{
peer.Ungrab(false);
}
}
internal new static object targetToPeer(object target)
{
return SunToolkit.targetToPeer(target);
}
internal new static void targetDisposedPeer(object target, object peer)
{
SunToolkit.targetDisposedPeer(target, peer);
}
internal static void BeginInvoke(MethodInvoker del)
{
if (bogusForm.InvokeRequired)
{
bogusForm.BeginInvoke(del);
}
else
{
del();
}
}
internal static void BeginInvoke<T>(Action<T> del, T t)
{
if (bogusForm.InvokeRequired)
{
bogusForm.BeginInvoke(del, t);
}
else
{
del(t);
}
}
internal static void Invoke<T>(Action<T> del, T t)
{
if (bogusForm.InvokeRequired)
{
bogusForm.Invoke(del, t);
}
else
{
del(t);
}
}
internal static TResult Invoke<TResult>(Func<TResult> del)
{
if (bogusForm.InvokeRequired)
{
return (TResult)bogusForm.Invoke(del);
}
else
{
return del();
}
}
internal static void Invoke(MethodInvoker del)
{
if (bogusForm.InvokeRequired)
{
bogusForm.Invoke(del);
}
else
{
del();
}
}
}
sealed class NetMenuBarPeer : java.awt.peer.MenuBarPeer
{
internal readonly MainMenu menu = new MainMenu();
internal NetMenuBarPeer(java.awt.MenuBar target)
{
menu.Tag = target;
for (int i = 0; i < target.getMenuCount(); i++)
{
addMenu(target.getMenu(i));
}
}
public void addHelpMenu(java.awt.Menu m)
{
addMenu(m);
}
public void addMenu(java.awt.Menu m)
{
if (m.getPeer() == null)
{
m.addNotify();
}
NetToolkit.Invoke(delegate { menu.MenuItems.Add(((NetMenuPeer)m.getPeer()).menu); });
}
public void delMenu(int i)
{
NetToolkit.Invoke(delegate { menu.MenuItems.RemoveAt(i); });
}
public void dispose()
{
NetToolkit.Invoke(delegate { menu.Dispose(); });
}
public void setFont(java.awt.Font f)
{
throw new NotImplementedException();
}
}
sealed class NetMenuPeer : java.awt.peer.MenuPeer
{
internal readonly MenuItem menu = new MenuItem();
internal NetMenuPeer(java.awt.Menu target)
{
menu.Tag = target;
menu.Text = target.getLabel();
for (int i = 0; i < target.getItemCount(); i++)
{
addItem(target.getItem(i));
}
}
public void addItem(java.awt.MenuItem item)
{
if (item.getPeer() == null)
{
item.addNotify();
}
if (item.getPeer() is NetMenuItemPeer)
{
NetToolkit.Invoke(delegate { menu.MenuItems.Add(((NetMenuItemPeer)item.getPeer()).menuitem); });
}
else
{
NetToolkit.Invoke(delegate { menu.MenuItems.Add(((NetMenuPeer)item.getPeer()).menu); });
}
}
public void addSeparator()
{
NetToolkit.Invoke(delegate { menu.MenuItems.Add(new MenuItem("-")); });
}
public void delItem(int i)
{
NetToolkit.Invoke(delegate { menu.MenuItems.RemoveAt(i); });
}
public void dispose()
{
NetToolkit.Invoke(delegate { menu.Dispose(); });
}
public void setFont(java.awt.Font f)
{
throw new NotImplementedException();
}
public void disable()
{
setEnabled(false);
}
public void enable()
{
setEnabled(true);
}
public void setEnabled(bool b)
{
NetToolkit.Invoke(delegate { menu.Enabled = b; });
}
public void setLabel(string str)
{
NetToolkit.Invoke(delegate { menu.Text = str; });
}
}
class NetMenuItemPeer : java.awt.peer.MenuItemPeer
{
protected readonly java.awt.MenuItem target;
internal readonly MenuItem menuitem = new MenuItem();
internal NetMenuItemPeer(java.awt.MenuItem target)
{
this.target = target;
setEnabled(target.isEnabled());
setLabel(target.getLabel());
menuitem.Click += OnClick;
}
protected virtual void OnClick(object sender, EventArgs e)
{
long when = java.lang.System.currentTimeMillis();
int modifiers = NetComponentPeer.GetModifiers(Control.ModifierKeys);
NetToolkit.executeOnEventHandlerThread(target, Delegates.toRunnable(delegate
{
NetToolkit.postEvent(NetToolkit.targetToAppContext(target), new java.awt.@event.ActionEvent(target, java.awt.@event.ActionEvent.ACTION_PERFORMED,
target.getActionCommand(), when, modifiers));
}));
}
public void disable()
{
setEnabled(false);
}
public void enable()
{
setEnabled(true);
}
public void setEnabled(bool b)
{
NetToolkit.Invoke(delegate { menuitem.Enabled = b; });
}
public void setLabel(string str)
{
NetToolkit.Invoke(delegate { menuitem.Text = str; });
}
public void dispose()
{
NetToolkit.Invoke(delegate { menuitem.Dispose(); });
}
public void setFont(java.awt.Font f)
{
}
}
sealed class NetCheckboxMenuItemPeer : NetMenuItemPeer, java.awt.peer.CheckboxMenuItemPeer
{
internal NetCheckboxMenuItemPeer(java.awt.CheckboxMenuItem target)
: base(target)
{
setState(target.getState());
}
protected override void OnClick(object sender, EventArgs e)
{
java.awt.CheckboxMenuItem target = (java.awt.CheckboxMenuItem)this.target;
NetToolkit.executeOnEventHandlerThread(target, Delegates.toRunnable(delegate
{
bool state = !menuitem.Checked;
target.setState(state);
NetToolkit.postEvent(NetToolkit.targetToAppContext(target), new java.awt.@event.ItemEvent(target, java.awt.@event.ItemEvent.ITEM_STATE_CHANGED,
target.getLabel(), (state)
? java.awt.@event.ItemEvent.SELECTED
: java.awt.@event.ItemEvent.DESELECTED));
}));
}
public void setState(bool b)
{
NetToolkit.Invoke(delegate { menuitem.Checked = b; });
}
}
internal class NetDragSourceContextPeer : sun.awt.dnd.SunDragSourceContextPeer
{
private static readonly NetDragSourceContextPeer theInstance = new NetDragSourceContextPeer(null);
private bool dragStart = false;
private NetDragSourceContextPeer(java.awt.dnd.DragGestureEvent dge) : base(dge)
{
}
public static NetDragSourceContextPeer createDragSourceContextPeer(java.awt.dnd.DragGestureEvent dge)
{
theInstance.setTrigger(dge);
return theInstance;
}
public override void startSecondaryEventLoop()
{
//NetToolkit.startSecondaryEventLoop();
}
public override void quitSecondaryEventLoop()
{
//NetToolkit.quitSecondaryEventLoop();
}
internal static new java.awt.dnd.DragSourceContext getDragSourceContext()
{
return theInstance.getDragSourceContextCore();
}
internal static NetDragSourceContextPeer getInstance()
{
return theInstance;
}
internal java.awt.dnd.DragSourceContext getDragSourceContextCore()
{
return base.getDragSourceContext();
}
internal new void dragDropFinished(bool success, int operations, int x, int y)
{
if (dragStart)
{
java.awt.EventQueue.invokeLater(Delegates.toRunnable(delegate {
base.dragDropFinished(success, operations, x, y);
}));
}
dragStart = false;
}
protected override void startDrag(java.awt.datatransfer.Transferable trans, long[] formats, Map formatMap)
{
dragStart = true;
long nativeCtxtLocal = 0;
nativeCtxtLocal = createDragSource(getTrigger().getComponent(),
trans,
getTrigger().getTriggerEvent(),
getTrigger().getSourceAsDragGestureRecognizer().getSourceActions(),
formats,
formatMap);
NetDropTargetContextPeer.setCurrentJVMLocalSourceTransferable(trans);
}
private long createDragSource(java.awt.Component component,
java.awt.datatransfer.Transferable transferable,
java.awt.@event.InputEvent nativeTrigger,
int actions,
long[] formats,
Map formatMap)
{
java.awt.Component controlOwner = component;
while (controlOwner!=null && (controlOwner.getPeer() == null || controlOwner.getPeer() is sun.awt.NullComponentPeer))
{
controlOwner = controlOwner.getParent();
}
if (controlOwner != null)
{
NetComponentPeer peer = controlOwner.getPeer() as NetComponentPeer;
if (peer != null)
{
peer.performedDragDropEffects = DragDropEffects.None;
Control control = peer.Control;
if (control != null)
{
java.awt.dnd.DragSource dragSource = getTrigger().getDragSource();
IDataObject data = NetDataTransferer.getInstanceImpl().getDataObject(transferable,
NetDataTransferer.adaptFlavorMap(dragSource.getFlavorMap()));
NetToolkit.BeginInvoke(delegate
{
DragDropEffects effects = control.DoDragDrop(data, DragDropEffects.All);
if (effects == DragDropEffects.None && peer.performedDragDropEffects!=DragDropEffects.None)
{
effects = peer.performedDragDropEffects;
}
peer.performedDragDropEffects = DragDropEffects.None;
dragDropFinished(effects != DragDropEffects.None,
NetComponentPeer.getAction(effects),
Control.MousePosition.X, Control.MousePosition.Y);
});
}
}
}
return 0;
}
protected override void setNativeCursor(long nativeCtxt, java.awt.Cursor c, int cType)
{
}
}
internal class NetDropTargetContextPeer : sun.awt.dnd.SunDropTargetContextPeer
{
private IDataObject data;
internal static NetDropTargetContextPeer getNetDropTargetContextPeer()
{
return new NetDropTargetContextPeer();
}
internal int handleEnterMessage(java.awt.Component component,
int x, int y,
int dropAction,
int actions,
long[] formats,
long nativeCtxt)
{
return postDropTargetEvent(component, x, y, dropAction, actions,
formats, nativeCtxt,
sun.awt.dnd.SunDropTargetEvent.MOUSE_ENTERED,
sun.awt.dnd.SunDropTargetContextPeer.DISPATCH_SYNC);
}
internal void handleExitMessage(java.awt.Component component,
long nativeCtxt)
{
postDropTargetEvent(component, 0, 0, java.awt.dnd.DnDConstants.ACTION_NONE,
java.awt.dnd.DnDConstants.ACTION_NONE, null, nativeCtxt,
sun.awt.dnd.SunDropTargetEvent.MOUSE_EXITED,
sun.awt.dnd.SunDropTargetContextPeer.DISPATCH_SYNC);
}
internal int handleMotionMessage(java.awt.Component component,
int x, int y,
int dropAction,
int actions, long[] formats,
long nativeCtxt)
{
return postDropTargetEvent(component, x, y, dropAction, actions,
formats, nativeCtxt,
sun.awt.dnd.SunDropTargetEvent.MOUSE_DRAGGED,
sun.awt.dnd.SunDropTargetContextPeer.DISPATCH_SYNC);
}
internal void handleDropMessage(java.awt.Component component,
int x, int y,
int dropAction, int actions,
long[] formats,
long nativeCtxt, IDataObject data)
{
this.data = data;
postDropTargetEvent(component, x, y, dropAction, actions,
formats, nativeCtxt,
sun.awt.dnd.SunDropTargetEvent.MOUSE_DROPPED,
!sun.awt.dnd.SunDropTargetContextPeer.DISPATCH_SYNC);
}
internal new int postDropTargetEvent(java.awt.Component component,
int x, int y,
int dropAction,
int actions,
long[] formats,
long nativeCtxt,
int eventID,
bool dispatchType)
{
return base.postDropTargetEvent(component, x, y,
dropAction, actions, formats, nativeCtxt, eventID, dispatchType);
}
protected override void doDropDone(bool success, int dropAction, bool isLocal)
{
// Don't do anything as .NET framework already handle the message pump
}
public override bool isDataFlavorSupported(java.awt.datatransfer.DataFlavor df)
{
if (isTransferableJVMLocal())
return base.isDataFlavorSupported(df);
return base.isDataFlavorSupported(df);
}
public override object getTransferData(java.awt.datatransfer.DataFlavor df)
{
if (isTransferableJVMLocal())
return base.getTransferData(df);
return new NetClipboardTransferable(data).getTransferData(df);
}
protected override object getNativeData(long l)
{
throw new NotImplementedException();
}
}
internal class NetMouseDragGestureRecognizer : java.awt.dnd.MouseDragGestureRecognizer
{
protected static int motionThreshold;
protected static readonly int ButtonMask = java.awt.@event.InputEvent.BUTTON1_DOWN_MASK |
java.awt.@event.InputEvent.BUTTON2_DOWN_MASK |
java.awt.@event.InputEvent.BUTTON3_DOWN_MASK;
public NetMouseDragGestureRecognizer(java.awt.dnd.DragSource source, java.awt.Component component1, int actions,
java.awt.dnd.DragGestureListener listener) :
base(source, component1, actions, listener)
{
}
protected int mapDragOperationFromModifiers(java.awt.@event.MouseEvent e)
{
int mods = e.getModifiersEx();
int btns = mods & ButtonMask;
// Prohibit multi-button drags.
if (!(btns == java.awt.@event.InputEvent.BUTTON1_DOWN_MASK ||
btns == java.awt.@event.InputEvent.BUTTON2_DOWN_MASK ||
btns == java.awt.@event.InputEvent.BUTTON3_DOWN_MASK))
{
return java.awt.dnd.DnDConstants.ACTION_NONE;
}
return
sun.awt.dnd.SunDragSourceContextPeer.convertModifiersToDropAction(mods,
getSourceActions());
}
public override void mouseClicked(java.awt.@event.MouseEvent e)
{
// do nothing
}
public override void mousePressed(java.awt.@event.MouseEvent e)
{
events.clear();
if (mapDragOperationFromModifiers(e) != java.awt.dnd.DnDConstants.ACTION_NONE)
{
try
{
motionThreshold = java.awt.dnd.DragSource.getDragThreshold();
}
catch
{
motionThreshold = 5;
}
appendEvent(e);
}
}
public override void mouseReleased(java.awt.@event.MouseEvent e)
{
events.clear();
}
public override void mouseEntered(java.awt.@event.MouseEvent e)
{
events.clear();
}
public override void mouseExited(java.awt.@event.MouseEvent e)
{
if (!events.isEmpty())
{ // gesture pending
int dragAction = mapDragOperationFromModifiers(e);
if (dragAction == java.awt.dnd.DnDConstants.ACTION_NONE)
{
events.clear();
}
}
}
public override void mouseDragged(java.awt.@event.MouseEvent e)
{
if (!events.isEmpty())
{ // gesture pending
int dop = mapDragOperationFromModifiers(e);
if (dop == java.awt.dnd.DnDConstants.ACTION_NONE)
{
return;
}
java.awt.@event.MouseEvent trigger = (java.awt.@event.MouseEvent)events.get(0);
java.awt.Point origin = trigger.getPoint();
java.awt.Point current = e.getPoint();
int dx = java.lang.Math.abs(origin.x - current.x);
int dy = java.lang.Math.abs(origin.y - current.y);
if (dx > motionThreshold || dy > motionThreshold)
{
fireDragGestureRecognized(dop, ((java.awt.@event.MouseEvent)getTriggerEvent()).getPoint());
}
else
appendEvent(e);
}
}
}
class NetInputMethodDescriptor : java.awt.im.spi.InputMethodDescriptor
{
public java.awt.im.spi.InputMethod createInputMethod()
{
throw new NotImplementedException();
}
public Locale[] getAvailableLocales()
{
// TODO Feature with .NET 3.0 available
//IEnumerable languages = System.Windows.Input.InputLanguageManager.AvailableInputLanguages;
// as a hack we return the default locale
return new Locale[]{Locale.getDefault()};
}
public string getInputMethodDisplayName(Locale inputLocale, Locale displayLanguage)
{
// copied from WInputMethodDescriptor
// We ignore the input locale.
// When displaying for the default locale, rely on the localized AWT properties;
// for any other locale, fall back to English.
String name = "System Input Methods";
if (Locale.getDefault().equals(displayLanguage))
{
name = java.awt.Toolkit.getProperty("AWT.HostInputMethodDisplayName", name);
}
return name;
}
public java.awt.Image getInputMethodIcon(Locale l)
{
//WInputMethodDescriptor return also ever null
return null;
}
public bool hasDynamicLocaleList()
{
// Java return also true
return true;
}
}
class NetCustomCursor : java.awt.Cursor
{
private Cursor cursor;
public Cursor Cursor
{
get { return cursor; }
}
internal NetCustomCursor(java.awt.Image cursorIm, java.awt.Point hotSpot, String name) // throws IndexOutOfBoundsException
: base(name)
{
java.awt.Toolkit toolkit = java.awt.Toolkit.getDefaultToolkit();
// Make sure image is fully loaded.
java.awt.Component c = new java.awt.Canvas(); // for its imageUpdate method
java.awt.MediaTracker tracker = new java.awt.MediaTracker(c);
tracker.addImage(cursorIm, 0);
try
{
tracker.waitForAll();
}
catch (java.lang.InterruptedException)
{
}
int width = cursorIm.getWidth(c);
int height = cursorIm.getHeight(c);
// Fix for bug 4212593 The Toolkit.createCustomCursor does not
// check absence of the image of cursor
// If the image is invalid, the cursor will be hidden (made completely
// transparent). In this case, getBestCursorSize() will adjust negative w and h,
// but we need to set the hotspot inside the image here.
if (tracker.isErrorAny() || width < 0 || height < 0)
{
hotSpot.x = hotSpot.y = 0;
}
// Scale image to nearest supported size.
java.awt.Dimension nativeSize = toolkit.getBestCursorSize(width, height);
if (nativeSize.width != width || nativeSize.height != height)
{
cursorIm = cursorIm.getScaledInstance(nativeSize.width,
nativeSize.height,
java.awt.Image.SCALE_DEFAULT);
width = nativeSize.width;
height = nativeSize.height;
}
// Verify that the hotspot is within cursor bounds.
if (hotSpot.x >= width || hotSpot.y >= height || hotSpot.x < 0 || hotSpot.y < 0)
{
throw new ArgumentException("invalid hotSpot");
}
NetProducerImage npi = new NetProducerImage(cursorIm.getSource());
cursorIm.getSource().startProduction(npi);
Bitmap bitmap = npi.getBitmap();
IntPtr hIcon = bitmap.GetHicon();
cursor = new Cursor(hIcon);
}
}
sealed class NetLightweightComponentPeer : NetComponentPeer<java.awt.Component, Control>, java.awt.peer.LightweightPeer
{
public NetLightweightComponentPeer(java.awt.Component target)
: base(target)
{
}
protected override Control CreateControl()
{
throw new NotImplementedException();
}
}
sealed class NetLightweightContainerPeer : NetContainerPeer<java.awt.Container, ContainerControl>, java.awt.peer.LightweightPeer
{
public NetLightweightContainerPeer(java.awt.Container target)
: base(target)
{
}
}
abstract class NetComponentPeer : java.awt.peer.ComponentPeer
{
internal bool eraseBackground = true;
public abstract void applyShape(sun.java2d.pipe.Region r);
public abstract bool canDetermineObscurity();
public abstract int checkImage(java.awt.Image i1, int i2, int i3, java.awt.image.ImageObserver io);
public abstract void coalescePaintEvent(java.awt.@event.PaintEvent pe);
public abstract void createBuffers(int i, java.awt.BufferCapabilities bc);
public abstract java.awt.Image createImage(int i1, int i2);
public abstract java.awt.Image createImage(java.awt.image.ImageProducer ip);
public abstract java.awt.image.VolatileImage createVolatileImage(int i1, int i2);
public abstract void destroyBuffers();
public abstract void disable();
public abstract void dispose();
public abstract void enable();
public abstract void flip(java.awt.BufferCapabilities.FlipContents bcfc);
public abstract java.awt.Image getBackBuffer();
public abstract java.awt.Rectangle getBounds();
public abstract java.awt.image.ColorModel getColorModel();
public abstract java.awt.FontMetrics getFontMetrics(java.awt.Font f);
public abstract java.awt.Graphics getGraphics();
public abstract java.awt.GraphicsConfiguration getGraphicsConfiguration();
public abstract java.awt.Point getLocationOnScreen();
public abstract java.awt.Dimension getMinimumSize();
public abstract java.awt.Dimension getPreferredSize();
public abstract java.awt.Toolkit getToolkit();
public abstract void handleEvent(java.awt.AWTEvent awte);
public abstract bool handlesWheelScrolling();
public abstract void hide();
public abstract bool isFocusable();
public abstract bool isObscured();
public abstract bool isReparentSupported();
public abstract void layout();
public abstract java.awt.Dimension minimumSize();
public abstract void paint(java.awt.Graphics g);
public abstract java.awt.Dimension preferredSize();
public abstract bool prepareImage(java.awt.Image i1, int i2, int i3, java.awt.image.ImageObserver io);
public abstract void print(java.awt.Graphics g);
public abstract void repaint(long l, int i1, int i2, int i3, int i4);
public abstract void reparent(java.awt.peer.ContainerPeer cp);
public abstract bool requestFocus(java.awt.Component c, bool b1, bool b2, long l, CausedFocusEvent.Cause cfec);
public abstract void reshape(int i1, int i2, int i3, int i4);
public abstract void setBackground(java.awt.Color c);
public abstract void setBounds(int i1, int i2, int i3, int i4, int i5);
public abstract void setEnabled(bool b);
public abstract void setFont(java.awt.Font f);
public abstract void setForeground(java.awt.Color c);
public abstract void setVisible(bool b);
public abstract void show();
public abstract void updateCursorImmediately();
internal DragDropEffects performedDragDropEffects = DragDropEffects.None;
internal abstract Control Control { get; }
internal abstract java.awt.Component Target { get; }
internal abstract int getInsetsLeft();
internal abstract int getInsetsTop();
internal static int getAction(DragDropEffects effects)
{
int actions = java.awt.dnd.DnDConstants.ACTION_NONE;
switch (effects)
{
case DragDropEffects.None:
actions = java.awt.dnd.DnDConstants.ACTION_NONE;
break;
case DragDropEffects.Copy:
actions = java.awt.dnd.DnDConstants.ACTION_COPY;
break;
case DragDropEffects.Move:
actions = java.awt.dnd.DnDConstants.ACTION_MOVE;
break;
case DragDropEffects.Move | DragDropEffects.Copy:
actions = java.awt.dnd.DnDConstants.ACTION_COPY_OR_MOVE;
break;
case DragDropEffects.Link:
actions = java.awt.dnd.DnDConstants.ACTION_LINK;
break;
}
return actions;
}
internal static int GetMouseEventModifiers(MouseEventArgs ev)
{
int modifiers = GetModifiers(Control.ModifierKeys);
//Which button was pressed or released, because it can only one that it is a switch
MouseButtons button = ev.Button;
switch (button)
{
case MouseButtons.Left:
modifiers |= java.awt.@event.InputEvent.BUTTON1_MASK;
break;
case MouseButtons.Middle:
modifiers |= java.awt.@event.InputEvent.BUTTON2_MASK;
break;
case MouseButtons.Right:
modifiers |= java.awt.@event.InputEvent.BUTTON3_MASK;
break;
}
return modifiers;
}
internal static int GetModifiers(Keys keys)
{
int modifiers = 0;
if ((keys & Keys.Shift) != 0)
{
modifiers |= java.awt.@event.InputEvent.SHIFT_DOWN_MASK;
}
switch (keys & (Keys.Control | Keys.Alt))
{
case Keys.Control:
modifiers |= java.awt.@event.InputEvent.CTRL_DOWN_MASK;
break;
case Keys.Alt:
modifiers |= java.awt.@event.InputEvent.ALT_DOWN_MASK;
break;
case Keys.Control | Keys.Alt:
modifiers |= java.awt.@event.InputEvent.ALT_GRAPH_DOWN_MASK;
break;
}
if ((Control.MouseButtons & MouseButtons.Left) != 0)
{
modifiers |= java.awt.@event.InputEvent.BUTTON1_DOWN_MASK;
}
if ((Control.MouseButtons & MouseButtons.Middle) != 0)
{
modifiers |= java.awt.@event.InputEvent.BUTTON2_DOWN_MASK;
}
if ((Control.MouseButtons & MouseButtons.Right) != 0)
{
modifiers |= java.awt.@event.InputEvent.BUTTON3_DOWN_MASK;
}
return modifiers;
}
internal static int GetButton(MouseEventArgs e)
{
if ((e.Button & MouseButtons.Left) != 0)
{
return java.awt.@event.MouseEvent.BUTTON1;
}
else if ((e.Button & MouseButtons.Middle) != 0)
{
return java.awt.@event.MouseEvent.BUTTON2;
}
else if ((e.Button & MouseButtons.Right) != 0)
{
return java.awt.@event.MouseEvent.BUTTON3;
}
else
{
return java.awt.@event.MouseEvent.NOBUTTON;
}
}
internal static NetComponentPeer FromControl(Control control)
{
return (NetComponentPeer)control.Tag;
}
}
abstract class NetComponentPeer<T, C> : NetComponentPeer
where T : java.awt.Component
where C : Control
{
protected static readonly java.awt.Font defaultFont = new java.awt.Font(java.awt.Font.DIALOG, java.awt.Font.PLAIN, 12);
internal readonly T target;
internal readonly C control;
private bool isMouseClick;
private bool isDoubleClick;
private bool isPopupMenu;
private int oldWidth = -1;
private int oldHeight = -1;
private bool sm_suppressFocusAndActivation;
private bool m_callbacksEnabled;
//private int m_validationNestCount;
private int serialNum = 0;
private bool isLayouting = false;
private bool paintPending = false;
private RepaintArea paintArea;
private java.awt.Font font;
private java.awt.Color foreground;
private java.awt.Color background;
private volatile bool disposed;
private NetDropTargetContextPeer dropTargetPeer;
internal override Control Control
{
get { return control; }
}
internal override java.awt.Component Target
{
get { return target; }
}
public NetComponentPeer(T target)
{
this.target = target;
this.paintArea = new RepaintArea();
java.awt.Container parent = SunToolkit.getNativeContainer(target);
NetComponentPeer parentPeer = (NetComponentPeer)NetToolkit.targetToPeer(parent);
control = Create(parentPeer);
// fix for 5088782: check if window object is created successfully
//checkCreation();
//this.winGraphicsConfig = (NetGraphicsConfiguration)getGraphicsConfiguration();
/*
this.surfaceData =
winGraphicsConfig.createSurfaceData(this, numBackBuffers);
*/
initialize();
start(); // Initialize enable/disable state, turn on callbacks
}
protected virtual void initialize()
{
if (target.isVisible())
{
show(); // the wnd starts hidden
}
java.awt.Color fg = target.getForeground();
if (fg != null)
{
setForeground(fg);
}
// Set background color in C++, to avoid inheriting a parent's color.
java.awt.Font f = target.getFont();
if (f != null)
{
setFont(f);
}
if (!target.isEnabled())
{
disable();
}
java.awt.Rectangle r = target.getBounds();
setBounds(r.x, r.y, r.width, r.height, java.awt.peer.ComponentPeer.__Fields.SET_BOUNDS);
// this is from initialize() in WCanvasPeer.java
eraseBackground = !SunToolkit.getSunAwtNoerasebackground();
if (!PaintEventDispatcher.getPaintEventDispatcher().shouldDoNativeBackgroundErase(target))
{
eraseBackground = false;
}
}
void start()
{
NetToolkit.BeginInvoke(delegate
{
hookEvents();
// JDK native code also disables the window here, but since that is already done in initialize(),
// I don't see the point
EnableCallbacks(true);
control.Invalidate();
control.Update();
});
}
void EnableCallbacks(bool enabled)
{
m_callbacksEnabled = enabled;
}
private C Create(NetComponentPeer parent)
{
C control = CreateControl();
control.Tag = this;
if (parent != null)
{
Form form = control as Form;
if (form != null)
{
form.Owner = parent.Control.FindForm();
}
else
{
control.Parent = parent.Control;
}
}
NetToolkit.CreateNative(control);
return control;
}
protected abstract C CreateControl();
void pShow()
{
NetToolkit.BeginInvoke(delegate { control.Visible = true; });
}
void Enable(bool enable)
{
sm_suppressFocusAndActivation = true;
control.Enabled = enable;
sm_suppressFocusAndActivation = false;
}
internal virtual void hookEvents()
{
// TODO we really only should hook these events when they are needed...
control.KeyDown += new KeyEventHandler(OnKeyDown);
control.KeyUp += new KeyEventHandler(OnKeyUp);
control.KeyPress += new KeyPressEventHandler(OnKeyPress);
control.MouseMove += new MouseEventHandler(OnMouseMove);
control.MouseDown += new MouseEventHandler(OnMouseDown);
control.MouseWheel += new MouseEventHandler(OnMouseWheel);
control.Click += new EventHandler(OnClick);
control.DoubleClick += new EventHandler(OnDoubleClick);
control.MouseUp += new MouseEventHandler(OnMouseUp);
control.MouseEnter += new EventHandler(OnMouseEnter);
control.MouseLeave += new EventHandler(OnMouseLeave);
control.GotFocus += new EventHandler(OnGotFocus);
control.LostFocus += new EventHandler(OnLostFocus);
//control.Leave += new EventHandler(OnBoundsChanged);
control.Paint += new PaintEventHandler(OnPaint);
control.ContextMenu = new ContextMenu();
control.ContextMenu.Popup += new EventHandler(OnPopupMenu);
control.AllowDrop = true;
control.DragDrop += new DragEventHandler(OnDragDrop);
control.DragOver += new DragEventHandler(OnDragOver);
control.DragLeave += new EventHandler(OnDragLeave);
control.DragEnter += new DragEventHandler(OnDragEnter);
control.QueryContinueDrag += new QueryContinueDragEventHandler(OnQueryContinueDrag);
}
internal virtual void unhookEvents()
{
control.KeyDown -= new KeyEventHandler(OnKeyDown);
control.KeyUp -= new KeyEventHandler(OnKeyUp);
control.KeyPress -= new KeyPressEventHandler(OnKeyPress);
control.MouseMove -= new MouseEventHandler(OnMouseMove);
control.MouseDown -= new MouseEventHandler(OnMouseDown);
control.MouseWheel -= new MouseEventHandler(OnMouseWheel);
control.Click -= new EventHandler(OnClick);
control.DoubleClick -= new EventHandler(OnDoubleClick);
control.MouseUp -= new MouseEventHandler(OnMouseUp);
control.MouseEnter -= new EventHandler(OnMouseEnter);
control.MouseLeave -= new EventHandler(OnMouseLeave);
control.GotFocus -= new EventHandler(OnGotFocus);
control.LostFocus -= new EventHandler(OnLostFocus);
//control.Leave -= new EventHandler(OnBoundsChanged);
control.Paint -= new PaintEventHandler(OnPaint);
control.DragDrop -= new DragEventHandler(OnDragDrop);
control.DragOver -= new DragEventHandler(OnDragOver);
control.DragLeave -= new EventHandler(OnDragLeave);
control.DragEnter -= new DragEventHandler(OnDragEnter);
if (control.ContextMenu != null)
control.ContextMenu.Popup -= new EventHandler(OnPopupMenu);
}
protected void SendEvent(java.awt.AWTEvent evt)
{
postEvent(evt);
}
/// <summary>
/// Get the left insets of the .NET Window.
/// In .NET the coordinate of a window start on the most left, top point with 0,0
/// In Java the most left, top point with 0,0 is in the detail area of the window.
/// In all not Windows Component this return ever 0.
/// </summary>
/// <returns></returns>
internal override int getInsetsLeft()
{
return 0;
}
/// <summary>
/// Get the top insets of the .NET Window.
/// In .NET the coordinate of a window start on the most left, top point with 0,0
/// In Java the most left, top point with 0,0 is in the detail area of the window.
/// In all not Windows Component this return ever 0.
/// </summary>
/// <returns></returns>
internal override int getInsetsTop()
{
return 0;
}
/// <summary>
/// .NET calculates the offset relative to the detail area.
/// Java uses the top left point of a window.
/// That means we must compensate the coordinate of a component
/// if the parent is a window, frame or dialog.
/// </summary>
/// <returns>The offset of the details area in the parent</returns>
private Point getParentOffset()
{
if (!(target is java.awt.Window))
{
java.awt.Container parent = target.getParent();
if (parent != null)
{
NetComponentPeer peer = parent.getPeer() as NetComponentPeer;
if (peer != null)
{
return new Point(peer.getInsetsLeft(), peer.getInsetsTop());
}
}
}
return new Point();
}
private void OnPaint(object sender, PaintEventArgs e)
{
//CheckFontSmoothingSettings(GetHWnd());
/* Set draw state */
//SetDrawState(GetDrawState() | JAWT_LOCK_CLIP_CHANGED);
WmPaint(e.Graphics, e.ClipRectangle);
}
private void WmPaint(Graphics g, Rectangle r)
{
handlePaint(r.X + getInsetsLeft(), r.Y + getInsetsTop(), r.Width, r.Height);
}
/* Invoke a paint() method call on the target, without clearing the
* damaged area. This is normally called by a native control after
* it has painted itself.
*
* NOTE: This is called on the privileged toolkit thread. Do not
* call directly into user code using this thread!
*/
private void handlePaint(int x, int y, int w, int h)
{
postPaintIfNecessary(x, y, w, h);
}
private void postPaintIfNecessary(int x, int y, int w, int h)
{
if (!ComponentAccessor.getIgnoreRepaint(target))
{
java.awt.@event.PaintEvent evt = PaintEventDispatcher.getPaintEventDispatcher().createPaintEvent(target, x, y, w, h);
if (evt != null)
{
postEvent(evt);
}
}
}
private static int MapKeyCode(Keys key)
{
switch (key)
{
case Keys.Delete:
return java.awt.@event.KeyEvent.VK_DELETE;
case Keys.Enter:
return java.awt.@event.KeyEvent.VK_ENTER;
default:
return (int)key;
}
}
private void OnKeyDown(object sender, KeyEventArgs e)
{
long when = java.lang.System.currentTimeMillis();
int modifiers = GetModifiers(e.Modifiers);
int keyCode = MapKeyCode(e.KeyCode);
// TODO set keyChar
char keyChar = ' ';
int keyLocation = java.awt.@event.KeyEvent.KEY_LOCATION_STANDARD;
java.awt.EventQueue.invokeLater(Delegates.toRunnable(delegate {
postEvent(new java.awt.@event.KeyEvent(target, java.awt.@event.KeyEvent.KEY_PRESSED, when, modifiers, keyCode, keyChar, keyLocation));
}));
}
private void OnQueryContinueDrag(object sender, QueryContinueDragEventArgs e)
{
}
private void OnDragEnter(object sender, DragEventArgs e)
{
IDataObject obj = e.Data;
long[] formats = NetDataTransferer.getInstanceImpl().getClipboardFormatCodes(obj.GetFormats());
dropTargetPeer = NetDropTargetContextPeer.getNetDropTargetContextPeer();
int actions = dropTargetPeer.handleEnterMessage(target, e.X, e.Y, getDropAction(e.AllowedEffect, e.KeyState), getAction(e.AllowedEffect),
formats, 0);
e.Effect = getDragDropEffects(actions);
}
private void OnDragOver(object sender, DragEventArgs e)
{
IDataObject obj = e.Data;
long[] formats = NetDataTransferer.getInstanceImpl().getClipboardFormatCodes(obj.GetFormats());
dropTargetPeer = NetDropTargetContextPeer.getNetDropTargetContextPeer();
int actions = dropTargetPeer.handleMotionMessage(target, e.X, e.Y, getDropAction(e.AllowedEffect, e.KeyState), getAction(e.AllowedEffect),
formats, 0);
e.Effect = getDragDropEffects(actions);
}
private void OnDragLeave(object sender, EventArgs e)
{
if (dropTargetPeer!=null)
dropTargetPeer.handleExitMessage(target, 0);
dropTargetPeer = null;
}
private void OnDragDrop(object sender, DragEventArgs e)
{
IDataObject obj = e.Data;
long[] formats = NetDataTransferer.getInstanceImpl().getClipboardFormatCodes(obj.GetFormats());
int actions = getAction(e.Effect);
if (dropTargetPeer != null)
dropTargetPeer.handleDropMessage(target, e.X, e.Y, getAction(e.Effect), getAction(e.AllowedEffect),
formats, 0, e.Data);
NetDragSourceContextPeer.getInstance().dragDropFinished(true, actions, e.X, e.Y);
performedDragDropEffects = e.Effect;
dropTargetPeer = null;
}
private static DragDropEffects getDragDropEffects(int actions)
{
switch(actions)
{
case java.awt.dnd.DnDConstants.ACTION_COPY:
return DragDropEffects.Copy;
case java.awt.dnd.DnDConstants.ACTION_MOVE:
return DragDropEffects.Move;
case java.awt.dnd.DnDConstants.ACTION_COPY_OR_MOVE:
return DragDropEffects.Move | DragDropEffects.Copy;
case java.awt.dnd.DnDConstants.ACTION_LINK:
return DragDropEffects.Link;
default:
return DragDropEffects.None;
}
}
private static int getDropAction(DragDropEffects effects, int keyState)
{
int ret = java.awt.dnd.DnDConstants.ACTION_NONE;
const int MK_CONTROL = 0x8;
const int MK_SHIFT = 0x4;
// const int WM_MOUSEWHEEL = 0x20A;
// const int MK_LBUTTON = 0x1;
// const int MK_MBUTTON = 0x10;
// const int MK_RBUTTON = 0x2;
// const int MK_XBUTTON1 = 0x20;
// const int MK_XBUTTON2 = 0x40;
switch (keyState & (MK_CONTROL | MK_SHIFT))
{
case MK_CONTROL:
if ((effects & DragDropEffects.Copy) == DragDropEffects.Copy)
ret = java.awt.dnd.DnDConstants.ACTION_COPY;
else
ret = java.awt.dnd.DnDConstants.ACTION_NONE;
break;
case MK_CONTROL | MK_SHIFT:
if ((effects & DragDropEffects.Link) == DragDropEffects.Link)
ret = java.awt.dnd.DnDConstants.ACTION_LINK;
else
ret = java.awt.dnd.DnDConstants.ACTION_NONE;
break;
case MK_SHIFT:
if ((effects & DragDropEffects.Move) == DragDropEffects.Move)
ret = java.awt.dnd.DnDConstants.ACTION_MOVE;
else
ret = java.awt.dnd.DnDConstants.ACTION_NONE;
break;
default:
if ((effects & DragDropEffects.Move) == DragDropEffects.Move)
{
ret = java.awt.dnd.DnDConstants.ACTION_MOVE;
}
else if ((effects & DragDropEffects.Copy) == DragDropEffects.Copy)
{
ret = java.awt.dnd.DnDConstants.ACTION_COPY;
}
else if ((effects & DragDropEffects.Link) == DragDropEffects.Link)
{
ret = java.awt.dnd.DnDConstants.ACTION_LINK;
}
break;
}
return ret;
}
private void OnKeyUp(object sender, KeyEventArgs e)
{
long when = java.lang.System.currentTimeMillis();
int modifiers = GetModifiers(e.Modifiers);
int keyCode = MapKeyCode(e.KeyCode);
// TODO set keyChar
char keyChar = ' ';
int keyLocation = java.awt.@event.KeyEvent.KEY_LOCATION_STANDARD;
java.awt.EventQueue.invokeLater(Delegates.toRunnable(delegate {
postEvent(new java.awt.@event.KeyEvent(target, java.awt.@event.KeyEvent.KEY_RELEASED, when, modifiers, keyCode, keyChar, keyLocation));
}));
}
protected virtual void OnKeyPress(object sender, KeyPressEventArgs e)
{
long when = java.lang.System.currentTimeMillis();
int modifiers = GetModifiers(Control.ModifierKeys);
int keyCode = java.awt.@event.KeyEvent.VK_UNDEFINED;
char keyChar = e.KeyChar;
int keyLocation = java.awt.@event.KeyEvent.KEY_LOCATION_UNKNOWN;
java.awt.EventQueue.invokeLater(Delegates.toRunnable(delegate {
postEvent(new java.awt.@event.KeyEvent(target, java.awt.@event.KeyEvent.KEY_TYPED, when, modifiers, keyCode, keyChar, keyLocation));
}));
}
private void postMouseEvent(MouseEventArgs ev, int id, int clicks)
{
long when = java.lang.System.currentTimeMillis();
int modifiers = GetMouseEventModifiers(ev);
int button = GetButton(ev);
int clickCount = clicks;
int x = ev.X + getInsetsLeft(); //The Inset correctur is needed for Window and extended classes
int y = ev.Y + getInsetsTop();
bool isPopup = isPopupMenu;
java.awt.EventQueue.invokeLater(Delegates.toRunnable(delegate {
postEvent(new java.awt.@event.MouseEvent(target, id, when, modifiers, x, y, clickCount, isPopup, button));
}));
isPopupMenu = false;
}
private void postMouseEvent(EventArgs ev, int id)
{
long when = java.lang.System.currentTimeMillis();
int modifiers = GetModifiers(Control.ModifierKeys);
int button = 0;
int clickCount = 0;
int x = Control.MousePosition.X - control.Location.X;
int y = Control.MousePosition.Y - control.Location.Y;
bool isPopup = isPopupMenu;
java.awt.EventQueue.invokeLater(Delegates.toRunnable(delegate {
postEvent(new java.awt.@event.MouseEvent(target, id, when, modifiers, x, y, clickCount, isPopup, button));
}));
isPopupMenu = false;
}
private void postMouseWheelEvent(EventArgs ev, int id, int delta)
{
long when = java.lang.System.currentTimeMillis();
int modifiers = GetModifiers(Control.ModifierKeys);
int scrollAmount = -delta * SystemInformation.MouseWheelScrollLines / 120;
int clickCount = 0;
int x = Control.MousePosition.X - control.Location.X;
int y = Control.MousePosition.Y - control.Location.Y;
bool isPopup = isPopupMenu;
java.awt.EventQueue.invokeLater(Delegates.toRunnable(delegate
{
postEvent(new java.awt.@event.MouseWheelEvent(target, id, when, modifiers, x, y, clickCount, isPopup, java.awt.@event.MouseWheelEvent.WHEEL_UNIT_SCROLL, scrollAmount, scrollAmount));
}));
}
protected virtual void OnMouseMove(object sender, MouseEventArgs ev)
{
if((ev.Button & (MouseButtons.Left | MouseButtons.Right)) != 0)
{
postMouseEvent(ev, java.awt.@event.MouseEvent.MOUSE_DRAGGED, ev.Clicks);
}
else
{
postMouseEvent(ev, java.awt.@event.MouseEvent.MOUSE_MOVED, ev.Clicks);
}
}
protected virtual void OnMouseDown(object sender, MouseEventArgs ev)
{
isMouseClick = false;
isDoubleClick = false;
isPopupMenu = false;
postMouseEvent(ev, java.awt.@event.MouseEvent.MOUSE_PRESSED, ev.Clicks);
}
private void OnMouseWheel(object sender, MouseEventArgs ev)
{
postMouseWheelEvent(ev, java.awt.@event.MouseEvent.MOUSE_WHEEL, ev.Delta);
}
private void OnClick(object sender, EventArgs ev)
{
isMouseClick = true;
}
private void OnDoubleClick(object sender, EventArgs ev)
{
isDoubleClick = true;
}
private void OnMouseUp(object sender, MouseEventArgs ev)
{
postMouseEvent(ev, java.awt.@event.MouseEvent.MOUSE_RELEASED, ev.Clicks);
if (isMouseClick)
{
//We make our own mouse click event because the event order is different in .NET
//in .NET the click occured before MouseUp
int clicks = ev.Clicks;
if (isDoubleClick)
{
clicks = 2;
}
postMouseEvent(ev, java.awt.@event.MouseEvent.MOUSE_CLICKED, clicks);
}
isMouseClick = false;
}
private void OnMouseEnter(object sender, EventArgs ev)
{
postMouseEvent(ev, java.awt.@event.MouseEvent.MOUSE_ENTERED);
}
private void OnMouseLeave(object sender, EventArgs ev)
{
postMouseEvent(ev, java.awt.@event.MouseEvent.MOUSE_EXITED);
}
private void OnGotFocus(object sender, EventArgs e)
{
if (sm_suppressFocusAndActivation)
{
return;
}
java.awt.EventQueue.invokeLater(Delegates.toRunnable(delegate {
postEvent(new java.awt.@event.FocusEvent(target, java.awt.@event.FocusEvent.FOCUS_GAINED));
}));
}
private void OnLostFocus(object sender, EventArgs e)
{
java.awt.EventQueue.invokeLater(Delegates.toRunnable(delegate {
postEvent(new java.awt.@event.FocusEvent(target, java.awt.@event.FocusEvent.FOCUS_LOST));
}));
}
/*
* Called from native code (on Toolkit thread) in order to
* dynamically layout the Container during resizing
*/
internal void dynamicallyLayoutContainer() {
// If we got the WM_SIZING, this must be a Container, right?
// In fact, it must be the top-level Container.
//if (log.isLoggable(Level.FINE)) {
// java.awt.Container parent = NetToolkit.getNativeContainer((java.awt.Component)target);
// if (parent != null) {
// log.log(Level.FINE, "Assertion (parent == null) failed");
// }
//}
java.awt.Container cont = (java.awt.Container)(object)target;
NetToolkit.executeOnEventHandlerThread(cont, Delegates.toRunnable(delegate {
// Discarding old paint events doesn't seem to be necessary.
cont.invalidate();
cont.validate();
//if (surfaceData instanceof OGLSurfaceData) {
// // 6290245: When OGL is enabled, it is necessary to
// // replace the SurfaceData for each dynamic layout
// // request so that the OGL viewport stays in sync
// // with the window bounds.
// try {
// replaceSurfaceData();
// } catch (InvalidPipeException e) {
// // REMIND: this is unlikely to occur for OGL, but
// // what do we do if surface creation fails?
// }
//}
// Forcing a paint here doesn't seem to be necessary.
// paintDamagedAreaImmediately();
}));
}
/*
* Paints any portion of the component that needs updating
* before the call returns (similar to the Win32 API UpdateWindow)
*/
internal void paintDamagedAreaImmediately()
{
// force Windows to send any pending WM_PAINT events so
// the damage area is updated on the Java side
updateWindow();
// make sure paint events are transferred to main event queue
// for coalescing
NetToolkit.flushPendingEvents();
// paint the damaged area
paintArea.paint(target, shouldClearRectBeforePaint());
}
private void updateWindow()
{
NetToolkit.BeginInvoke(delegate
{
control.Update();
});
}
/* override and return false on components that DO NOT require
a clearRect() before painting (i.e. native components) */
public virtual bool shouldClearRectBeforePaint()
{
return true;
}
private void OnPopupMenu(object sender, EventArgs ev)
{
isPopupMenu = true;
}
/*
* Post an event. Queue it for execution by the callback thread.
*/
internal void postEvent(java.awt.AWTEvent evt)
{
NetToolkit.postEvent(NetToolkit.targetToAppContext(target), evt);
}
// Routines to support deferred window positioning.
public void beginLayout()
{
// Skip all painting till endLayout
isLayouting = true;
}
public void endLayout()
{
if (!paintArea.isEmpty() && !paintPending &&
!target.getIgnoreRepaint())
{
// if not waiting for native painting repaint damaged area
postEvent(new java.awt.@event.PaintEvent(target, java.awt.@event.PaintEvent.PAINT, new java.awt.Rectangle()));
}
isLayouting = false;
}
public void beginValidate()
{
// Invoke(delegate
// {
// if (m_validationNestCount == 0)
// {
// m_hdwp = BeginDeferWindowPos();
// }
// m_validationNestCount++;
// });
}
public void endValidate()
{
// Invoke(delegate
// {
// m_validationNestCount--;
// if (m_validationNestCount == 0) {
// // if this call to EndValidate is not nested inside another
// // Begin/EndValidate pair, end deferred window positioning
// ::EndDeferWindowPos(m_hdwp);
// m_hdwp = NULL;
// }
// });
}
// Returns true if we are inside begin/endLayout and
// are waiting for native painting
public bool isPaintPending()
{
return paintPending && isLayouting;
}
public override int checkImage(java.awt.Image img, int width, int height, java.awt.image.ImageObserver ob)
{
return getToolkit().checkImage(img, width, height, ob);
}
public override java.awt.Image createImage(java.awt.image.ImageProducer prod)
{
NetProducerImage npi = new NetProducerImage(prod);
prod.startProduction(npi);
return new java.awt.image.BufferedImage(npi.getBitmap());
}
public override java.awt.Image createImage(int width, int height)
{
return new java.awt.image.BufferedImage(width, height, java.awt.image.BufferedImage.TYPE_INT_ARGB);
}
public override void disable()
{
NetToolkit.BeginInvoke(delegate { Enable( false ); });
}
public override void dispose()
{
bool callDisposed = true;
lock(this)
{
if (disposed)
callDisposed = false;
disposed = true;
}
if (callDisposed)
{
disposeImpl();
}
}
protected virtual void disposeImpl()
{
NetToolkit.targetDisposedPeer(target, this);
NetToolkit.Invoke(nativeDispose);
}
protected virtual void nativeDispose()
{
unhookEvents();
control.Dispose();
}
public override void enable()
{
NetToolkit.BeginInvoke(delegate { Enable(true); });
}
public override java.awt.image.ColorModel getColorModel()
{
//we return the default ColorModel because this causes the least problems with conversions
return java.awt.image.ColorModel.getRGBdefault();
}
public override java.awt.FontMetrics getFontMetrics(java.awt.Font f)
{
return new NetFontMetrics(f);
}
public override java.awt.Graphics getGraphics()
{
if (!control.IsDisposed)
{
/* Fix for bug 4746122. Color and Font shouldn't be null */
java.awt.Color bgColor = background;
if (bgColor == null)
{
bgColor = java.awt.SystemColor.window;
}
java.awt.Color fgColor = foreground;
if (fgColor == null)
{
fgColor = java.awt.SystemColor.windowText;
}
java.awt.Font font = this.font;
if (font == null)
{
font = defaultFont;
}
return new ComponentGraphics(this.control, fgColor, bgColor, font);
}
return null;
}
public override java.awt.Point getLocationOnScreen()
{
return NetToolkit.Invoke<java.awt.Point>(delegate
{
Point p = new Point();
p = control.PointToScreen(p);
return new java.awt.Point(p.X, p.Y);
});
}
public override java.awt.Dimension getMinimumSize()
{
return target.getSize();
}
public override java.awt.Dimension getPreferredSize()
{
return getMinimumSize();
}
public override java.awt.Toolkit getToolkit()
{
return java.awt.Toolkit.getDefaultToolkit();
}
// returns true if the event has been handled and shouldn't be propagated
// though handleEvent method chain - e.g. WTextFieldPeer returns true
// on handling '\n' to prevent it from being passed to native code
public virtual bool handleJavaKeyEvent(java.awt.@event.KeyEvent e) { return false; }
private void nativeHandleEvent(java.awt.AWTEvent e)
{
// TODO arrghh!! code from void AwtComponent::_NativeHandleEvent(void *param) in awt_Component.cpp should be here
}
public override void handleEvent(java.awt.AWTEvent e)
{
int id = e.getID();
if (((java.awt.Component)target).isEnabled() && (e is java.awt.@event.KeyEvent) && !((java.awt.@event.KeyEvent)e).isConsumed())
{
if (handleJavaKeyEvent((java.awt.@event.KeyEvent)e))
{
return;
}
}
switch (id)
{
case java.awt.@event.PaintEvent.PAINT:
// Got native painting
paintPending = false;
// Fallthrough to next statement
goto case java.awt.@event.PaintEvent.UPDATE;
case java.awt.@event.PaintEvent.UPDATE:
// Skip all painting while layouting and all UPDATEs
// while waiting for native paint
if (!isLayouting && !paintPending)
{
paintArea.paint(target, shouldClearRectBeforePaint());
}
return;
default:
break;
}
// Call the native code
nativeHandleEvent(e);
}
public override void hide()
{
NetToolkit.BeginInvoke(delegate { control.Visible = false; });
}
public bool isFocusTraversable()
{
return true;
}
public override java.awt.Dimension minimumSize()
{
return getMinimumSize();
}
public override java.awt.Dimension preferredSize()
{
return getPreferredSize();
}
public override void paint(java.awt.Graphics graphics)
{
target.paint(graphics);
}
public override bool prepareImage(java.awt.Image img, int width, int height, java.awt.image.ImageObserver ob)
{
return getToolkit().prepareImage(img, width, height, ob);
}
public override void print(java.awt.Graphics graphics)
{
throw new NotImplementedException();
}
public override void repaint(long tm, int x, int y, int width, int height)
{
}
public void requestFocus()
{
NetToolkit.Invoke<bool>(control.Focus);
}
/// <summary>
///
/// </summary>
/// <param name="request">the component for which the focus is requested</param>
/// <param name="temporary">indicates if the focus change is temporary (true) or permanent (false)</param>
/// <param name="allowWindowFocus">indicates if it's allowed to change window focus</param>
/// <param name="time">the timestamp</param>
/// <returns></returns>
public bool requestFocus(java.awt.Component request, bool temporary, bool allowWindowFocus, long time)
{
if (!getEnabled() || !getVisible())
{
return false;
}
postEvent(new java.awt.@event.FocusEvent(request, java.awt.@event.FocusEvent.FOCUS_GAINED, temporary, target));
return true;
}
public override void reshape(int x, int y, int width, int height)
{
NetToolkit.BeginInvoke(delegate
{
Form window = control.FindForm();
if (window is MyForm)
{
java.awt.Insets insets = ((MyForm)window).peerInsets;
control.SetBounds(x - insets.left, y - insets.top, width, height);
}
else
{
control.SetBounds(x, y, width, height);
}
//If the .NET control does not accept the new bounds (minimum size, maximum size)
//then we need to reflect the real bounds on the .NET site to the Java site
Rectangle bounds = control.Bounds;
if (bounds.X != x)
{
ComponentAccessor.setX(target, bounds.X);
}
if (bounds.Y != y)
{
ComponentAccessor.setY(target, bounds.Y);
}
if (bounds.Width != width)
{
ComponentAccessor.setWidth(target, bounds.Width);
}
if (bounds.Height != height)
{
ComponentAccessor.setHeight(target, bounds.Height);
}
});
}
public override void setBackground(java.awt.Color color)
{
lock (this)
{
this.background = color;
NetToolkit.BeginInvoke(delegate { control.BackColor = J2C.ConvertColor(color); });
}
}
private void reshapeNoCheck(int x, int y, int width, int height)
{
NetToolkit.BeginInvoke(delegate { control.SetBounds(x, y, width, height); });
}
public override void setBounds(int x, int y, int width, int height, int op)
{
// Should set paintPending before reahape to prevent
// thread race between paint events
// Native components do redraw after resize
paintPending = (width != oldWidth) || (height != oldHeight);
if ((op & java.awt.peer.ComponentPeer.__Fields.NO_EMBEDDED_CHECK) != 0)
{
reshapeNoCheck(x, y, width, height);
}
else
{
reshape(x, y, width, height);
}
if ((width != oldWidth) || (height != oldHeight))
{
// Only recreate surfaceData if this setBounds is called
// for a resize; a simple move should not trigger a recreation
try
{
//replaceSurfaceData();
}
catch (sun.java2d.InvalidPipeException)
{
// REMIND : what do we do if our surface creation failed?
}
oldWidth = width;
oldHeight = height;
}
serialNum++;
}
private void setCursorImpl(java.awt.Cursor cursor)
{
if (cursor is NetCustomCursor)
{
NetCustomCursor ncc = (NetCustomCursor)cursor;
control.Cursor = ncc.Cursor;
return;
}
switch(cursor.getType())
{
case java.awt.Cursor.WAIT_CURSOR:
control.Cursor = Cursors.WaitCursor;
break;
case java.awt.Cursor.DEFAULT_CURSOR:
control.Cursor = Cursors.Default;
break;
case java.awt.Cursor.HAND_CURSOR:
control.Cursor = Cursors.Hand;
break;
case java.awt.Cursor.CROSSHAIR_CURSOR:
control.Cursor = Cursors.Cross;
break;
case java.awt.Cursor.W_RESIZE_CURSOR:
case java.awt.Cursor.E_RESIZE_CURSOR:
control.Cursor = Cursors.SizeWE;
break;
case java.awt.Cursor.MOVE_CURSOR:
control.Cursor = Cursors.SizeAll;
break;
case java.awt.Cursor.N_RESIZE_CURSOR:
case java.awt.Cursor.S_RESIZE_CURSOR:
control.Cursor = Cursors.SizeNS;
break;
case java.awt.Cursor.NE_RESIZE_CURSOR:
case java.awt.Cursor.SW_RESIZE_CURSOR:
control.Cursor = Cursors.SizeNESW;
break;
case java.awt.Cursor.NW_RESIZE_CURSOR:
case java.awt.Cursor.SE_RESIZE_CURSOR:
control.Cursor = Cursors.SizeNWSE;
break;
case java.awt.Cursor.TEXT_CURSOR:
control.Cursor = Cursors.IBeam;
break;
default:
Console.WriteLine("setCursor not implement for: " + cursor);
break;
}
}
public void setCursor(java.awt.Cursor cursor)
{
NetToolkit.Invoke(setCursorImpl, cursor);
}
public bool getEnabled()
{
return NetToolkit.Invoke<bool>(delegate { return control.Enabled; });
}
public bool getFocused()
{
return NetToolkit.Invoke<bool>(delegate { return control.Focused; });
}
public bool getVisible()
{
return NetToolkit.Invoke<bool>(delegate { return control.Visible; });
}
public override void setEnabled(bool enabled)
{
if (enabled)
{
enable();
}
else
{
disable();
}
}
public override void setFont(java.awt.Font font)
{
lock (this)
{
this.font = font;
NetToolkit.BeginInvoke(delegate { control.Font = font.getNetFont(); });
}
}
public override void setForeground(java.awt.Color color)
{
lock (this)
{
this.foreground = color;
NetToolkit.BeginInvoke(delegate { control.ForeColor = J2C.ConvertColor(color); });
}
}
public override void setVisible(bool visible)
{
if (visible)
{
show();
}
else
{
hide();
}
}
public override void show()
{
java.awt.Dimension s = target.getSize();
oldHeight = s.height;
oldWidth = s.width;
pShow();
}
/*
* Return the GraphicsConfiguration associated with this peer, either
* the locally stored winGraphicsConfig, or that of the target Component.
*/
public override java.awt.GraphicsConfiguration getGraphicsConfiguration()
{
// we don't need a treelock here, since
// Component.getGraphicsConfiguration() gets it itself.
return target.getGraphicsConfiguration();
}
public void setEventMask (long mask)
{
//Console.WriteLine("NOTE: NetComponentPeer.setEventMask not implemented");
}
public override bool isObscured()
{
// should never be called because we return false from canDetermineObscurity()
return true;
}
public override bool canDetermineObscurity()
{
// JDK returns true here and uses GetClipBox to determine if the window is partially obscured,
// this is an optimization for scrolling in javax.swing.JViewport, since there appears to be
// no managed equivalent of GetClipBox, we'll simply return false and forgo the optimization.
return false;
}
public override void coalescePaintEvent(java.awt.@event.PaintEvent e)
{
java.awt.Rectangle r = e.getUpdateRect();
if (!(e is sun.awt.@event.IgnorePaintEvent))
{
paintArea.add(r, e.getID());
}
}
public override void updateCursorImmediately()
{
}
public override java.awt.image.VolatileImage createVolatileImage(int width, int height)
{
return new NetVolatileImage(target, width, height);
}
public override bool handlesWheelScrolling()
{
return true;
}
public override void createBuffers(int x, java.awt.BufferCapabilities capabilities)
{
throw new NotImplementedException();
}
public override java.awt.Image getBackBuffer()
{
throw new NotImplementedException();
}
public override void flip(java.awt.BufferCapabilities.FlipContents contents)
{
throw new NotImplementedException();
}
public override void destroyBuffers()
{
throw new NotImplementedException();
}
public override bool isFocusable()
{
return false;
}
protected bool isDisposed()
{
return disposed;
}
public override java.awt.Rectangle getBounds()
{
return target.getBounds();
}
public override void reparent(java.awt.peer.ContainerPeer parent)
{
throw new NotImplementedException();
}
public override bool isReparentSupported()
{
return false;
}
// Do nothing for heavyweight implementation
public override void layout()
{
}
public override void applyShape(sun.java2d.pipe.Region shape)
{
NetToolkit.BeginInvoke(ApplyShapeImpl, shape);
}
private void ApplyShapeImpl(sun.java2d.pipe.Region shape)
{
control.Region = J2C.ConvertRegion(shape);
}
//copied form KeyboardFocusManager
private const int SNFH_FAILURE = 0;
private const int SNFH_SUCCESS_HANDLED = 1;
private const int SNFH_SUCCESS_PROCEED = 2;
private static java.lang.reflect.Method shouldNativelyFocusHeavyweight;
private static java.lang.reflect.Method processSynchronousLightweightTransfer;
private static java.lang.reflect.Method removeLastFocusRequest;
public override bool requestFocus(java.awt.Component lightweightChild, bool temporary, bool focusedWindowChangeAllowed, long time, sun.awt.CausedFocusEvent.Cause cause)
{
// this is a interpretation of the code in WComponentPeer.java and awt_component.cpp
try
{
if (processSynchronousLightweightTransfer == null)
{
java.security.AccessController.doPrivileged(Delegates.toPrivilegedAction(delegate
{
java.lang.Class keyboardFocusManagerCls = typeof(java.awt.KeyboardFocusManager);
java.lang.reflect.Method method = keyboardFocusManagerCls.getDeclaredMethod(
"processSynchronousLightweightTransfer",
typeof(java.awt.Component),
typeof(java.awt.Component),
java.lang.Boolean.TYPE,
java.lang.Boolean.TYPE,
java.lang.Long.TYPE);
method.setAccessible(true);
processSynchronousLightweightTransfer = method;
return null;
}));
}
processSynchronousLightweightTransfer.invoke(
null,
target,
lightweightChild,
java.lang.Boolean.valueOf(temporary),
java.lang.Boolean.valueOf(focusedWindowChangeAllowed),
java.lang.Long.valueOf(time));
}
catch
{
return true;
}
if (shouldNativelyFocusHeavyweight == null)
{
java.security.AccessController.doPrivileged(Delegates.toPrivilegedAction(delegate
{
java.lang.Class keyboardFocusManagerCls = typeof(java.awt.KeyboardFocusManager);
java.lang.reflect.Method method = keyboardFocusManagerCls.getDeclaredMethod(
"shouldNativelyFocusHeavyweight",
typeof(java.awt.Component),
typeof(java.awt.Component),
java.lang.Boolean.TYPE,
java.lang.Boolean.TYPE,
java.lang.Long.TYPE,
typeof(sun.awt.CausedFocusEvent.Cause));
method.setAccessible(true);
shouldNativelyFocusHeavyweight = method;
return null;
}));
}
int retval = ((java.lang.Integer)shouldNativelyFocusHeavyweight.invoke(
null,
target,
lightweightChild,
java.lang.Boolean.valueOf(temporary),
java.lang.Boolean.valueOf(focusedWindowChangeAllowed),
java.lang.Long.valueOf(time),
cause)).intValue();
if (retval == SNFH_SUCCESS_HANDLED)
{
return true;
}
else if (retval == SNFH_SUCCESS_PROCEED)
{
if (getFocused())
{
return true;
}
if (removeLastFocusRequest == null)
{
java.security.AccessController.doPrivileged(Delegates.toPrivilegedAction(delegate
{
java.lang.Class keyboardFocusManagerCls = typeof(java.awt.KeyboardFocusManager);
java.lang.reflect.Method method = keyboardFocusManagerCls.getDeclaredMethod(
"removeLastFocusRequest",
typeof(java.awt.Component));
method.setAccessible(true);
removeLastFocusRequest = method;
return null;
}));
}
removeLastFocusRequest.invoke(null, target);
}
//SNFH_FAILURE
return false;
}
}
sealed class NetScrollbarPeer : NetComponentPeer<java.awt.Scrollbar, ScrollBar>, java.awt.peer.ScrollbarPeer
{
internal NetScrollbarPeer(java.awt.Scrollbar target)
: base(target)
{
}
public void setLineIncrement(int i)
{
}
public void setPageIncrement(int i)
{
}
public void setValues(int i1, int i2, int i3, int i4)
{
}
protected override ScrollBar CreateControl()
{
switch (target.getOrientation())
{
case java.awt.Scrollbar.VERTICAL:
return new VScrollBar();
default:
return new HScrollBar();
}
}
}
sealed class NetScrollPanePeer : NetComponentPeer<java.awt.ScrollPane, ScrollableControl>, java.awt.peer.ScrollPanePeer
{
internal NetScrollPanePeer(java.awt.ScrollPane pane)
: base(pane)
{
}
public void childResized(int i1, int i2)
{
}
public int getHScrollbarHeight()
{
return NetToolkit.Invoke<int>(delegate { return 0; });
}
public int getVScrollbarWidth()
{
return NetToolkit.Invoke<int>(delegate { return 0; });
}
public void setScrollPosition(int i1, int i2)
{
}
public void setUnitIncrement(java.awt.Adjustable a, int i)
{
}
public void setValue(java.awt.Adjustable a, int i)
{
}
public java.awt.Insets getInsets()
{
return NetToolkit.Invoke<java.awt.Insets>(delegate { return new java.awt.Insets(0, 0, 0, 0); });
}
public java.awt.Insets insets()
{
return getInsets();
}
public bool isRestackSupported()
{
return false;
}
public void restack()
{
throw new NotImplementedException();
}
protected override ScrollableControl CreateControl()
{
return new ScrollableControl();
}
}
sealed class NetButtonPeer : NetComponentPeer<java.awt.Button, Button>, java.awt.peer.ButtonPeer
{
public NetButtonPeer(java.awt.Button awtbutton)
: base(awtbutton)
{
if (!awtbutton.isBackgroundSet())
{
awtbutton.setBackground(java.awt.SystemColor.control);
}
control.BackColor = Color.FromArgb(awtbutton.getBackground().getRGB());
control.Text = awtbutton.getLabel();
control.Click += new EventHandler(OnClick);
}
private void OnClick(object sender, EventArgs e)
{
// TODO set all these properties correctly
string cmd = "";
long when = 0;
int modifiers = 0;
postEvent(new java.awt.@event.ActionEvent(target, java.awt.@event.ActionEvent.ACTION_PERFORMED, cmd, when, modifiers));
}
public void setLabel(string label)
{
NetToolkit.Invoke(delegate { control.Text = label; });
}
public override java.awt.Dimension getMinimumSize()
{
using(Graphics g = control.CreateGraphics())
{
// TODO get these fudge factors from somewhere
return new java.awt.Dimension((int)Math.Round(12 + g.MeasureString(control.Text, control.Font).Width) * 8 / 7, 6 + control.Font.Height * 8 / 7);
}
}
public override bool shouldClearRectBeforePaint()
{
return false;
}
protected override Button CreateControl()
{
return new Button();
}
}
abstract class NetTextComponentPeer<T> : NetComponentPeer<T, TextBox>, java.awt.peer.TextComponentPeer
where T : java.awt.TextComponent
{
public NetTextComponentPeer(java.awt.TextComponent textComponent)
: base((T)textComponent)
{
if(!target.isBackgroundSet())
{
target.setBackground(java.awt.SystemColor.window);
}
setBackground(target.getBackground());
control.AutoSize = false;
control.Text = target.getText();
}
public override bool isFocusable()
{
return true;
}
protected override void OnKeyPress(object sender, KeyPressEventArgs e)
{
base.OnKeyPress(sender, e);
// TODO for TextAreas this probably isn't the right behaviour
if(e.KeyChar == '\r')
{
// TODO set all these properties correctly
string cmd = "";
long when = 0;
int modifiers = 0;
postEvent(new java.awt.@event.ActionEvent(target, java.awt.@event.ActionEvent.ACTION_PERFORMED, cmd, when, modifiers));
}
}
public int getSelectionEnd()
{
return NetToolkit.Invoke<int>(delegate { return control.SelectionStart + control.SelectionLength; });
}
public int getSelectionStart()
{
return NetToolkit.Invoke<int>(delegate { return control.SelectionStart; });
}
public string getText()
{
return NetToolkit.Invoke<string>(delegate { return control.Text; });
}
public void setText(string text)
{
NetToolkit.Invoke(delegate { control.Text = text; });
}
public void select(int start_pos, int end_pos)
{
throw new NotImplementedException();
}
public void setEditable(bool editable)
{
throw new NotImplementedException();
}
public int getCaretPosition()
{
return getSelectionStart();
}
private void setCaretPositionImpl(int pos)
{
control.SelectionStart = pos;
control.SelectionLength = 0;
}
public void setCaretPosition(int pos)
{
NetToolkit.Invoke(setCaretPositionImpl, pos);
}
public long filterEvents(long filter)
{
throw new NotImplementedException();
}
public int getIndexAtPoint(int x, int y)
{
throw new NotImplementedException();
}
public java.awt.Rectangle getCharacterBounds(int pos)
{
throw new NotImplementedException();
}
public java.awt.im.InputMethodRequests getInputMethodRequests()
{
throw new NotImplementedException();
}
protected sealed override TextBox CreateControl()
{
return new TextBox();
}
}
sealed class NetChoicePeer : NetComponentPeer<java.awt.Choice, RadioButton>, java.awt.peer.ChoicePeer
{
public NetChoicePeer(java.awt.Choice target)
: base(target)
{
}
public void add(string str, int i)
{
// TODO: Add NetChoicePeer.add implementation
}
public void addItem(string str, int i)
{
// TODO: Add NetChoicePeer.addItem implementation
}
public void select(int i)
{
// TODO: Add NetChoicePeer.select implementation
}
public void removeAll()
{
// TODO: Add NetChoicePeer.removeAll implementation
}
public void remove(int i)
{
// TODO: Add NetChoicePeer.remove implementation
}
protected override RadioButton CreateControl()
{
return new RadioButton();
}
}
sealed class NetCheckboxPeer : NetComponentPeer<java.awt.Checkbox, CheckBox>, java.awt.peer.CheckboxPeer
{
public NetCheckboxPeer(java.awt.Checkbox target)
: base(target)
{
}
public void setCheckboxGroup(java.awt.CheckboxGroup cg)
{
// TODO: Add NetCheckboxPeer.setCheckboxGroup implementation
}
public void setState(bool b)
{
// TODO: Add NetCheckboxPeer.setState implementation
}
public void setLabel(string str)
{
// TODO: Add NetCheckboxPeer.setLabel implementation
}
protected override CheckBox CreateControl()
{
return new CheckBox();
}
}
sealed class NetLabelPeer : NetComponentPeer<java.awt.Label, Label>, java.awt.peer.LabelPeer
{
public NetLabelPeer(java.awt.Label jlabel)
: base(jlabel)
{
control.Text = jlabel.getText();
setAlignment(jlabel.getAlignment());
}
public void setAlignment(int align)
{
ContentAlignment alignment;
switch(align)
{
case java.awt.Label.LEFT:
alignment = ContentAlignment.TopLeft;
break;
case java.awt.Label.CENTER:
alignment = ContentAlignment.TopCenter;
break;
case java.awt.Label.RIGHT:
alignment = ContentAlignment.TopRight;
break;
default:
return;
}
NetToolkit.Invoke(setAlignImpl, alignment);
}
private void setAlignImpl(ContentAlignment alignment)
{
control.TextAlign = (ContentAlignment)alignment;
}
public void setText(string s)
{
NetToolkit.Invoke(setTextImpl, s);
}
private void setTextImpl(string s)
{
control.Text = s;
}
public override java.awt.Dimension preferredSize()
{
return NetToolkit.Invoke<java.awt.Dimension>(getPreferredSizeImpl);
}
private java.awt.Dimension getPreferredSizeImpl()
{
// HACK get these fudge factors from somewhere
return new java.awt.Dimension(control.PreferredWidth, 2 + control.PreferredHeight);
}
public override bool shouldClearRectBeforePaint()
{
// is native control, don't clear
return false;
}
protected override Label CreateControl()
{
return new Label();
}
}
sealed class NetTextFieldPeer : NetTextComponentPeer<java.awt.TextField>, java.awt.peer.TextFieldPeer
{
public NetTextFieldPeer(java.awt.TextField textField)
: base(textField)
{
setEchoCharacterImpl(textField.getEchoChar());
}
public java.awt.Dimension minimumSize(int len)
{
return getMinimumSize(len);
}
public java.awt.Dimension preferredSize(int len)
{
return getPreferredSize(len);
}
public java.awt.Dimension getMinimumSize(int len)
{
return getPreferredSize(len);
}
public java.awt.Dimension getPreferredSize(int len)
{
// TODO use control.Invoke
using(Graphics g = control.CreateGraphics())
{
return new java.awt.Dimension((int)Math.Round((g.MeasureString("abcdefghijklm", control.Font).Width * len) / 13), ((TextBox)control).PreferredHeight);
}
}
public void setEchoChar(char echo_char)
{
setEchoCharacter(echo_char);
}
private void setEchoCharacterImpl(char echo_char)
{
control.PasswordChar = echo_char;
}
public void setEchoCharacter(char echo_char)
{
control.Invoke(new Action<char>(setEchoCharacterImpl), echo_char);
}
public override bool handleJavaKeyEvent(java.awt.@event.KeyEvent e)
{
switch (e.getID())
{
case java.awt.@event.KeyEvent.KEY_TYPED:
if ((e.getKeyChar() == '\n') && !e.isAltDown() && !e.isControlDown())
{
postEvent(new java.awt.@event.ActionEvent(target, java.awt.@event.ActionEvent.ACTION_PERFORMED,
getText(), e.getWhen(), e.getModifiers()));
return true;
}
break;
}
return false;
}
}
sealed class NetTextAreaPeer : NetTextComponentPeer<java.awt.TextArea>, java.awt.peer.TextAreaPeer
{
public NetTextAreaPeer(java.awt.TextArea textArea)
: base(textArea)
{
control.ReadOnly = !((java.awt.TextArea)target).isEditable();
control.WordWrap = false;
control.ScrollBars = ScrollBars.Both;
control.Multiline = true;
}
public void insert(string text, int pos)
{
NetToolkit.Invoke(delegate { control.Text = control.Text.Insert(pos, text); });
}
public void insertText(string text, int pos)
{
insert(text, pos);
}
public override java.awt.Dimension getMinimumSize()
{
return getMinimumSize(10, 60);
}
public java.awt.Dimension minimumSize(int rows, int cols)
{
return getMinimumSize(rows, cols);
}
public java.awt.Dimension getMinimumSize(int rows, int cols)
{
java.awt.FontMetrics fm = getFontMetrics(target.getFont());
return new java.awt.Dimension(fm.charWidth('0') * cols + 20, fm.getHeight() * rows + 20);
}
public java.awt.Dimension preferredSize(int rows, int cols)
{
return getPreferredSize(rows, cols);
}
public java.awt.Dimension getPreferredSize(int rows, int cols)
{
return getMinimumSize(rows, cols);
}
public void replaceRange(string text, int start_pos, int end_pos)
{
throw new NotImplementedException();
}
public void replaceText(string text, int start_pos, int end_pos)
{
throw new NotImplementedException();
}
}
class NetContainerPeer<T, C> : NetComponentPeer<T, C>, java.awt.peer.ContainerPeer
where T : java.awt.Container
where C : Control
{
/// <summary>
/// The native insets of the .NET Window
/// </summary>
protected java.awt.Insets _insets = new java.awt.Insets(0, 0, 0, 0);
public NetContainerPeer(java.awt.Container awtcontainer)
: base((T)awtcontainer)
{
}
internal override int getInsetsLeft()
{
return _insets.left; ;
}
internal override int getInsetsTop()
{
return _insets.top;
}
public java.awt.Insets insets()
{
return getInsets();
}
public java.awt.Insets getInsets()
{
return _insets;
}
public bool isRestackSupported()
{
return false;
}
public void cancelPendingPaint(int x, int y, int width, int height)
{
throw new NotImplementedException();
}
public void restack()
{
throw new NotImplementedException();
}
protected override C CreateControl()
{
throw new NotImplementedException();
}
}
sealed class NetPanelPeer : NetContainerPeer<java.awt.Panel, Control>, java.awt.peer.PanelPeer
{
public NetPanelPeer(java.awt.Panel panel)
: base(panel)
{
}
protected override Control CreateControl()
{
throw new NotImplementedException();
}
}
sealed class NewCanvasPeer : NetComponentPeer<java.awt.Canvas, Control>, java.awt.peer.CanvasPeer
{
public NewCanvasPeer(java.awt.Canvas canvas)
: base(canvas)
{
}
protected override Control CreateControl()
{
throw new NotImplementedException();
}
}
class NetWindowPeer : NetContainerPeer<java.awt.Window, Form>, java.awt.peer.WindowPeer
{
// we can't use NetDialogPeer as blocker may be an instance of NetPrintDialogPeer that
// extends NetWindowPeer, not NetDialogPeer
private NetWindowPeer modalBlocker;
private bool modalSavedEnabled;
private static NetWindowPeer grabbedWindow;
public NetWindowPeer(java.awt.Window window)
: base(window)
{
//form.Shown += new EventHandler(OnOpened); Will already post in java.awt.Window.show()
control.Closing += new CancelEventHandler(OnClosing);
control.Closed += new EventHandler(OnClosed);
control.Activated += new EventHandler(OnActivated);
control.Deactivate += new EventHandler(OnDeactivate);
control.SizeChanged += new EventHandler(OnSizeChanged);
control.Resize += new EventHandler(OnResize);
control.Move += new EventHandler(OnMove);
}
protected override void initialize()
{
base.initialize();
updateIconImages();
if (target.getBackground() == null)
{
target.setBackground(target is java.awt.Dialog ? java.awt.SystemColor.control : java.awt.SystemColor.window);
}
control.BackColor = J2C.ConvertColor(target.getBackground());
if (target.getForeground() == null)
{
target.setForeground(java.awt.SystemColor.windowText);
}
if (target.getFont() == null)
{
//target.setFont(defaultFont);
//HACK: Sun is calling setFont(Font) here and this is calling firePropertyChange("font", oldFont, newFont)
//but this produce a deadlock with getTreeLock() because the creating of the peer is already in this synchronized
java.security.AccessController.doPrivileged(Delegates.toPrivilegedAction(delegate
{
java.lang.Class component = typeof(java.awt.Component);
java.lang.reflect.Field field = component.getDeclaredField("font");
field.setAccessible(true);
field.set(target, defaultFont);
java.lang.reflect.Method method = component.getDeclaredMethod(
"firePropertyChange",
typeof(java.lang.String),
typeof(java.lang.Object),
typeof(java.lang.Object));
method.setAccessible(true);
method.invoke(target, "font", null, defaultFont);
return null;
}));
}
}
private void OnResize(object sender, EventArgs e)
{
// WmSizing
SendComponentEvent(java.awt.@event.ComponentEvent.COMPONENT_RESIZED);
dynamicallyLayoutContainer();
}
private void OnMove(object sender, EventArgs e)
{
// WmMove
ComponentAccessor.setX(target, control.Left);
ComponentAccessor.setY(target, control.Top);
SendComponentEvent(java.awt.@event.ComponentEvent.COMPONENT_MOVED);
}
/*
* Although this function sends ComponentEvents, it needs to be defined
* here because only top-level windows need to have move and resize
* events fired from native code. All contained windows have these events
* fired from common Java code.
*/
private void SendComponentEvent(int eventId)
{
SendEvent(new java.awt.@event.ComponentEvent(target, eventId));
}
private void OnSizeChanged(object sender, EventArgs e)
{
// WmSize
typeof(java.awt.Component).GetField("width", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(target, control.Width);
typeof(java.awt.Component).GetField("height", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(target, control.Height);
SendComponentEvent(java.awt.@event.ComponentEvent.COMPONENT_RESIZED);
}
private void OnOpened(object sender, EventArgs e)
{
postEvent(new java.awt.@event.WindowEvent((java.awt.Window)target, java.awt.@event.WindowEvent.WINDOW_OPENED));
}
private void OnClosing(object sender, CancelEventArgs e)
{
e.Cancel = true;
postEvent(new java.awt.@event.WindowEvent((java.awt.Window)target, java.awt.@event.WindowEvent.WINDOW_CLOSING));
}
private void OnClosed(object sender, EventArgs e)
{
postEvent(new java.awt.@event.WindowEvent((java.awt.Window)target, java.awt.@event.WindowEvent.WINDOW_CLOSED));
}
private const int WA_ACTIVE = 1;
private const int WA_INACTIVE = 2;
private void OnActivated(object sender, EventArgs e)
{
WmActivate(WA_ACTIVE, control.WindowState == FormWindowState.Minimized, null);
}
private void OnDeactivate(object sender, EventArgs e)
{
WmActivate(WA_INACTIVE, control.WindowState == FormWindowState.Minimized, null);
}
private void WmActivate(int nState, bool fMinimized, Control opposite)
{
int type;
if (nState != WA_INACTIVE)
{
type = java.awt.@event.WindowEvent.WINDOW_GAINED_FOCUS;
}
else
{
if (grabbedWindow != null && !grabbedWindow.IsOneOfOwnersOf(this))
{
grabbedWindow.Ungrab(true);
}
type = java.awt.@event.WindowEvent.WINDOW_LOST_FOCUS;
}
SendWindowEvent(type, opposite);
}
private void SendWindowEvent(int id, Control opposite) { SendWindowEvent(id, opposite, 0, 0); }
private void SendWindowEvent(int id, Control opposite, int oldState, int newState)
{
java.awt.AWTEvent evt = new java.awt.@event.WindowEvent((java.awt.Window)target, id, null);
if (id == java.awt.@event.WindowEvent.WINDOW_GAINED_FOCUS
|| id == java.awt.@event.WindowEvent.WINDOW_LOST_FOCUS)
{
Type type = typeof(java.awt.Component).Assembly.GetType("java.awt.SequencedEvent");
ConstructorInfo cons = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, null, new Type[] { typeof(java.awt.AWTEvent) }, null);
evt = (java.awt.AWTEvent)cons.Invoke(new object[] { evt });
}
SendEvent(evt);
}
public override java.awt.Graphics getGraphics()
{
java.awt.Graphics g = base.getGraphics();
java.awt.Insets insets = getInsets();
g.translate(-insets.left, -insets.top);
g.setClip(insets.left, insets.top, control.ClientRectangle.Width, control.ClientRectangle.Height);
return g;
}
public override bool shouldClearRectBeforePaint()
{
// clearing the window before repainting causes the controls to "flicker" on screen
return false;
}
/// <summary>
/// Set the border style of the window and recalc the insets
/// </summary>
/// <param name="style">the new style</param>
protected void setFormBorderStyle(FormBorderStyle style)
{
NetToolkit.BeginInvoke(delegate
{
control.FormBorderStyle = style;
//Calculate the Insets one time
//This is many faster because there no thread change is needed.
CalcInsetsImpl();
});
}
protected void CalcInsetsImpl()
{
Rectangle client = control.ClientRectangle;
if (client.Height == 0)
{
// HACK for .NET bug if form has the minimum size then ClientRectangle is not recalulate
// if the FormBorderStyle is changed
Size size = control.Size;
size.Height++;
control.Size = size;
size.Height--;
control.Size = size;
client = control.ClientRectangle;
}
Rectangle r = control.RectangleToScreen(client);
int x = r.Location.X - control.Location.X;
int y = r.Location.Y - control.Location.Y;
// only modify this instance, since it's shared by the control-peers of this form
_insets.top = y;
_insets.left = x;
_insets.bottom = control.Height - client.Height - y;
if (control.Menu != null)
{
_insets.bottom += SystemInformation.MenuHeight;
}
_insets.right = control.Width - client.Width - x;
}
public override void reshape(int x, int y, int width, int height)
{
NetToolkit.BeginInvoke(delegate
{
control.SetBounds(x, y, width, height);
//If the .NET control does not accept the new bounds (minimum size, maximum size)
//then we need to reflect the real bounds on the .NET site to the Java site
Rectangle bounds = control.Bounds;
if (bounds.X != x)
{
ComponentAccessor.setX(target, bounds.X);
}
if (bounds.Y != y)
{
ComponentAccessor.setY(target, bounds.Y);
}
if (bounds.Width != width)
{
ComponentAccessor.setWidth(target, bounds.Width);
}
if (bounds.Height != height)
{
ComponentAccessor.setHeight(target, bounds.Height);
}
});
}
public void toBack()
{
NetToolkit.BeginInvoke(control.SendToBack);
}
public void toFront()
{
NetToolkit.BeginInvoke(control.Activate);
}
public bool requestWindowFocus()
{
return NetToolkit.Invoke<bool>(control.Focus);
}
public void setAlwaysOnTop(bool alwaysOnTop)
{
// The .NET property TopMost does not work with a not focusable Window
// that we need to set the window flags directly. To reduce double code
// we call updateFocusableWindowState().
updateFocusableWindowState();
}
public bool isModalBlocked()
{
return modalBlocker != null;
}
public void setModalBlocked(java.awt.Dialog dialog, bool blocked)
{
lock (target.getTreeLock()) // State lock should always be after awtLock
{
// use NetWindowPeer instead of NetDialogPeer because of FileDialogs and PrintDialogs
NetWindowPeer blockerPeer = (NetWindowPeer)dialog.getPeer();
if (blocked)
{
modalBlocker = blockerPeer;
modalSavedEnabled = control.Enabled;
disable();
}
else
{
modalBlocker = null;
if(modalSavedEnabled){
enable();
}
else
{
disable();
}
}
}
}
public void updateFocusableWindowState()
{
((UndecoratedForm)control).SetWindowState(((java.awt.Window)target).isFocusableWindow(), ((java.awt.Window)target).isAlwaysOnTop());
}
public void updateIconImages()
{
java.util.List imageList = ((java.awt.Window) target).getIconImages();
Bitmap originalImage;
if (imageList == null || imageList.size() == 0)
{
originalImage = null;
}
else
{
java.awt.Image image = (java.awt.Image)imageList.get(0);
originalImage = ((java.awt.image.BufferedImage)image).getBitmap();
}
NetToolkit.BeginInvoke(delegate
{
Size iconSize = SystemInformation.IconSize;
using (Bitmap scaleBitmap = originalImage == null ? null : new Bitmap(originalImage, iconSize))
{
((Form) control).Icon = scaleBitmap == null ? null : Icon.FromHandle(scaleBitmap.GetHicon());
}
});
}
public void updateMinimumSize()
{
java.awt.Dimension dim = target.getMinimumSize();
NetToolkit.BeginInvoke(delegate
{
control.MinimumSize = new Size(dim.width, dim.height);
});
}
protected override Form CreateControl()
{
UndecoratedForm form = new UndecoratedForm();
form.SetWindowState(target.isFocusableWindow(),target.isAlwaysOnTop());
return form;
}
protected override void OnMouseDown(object sender, MouseEventArgs ev)
{
if (grabbedWindow != null && !grabbedWindow.IsOneOfOwnersOf(this))
{
grabbedWindow.Ungrab(true);
}
base.OnMouseDown(sender, ev);
}
internal void Grab()
{
//copy from file awt_Windows.cpp
if (grabbedWindow != null)
{
grabbedWindow.Ungrab(true);
}
grabbedWindow = this;
if (Form.ActiveForm == null)
{
Ungrab(true);
}
else if (control != Form.ActiveForm)
{
toFront();
}
}
internal void Ungrab(bool doPost)
{
//copy from file awt_Windows.cpp
if (grabbedWindow == this)
{
if (doPost)
{
SendEvent(new sun.awt.UngrabEvent(this.target));
}
grabbedWindow = null;
}
}
private bool IsOneOfOwnersOf(NetWindowPeer window)
{
while (window != null)
{
if (window == this)
{
return true;
}
java.awt.Container parent = window.target.getParent();
window = parent == null ? null : (NetWindowPeer)parent.getPeer();
}
return false;
}
}
sealed class NetFramePeer : NetWindowPeer, java.awt.peer.FramePeer
{
public NetFramePeer(java.awt.Frame frame)
: base(frame)
{
}
protected override void initialize()
{
base.initialize();
java.awt.Frame target = (java.awt.Frame)this.target;
if (target.getTitle() != null)
{
setTitle(target.getTitle());
}
setResizable(target.isResizable());
setState(target.getExtendedState());
}
public void setMenuBar(java.awt.MenuBar mb)
{
if (mb == null)
{
NetToolkit.Invoke(delegate
{
control.Menu = null;
CalcInsetsImpl();
});
}
else
{
mb.addNotify();
NetToolkit.Invoke(delegate
{
control.Menu = ((NetMenuBarPeer)mb.getPeer()).menu;
CalcInsetsImpl();
});
}
}
public void setResizable(bool resizable)
{
if (resizable)
{
setFormBorderStyle(FormBorderStyle.Sizable);
}
else
{
setFormBorderStyle(FormBorderStyle.FixedSingle);
}
}
public void setTitle(string title)
{
NetToolkit.BeginInvoke(delegate { control.Text = title; });
}
public int getState()
{
Form f = (Form)control;
FormWindowState state = f.WindowState;
switch (state)
{
case FormWindowState.Normal:
return java.awt.Frame.NORMAL;
case FormWindowState.Maximized:
return java.awt.Frame.MAXIMIZED_BOTH;
case FormWindowState.Minimized:
return java.awt.Frame.ICONIFIED;
default:
throw new InvalidEnumArgumentException();
}
}
public void setState(int state)
{
NetToolkit.BeginInvoke(delegate
{
MyForm form = (MyForm) control;
switch(state)
{
case java.awt.Frame.NORMAL:
form.WindowState = FormWindowState.Normal;
break;
case java.awt.Frame.MAXIMIZED_BOTH:
form.WindowState = FormWindowState.Maximized;
break;
case java.awt.Frame.ICONIFIED:
form.WindowState = FormWindowState.Minimized;
break;
}
});
}
public void setMaximizedBounds(java.awt.Rectangle rect)
{
((MyForm)control).setMaximizedBounds(rect);
}
public void setBoundsPrivate(int x, int y, int width, int height)
{
NetToolkit.Invoke(delegate { control.Bounds = new Rectangle(x, y, width, height); });
}
public java.awt.Rectangle getBoundsPrivate()
{
throw new NotImplementedException();
}
protected override Form CreateControl()
{
return new MyForm(_insets);
}
}
sealed class NetDialogPeer : NetWindowPeer, java.awt.peer.DialogPeer
{
public NetDialogPeer(java.awt.Dialog target)
: base(target)
{
control.MaximizeBox = false;
control.MinimizeBox = false;
control.ShowInTaskbar = false;
setTitle(target.getTitle());
setResizable(target.isResizable());
}
public void setTitle(string title)
{
NetToolkit.Invoke(delegate { control.Text = title; });
}
public void setResizable(bool resizable)
{
if (resizable)
{
setFormBorderStyle(FormBorderStyle.Sizable);
}
else
{
setFormBorderStyle(FormBorderStyle.FixedDialog);
}
}
public void blockWindows(List toBlock)
{
// code copies from sun.awt.windows.WDialogPeer.java
for (Iterator it = toBlock.iterator(); it.hasNext();) {
java.awt.Window w = (java.awt.Window)it.next();
java.awt.peer.WindowPeer wp = (java.awt.peer.WindowPeer)ComponentAccessor.getPeer(w);
if (wp != null) {
wp.setModalBlocked((java.awt.Dialog)target, true);
}
}
}
protected override Form CreateControl()
{
return new MyForm(_insets);
}
}
sealed class NetKeyboardFocusManagerPeer : java.awt.peer.KeyboardFocusManagerPeer
{
private readonly java.awt.KeyboardFocusManager manager;
private static java.lang.reflect.Method m_removeLastFocusRequest;
public NetKeyboardFocusManagerPeer(java.awt.KeyboardFocusManager manager)
{
this.manager = manager;
}
public void clearGlobalFocusOwner(java.awt.Window activeWindow)
{
}
public java.awt.Component getCurrentFocusOwner()
{
return getNativeFocusOwner();
}
public void setCurrentFocusOwner(java.awt.Component component)
{
}
public java.awt.Window getCurrentFocusedWindow()
{
return getNativeFocusedWindow();
}
private static java.awt.Component getNativeFocusOwner()
{
return NetToolkit.Invoke<java.awt.Component>(delegate
{
UndecoratedForm form = Form.ActiveForm as UndecoratedForm;
if (form != null)
{
Control control = form.ActiveControl;
while (control is ContainerControl)
{
control = ((ContainerControl)control).ActiveControl;
}
NetComponentPeer peer;
if (control == null)
{
peer = NetComponentPeer.FromControl(form);
}
else
{
while ((peer = NetComponentPeer.FromControl(form)) == null)
{
control = control.Parent;
}
}
return peer.Target;
}
return null;
});
}
private static java.awt.Window getNativeFocusedWindow()
{
return NetToolkit.Invoke<java.awt.Window>(delegate
{
Form form = Form.ActiveForm;
if (form != null)
{
NetComponentPeer peer = NetComponentPeer.FromControl(form);
if (peer != null)
{
return (java.awt.Window)peer.Target;
}
}
return null;
});
}
public static void removeLastFocusRequest(java.awt.Component heavyweight)
{
try
{
if (m_removeLastFocusRequest == null)
{
m_removeLastFocusRequest = SunToolkit.getMethod(typeof(java.awt.KeyboardFocusManager), "removeLastFocusRequest",
new java.lang.Class[] { typeof(java.awt.Component) });
}
m_removeLastFocusRequest.invoke(null, new Object[] { heavyweight });
}
catch (java.lang.reflect.InvocationTargetException ite)
{
ite.printStackTrace();
}
catch (java.lang.IllegalAccessException ex)
{
ex.printStackTrace();
}
}
}
sealed class NetListPeer : NetComponentPeer<java.awt.List, ListBox>, java.awt.peer.ListPeer
{
internal NetListPeer(java.awt.List target)
: base(target)
{
control.IntegralHeight = false;
setMultipleMode(target.isMultipleMode());
for (int i = 0; i < target.getItemCount(); i++)
{
add(target.getItem(i), i);
if (target.isSelected(i))
{
select(i);
}
}
makeVisible(target.getVisibleIndex());
}
public void add(string item, int index)
{
NetToolkit.Invoke(delegate { control.Items.Insert(index, item); });
}
public void addItem(string item, int index)
{
add(item, index);
}
public void clear()
{
NetToolkit.Invoke(delegate { control.Items.Clear(); });
}
public void delItems(int start_index, int end_index)
{
NetToolkit.Invoke(delegate
{
for (int i = start_index; i < end_index; i++)
{
control.Items.RemoveAt(start_index);
}
});
}
public void deselect(int index)
{
NetToolkit.Invoke(delegate { control.SelectedIndices.Remove(index); });
}
public int[] getSelectedIndexes()
{
return NetToolkit.Invoke<int[]>(delegate
{
ListBox.SelectedIndexCollection sic = control.SelectedIndices;
int[] indexes = new int[sic.Count];
sic.CopyTo(indexes, 0);
return indexes;
});
}
public void makeVisible(int index)
{
NetToolkit.Invoke(delegate { control.TopIndex = index; });
}
public java.awt.Dimension minimumSize(int s)
{
return getMinimumSize(s);
}
public java.awt.Dimension preferredSize(int s)
{
return getPreferredSize(s);
}
public void removeAll()
{
clear();
}
public void select(int index)
{
NetToolkit.Invoke(delegate { control.SelectedIndices.Add(index); });
}
public void setMultipleMode(bool multi)
{
NetToolkit.Invoke(delegate { control.SelectionMode = multi ? SelectionMode.MultiSimple : SelectionMode.One; });
}
public void setMultipleSelections(bool multi)
{
setMultipleMode(multi);
}
public java.awt.Dimension getPreferredSize(int s)
{
return getMinimumSize(s);
}
public java.awt.Dimension getMinimumSize(int s)
{
return new java.awt.Dimension(100, 100);
}
protected override ListBox CreateControl()
{
return new ListBox();
}
}
sealed class NetDesktopPeer : java.awt.peer.DesktopPeer
{
private static void ShellExecute(string file, string verb)
{
try
{
ProcessStartInfo psi = new ProcessStartInfo(file);
psi.UseShellExecute = true;
psi.Verb = verb;
Process p = Process.Start(psi);
if (p != null)
{
p.Dispose();
}
}
catch (System.ComponentModel.Win32Exception x)
{
throw new java.io.IOException(x.Message);
}
}
public void browse(URI uri)
{
ShellExecute(uri.toString(), "open");
}
public void edit(java.io.File f)
{
ShellExecute(f.toString(), "edit");
}
public bool isSupported(java.awt.Desktop.Action da)
{
return da == java.awt.Desktop.Action.BROWSE
|| da == java.awt.Desktop.Action.EDIT
|| da == java.awt.Desktop.Action.MAIL
|| da == java.awt.Desktop.Action.OPEN
|| da == java.awt.Desktop.Action.PRINT;
}
public void mail(URI uri)
{
if (uri.getScheme().ToLower(System.Globalization.CultureInfo.InvariantCulture) != "mailto")
{
throw new java.lang.IllegalArgumentException("URI scheme is not \"mailto\"");
}
ShellExecute(uri.toString(), "open");
}
public void mail()
{
ShellExecute("mailto:", "open");
}
public void open(java.io.File f)
{
ShellExecute(f.toString(), "open");
}
public void print(java.io.File f)
{
ShellExecute(f.toString(), "print");
}
}
//also WFileDialogPeer extends from WWindowPeer
class NetFileDialogPeer : NetWindowPeer, java.awt.peer.FileDialogPeer
{
internal NetFileDialogPeer(java.awt.FileDialog dialog) : base(dialog)
{
}
public void setDirectory(string str)
{
}
public void setFile(string str)
{
}
public void setFilenameFilter(java.io.FilenameFilter ff)
{
}
public void setResizable(bool b)
{
}
public void setTitle(string str)
{
}
public override void show()
{
java.awt.FileDialog dialog = (java.awt.FileDialog)target;
if (dialog.getMode() != java.awt.FileDialog.LOAD)
{
throw new NotImplementedException();
}
Thread t = new Thread((ThreadStart)delegate
{
using (OpenFileDialog dlg = new OpenFileDialog())
{
if (dlg.ShowDialog() == DialogResult.OK)
{
dialog.setFile(Path.GetFileName(dlg.FileName));
dialog.setDirectory(Path.GetDirectoryName(dlg.FileName) + java.io.File.separator);
dialog.hide();
}
else
{
dialog.setFile(null);
dialog.hide();
}
}
});
t.SetApartmentState(ApartmentState.STA);
t.Start();
}
public void blockWindows(List l)
{
throw new NotImplementedException();
}
}
class NetSystemTrayPeer : java.awt.peer.SystemTrayPeer
{
private java.awt.SystemTray target;
internal NetSystemTrayPeer(java.awt.SystemTray target)
{
this.target = target;
}
public java.awt.Dimension getTrayIconSize()
{
return new java.awt.Dimension(NetTrayIconPeer.TRAY_ICON_WIDTH, NetTrayIconPeer.TRAY_ICON_HEIGHT);
}
public bool isSupported()
{
return ((NetToolkit) java.awt.Toolkit.getDefaultToolkit()).isTraySupported();
}
}
sealed class NetPopupMenuPeer : java.awt.peer.PopupMenuPeer
{
private readonly java.awt.PopupMenu target;
private readonly ContextMenu menu = new ContextMenu();
internal NetPopupMenuPeer(java.awt.PopupMenu target)
{
this.target = target;
for (int i = 0; i < target.getItemCount(); i++)
{
addItem(target.getItem(i));
}
}
public void show(java.awt.Event e)
{
show((java.awt.Component)e.target, new java.awt.Point(e.x, e.y));
}
public void show(java.awt.Component origin, java.awt.Point p)
{
NetComponentPeer peer = (NetComponentPeer)origin.getPeer();
Point pt = new Point(p.x, p.y);
pt.Offset(- peer.getInsetsLeft(), - peer.getInsetsTop());
NetToolkit.Invoke(delegate { menu.Show(peer.Control, pt); });
}
public void dispose()
{
NetToolkit.Invoke(delegate { menu.Dispose(); });
}
public void setFont(java.awt.Font f)
{
throw new NotImplementedException();
}
public void disable()
{
setEnabled(false);
}
public void enable()
{
setEnabled(true);
}
public void setEnabled(bool b)
{
NetToolkit.Invoke(delegate
{
for (int i = 0; i < target.getItemCount(); i++)
{
menu.MenuItems[i].Enabled = b && target.getItem(i).isEnabled();
}
});
}
public void setLabel(string str)
{
}
public void addItem(java.awt.MenuItem item)
{
if (item.getPeer() == null)
{
item.addNotify();
}
if (item.getPeer() is NetMenuItemPeer)
{
NetToolkit.Invoke(delegate { menu.MenuItems.Add(((NetMenuItemPeer)item.getPeer()).menuitem); });
}
else
{
NetToolkit.Invoke(delegate { menu.MenuItems.Add(((NetMenuPeer)item.getPeer()).menu); });
}
}
public void addSeparator()
{
NetToolkit.Invoke(delegate { menu.MenuItems.Add(new MenuItem("-")); });
}
public void delItem(int i)
{
NetToolkit.Invoke(delegate { menu.MenuItems.RemoveAt(i); });
}
}
class NetTrayIconPeer : java.awt.peer.TrayIconPeer
{
internal const int TRAY_ICON_WIDTH = 16;
internal const int TRAY_ICON_HEIGHT = 16;
internal const int TRAY_ICON_MASK_SIZE = TRAY_ICON_WIDTH*TRAY_ICON_HEIGHT/8;
private java.awt.TrayIcon target;
private NotifyIcon notifyIcon;
private java.awt.Frame popupParent = new java.awt.Frame("PopupMessageWindow");
private java.awt.PopupMenu popup;
private bool disposed;
private bool isPopupMenu;
internal NetTrayIconPeer(java.awt.TrayIcon target)
{
this.target = target;
popupParent.addNotify();
create();
updateImage();
}
public void displayMessage(string caption, string text, string messageType)
{
ToolTipIcon icon = ToolTipIcon.None;
switch(messageType)
{
case "ERROR" :
icon = ToolTipIcon.Error;
break;
case "WARNING" :
icon = ToolTipIcon.Warning;
break;
case "INFO" :
icon = ToolTipIcon.Info;
break;
case "NONE" :
icon = ToolTipIcon.None;
break;
}
NetToolkit.BeginInvoke(delegate
{
notifyIcon.ShowBalloonTip(10000, caption, text, icon);
});
}
private void create()
{
NetToolkit.Invoke(delegate
{
notifyIcon = new NotifyIcon();
hookEvents();
notifyIcon.Visible = true;
});
}
public void dispose()
{
bool callDisposed = true;
lock (this)
{
if (disposed)
callDisposed = false;
disposed = true;
}
if (callDisposed)
disposeImpl();
}
protected void disposeImpl()
{
if (popupParent != null)
{
popupParent.dispose();
}
NetToolkit.targetDisposedPeer(target, this);
NetToolkit.BeginInvoke(nativeDispose);
}
private void hookEvents()
{
notifyIcon.MouseClick += new MouseEventHandler(OnClick);
notifyIcon.MouseDoubleClick += new MouseEventHandler(OnDoubleClick);
notifyIcon.MouseDown += new MouseEventHandler(OnMouseDown);
notifyIcon.MouseUp += new MouseEventHandler(OnMouseUp);
notifyIcon.MouseMove += new MouseEventHandler(OnMouseMove);
}
private void unhookEvents()
{
notifyIcon.MouseClick -= new MouseEventHandler(OnClick);
notifyIcon.MouseDoubleClick -= new MouseEventHandler(OnDoubleClick);
notifyIcon.MouseDown -= new MouseEventHandler(OnMouseDown);
notifyIcon.MouseUp -= new MouseEventHandler(OnMouseUp);
notifyIcon.MouseMove -= new MouseEventHandler(OnMouseMove);
}
internal void postEvent(java.awt.AWTEvent evt)
{
NetToolkit.postEvent(NetToolkit.targetToAppContext(target), evt);
}
private void postMouseEvent(MouseEventArgs ev, int id, int clicks)
{
long when = java.lang.System.currentTimeMillis();
int modifiers = NetComponentPeer.GetMouseEventModifiers(ev);
int button = NetComponentPeer.GetButton(ev);
int clickCount = clicks;
int x = Control.MousePosition.X;
int y = Control.MousePosition.Y;
bool isPopup = isPopupMenu;
java.awt.EventQueue.invokeLater(Delegates.toRunnable(delegate
{
java.awt.Component fake = new java.awt.TextField();
java.awt.@event.MouseEvent mouseEvent = new java.awt.@event.MouseEvent(fake, id, when, modifiers, x, y, clickCount, isPopup, button);
mouseEvent.setSource(target);
postEvent(mouseEvent);
}));
isPopupMenu = false;
}
private void postMouseEvent(EventArgs ev, int id)
{
long when = java.lang.System.currentTimeMillis();
int modifiers = NetComponentPeer.GetModifiers(Control.ModifierKeys);
int button = 0;
int clickCount = 0;
int x = Control.MousePosition.X;
int y = Control.MousePosition.Y;
bool isPopup = isPopupMenu;
java.awt.EventQueue.invokeLater(Delegates.toRunnable(delegate
{
java.awt.Component fake = new java.awt.TextField();
java.awt.@event.MouseEvent mouseEvent = new java.awt.@event.MouseEvent(fake, id, when, modifiers, x, y, clickCount, isPopup, button);
mouseEvent.setSource(target);
postEvent(mouseEvent);
}));
isPopupMenu = false;
}
protected virtual void OnMouseDown(object sender, MouseEventArgs ev)
{
isPopupMenu = false;
postMouseEvent(ev, java.awt.@event.MouseEvent.MOUSE_PRESSED, ev.Clicks);
}
private void OnClick(object sender, MouseEventArgs ev)
{
postMouseEvent(ev, java.awt.@event.MouseEvent.MOUSE_CLICKED, ev.Clicks);
}
private void OnDoubleClick(object sender, MouseEventArgs ev)
{
postMouseEvent(ev, java.awt.@event.MouseEvent.MOUSE_CLICKED, ev.Clicks);
long when = java.lang.System.currentTimeMillis();
int modifiers = NetComponentPeer.GetModifiers(Control.ModifierKeys);
postEvent(new java.awt.@event.ActionEvent(target, java.awt.@event.ActionEvent.ACTION_PERFORMED, target.getActionCommand(), when, modifiers));
}
private void OnMouseUp(object sender, MouseEventArgs ev)
{
postMouseEvent(ev, java.awt.@event.MouseEvent.MOUSE_RELEASED, ev.Clicks);
}
private void OnMouseEnter(object sender, EventArgs ev)
{
postMouseEvent(ev, java.awt.@event.MouseEvent.MOUSE_ENTERED);
}
private void OnMouseLeave(object sender, EventArgs ev)
{
postMouseEvent(ev, java.awt.@event.MouseEvent.MOUSE_EXITED);
}
protected virtual void OnMouseMove(object sender, MouseEventArgs ev)
{
if ((ev.Button & (MouseButtons.Left | MouseButtons.Right)) != 0)
{
postMouseEvent(ev, java.awt.@event.MouseEvent.MOUSE_DRAGGED, ev.Clicks);
}
else
{
postMouseEvent(ev, java.awt.@event.MouseEvent.MOUSE_MOVED, ev.Clicks);
}
}
private void nativeDispose()
{
if (notifyIcon!=null)
{
unhookEvents();
notifyIcon.Dispose();
}
}
public void setToolTip(string str)
{
NetToolkit.BeginInvoke(delegate { notifyIcon.Text = str; });
}
protected bool isDisposed()
{
return disposed;
}
public void showPopupMenu(int x, int y)
{
if (isDisposed())
return;
java.lang.Runnable runnable = Delegates.toRunnable(delegate
{
java.awt.PopupMenu newPopup = ((java.awt.TrayIcon)target).getPopupMenu();
if (popup != newPopup) {
if (popup != null) {
popupParent.remove(popup);
}
if (newPopup != null) {
popupParent.add(newPopup);
}
popup = newPopup;
}
if (popup != null) {
((NetPopupMenuPeer)popup.getPeer()).show(popupParent, new java.awt.Point(x, y));
}
});
SunToolkit.executeOnEventHandlerThread(target, runnable);
}
public void updateImage()
{
java.awt.Image image = ((java.awt.TrayIcon) target).getImage();
if (image != null)
{
updateNativeImage(image);
}
}
private void updateNativeImage(java.awt.Image image)
{
lock (this)
{
if (isDisposed())
return;
bool autosize = ((java.awt.TrayIcon) target).isImageAutoSize();
using (Bitmap bitmap = getNativeImage(image, autosize))
{
IntPtr hicon = bitmap.GetHicon();
Icon icon = Icon.FromHandle(hicon);
notifyIcon.Icon = icon;
}
}
}
private Bitmap getNativeImage(java.awt.Image image, bool autosize)
{
if (image is NoImage)
return new Bitmap(TRAY_ICON_WIDTH, TRAY_ICON_HEIGHT);
else
{
Image netImage = J2C.ConvertImage(image);
if (autosize)
return new Bitmap(netImage, TRAY_ICON_WIDTH, TRAY_ICON_HEIGHT);
else
return new Bitmap(netImage);
}
}
}
internal class NetMouseInfoPeer : java.awt.peer.MouseInfoPeer
{
public int fillPointWithCoords(java.awt.Point p)
{
p.x = Cursor.Position.X;
p.y = Cursor.Position.Y;
//TODO multi screen device
return 0; //return the number of the screen device
}
[DllImport("user32.dll")]
private static extern IntPtr WindowFromPoint(POINT Point);
[StructLayout(LayoutKind.Sequential)]
private struct POINT
{
private int X;
private int Y;
internal POINT(Point pt)
{
this.X = pt.X;
this.Y = pt.Y;
}
}
public bool isWindowUnderMouse(java.awt.Window window)
{
if (NetToolkit.isWin32())
{
NetWindowPeer peer = (NetWindowPeer)window.getPeer();
if (peer != null)
{
IntPtr hWnd = WindowFromPoint(new POINT(Cursor.Position));
return peer.control.Handle.Equals(hWnd);
}
return false;
}
else
{
throw new NotImplementedException();
}
}
}
public class NetClipboard : java.awt.datatransfer.Clipboard
{
public static readonly java.awt.datatransfer.FlavorTable flavorMap =
(java.awt.datatransfer.FlavorTable)java.awt.datatransfer.SystemFlavorMap.getDefaultFlavorMap();
public NetClipboard() : base("System") { }
public override void setContents(java.awt.datatransfer.Transferable contents, java.awt.datatransfer.ClipboardOwner owner)
{
if (contents == null)
{
throw new java.lang.NullPointerException("contents");
}
java.awt.datatransfer.ClipboardOwner oldOwner = this.owner;
java.awt.datatransfer.Transferable oldContents = this.contents;
try
{
this.owner = owner;
this.contents = new sun.awt.datatransfer.TransferableProxy(contents, true);
setContentsNative(contents);
}
finally
{
if (oldOwner != null && oldOwner != owner)
{
java.awt.EventQueue.invokeLater(Delegates.toRunnable(delegate()
{
oldOwner.lostOwnership(this, oldContents);
}));
}
}
}
private void setContentsNative(java.awt.datatransfer.Transferable contents)
{
IDataObject clipObj = NetDataTransferer.getInstanceImpl().getDataObject(contents, flavorMap);
NetToolkit.BeginInvoke(delegate
{
Clipboard.SetDataObject(clipObj, true);
});
}
public override java.awt.datatransfer.Transferable getContents(object requestor)
{
if (contents != null)
{
return contents;
}
return new NetClipboardTransferable(Clipboard.GetDataObject());
}
}
public class NetClipboardTransferable : java.awt.datatransfer.Transferable
{
private readonly Map flavorToData = new HashMap();
private readonly java.awt.datatransfer.DataFlavor[] flavors;
public NetClipboardTransferable(IDataObject data)
{
flavorToData = NetDataTransferer.getInstanceImpl().translateFromClipboard(data);
flavors = (java.awt.datatransfer.DataFlavor[])flavorToData.keySet().toArray(new java.awt.datatransfer.DataFlavor[0]);
}
public java.awt.datatransfer.DataFlavor[] getTransferDataFlavors()
{
return flavors;
}
public object getTransferData(java.awt.datatransfer.DataFlavor df)
{
return flavorToData.get(df);
}
public bool isDataFlavorSupported(java.awt.datatransfer.DataFlavor df)
{
return flavorToData.containsKey(df);
}
}
public class NetDataTransferer : sun.awt.IkvmDataTransferer
{
class NetToolkitThreadBlockedHandler : sun.awt.datatransfer.ToolkitThreadBlockedHandler
{
private bool locked;
private Thread owner;
protected bool isOwned()
{
return (locked && Thread.CurrentThread == owner);
}
public void enter()
{
if (!isOwned())
{
throw new java.lang.IllegalMonitorStateException();
}
unlock();
if (Application.MessageLoop)
{
Application.DoEvents();
}
@lock();
}
public void exit()
{
if (!isOwned())
{
throw new java.lang.IllegalMonitorStateException();
}
}
public void @lock() {
lock(this)
{
if (locked && Thread.CurrentThread == owner)
{
throw new java.lang.IllegalMonitorStateException();
}
do
{
if (!locked)
{
locked = true;
owner = Thread.CurrentThread;
}
else
{
try
{
Monitor.Wait(this);
}
catch (ThreadInterruptedException)
{
// try again
}
}
} while (owner != Thread.CurrentThread);
}
}
public void unlock()
{
lock (this)
{
if (Thread.CurrentThread != owner)
{
throw new java.lang.IllegalMonitorStateException();
}
owner = null;
locked = false;
Monitor.Pulse(this);
}
}
}
private static readonly NetDataTransferer instance = new NetDataTransferer();
private static readonly NetToolkitThreadBlockedHandler handler = new NetToolkitThreadBlockedHandler();
public static NetDataTransferer getInstanceImpl()
{
return instance;
}
internal long[] getClipboardFormatCodes(string[] formats)
{
long[] longData = new long[formats.Length];
for(int i=0; i<formats.Length; i++)
{
DataFormats.Format dataFormat = DataFormats.GetFormat(formats[i]);
longData[i] = dataFormat==null?0:dataFormat.Id;
}
return longData;
}
internal string getNativeClipboardFormatName(long format)
{
DataFormats.Format dataFormat = DataFormats.GetFormat((int)format);
if (dataFormat == null)
return null;
else
return dataFormat.Name;
}
internal Map translateFromClipboard(IDataObject data)
{
java.awt.datatransfer.FlavorTable defaultFlavorMap = (java.awt.datatransfer.FlavorTable)java.awt.datatransfer.SystemFlavorMap.getDefaultFlavorMap();
Map/*<DataFlavor,object>*/ map = new HashMap();
if (data == null)
{
return map;
}
string[] formats = data.GetFormats();
if (formats != null && formats.Length > 0)
{
long[] longFormats = getClipboardFormatCodes(formats);
Map /*<DataFlavor,long>*/ flavorMap = getFlavorsForFormats(longFormats, defaultFlavorMap);
java.awt.datatransfer.DataFlavor[] flavors =
(java.awt.datatransfer.DataFlavor[])
(flavorMap.keySet().toArray(new java.awt.datatransfer.DataFlavor[0]));
for(int i=0; i<flavors.Length; i++)
{
java.awt.datatransfer.DataFlavor df = flavors[i];
long format = ((java.lang.Long) flavorMap.get(df)).longValue();
string stringFormat = getNativeClipboardFormatName(format);
if (stringFormat==null) continue; // clipboard format is not registered in Windows system
object formatData = data.GetData(stringFormat);
if (formatData == null) continue; // no data for that format
object translatedData = null;
if (df.isFlavorJavaFileListType())
{
// translate string[] into java.util.List<java.io.File>
string[] nativeFileList = (string[])formatData;
List fileList = new ArrayList(nativeFileList.Length);
for (int j = 0; j < nativeFileList.Length; j++)
{
java.io.File file = new java.io.File(nativeFileList[i]);
fileList.add(file);
}
translatedData = fileList;
}
else if (java.awt.datatransfer.DataFlavor.imageFlavor.equals(df) && formatData is Bitmap)
{
// translate System.Drawing.Bitmap into java.awt.Image
translatedData = new java.awt.image.BufferedImage((Bitmap) formatData);
}
else if (formatData is string)
{
if (df.isFlavorTextType())
translatedData = formatData;
else if (((java.lang.Class)typeof(java.io.Reader)).equals(df.getRepresentationClass()))
translatedData = new java.io.StringReader((string) formatData);
else if (((java.lang.Class)typeof(java.io.InputStream)).equals(df.getRepresentationClass()))
translatedData = new java.io.StringBufferInputStream((string)formatData);
else
throw new java.awt.datatransfer.UnsupportedFlavorException(df);
}
if (translatedData!=null)
map.put(df, translatedData);
}
}
return map;
}
internal IDataObject getDataObject(java.awt.datatransfer.Transferable transferable, java.awt.datatransfer.FlavorTable flavorMap)
{
DataObject obj = new DataObject();
SortedMap/*<java.lang.Long,java.awt.datatransfer.DataFlavor>*/ formatMap = getFormatsForTransferable(transferable, flavorMap);
for (Iterator iterator = formatMap.entrySet().iterator(); iterator.hasNext();)
{
Map.Entry entry = (Map.Entry) iterator.next();
java.lang.Long lFormat = (java.lang.Long) entry.getKey();
long format = lFormat == null ? -1 : lFormat.longValue();
java.awt.datatransfer.DataFlavor flavor = (java.awt.datatransfer.DataFlavor) entry.getValue();
object contents = transferable.getTransferData(flavor);
if (contents==null) continue;
try
{
if (java.awt.datatransfer.DataFlavor.javaFileListFlavor.equals(flavor))
{
List list = (List)contents;
System.Collections.Specialized.StringCollection files =
new System.Collections.Specialized.StringCollection();
for (int i = 0; i < list.size(); i++)
{
files.Add(((java.io.File) list.get(i)).getAbsolutePath());
}
obj.SetFileDropList(files);
}
else if (flavor.isFlavorTextType())
{
if (contents is string)
obj.SetText((string) transferable.getTransferData(flavor));
}
else if (java.awt.datatransfer.DataFlavor.imageFlavor.equals(flavor))
{
java.awt.Image image = contents as java.awt.Image;
if (image != null)
{
Image netImage = J2C.ConvertImage(image);
if (netImage != null)
{
obj.SetImage(netImage);
}
}
}
else if (flavor.isRepresentationClassCharBuffer())
{
if (!(isFlavorCharsetTextType(flavor) && isTextFormat(format)))
{
throw new IOException("cannot transfer non-text data as CharBuffer");
}
java.nio.CharBuffer buffer = (java.nio.CharBuffer)contents;
int size = buffer.remaining();
char[] chars = new char[size];
buffer.get(chars, 0, size);
obj.SetText(new string(chars));
}
else
{
// don't know what to do with it...
obj.SetData(transferable.getTransferData(flavor));
}
}
catch (java.io.IOException e)
{
if (!(flavor.isMimeTypeEqual(java.awt.datatransfer.DataFlavor.javaJVMLocalObjectMimeType) &&
e is java.io.NotSerializableException))
{
e.printStackTrace();
}
}
}
return obj;
}
protected override string getClipboardFormatName(long format)
{
return getNativeClipboardFormatName(format);
}
protected override byte[] imageToStandardBytes(java.awt.Image image, string mimeType)
{
if (image is NoImage) return null;
Image netImage = J2C.ConvertImage(image);
ImageFormat format;
switch(mimeType)
{
case "image/jpg":
case "image/jpeg":
format = ImageFormat.Jpeg;
break;
case "image/png":
format = ImageFormat.Png;
break;
case "image/gif":
format = ImageFormat.Gif;
break;
case "image/x-win-metafile":
case "image/x-wmf":
case "image/wmf":
format = ImageFormat.Wmf;
break;
default:
return null;
}
using(MemoryStream stream = new MemoryStream())
{
netImage.Save(stream, format);
return stream.GetBuffer();
}
}
public override sun.awt.datatransfer.ToolkitThreadBlockedHandler getToolkitThreadBlockedHandler()
{
return handler;
}
}
}
|