[go: up one dir, main page]

File: Fl_cocoa.mm

package info (click to toggle)
fltk1.3 1.3.5-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 24,212 kB
  • sloc: cpp: 104,591; ansic: 88,673; sh: 6,607; makefile: 1,887; perl: 27; xml: 7
file content (4904 lines) | stat: -rw-r--r-- 170,113 bytes parent folder | download
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
//
// "$Id$"
//
// MacOS-Cocoa specific code for the Fast Light Tool Kit (FLTK).
//
// Copyright 1998-2016 by Bill Spitzak and others.
//
// This library is free software. Distribution and use rights are outlined in
// the file "COPYING" which should have been included with this file.  If this
// file is missing or damaged, see the license at:
//
//     http://www.fltk.org/COPYING.php
//
// Please report all bugs and problems on the following page:
//
//     http://www.fltk.org/str.php
//

//// From the inner edge of a MetroWerks CodeWarrior CD:
// (without permission)
//
// "Three Compiles for 68Ks under the sky,
// Seven Compiles for PPCs in their fragments of code,
// Nine Compiles for Mortal Carbon doomed to die,
// One Compile for Mach-O Cocoa on its Mach-O throne,
// in the Land of MacOS X where the Drop-Shadows lie.
// 
// One Compile to link them all, One Compile to merge them,
// One Compile to copy them all and in the bundle bind them,
// in the Land of MacOS X where the Drop-Shadows lie."

#ifdef __APPLE__

#define CONSOLIDATE_MOTION 0
extern "C" {
#include <pthread.h>
}

#include <FL/x.H>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Tooltip.H>
#include <FL/Fl_Printer.H>
#include <FL/Fl_Copy_Surface.H>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdarg.h>
#include <math.h>
#include <limits.h>
#include <dlfcn.h>
#include <string.h>

#import <Cocoa/Cocoa.h>

// #define DEBUG_SELECT		// UNCOMMENT FOR SELECT()/THREAD DEBUGGING
#ifdef DEBUG_SELECT
#include <stdio.h>		// testing
#define DEBUGMSG(msg)		if ( msg ) fprintf(stderr, msg);
#define DEBUGPERRORMSG(msg)	if ( msg ) perror(msg)
#define DEBUGTEXT(txt)		txt
#else
#define DEBUGMSG(msg)
#define DEBUGPERRORMSG(msg)
#define DEBUGTEXT(txt)		NULL
#endif /*DEBUG_SELECT*/

// external functions
extern void fl_fix_focus();
extern unsigned short *fl_compute_macKeyLookUp();
extern int fl_send_system_handlers(void *e);

// forward definition of functions in this file
// converting cr lf converter function
static size_t convert_crlf(char * string, size_t len);
static void createAppleMenu(void);
static void cocoaMouseHandler(NSEvent *theEvent);
static void clipboard_check(void);
static unsigned make_current_counts = 0; // if > 0, then Fl_Window::make_current() can be called only once
static NSBitmapImageRep* rect_to_NSBitmapImageRep(Fl_Window *win, int x, int y, int w, int h);

int fl_mac_os_version = Fl_X::calc_mac_os_version();		// the version number of the running Mac OS X (e.g., 100604 for 10.6.4)
int fl_mac_quit_early = 1; // set it to 0 so cmd-Q does not terminate app but merely terminates the event loop

// public variables
CGContextRef fl_gc = 0;
void *fl_capture = 0;			// (NSWindow*) we need this to compensate for a missing(?) mouse capture
bool fl_show_iconic;                    // true if called from iconize() - shows the next created window in collapsed state
//int fl_disable_transient_for;           // secret method of removing TRANSIENT_FOR
Window fl_window;
Fl_Window *Fl_Window::current_;

// forward declarations of variables in this file
static int got_events = 0;
static Fl_Window* resize_from_system;
static int main_screen_height; // height of menubar-containing screen used to convert between Cocoa and FLTK global screen coordinates
// through_drawRect = YES means the drawRect: message was sent to the view, 
// thus the graphics context was prepared by the system
static BOOL through_drawRect = NO; 
// through_Fl_X_flush = YES means Fl_X::flush() was called
static BOOL through_Fl_X_flush = NO;
static BOOL views_use_CA = NO; // YES means views are layer-backed, as on macOS 10.14 when linked with SDK 10.14
static int im_enabled = -1;
// OS version-dependent pasteboard type names
#if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6
#define NSPasteboardTypeTIFF @"public.tiff"
#define NSPasteboardTypePDF @"com.adobe.pdf"
#define NSPasteboardTypeString @"public.utf8-plain-text"
#endif
static NSString *TIFF_pasteboard_type = (fl_mac_os_version >= 100600 ? NSPasteboardTypeTIFF : NSTIFFPboardType);
static NSString *PDF_pasteboard_type = (fl_mac_os_version >= 100600 ? NSPasteboardTypePDF : NSPDFPboardType);
static NSString *PICT_pasteboard_type = (fl_mac_os_version >= 100600 ? @"com.apple.pict" : NSPICTPboardType);
static NSString *UTF8_pasteboard_type = (fl_mac_os_version >= 100600 ? NSPasteboardTypeString : NSStringPboardType);
static bool in_nsapp_run = false; // true during execution of [NSApp run]
static NSMutableArray *dropped_files_list = nil; // list of files dropped at app launch
typedef void (*open_cb_f_type)(const char *);
static open_cb_f_type get_open_cb();
#if CONSOLIDATE_MOTION
static Fl_Window* send_motion;
extern Fl_Window* fl_xmousewin;
#endif

enum { FLTKTimerEvent = 1, FLTKDataReadyEvent };

// Carbon functions and definitions

typedef void *TSMDocumentID;

extern "C" enum {
 kTSMDocumentEnabledInputSourcesPropertyTag = 'enis' //  from Carbon/TextServices.h
};

// Undocumented voodoo. Taken from Mozilla.
static const int smEnableRomanKybdsOnly = -23;

typedef TSMDocumentID (*TSMGetActiveDocument_type)(void);
static TSMGetActiveDocument_type TSMGetActiveDocument;
typedef OSStatus (*TSMSetDocumentProperty_type)(TSMDocumentID, OSType, UInt32, void*);
static TSMSetDocumentProperty_type TSMSetDocumentProperty;
typedef OSStatus (*TSMRemoveDocumentProperty_type)(TSMDocumentID, OSType);
static TSMRemoveDocumentProperty_type TSMRemoveDocumentProperty;
typedef CFArrayRef (*TISCreateASCIICapableInputSourceList_type)(void);
static TISCreateASCIICapableInputSourceList_type TISCreateASCIICapableInputSourceList;

typedef void (*KeyScript_type)(short);
static KeyScript_type KeyScript;


/* fltk-utf8 placekeepers */
void fl_reset_spot()
{
}

void fl_set_spot(int font, int size, int X, int Y, int W, int H, Fl_Window *win)
{
}

void fl_set_status(int x, int y, int w, int h)
{
}

/*
 * Mac keyboard lookup table
 */
static unsigned short* macKeyLookUp = NULL;

/*
 * convert the current mouse chord into the FLTK modifier state
 */
static unsigned int mods_to_e_state( NSUInteger mods )
{
  long state = 0;
  if ( mods & NSCommandKeyMask ) state |= FL_META;
  if ( mods & NSAlternateKeyMask ) state |= FL_ALT;
  if ( mods & NSControlKeyMask ) state |= FL_CTRL;
  if ( mods & NSShiftKeyMask ) state |= FL_SHIFT;
  if ( mods & NSAlphaShiftKeyMask ) state |= FL_CAPS_LOCK;
  unsigned int ret = ( Fl::e_state & 0xff000000 ) | state;
  Fl::e_state = ret;
  //printf( "State 0x%08x (%04x)\n", Fl::e_state, mods );
  return ret;
}

// these pointers are set by the Fl::lock() function:
static void nothing() {}
void (*fl_lock_function)() = nothing;
void (*fl_unlock_function)() = nothing;

//
// Select interface -- how it's implemented:
//     When the user app configures one or more file descriptors to monitor
//     with Fl::add_fd(), we start a separate thread to select() the  data,
//     sending a custom OSX 'FLTK data ready event' to the parent  thread's
//     RunApplicationLoop(), so that it triggers the data  ready  callbacks
//     in the parent thread.                               -erco 04/04/04
//     
#define POLLIN  1
#define POLLOUT 4
#define POLLERR 8

// Class to handle select() 'data ready'
class DataReady
{
  struct FD
  {
    int fd;
    short events;
    void (*cb)(int, void*);
    void* arg;
  };
  int nfds, fd_array_size;
  FD *fds;
  pthread_t tid;		// select()'s thread id
  
  // Data that needs to be locked (all start with '_')
  pthread_mutex_t _datalock;	// data lock
  fd_set _fdsets[3];		// r/w/x sets user wants to monitor
  int _maxfd;			// max fd count to monitor
  int _cancelpipe[2];		// pipe used to help cancel thread
  
public:
  DataReady()
  {
    nfds = 0;
    fd_array_size = 0;
    fds = 0;
    tid = 0;
    
    pthread_mutex_init(&_datalock, NULL);
    FD_ZERO(&_fdsets[0]); FD_ZERO(&_fdsets[1]); FD_ZERO(&_fdsets[2]);
    _cancelpipe[0] = _cancelpipe[1] = 0;
    _maxfd = -1;
  }
  
  ~DataReady()
  {
    CancelThread(DEBUGTEXT("DESTRUCTOR\n"));
    if (fds) { free(fds); fds = 0; }
    nfds = 0;
  }
  
  // Locks
  //    The convention for locks: volatile vars start with '_',
  //    and must be locked before use. Locked code is prefixed 
  //    with /*LOCK*/ to make painfully obvious esp. in debuggers. -erco
  //
  void DataLock() { pthread_mutex_lock(&_datalock); }
  void DataUnlock() { pthread_mutex_unlock(&_datalock); }
  
  // Accessors
  int IsThreadRunning() { return(tid ? 1 : 0); }
  int GetNfds() { return(nfds); }
  int GetCancelPipe(int ix) { return(_cancelpipe[ix]); }
  fd_set GetFdset(int ix) { return(_fdsets[ix]); }
  
  // Methods
  void AddFD(int n, int events, void (*cb)(int, void*), void *v);
  void RemoveFD(int n, int events);
  int CheckData(fd_set& r, fd_set& w, fd_set& x);
  void HandleData(fd_set& r, fd_set& w, fd_set& x);
  static void* DataReadyThread(void *self);
  void StartThread(void);
  void CancelThread(const char *reason);
};

static DataReady dataready;

void DataReady::AddFD(int n, int events, void (*cb)(int, void*), void *v)
{
  RemoveFD(n, events);
  int i = nfds++;
  if (i >= fd_array_size) 
  {
    fl_open_display(); // necessary for NSApp to be defined and the event loop to work
    FD *temp;
    fd_array_size = 2*fd_array_size+1;
    if (!fds) { temp = (FD*)malloc(fd_array_size*sizeof(FD)); }
    else { temp = (FD*)realloc(fds, fd_array_size*sizeof(FD)); }
    if (!temp) return;
    fds = temp;
  }
  fds[i].cb  = cb;
  fds[i].arg = v;
  fds[i].fd  = n;
  fds[i].events = events;
  DataLock();
  /*LOCK*/  if (events & POLLIN)  FD_SET(n, &_fdsets[0]);
  /*LOCK*/  if (events & POLLOUT) FD_SET(n, &_fdsets[1]);
  /*LOCK*/  if (events & POLLERR) FD_SET(n, &_fdsets[2]);
  /*LOCK*/  if (n > _maxfd) _maxfd = n;
  DataUnlock();
}

// Remove an FD from the array
void DataReady::RemoveFD(int n, int events)
{
  int i,j;
  _maxfd = -1; // recalculate maxfd on the fly
  for (i=j=0; i<nfds; i++) {
    if (fds[i].fd == n) {
      int e = fds[i].events & ~events;
      if (!e) continue; // if no events left, delete this fd
      fds[i].events = e;
    }
    if (fds[i].fd > _maxfd) _maxfd = fds[i].fd;
    // move it down in the array if necessary:
    if (j<i) {
      fds[j] = fds[i];
    }
    j++;
  }
  nfds = j;
  DataLock();
  /*LOCK*/  if (events & POLLIN)  FD_CLR(n, &_fdsets[0]);
  /*LOCK*/  if (events & POLLOUT) FD_CLR(n, &_fdsets[1]);
  /*LOCK*/  if (events & POLLERR) FD_CLR(n, &_fdsets[2]);
  DataUnlock();
}

// CHECK IF USER DATA READY, RETURNS r/w/x INDICATING WHICH IF ANY
int DataReady::CheckData(fd_set& r, fd_set& w, fd_set& x)
{
  int ret;
  DataLock();
  /*LOCK*/  timeval t = { 0, 1 };		// quick check
  /*LOCK*/  r = _fdsets[0], w = _fdsets[1], x = _fdsets[2];
  /*LOCK*/  ret = ::select(_maxfd+1, &r, &w, &x, &t);
  DataUnlock();
  if ( ret == -1 ) {
    DEBUGPERRORMSG("CheckData(): select()");
  }
  return(ret);
}

// HANDLE DATA READY CALLBACKS
void DataReady::HandleData(fd_set& r, fd_set& w, fd_set& x)
{
  for (int i=0; i<nfds; i++) {
    int f = fds[i].fd;
    short revents = 0;
    if (FD_ISSET(f, &r)) revents |= POLLIN;
    if (FD_ISSET(f, &w)) revents |= POLLOUT;
    if (FD_ISSET(f, &x)) revents |= POLLERR;
    if (fds[i].events & revents) {
      DEBUGMSG("DOING CALLBACK: ");
      fds[i].cb(f, fds[i].arg);
      DEBUGMSG("DONE\n");
    }
  }
}

// DATA READY THREAD
//    This thread watches for changes in user's file descriptors.
//    Sends a 'data ready event' to the main thread if any change.
//
void* DataReady::DataReadyThread(void *o)
{
  DataReady *self = (DataReady*)o;
  while ( 1 ) {					// loop until thread cancel or error
    // Thread safe local copies of data before each select()
    self->DataLock();
    /*LOCK*/  int maxfd = self->_maxfd;
    /*LOCK*/  fd_set r = self->GetFdset(0);
    /*LOCK*/  fd_set w = self->GetFdset(1);
    /*LOCK*/  fd_set x = self->GetFdset(2);
    /*LOCK*/  int cancelpipe = self->GetCancelPipe(0);
    /*LOCK*/  if ( cancelpipe > maxfd ) maxfd = cancelpipe;
    /*LOCK*/  FD_SET(cancelpipe, &r);		// add cancelpipe to fd's to watch
    /*LOCK*/  FD_SET(cancelpipe, &x);
    self->DataUnlock();
    // timeval t = { 1000, 0 };	// 1000 seconds;
    timeval t = { 2, 0 };	// HACK: 2 secs prevents 'hanging' problem
    int ret = ::select(maxfd+1, &r, &w, &x, &t);
    pthread_testcancel();	// OSX 10.0.4 and older: needed for parent to cancel
    switch ( ret ) {
      case 0:	// NO DATA
        continue;
      case -1:	// ERROR
      {
        DEBUGPERRORMSG("CHILD THREAD: select() failed");
        return(NULL);		// error? exit thread
      }
      default:	// DATA READY
      {
        if (FD_ISSET(cancelpipe, &r) || FD_ISSET(cancelpipe, &x)) 	// cancel?
	  { return(NULL); }						// just exit
        DEBUGMSG("CHILD THREAD: DATA IS READY\n");
        NSAutoreleasePool *localPool = [[NSAutoreleasePool alloc] init];
        NSEvent *event = [NSEvent otherEventWithType:NSApplicationDefined
                                            location:NSMakePoint(0,0)
                                       modifierFlags:0
                                           timestamp:0
                                        windowNumber:0 context:NULL subtype:FLTKDataReadyEvent data1:0 data2:0];
        [NSApp postEvent:event atStart:NO];
        [localPool release];
        return(NULL);		// done with thread
      }
    }
  }
}

// START 'DATA READY' THREAD RUNNING, CREATE INTER-THREAD PIPE
void DataReady::StartThread(void)
{
  CancelThread(DEBUGTEXT("STARTING NEW THREAD\n"));
  DataLock();
  /*LOCK*/  pipe(_cancelpipe);	// pipe for sending cancel msg to thread
  DataUnlock();
  DEBUGMSG("*** START THREAD\n");
  pthread_create(&tid, NULL, DataReadyThread, (void*)this);
}

// CANCEL 'DATA READY' THREAD, CLOSE PIPE
void DataReady::CancelThread(const char *reason)
{
  if ( tid ) {
    DEBUGMSG("*** CANCEL THREAD: ");
    DEBUGMSG(reason);
    if ( pthread_cancel(tid) == 0 ) {		// cancel first
      DataLock();
      /*LOCK*/  write(_cancelpipe[1], "x", 1);	// wake thread from select
      DataUnlock();
      pthread_join(tid, NULL);			// wait for thread to finish
    }
    tid = 0;
    DEBUGMSG("(JOINED) OK\n");
  }
  // Close pipe if open
  DataLock();
  /*LOCK*/  if ( _cancelpipe[0] ) { close(_cancelpipe[0]); _cancelpipe[0] = 0; }
  /*LOCK*/  if ( _cancelpipe[1] ) { close(_cancelpipe[1]); _cancelpipe[1] = 0; }
  DataUnlock();
}

void Fl::add_fd( int n, int events, void (*cb)(int, void*), void *v )
{
  dataready.AddFD(n, events, cb, v);
}

void Fl::add_fd(int fd, void (*cb)(int, void*), void* v)
{
  dataready.AddFD(fd, POLLIN, cb, v);
}

void Fl::remove_fd(int n, int events)
{
  dataready.RemoveFD(n, events);
}

void Fl::remove_fd(int n)
{
  dataready.RemoveFD(n, -1);
}

/*
 * Check if there is actually a message pending
 */
int fl_ready()
{
  NSEvent *retval = [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:[NSDate dateWithTimeIntervalSinceNow:0]
				    inMode:NSDefaultRunLoopMode dequeue:NO];
  return retval != nil;
}


static void processFLTKEvent(void) {
  fl_lock_function();
  dataready.CancelThread(DEBUGTEXT("DATA READY EVENT\n"));
  
  // CHILD THREAD TELLS US DATA READY
  //     Check to see what's ready, and invoke user's cb's
  //
  fd_set r,w,x;
  switch(dataready.CheckData(r,w,x)) {
    case 0:	// NO DATA
      break;
    case -1:	// ERROR
      break;
    default:	// DATA READY
      dataready.HandleData(r,w,x);
      break;
  }
  fl_unlock_function();
  return;
}


/*
 * break the current event loop
 */
static void breakMacEventLoop()
{  
  NSEvent *event = [NSEvent otherEventWithType:NSApplicationDefined location:NSMakePoint(0,0)
                                 modifierFlags:0 timestamp:0
                                  windowNumber:0 context:NULL subtype:FLTKTimerEvent data1:0 data2:0];
  [NSApp postEvent:event atStart:NO];
}

//
// MacOS X timers
//

struct MacTimeout {
  Fl_Timeout_Handler callback;
  void* data;
  CFRunLoopTimerRef timer;
  char pending; 
  CFAbsoluteTime next_timeout; // scheduled time for this timer
};
static MacTimeout* mac_timers;
static int mac_timer_alloc;
static int mac_timer_used;
static MacTimeout* current_timer;  // the timer that triggered its callback function

static void realloc_timers()
{
  if (mac_timer_alloc == 0) {
    mac_timer_alloc = 8;
    fl_open_display(); // needed because the timer creates an event
  }
  mac_timer_alloc *= 2;
  MacTimeout* new_timers = new MacTimeout[mac_timer_alloc];
  memset(new_timers, 0, sizeof(MacTimeout)*mac_timer_alloc);
  memcpy(new_timers, mac_timers, sizeof(MacTimeout) * mac_timer_used);
  if (current_timer) {
    MacTimeout* newCurrent = new_timers + (current_timer - mac_timers);
    current_timer = newCurrent;
  }
  MacTimeout* delete_me = mac_timers;
  mac_timers = new_timers;
  delete [] delete_me;
}

static void delete_timer(MacTimeout& t)
{
  if (t.timer) {
    CFRunLoopRemoveTimer(CFRunLoopGetCurrent(),
		      t.timer,
		      kCFRunLoopDefaultMode);
    CFRelease(t.timer);
    memset(&t, 0, sizeof(MacTimeout));
  }
}

static void do_timer(CFRunLoopTimerRef timer, void* data)
{
  fl_lock_function();
  fl_intptr_t timerId = (fl_intptr_t)data;
  current_timer = &mac_timers[timerId];
  current_timer->pending = 0;
  (current_timer->callback)(current_timer->data);
  if (current_timer && current_timer->pending == 0)
    delete_timer(*current_timer);
  current_timer = NULL;

  breakMacEventLoop();
  fl_unlock_function();
}

void Fl::add_timeout(double time, Fl_Timeout_Handler cb, void* data)
{
  // check, if this timer slot exists already
  for (int i = 0; i < mac_timer_used; ++i) {
    MacTimeout& t = mac_timers[i];
    // if so, simply change the fire interval
    if (t.callback == cb  &&  t.data == data) {
      t.next_timeout = CFAbsoluteTimeGetCurrent() + time;
      CFRunLoopTimerSetNextFireDate(t.timer, t.next_timeout );
      t.pending = 1;
      return;
    }
  }
  // no existing timer to use. Create a new one:
  fl_intptr_t timer_id = -1;
  // find an empty slot in the timer array
  for (int i = 0; i < mac_timer_used; ++i) {
    if ( !mac_timers[i].timer ) {
      timer_id = i;
      break;
    }
  }
  // if there was no empty slot, append a new timer
  if (timer_id == -1) {
    // make space if needed
    if (mac_timer_used == mac_timer_alloc) {
      realloc_timers();
    }
    timer_id = mac_timer_used++;
  }
  // now install a brand new timer
  MacTimeout& t = mac_timers[timer_id];
  CFRunLoopTimerContext context = {0, (void*)timer_id, NULL,NULL,NULL};
  CFRunLoopTimerRef timerRef = CFRunLoopTimerCreate(kCFAllocatorDefault, 
						    CFAbsoluteTimeGetCurrent() + time,
						    1E30,  
						    0,
						    0,
						    do_timer,
						    &context
						    );
  if (timerRef) {
    CFRunLoopAddTimer(CFRunLoopGetCurrent(),
		      timerRef,
		      kCFRunLoopDefaultMode);
    t.callback = cb;
    t.data     = data;
    t.timer    = timerRef;
    t.pending  = 1;
    t.next_timeout = CFRunLoopTimerGetNextFireDate(timerRef);
  }
}

void Fl::repeat_timeout(double time, Fl_Timeout_Handler cb, void* data)
{
  // k = how many times 'time' seconds after the last scheduled timeout until the future
  double k = ceil( (CFAbsoluteTimeGetCurrent() - current_timer->next_timeout) / time);
  if (k < 1) k = 1;
  current_timer->next_timeout += k * time;
  CFRunLoopTimerSetNextFireDate(current_timer->timer, current_timer->next_timeout );
  current_timer->callback = cb;
  current_timer->data = data;
  current_timer->pending = 1;
}

int Fl::has_timeout(Fl_Timeout_Handler cb, void* data)
{
  for (int i = 0; i < mac_timer_used; ++i) {
    MacTimeout& t = mac_timers[i];
    if (t.callback == cb  &&  t.data == data && t.pending) {
      return 1;
    }
  }
  return 0;
}

void Fl::remove_timeout(Fl_Timeout_Handler cb, void* data)
{
  for (int i = 0; i < mac_timer_used; ++i) {
    MacTimeout& t = mac_timers[i];
    if (t.callback == cb  && ( t.data == data || data == NULL)) {
      delete_timer(t);
    }
  }
}

@interface FLWindow : NSWindow {
  Fl_Window *w;
}
- (FLWindow*)initWithFl_W:(Fl_Window *)flw 
	      contentRect:(NSRect)rect 
		styleMask:(NSUInteger)windowStyle;
- (Fl_Window *)getFl_Window;
- (void)recursivelySendToSubwindows:(SEL)sel;
- (void)setSubwindowFrame;
- (void)checkSubwindowFrame;
- (void)waitForExpose;
- (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen *)screen;
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
- (NSPoint)convertBaseToScreen:(NSPoint)aPoint;
#endif
@end


@interface FLView : NSView <NSTextInput
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
, NSTextInputClient
#endif
> {
  BOOL in_key_event; // YES means keypress is being processed by handleEvent
  BOOL need_handle; // YES means Fl::handle(FL_KEYBOARD,) is needed after handleEvent processing
  NSInteger identifier;
  NSRange selectedRange;
}
+ (void)prepareEtext:(NSString*)aString;
+ (void)concatEtext:(NSString*)aString;
- (BOOL)process_keydown:(NSEvent*)theEvent;
- (id)initWithFrame:(NSRect)frameRect;
- (void)drawRect:(NSRect)rect;
- (BOOL)acceptsFirstResponder;
- (BOOL)acceptsFirstMouse:(NSEvent*)theEvent;
- (void)resetCursorRects;
- (BOOL)performKeyEquivalent:(NSEvent*)theEvent;
- (void)mouseUp:(NSEvent *)theEvent;
- (void)rightMouseUp:(NSEvent *)theEvent;
- (void)otherMouseUp:(NSEvent *)theEvent;
- (void)mouseDown:(NSEvent *)theEvent;
- (void)rightMouseDown:(NSEvent *)theEvent;
- (void)otherMouseDown:(NSEvent *)theEvent;
- (void)mouseMoved:(NSEvent *)theEvent;
- (void)mouseDragged:(NSEvent *)theEvent;
- (void)rightMouseDragged:(NSEvent *)theEvent;
- (void)otherMouseDragged:(NSEvent *)theEvent;
- (void)scrollWheel:(NSEvent *)theEvent;
- (void)magnifyWithEvent:(NSEvent *)theEvent;
- (void)keyDown:(NSEvent *)theEvent;
- (void)keyUp:(NSEvent *)theEvent;
- (void)flagsChanged:(NSEvent *)theEvent;
- (NSDragOperation)draggingEntered:(id < NSDraggingInfo >)sender;
- (NSDragOperation)draggingUpdated:(id < NSDraggingInfo >)sender;
- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender;
- (void)draggingExited:(id < NSDraggingInfo >)sender;
- (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)isLocal;
#if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
- (void)insertText:(id)aString replacementRange:(NSRange)replacementRange;
- (void)setMarkedText:(id)aString selectedRange:(NSRange)newSelection replacementRange:(NSRange)replacementRange;
- (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)aRange actualRange:(NSRangePointer)actualRange;
- (NSRect)firstRectForCharacterRange:(NSRange)aRange actualRange:(NSRangePointer)actualRange;
- (NSInteger)windowLevel;
#endif
- (BOOL)did_view_resolution_change;
@end

#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_8
@interface FLViewLayer : FLView // for layer-backed non-GL windows
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_12
< CALayerDelegate >
#endif
{
@public
  CGContextRef layer_data;
}
- (void)displayLayer:(CALayer *)layer;
- (void)viewFrameDidChange;
- (BOOL)wantsLayer;
- (void)dealloc;
- (BOOL)did_view_resolution_change;
@end
#endif //10_8


@implementation FLWindow
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
- (NSPoint)convertBaseToScreen:(NSPoint)aPoint
{
  if (fl_mac_os_version >= 100700) {
    NSRect r = [self convertRectToScreen:NSMakeRect(aPoint.x, aPoint.y, 0, 0)];
    return r.origin;
    }
  else {
    // replaces return [super convertBaseToScreen:aPoint] that may trigger a compiler warning
    typedef NSPoint (*convertIMP)(id, SEL, NSPoint);
    static convertIMP addr = (convertIMP)[NSWindow instanceMethodForSelector:@selector(convertBaseToScreen:)];
    return addr(self, @selector(convertBaseToScreen:), aPoint);
    }
}
#endif

- (FLWindow*)initWithFl_W:(Fl_Window *)flw 
	      contentRect:(NSRect)rect 
		styleMask:(NSUInteger)windowStyle 
{
  self = [super initWithContentRect:rect styleMask:windowStyle backing:NSBackingStoreBuffered defer:NO];
  if (self) {
    w = flw;
    if (fl_mac_os_version >= 100700) {
      // replaces [self setRestorable:NO] that may trigger a compiler warning
      typedef void (*setIMP)(id, SEL, BOOL);
      static setIMP addr = (setIMP)[NSWindow instanceMethodForSelector:@selector(setRestorable:)];
      addr(self, @selector(setRestorable:), NO);
      }
  }
  return self;
}
- (Fl_Window *)getFl_Window;
{
  return w;
}

- (BOOL)canBecomeKeyWindow
{
  if (Fl::modal_ && (Fl::modal_ != w))
    return NO;	// prevent the caption to be redrawn as active on click
		//  when another modal window is currently the key win
  return !(w->tooltip_window() || w->menu_window() || w->parent());
}

- (BOOL)canBecomeMainWindow
{
  if (Fl::modal_ && (Fl::modal_ != w))
    return NO;	// prevent the caption to be redrawn as active on click
		//  when another modal window is currently the key win

  return !(w->tooltip_window() || w->menu_window() || w->parent());
}

- (void)recursivelySendToSubwindows:(SEL)sel
{
  [self performSelector:sel];
  NSEnumerator *enumerator = [[self childWindows] objectEnumerator];
  id child;
  while ((child = [enumerator nextObject]) != nil) {
    if ([child isKindOfClass:[FLWindow class]]) [child recursivelySendToSubwindows:sel];
  }
}

- (void)setSubwindowFrame { // maps a subwindow at its correct position/size
  Fl_Window *parent = w->window();
  if (!parent) return;
  FLWindow *pxid = fl_xid(parent);
  if (!pxid) return;
  int bx = w->x(); int by = w->y();
  while (parent) {
    bx += parent->x();
    by += parent->y();
    parent = parent->window();
  }
  NSRect rp = NSMakeRect(bx, main_screen_height - (by + w->h()), w->w(), w->h());
  if (!NSEqualRects(rp, [self frame])) {
    [self setFrame:rp display:YES];
  }
  if (![self parentWindow]) {
    [pxid addChildWindow:self ordered:NSWindowAbove]; // needs OS X 10.2
    [self orderWindow:NSWindowAbove relativeTo:[pxid windowNumber]]; // necessary under 10.3
  }
}

- (void)checkSubwindowFrame {
  if (![self parentWindow]) return;
  // make sure this subwindow doesn't leak out of its parent window
  Fl_Window *from = w, *parent;
  CGRect full = CGRectMake(0, 0, w->w(), w->h()); // full subwindow area
  CGRect srect = full; // will become new subwindow clip
  int fromx = 0, fromy = 0;
  while ((parent = from->window()) != NULL) { // loop over all parent windows
    fromx -= from->x(); // parent origin in subwindow's coordinates
    fromy -= from->y();
    CGRect prect = CGRectMake(fromx, fromy, parent->w(), parent->h());
    srect = CGRectIntersection(prect, srect); // area of subwindow inside its parent
    from = parent;
  }
  CGRect *r = Fl_X::i(w)->subRect();
  CGRect current_clip = (r ? *r : full); // current subwindow clip
  if (!CGRectEqualToRect(srect, current_clip)) { // if new clip differs from current clip
    delete r;
    [[Fl_X::i(w)->xid contentView] setNeedsDisplay:YES]; // subwindow needs redrawn
    if (CGRectEqualToRect(srect, full)) r = NULL;
    else {
      r = new CGRect(srect);
      if (r->size.width == 0 && r->size.height == 0) r->origin.x = r->origin.y = 0;
    }
    Fl_X::i(w)->subRect(r);
  }
}

-(void)waitForExpose
{
  if ([self getFl_Window]->shown()) {
    // this makes freshly created windows appear on the screen, if they are not there already
    NSModalSession session = [NSApp beginModalSessionForWindow:self];
    [NSApp runModalSession:session];
    [NSApp endModalSession:session];
  }
}

/* With Mac OS 10.11 the green window button makes window fullscreen (covers system menu bar and dock).
 When there are subwindows, they are by default constrained not to cover the menu bar
 (this is arguably a Mac OS bug).
 Overriding the constrainFrameRect:toScreen: method removes this constraint.
 */
- (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen *)screen
{
  if ([self parentWindow]) return frameRect; // do not constrain subwindows
  return [super constrainFrameRect:frameRect toScreen:screen]; // will prevent a window from going above the menu bar
}
@end

@interface FLApplication : NSObject
{
}
+ (void)sendEvent:(NSEvent *)theEvent;
@end

/*
 * This function is the central event handler.
 * It reads events from the event queue using the given maximum time
 * Funny enough, it returns the same time that it got as the argument. 
 */
static double do_queued_events( double time = 0.0 ) 
{
  got_events = 0;
  
  // Check for re-entrant condition
  if ( dataready.IsThreadRunning() ) {
    dataready.CancelThread(DEBUGTEXT("AVOID REENTRY\n"));
  }
  
  // Start thread to watch for data ready
  if ( dataready.GetNfds() ) {
    dataready.StartThread();
  }
  
  fl_unlock_function();
  NSEvent *event = [NSApp nextEventMatchingMask:NSAnyEventMask 
                                      untilDate:[NSDate dateWithTimeIntervalSinceNow:time] 
                                         inMode:NSDefaultRunLoopMode dequeue:YES];  
  if (event != nil) {
    got_events = 1;
    [FLApplication sendEvent:event]; // will then call [NSApplication sendevent:]
  }
  fl_lock_function();
  
#if CONSOLIDATE_MOTION
  if (send_motion && send_motion == fl_xmousewin) {
    send_motion = 0;
    Fl::handle(FL_MOVE, fl_xmousewin);
  }
#endif
  
  return time;
}


/*
 * This public function handles all events. It wait a maximum of 
 * 'time' seconds for an event. This version returns 1 if events
 * other than the timeout timer were processed.
 *
 * \todo there is no socket handling in this code whatsoever
 */
int fl_wait( double time ) 
{
  do_queued_events( time );
  return (got_events);
}

static void drain_dropped_files_list() {
  open_cb_f_type open_cb = get_open_cb();
  if (!open_cb) {
    [dropped_files_list removeAllObjects];
    [dropped_files_list release];
    dropped_files_list = nil;
    return;
  }
  NSString *s = (NSString*)[dropped_files_list objectAtIndex:0];
  char *fname = strdup([s UTF8String]);
  [dropped_files_list removeObjectAtIndex:0];
  if ([dropped_files_list count] == 0) {
    [dropped_files_list release];
    dropped_files_list = nil;
  }
  open_cb(fname);
  free(fname);
}

double fl_mac_flush_and_wait(double time_to_wait) {
  if (dropped_files_list) { // when the list of dropped files is not empty, open one and remove it from list
    drain_dropped_files_list();
  }
  static int in_idle = 0;
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  if (Fl::idle) {
    if (!in_idle) {
      in_idle = 1;
      Fl::idle();
      in_idle = 0;
    }
    // the idle function may turn off idle, we can then wait:
    if (Fl::idle) time_to_wait = 0.0;
  }
  if (fl_mac_os_version < 1011) NSDisableScreenUpdates(); // 10.3 Makes updates to all windows appear as a single event
  Fl::flush();
  if (fl_mac_os_version < 1011) NSEnableScreenUpdates(); // 10.3
  if (Fl::idle && !in_idle) // 'idle' may have been set within flush()
    time_to_wait = 0.0;
  double retval = fl_wait(time_to_wait);
  if (fl_gc) {
    Fl_X::q_release_context();
    }
  [pool release];
  return retval;
}


static NSInteger max_normal_window_level(void)
{
  Fl_X *x;
  NSInteger max_level;

  max_level = 0;

  for (x = Fl_X::first;x;x = x->next) {
    NSInteger level;
    FLWindow *cw = x->xid;
    Fl_Window *win = x->w;
    if (!win || !cw || ![cw isVisible])
      continue;
    if (win->modal() || win->non_modal())
      continue;
    level = [cw level];
    if (level >= max_level)
      max_level = level;
  }

  return max_level;
}

// appropriate window level for modal windows
static NSInteger modal_window_level(void)
{
  NSInteger level;

  level = max_normal_window_level();
  if (level < NSModalPanelWindowLevel)
    return NSModalPanelWindowLevel;

  // Need some room for non-modal windows
  level += 2;

  // We cannot exceed this
  if (level > CGShieldingWindowLevel())
    return CGShieldingWindowLevel();

  return level;
}

// appropriate window level for non-modal windows
static NSInteger non_modal_window_level(void)
{
  NSInteger level;

  level = max_normal_window_level();
  if (level < NSFloatingWindowLevel)
    return NSFloatingWindowLevel;

  level += 1;

  if (level > CGShieldingWindowLevel())
    return CGShieldingWindowLevel();

  return level;
}

// makes sure modal and non-modal windows stay on top
static void fixup_window_levels(void)
{
  NSInteger modal_level, non_modal_level;

  Fl_X *x;
  FLWindow *prev_modal, *prev_non_modal;

  modal_level = modal_window_level();
  non_modal_level = non_modal_window_level();

  prev_modal = NULL;
  prev_non_modal = NULL;

  for (x = Fl_X::first;x;x = x->next) {
    FLWindow *cw = x->xid;
    Fl_Window *win = x->w;
    if (!win || !cw || ![cw isVisible])
      continue;
    if (win->modal()) {
      if ([cw level] != modal_level) {
        [cw setLevel:modal_level];
        // changing level puts then in front, so make sure the
        // stacking isn't messed up
        if (prev_modal != NULL)
          [cw orderWindow:NSWindowBelow
              relativeTo:[prev_modal windowNumber]];
      }
      prev_modal = cw;
    } else if (win->non_modal()) {
      if ([cw level] != non_modal_level) {
        [cw setLevel:non_modal_level];
        if (prev_non_modal != NULL)
          [cw orderWindow:NSWindowBelow
              relativeTo:[prev_non_modal windowNumber]];
      }
      prev_non_modal = cw;
    }
  }
}


// updates Fl::e_x, Fl::e_y, Fl::e_x_root, and Fl::e_y_root
static void update_e_xy_and_e_xy_root(NSWindow *nsw)
{
  NSPoint pt;
  pt = [nsw mouseLocationOutsideOfEventStream];
  Fl::e_x = int(pt.x);
  Fl::e_y = int([[nsw contentView] frame].size.height - pt.y);
  pt = [NSEvent mouseLocation];
  Fl::e_x_root = int(pt.x);
  Fl::e_y_root = int(main_screen_height - pt.y);
}


/*
 * Cocoa Mousewheel handler
 */
static void cocoaMouseWheelHandler(NSEvent *theEvent)
{
  // Handle the new "MightyMouse" mouse wheel events. Please, someone explain
  // to me why Apple changed the API on this even though the current API
  // supports two wheels just fine. Matthias,
  fl_lock_function();
  
  Fl_Window *window = (Fl_Window*)[(FLWindow*)[theEvent window] getFl_Window];
  if ( !window->shown() ) {
    fl_unlock_function();
    return;
  }
  Fl::first_window(window);
  
  // Under OSX, single mousewheel increments are 0.1,
  // so make sure they show up as at least 1..
  //
  float dx = [theEvent deltaX]; if ( fabs(dx) < 1.0 ) dx = (dx > 0) ? 1.0 : -1.0;
  float dy = [theEvent deltaY]; if ( fabs(dy) < 1.0 ) dy = (dy > 0) ? 1.0 : -1.0;
  if ([theEvent deltaX] != 0) {
    Fl::e_dx = (int)-dx;
    Fl::e_dy = 0;
    if ( Fl::e_dx) Fl::handle( FL_MOUSEWHEEL, window );
  } else if ([theEvent deltaY] != 0) {
    Fl::e_dx = 0;
    Fl::e_dy = (int)-dy;
    if ( Fl::e_dy) Fl::handle( FL_MOUSEWHEEL, window );
  } else {
    fl_unlock_function();
    return;
  }
  
  fl_unlock_function();
  
  //  return noErr;
}

/*
 * Cocoa Magnify Gesture Handler
 */
static void cocoaMagnifyHandler(NSEvent *theEvent)
{
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  fl_lock_function();
  Fl_Window *window = (Fl_Window*)[(FLWindow*)[theEvent window] getFl_Window];
  if ( !window->shown() ) {
    fl_unlock_function();
    return;
  }
  Fl::first_window(window);
  Fl::e_dy = [theEvent magnification]*1000; // 10.5.2
  if ( Fl::e_dy) {
    NSPoint pos = [theEvent locationInWindow];
    pos.y = window->h() - pos.y;
    NSUInteger mods = [theEvent modifierFlags];
    mods_to_e_state( mods );
    update_e_xy_and_e_xy_root([theEvent window]);
    Fl::handle( FL_ZOOM_GESTURE, window );
  }
  fl_unlock_function();
#endif
}

/*
 * Cocoa Mouse Button Handler
 */
static void cocoaMouseHandler(NSEvent *theEvent)
{
  static int keysym[] = { 0, FL_Button+1, FL_Button+3, FL_Button+2 };
  static int px, py;
  
  fl_lock_function();
  
  Fl_Window *window = (Fl_Window*)[(FLWindow*)[theEvent window] getFl_Window];
  if ( !window->shown() ) {
    fl_unlock_function();
    return;
  }
  Fl_Window *first = Fl::first_window();
  if (first != window && !(first->modal() || first->non_modal())) Fl::first_window(window);
  NSPoint pos = [theEvent locationInWindow];
  pos.y = window->h() - pos.y;
  NSInteger btn = [theEvent buttonNumber]  + 1;
  NSUInteger mods = [theEvent modifierFlags];  
  int sendEvent = 0;
  
  NSEventType etype = [theEvent type];
  if (etype == NSLeftMouseDown || etype == NSRightMouseDown || etype == NSOtherMouseDown) {
    if (btn == 1) Fl::e_state |= FL_BUTTON1;
    else if (btn == 3) Fl::e_state |= FL_BUTTON2;
    else if (btn == 2) Fl::e_state |= FL_BUTTON3;
  }
  else if (etype == NSLeftMouseUp || etype == NSRightMouseUp || etype == NSOtherMouseUp) {
    if (btn == 1) Fl::e_state &= ~FL_BUTTON1;
    else if (btn == 3) Fl::e_state &= ~FL_BUTTON2;
    else if (btn == 2) Fl::e_state &= ~FL_BUTTON3;
    }
    
  switch ( etype ) {
    case NSLeftMouseDown:
    case NSRightMouseDown:
    case NSOtherMouseDown:
      sendEvent = FL_PUSH;
      Fl::e_is_click = 1; 
      px = (int)pos.x; py = (int)pos.y;
      if ([theEvent clickCount] > 1) 
        Fl::e_clicks++;
      else
        Fl::e_clicks = 0;
      // fall through
    case NSLeftMouseUp:
    case NSRightMouseUp:
    case NSOtherMouseUp:
      if ( !window ) break;
      if ( !sendEvent ) {
        sendEvent = FL_RELEASE; 
      }
      Fl::e_keysym = keysym[ btn ];
      // fall through
    case NSMouseMoved:
      if ( !sendEvent ) {
        sendEvent = FL_MOVE; 
      }
      // fall through
    case NSLeftMouseDragged:
    case NSRightMouseDragged:
    case NSOtherMouseDragged: {
      if ( !sendEvent ) {
        sendEvent = FL_MOVE; // Fl::handle will convert into FL_DRAG
        if (fabs(pos.x-px)>5 || fabs(pos.y-py)>5) 
          Fl::e_is_click = 0;
      }
      mods_to_e_state( mods );
      update_e_xy_and_e_xy_root([theEvent window]);
      Fl::handle( sendEvent, window );
      }
      break;
    default:
      break;
  }
  
  fl_unlock_function();
  
  return;
}

@interface FLTextView : NSTextView // this subclass is only needed under OS X < 10.6 
{
  BOOL isActive;
}
+ (void)initialize;
+ (FLTextView*)singleInstance;
- (void)insertText:(id)aString;
- (void)doCommandBySelector:(SEL)aSelector;
- (void)setActive:(BOOL)a;
@end
static FLTextView *fltextview_instance = nil;
@implementation FLTextView
+ (void)initialize {
  NSRect rect={{0,0},{20,20}};
  fltextview_instance = [[FLTextView alloc] initWithFrame:rect];
}
+ (FLTextView*)singleInstance {
  return fltextview_instance;
}
- (void)insertText:(id)aString
{
  if (isActive) [[[NSApp keyWindow] contentView] insertText:aString];
}
- (void)doCommandBySelector:(SEL)aSelector
{
  [[[NSApp keyWindow] contentView] doCommandBySelector:aSelector];
}
- (void)setActive:(BOOL)a
{
  isActive = a;
}
@end


@interface FLWindowDelegate : NSObject 
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
<NSWindowDelegate>
#endif
+ (void)initialize;
+ (FLWindowDelegate*)singleInstance;
- (void)windowDidMove:(NSNotification *)notif;
- (void)windowDidResize:(NSNotification *)notif;
- (void)windowDidResignKey:(NSNotification *)notif;
- (void)windowDidBecomeKey:(NSNotification *)notif;
- (void)windowDidBecomeMain:(NSNotification *)notif;
- (void)windowDidDeminiaturize:(NSNotification *)notif;
- (void)fl_windowMiniaturize:(NSNotification *)notif;
- (void)windowDidMiniaturize:(NSNotification *)notif;
- (BOOL)windowShouldClose:(id)fl;
- (void)anyWindowWillClose:(NSNotification *)notif;
- (void)doNothing:(id)unused;
@end


/* make subwindows re-appear after appl unhide or window deminiaturize
 (not necessary with 10.5 and above)
 */
static void orderfront_subwindows(FLWindow *xid)
{
  NSArray *children = [xid childWindows]; // 10.2
  NSEnumerator *enumerator = [children objectEnumerator];
  id child;
  while ((child = [enumerator nextObject]) != nil) { // this undo-redo seems necessary under 10.3
    [xid removeChildWindow:child];
    [xid addChildWindow:child ordered:NSWindowAbove];
    [child orderWindow:NSWindowAbove relativeTo:[xid windowNumber]];
    orderfront_subwindows(child);
  }
}

#if FLTK_ABI_VERSION >= 10304
static const unsigned windowDidResize_mask = 1;
#else
static const unsigned long windowDidResize_mask = 1;
#endif

bool Fl_X::in_windowDidResize() {
#if FLTK_ABI_VERSION >= 10304
  return mapped_to_retina_ & windowDidResize_mask;
#else
  return (unsigned long)xidChildren & windowDidResize_mask;
#endif
}

void Fl_X::in_windowDidResize(bool b) {
#if FLTK_ABI_VERSION >= 10304
  if (b) mapped_to_retina_ |= windowDidResize_mask;
  else mapped_to_retina_ &= ~windowDidResize_mask;
#else
  if (b) xidChildren = (Fl_X*)((unsigned long)xidChildren | windowDidResize_mask);
  else xidChildren = (Fl_X*)((unsigned long)xidChildren & ~windowDidResize_mask);
#endif
}

#if FLTK_ABI_VERSION >= 10304
static const unsigned mapped_mask = 2;
static const unsigned changed_mask = 4;
#else
static const unsigned long mapped_mask = 2; // sizeof(unsigned long) = sizeof(Fl_X*)
static const unsigned long changed_mask = 4;
#endif

bool Fl_X::mapped_to_retina() {
#if FLTK_ABI_VERSION >= 10304
  return mapped_to_retina_ & mapped_mask;
#else
  return (unsigned long)xidChildren & mapped_mask;
#endif
}

void Fl_X::mapped_to_retina(bool b) {
#if FLTK_ABI_VERSION >= 10304
  if (b) mapped_to_retina_ |= mapped_mask;
  else mapped_to_retina_ &= ~mapped_mask;
#else
  if (b) xidChildren = (Fl_X*)((unsigned long)xidChildren | mapped_mask);
  else xidChildren = (Fl_X*)((unsigned long)xidChildren & ~mapped_mask);
#endif
}

bool Fl_X::changed_resolution() {
#if FLTK_ABI_VERSION >= 10304
  return mapped_to_retina_ & changed_mask;
#else
  return (unsigned long)xidChildren & changed_mask;
#endif
}

void Fl_X::changed_resolution(bool b) {
#if FLTK_ABI_VERSION >= 10304
  if (b) mapped_to_retina_ |= changed_mask;
  else mapped_to_retina_ &= ~changed_mask;
#else
  if (b) xidChildren = (Fl_X*)((unsigned long)xidChildren | changed_mask);
  else xidChildren = (Fl_X*)((unsigned long)xidChildren & ~changed_mask);
#endif
}


@interface FLWindowDelegateBefore10_6 : FLWindowDelegate
- (id)windowWillReturnFieldEditor:(NSWindow *)sender toObject:(id)client;
@end
@implementation FLWindowDelegateBefore10_6
- (id)windowWillReturnFieldEditor:(NSWindow *)sender toObject:(id)client
{
  return [FLTextView singleInstance];
}
@end

@interface FLWindowDelegateBefore10_5 : FLWindowDelegateBefore10_6
-(void)windowDidDeminiaturize:(NSNotification *)notif;
-(void)windowWillMiniaturize:(NSNotification *)notif;
@end
@implementation FLWindowDelegateBefore10_5
-(void)windowDidDeminiaturize:(NSNotification *)notif
{
  [super windowDidDeminiaturize:notif];
  fl_lock_function();
  orderfront_subwindows([notif object]);
  fl_unlock_function();
}
-(void)windowWillMiniaturize:(NSNotification *)notif
{
  [super fl_windowMiniaturize:notif];
  NSArray *children = [(NSWindow*)[notif object] childWindows]; // 10.2
  NSEnumerator *enumerator = [children objectEnumerator];
  id child;
  while ((child = [enumerator nextObject]) != nil) [child orderOut:self];
}
@end

static FLWindowDelegate *flwindowdelegate_instance = nil;
@implementation FLWindowDelegate
+ (void)initialize
{
  if (self == [FLWindowDelegate self]) {
    if (fl_mac_os_version < 100500) flwindowdelegate_instance = [FLWindowDelegateBefore10_5 alloc];
    else if (fl_mac_os_version < 100600) flwindowdelegate_instance = [FLWindowDelegateBefore10_6 alloc];
    else flwindowdelegate_instance = [FLWindowDelegate alloc];
    flwindowdelegate_instance = [flwindowdelegate_instance init];
  }
}
+ (FLWindowDelegate*)singleInstance {
  return flwindowdelegate_instance;
}
- (void)windowDidMove:(NSNotification *)notif
{
  FLWindow *nsw = (FLWindow*)[notif object];
  Fl_Window *window = [nsw getFl_Window];
  // don't process move for a subwindow of a miniaturized top window
  if (window->parent() && [fl_xid(window->top_window()) isMiniaturized]) return;
  fl_lock_function();
  resize_from_system = window;
  NSPoint pt2;
  pt2 = [nsw convertBaseToScreen:NSMakePoint(0, [[nsw contentView] frame].size.height)];
  update_e_xy_and_e_xy_root(nsw);
  pt2.y = main_screen_height - pt2.y;
  Fl_Window *parent = window->window();
  while (parent) {
    pt2.x -= parent->x();
    pt2.y -= parent->y();
    parent = parent->window();
  }
  window->position((int)pt2.x, (int)pt2.y);
  if (fl_mac_os_version < 100700) { // after move, redraw parent and children of GL windows
    parent = window->window();
    if (parent && parent->as_gl_window()) window->redraw();
    if (parent && window->as_gl_window()) parent->redraw();
  }
  resize_from_system = NULL;
  // at least since MacOS 10.10: OS sends windowDidMove to parent window and then to children
  // FLTK sets position of parent and children. setSubwindowFrame is no longer necessary.
  if (fl_mac_os_version < 101000) [nsw recursivelySendToSubwindows:@selector(setSubwindowFrame)];
  [nsw checkSubwindowFrame];
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_8
  FLView *view = (FLView*)[nsw contentView];
  if ([view layer]) [view did_view_resolution_change];
#endif
  fl_unlock_function();
}
- (void)windowDidResize:(NSNotification *)notif
{
  FLWindow *nsw = (FLWindow*)[notif object];
  if (![nsw isVisible]) return;
  fl_lock_function();
  Fl_Window *window = [nsw getFl_Window];
  NSRect r; NSPoint pt2;
  r = [[nsw contentView] frame];
  pt2 = [nsw convertBaseToScreen:NSMakePoint(0, r.size.height)];
  pt2.y = main_screen_height - pt2.y;
  Fl_Window *parent = window->window();
  while (parent) {
    pt2.x -= parent->x();
    pt2.y -= parent->y();
    parent = parent->window();
  }
  resize_from_system = window;
  if (window->as_gl_window() && Fl_X::i(window)) Fl_X::i(window)->in_windowDidResize(true);
  update_e_xy_and_e_xy_root(nsw);
  window->resize((int)pt2.x, (int)pt2.y, (int)r.size.width, (int)r.size.height);
  [nsw recursivelySendToSubwindows:@selector(setSubwindowFrame)];
  [nsw recursivelySendToSubwindows:@selector(checkSubwindowFrame)];
  if (window->as_gl_window() && Fl_X::i(window)) Fl_X::i(window)->in_windowDidResize(false);
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_8
  if (views_use_CA && !window->as_gl_window()) [(FLViewLayer*)[nsw contentView] viewFrameDidChange];
#endif
  fl_unlock_function();
}
- (void)windowDidResignKey:(NSNotification *)notif
{
  fl_lock_function();
  FLWindow *nsw = (FLWindow*)[notif object];
  Fl_Window *window = [nsw getFl_Window];
  /* Fullscreen windows obscure all other windows so we need to return
   to a "normal" level when the user switches to another window,
   unless this other window is above the fullscreen window */
  if (window->fullscreen_active() && [NSApp keyWindow] && [[NSApp keyWindow] level] <= [nsw level]) {
    [nsw setLevel:NSNormalWindowLevel];
    fixup_window_levels();
  }
  Fl::handle( FL_UNFOCUS, window);
  fl_unlock_function();
}
- (void)windowDidBecomeKey:(NSNotification *)notif
{
  fl_lock_function();
  FLWindow *nsw = (FLWindow*)[notif object];
  Fl_Window *w = [nsw getFl_Window];
  /* Restore previous fullscreen level */
  if (w->fullscreen_active()) {
    [nsw setLevel:NSStatusWindowLevel];
    fixup_window_levels();
  }
  Fl::handle( FL_FOCUS, w);
  fl_unlock_function();
}
- (void)windowDidBecomeMain:(NSNotification *)notif
{
  fl_lock_function();
  FLWindow *nsw = (FLWindow*)[notif object];
  Fl_Window *window = [nsw getFl_Window];
  Fl::first_window(window);
  update_e_xy_and_e_xy_root(nsw);
  fl_unlock_function();
}
- (void)windowDidDeminiaturize:(NSNotification *)notif
{
  fl_lock_function();
  FLWindow *nsw = (FLWindow*)[notif object];
  if ([nsw miniwindowImage]) { [nsw setMiniwindowImage:nil]; }
  Fl_Window *window = [nsw getFl_Window];
  [nsw recursivelySendToSubwindows:@selector(setSubwindowFrame)];
  Fl::handle(FL_SHOW, window);
  update_e_xy_and_e_xy_root(nsw);
  Fl::flush(); // Process redraws set by FL_SHOW.
  fl_unlock_function();
}
- (void)fl_windowMiniaturize:(NSNotification *)notif
{ // Same as windowWillMiniaturize before 10.5,
  // and called by windowDidMiniaturize after 10.5.
  // Subwindows are not captured in system-built miniature window image
  fl_lock_function();
  FLWindow *nsw = (FLWindow*)[notif object];
  if ([[nsw childWindows] count]) {
    // capture the window and its subwindows and use as miniature window image
    Fl_Window *window = [nsw getFl_Window];
    NSBitmapImageRep *bitmap = rect_to_NSBitmapImageRep(window, 0, 0, window->w(), window->h());
    NSImage *img = [[[NSImage alloc] initWithSize:NSMakeSize([bitmap pixelsWide], [bitmap pixelsHigh])] autorelease];
    [img addRepresentation:bitmap];
    [bitmap release];
    [nsw setMiniwindowImage:img];
  }
  fl_unlock_function();
}
- (void)windowDidMiniaturize:(NSNotification *)notif
{
  if (fl_mac_os_version >= 100500) [self fl_windowMiniaturize:notif];
  fl_lock_function();
  FLWindow *nsw = (FLWindow*)[notif object];
  Fl_Window *window = [nsw getFl_Window];
  Fl::handle(FL_HIDE, window);
  fl_unlock_function();
}
- (BOOL)windowShouldClose:(id)fl
{
  fl_lock_function();
  Fl::handle( FL_CLOSE, [(FLWindow *)fl getFl_Window] ); // this might or might not close the window
  fl_unlock_function();
  // the system doesn't need to send [fl close] because FLTK does it when needed
  return NO; 
}
- (void)anyWindowWillClose:(NSNotification *)notif
{
  fl_lock_function();
  if ([[notif object] isKeyWindow]) {
    // If the closing window is the key window,
    // find a bordered top-level window to become the new key window
    Fl_Window *w = Fl::first_window();
    while (w && (w->parent() || !w->border() || !w->visible())) {
      w = Fl::next_window(w);
    }
    if (w) {
      [Fl_X::i(w)->xid makeKeyWindow];
    }
  }
  fl_unlock_function();
}
- (void)doNothing:(id)unused
{
  return;
}
@end

@interface FLAppDelegate : NSObject 
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
<NSApplicationDelegate>
#endif
{
  @public
  open_cb_f_type open_cb;
  TSMDocumentID currentDoc;
}
- (void)applicationDidFinishLaunching:(NSNotification *)notification;
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication*)sender;
- (void)applicationDidBecomeActive:(NSNotification *)notify;
- (void)applicationDidChangeScreenParameters:(NSNotification *)aNotification;
- (void)applicationDidUpdate:(NSNotification *)aNotification;
- (void)applicationWillResignActive:(NSNotification *)notify;
- (void)applicationWillHide:(NSNotification *)notify;
- (void)applicationWillUnhide:(NSNotification *)notify;
- (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename;
@end
@implementation FLAppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)notification
{
  if (fl_mac_os_version >= 101300 && [NSApp isRunning]) [NSApp stop:nil];
}
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication*)sender
{
  fl_lock_function();
  NSApplicationTerminateReply reply = (fl_mac_quit_early ? NSTerminateNow : NSTerminateCancel);
  while ( Fl_X::first ) {
    Fl_Window *win = Fl::first_window();
    if (win->parent()) win = win->top_window();
    Fl_Widget_Tracker wt(win); // track the window object
    Fl::handle(FL_CLOSE, win);
    if (wt.exists() && win->shown()) { // the user didn't close win
      reply = NSTerminateCancel; // so we return to the main program now
      break;
    }
  }
  fl_unlock_function();
  return reply;
}
- (void)applicationDidBecomeActive:(NSNotification *)notify
{
  fl_lock_function();

  // update clipboard status
  clipboard_check();

  /**
   * Cocoa organizes the Z depth of windows on a global priority. FLTK however
   * expects the window manager to organize Z level by application. The trickery
   * below will change Z order during activation and deactivation.
   */
  fixup_window_levels();

  fl_unlock_function();
}
- (void)applicationDidChangeScreenParameters:(NSNotification *)unused
{ // react to changes in screen numbers and positions
  fl_lock_function();
  main_screen_height = [[[NSScreen screens] objectAtIndex:0] frame].size.height;
  Fl::call_screen_init();
  // FLTK windows have already been notified they were moved,
  // but they had the old main_screen_height, so they must be notified again.
  NSArray *windows = [NSApp windows];
  int count = [windows count];
  for (int i = 0; i < count; i++) {
    NSWindow *win = [windows objectAtIndex:i];
    if ([win isKindOfClass:[FLWindow class]] && ![win parentWindow] && [win isVisible]) {
      [[NSNotificationCenter defaultCenter] postNotificationName:NSWindowDidMoveNotification object:win];
      }
    }
  Fl::handle(FL_SCREEN_CONFIGURATION_CHANGED, NULL);
  fl_unlock_function();
}
- (void)applicationDidUpdate:(NSNotification *)aNotification
{
  if (im_enabled != -1) {
    TSMDocumentID newDoc;
    // It is extremely unclear when Cocoa decides to create/update
    // the input context, but debugging reveals that it is done
    // by NSApplication:updateWindows. So check if the input context
    // has shifted after each such run so that we can update our
    // input methods status.
    newDoc = TSMGetActiveDocument();
    if (newDoc != currentDoc) {
      TSMDocumentID doc;
    
      doc = TSMGetActiveDocument();
      
      if (im_enabled)
        TSMRemoveDocumentProperty(doc, kTSMDocumentEnabledInputSourcesPropertyTag);
      else {
        CFArrayRef inputSources;
        
        inputSources = TISCreateASCIICapableInputSourceList();
        TSMSetDocumentProperty(doc, kTSMDocumentEnabledInputSourcesPropertyTag,
                               sizeof(CFArrayRef), &inputSources);
        CFRelease(inputSources);
      }
      currentDoc = newDoc;
    }
  }
}
- (void)applicationWillResignActive:(NSNotification *)notify
{
  fl_lock_function();
  Fl_X *x;
  FLWindow *top = 0;
  // sort in all regular windows
  for (x = Fl_X::first;x;x = x->next) {
    FLWindow *cw = x->xid;
    Fl_Window *win = x->w;
    if (win && cw) {
      if (win->modal()) {
      } else if (win->non_modal()) {
      } else {
        if (!top) top = cw;
      }
    }
  }
  // now sort in all modals
  for (x = Fl_X::first;x;x = x->next) {
    FLWindow *cw = x->xid;
    Fl_Window *win = x->w;
    if (win && cw && [cw isVisible]) {
      if (win->modal()) {
        [cw setLevel:NSNormalWindowLevel];
        if (top) [cw orderWindow:NSWindowAbove relativeTo:[top windowNumber]];
      }
    }
  }
  // finally all non-modals
  for (x = Fl_X::first;x;x = x->next) {
    FLWindow *cw = x->xid;
    Fl_Window *win = x->w;
    if (win && cw && [cw isVisible]) {
      if (win->non_modal()) {
        [cw setLevel:NSNormalWindowLevel];
        if (top) [cw orderWindow:NSWindowAbove relativeTo:[top windowNumber]];
      }
    }
  }
  fl_unlock_function();
}
- (void)applicationWillHide:(NSNotification *)notify
{
  fl_lock_function();
  Fl_X *x;
  for (x = Fl_X::first;x;x = x->next) {
    Fl_Window *window = x->w;
    if ( !window->parent() ) Fl::handle( FL_HIDE, window);
    }
  fl_unlock_function();
}
- (void)applicationWillUnhide:(NSNotification *)notify
{
  fl_lock_function();
  for (Fl_X *x = Fl_X::first;x;x = x->next) {
    Fl_Window *w = x->w;
    if ( !w->parent() && ![x->xid isMiniaturized]) {
      Fl::handle(FL_SHOW, w);
      }
  }
  fl_unlock_function();
}
- (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename
{
  if (fl_mac_os_version < 101300) {
    // without the next two statements, the opening of the 1st window is delayed by several seconds
    // under 10.8 ≤ Mac OS < 10.13 when a file is dragged on the application icon
    Fl_Window *firstw = Fl::first_window();
    if (firstw) firstw->wait_for_expose();
  } else if (in_nsapp_run) { // memorize all dropped filenames
    if (!dropped_files_list) dropped_files_list = [[NSMutableArray alloc] initWithCapacity:1];
    [dropped_files_list addObject:filename];
    return YES;
  }
  if (open_cb) {
    fl_lock_function();
    (*open_cb)([filename UTF8String]);
    Fl::flush(); // useful for AppleScript that does not break the event loop
    fl_unlock_function();
    return YES;
  }
  return NO;
}
@end

@interface FLAppDelegateBefore10_5 : FLAppDelegate
- (void)applicationDidUnhide:(NSNotification *)notify;
- (void)applicationDidUpdate:(NSNotification *)aNotification;
@end
@implementation FLAppDelegateBefore10_5
- (void)applicationDidUnhide:(NSNotification *)notify
{ // before 10.5, subwindows are lost when application is unhidden
  fl_lock_function();
  for (Fl_X *x = Fl_X::first; x; x = x->next) {
    if (![x->xid parentWindow]) {
      orderfront_subwindows(x->xid);
    }
  }
  fl_unlock_function();
}
- (void)applicationDidUpdate:(NSNotification *)aNotification
{
}
@end

static open_cb_f_type get_open_cb() {
  return ((FLAppDelegate*)[NSApp delegate])->open_cb;
}

/*
 * Install an open documents event handler...
 */
void fl_open_callback(void (*cb)(const char *)) {
  fl_open_display();
  ((FLAppDelegate*)[NSApp delegate])->open_cb = cb;
}

@implementation FLApplication
+ (void)sendEvent:(NSEvent *)theEvent
{
  if (fl_send_system_handlers(theEvent))
    return;

  NSEventType type = [theEvent type];  
  if (type == NSLeftMouseDown) {
    fl_lock_function();
    Fl_Window *grab = Fl::grab();
    if (grab) {
      FLWindow *win = (FLWindow *)[theEvent window];
      if ( [win isKindOfClass:[FLWindow class]] && grab != [win getFl_Window]) {
	// a click event out of a menu window, so we should close this menu
	// done here to catch also clicks on window title bar/resize box 
	cocoaMouseHandler(theEvent);
      }
    }
    fl_unlock_function();
  } else if (type == NSApplicationDefined) {
    if ([theEvent subtype] == FLTKDataReadyEvent) {
      processFLTKEvent();
    }
    return;
  } else if (type == NSKeyUp) {
    // The default sendEvent turns key downs into performKeyEquivalent when
    // modifiers are down, but swallows the key up if the modifiers include
    // command.  This one makes all modifiers consistent by always sending key ups.
    // FLView treats performKeyEquivalent to keyDown, but performKeyEquivalent is
    // still needed for the system menu.
    [[NSApp keyWindow] sendEvent:theEvent];
    return;
    }
  [NSApp sendEvent:theEvent]; 
}
@end

static BOOL is_bundled() {
  static int value = 2;
  if (value == 2) {
    value = 1;
    NSBundle *bundle = [NSBundle mainBundle];
    if (bundle) {
      NSString *exe = [[bundle executablePath] stringByStandardizingPath];
      NSString *bpath = [bundle bundlePath];
      NSString *exe_dir = [exe stringByDeletingLastPathComponent];
      if ([bpath isEqualToString:exe] || [bpath isEqualToString:exe_dir]) value = 0;
    } else value = 0;
  }
  return value == 1;
}

/* Prototype of undocumented function needed to support Mac OS 10.2 or earlier
 extern "C" {
 OSErr CPSEnableForegroundOperation(ProcessSerialNumber*, UInt32, UInt32, UInt32, UInt32);
 }
 */
static void foreground_and_activate() {
  if ( !is_bundled() ) { // only transform the application type for unbundled apps
    ProcessSerialNumber cur_psn = { 0, kCurrentProcess };
    TransformProcessType(&cur_psn, kProcessTransformToForegroundApplication); // needs Mac OS 10.3
    /* support of Mac OS 10.2 or earlier used this undocumented call instead
     err = CPSEnableForegroundOperation(&cur_psn, 0x03, 0x3C, 0x2C, 0x1103);
     */
  }
  [NSApp activateIgnoringOtherApps:YES];
}

void fl_open_display() {
  static char beenHereDoneThat = 0;
  if ( !beenHereDoneThat ) {
    beenHereDoneThat = 1;
    
    BOOL need_new_nsapp = (NSApp == nil);
    if (need_new_nsapp) [NSApplication sharedApplication];
    NSAutoreleasePool *localPool;
    localPool = [[NSAutoreleasePool alloc] init]; // never released
    FLAppDelegate *delegate = (fl_mac_os_version < 100500 ? [FLAppDelegateBefore10_5 alloc] : [FLAppDelegate alloc]);
    [(NSApplication*)NSApp setDelegate:[delegate init]];
    if (need_new_nsapp) {
      if (fl_mac_os_version >= 101300 && is_bundled()) {
        [NSApp activateIgnoringOtherApps:YES];
        in_nsapp_run = true;
        [NSApp run];
        in_nsapp_run = false;
      }
      else [NSApp finishLaunching];
    }
    // empty the event queue but keep system events for drag&drop of files at launch
    NSEvent *ign_event;
    do ign_event = [NSApp nextEventMatchingMask:(NSAnyEventMask & ~NSSystemDefinedMask)
					untilDate:[NSDate dateWithTimeIntervalSinceNow:0] 
					   inMode:NSDefaultRunLoopMode 
					  dequeue:YES];
    while (ign_event);
    
    if (![NSApp isActive]) foreground_and_activate();
    if (![NSApp servicesMenu]) createAppleMenu();
    main_screen_height = [[[NSScreen screens] objectAtIndex:0] frame].size.height;
    [[NSNotificationCenter defaultCenter] addObserver:[FLWindowDelegate singleInstance]
					     selector:@selector(anyWindowWillClose:) 
						 name:NSWindowWillCloseNotification 
					       object:nil];
    if (![NSThread isMultiThreaded]) {
      // With old OS X versions, it is necessary to create one thread for secondary pthreads to be
      // allowed to use cocoa, especially to create an NSAutoreleasePool.
      // We create a thread that does nothing so it completes very fast:
      [NSThread detachNewThreadSelector:@selector(doNothing:) toTarget:[FLWindowDelegate singleInstance] withObject:nil];
    }
  }
}


/*
 * get rid of allocated resources
 */
void fl_close_display() {
}

// Force a "Roman" or "ASCII" keyboard, which both the Mozilla and
// Safari people seem to think implies turning off advanced IME stuff
// (see nsTSMManager::SyncKeyScript in Mozilla and enableSecureTextInput
// in Safari/Webcore). Should be good enough for us then...

static int input_method_startup()
{
  static int retval = -1; // -1: not initialized, 0: not usable, 1: ready for use
  if (retval == -1) {
    fl_open_display();
    if (fl_mac_os_version >= 100500) {
      TSMGetActiveDocument = (TSMGetActiveDocument_type)Fl_X::get_carbon_function("TSMGetActiveDocument");
      TSMSetDocumentProperty = (TSMSetDocumentProperty_type)Fl_X::get_carbon_function("TSMSetDocumentProperty");
      TSMRemoveDocumentProperty = (TSMRemoveDocumentProperty_type)Fl_X::get_carbon_function("TSMRemoveDocumentProperty");
      TISCreateASCIICapableInputSourceList = (TISCreateASCIICapableInputSourceList_type)Fl_X::get_carbon_function("TISCreateASCIICapableInputSourceList");
      retval = (TSMGetActiveDocument && TSMSetDocumentProperty && TSMRemoveDocumentProperty && TISCreateASCIICapableInputSourceList ? 1 : 0);
    } else {
      KeyScript = (KeyScript_type)Fl_X::get_carbon_function("KeyScript");
      retval = (KeyScript? 1 : 0);
    }
  }
  return retval;
}

void Fl::enable_im() {
  if (!input_method_startup()) return;

  im_enabled = 1;

  if (fl_mac_os_version >= 100500) {
    ((FLAppDelegate*)[NSApp delegate])->currentDoc = NULL;
    [NSApp updateWindows]; // triggers [FLAppDelegate applicationDidUpdate]
  }
  else
    KeyScript(smKeyEnableKybds);
}

void Fl::disable_im() {
  if (!input_method_startup()) return;

  im_enabled = 0;

  if (fl_mac_os_version >= 100500) {
    ((FLAppDelegate*)[NSApp delegate])->currentDoc = NULL;
    [NSApp updateWindows]; // triggers [FLAppDelegate applicationDidUpdate]
  }
  else
    KeyScript(smEnableRomanKybdsOnly);
}


// Gets the border sizes and the titlebar size
static void get_window_frame_sizes(int &bx, int &by, int &bt) {
  static bool first = true;
  static int top, left, bottom;
  if (first) {
    first = false;
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSRect inside = { {20,20}, {100,100} };
    NSRect outside = [NSWindow  frameRectForContentRect:inside styleMask:NSTitledWindowMask];
    left = int(outside.origin.x - inside.origin.x);
    bottom = int(outside.origin.y - inside.origin.y);
    top = int(outside.size.height - inside.size.height) - bottom;
    [pool release];
    }
  bx = left;
  by = bottom;
  bt = top;
}

/*
 * smallest x coordinate in screen space of work area of menubar-containing display
 */
int Fl::x() {
  return int([[[NSScreen screens] objectAtIndex:0] visibleFrame].origin.x);
}


/*
 * smallest y coordinate in screen space of work area of menubar-containing display
 */
int Fl::y() {
  fl_open_display();
  NSRect visible = [[[NSScreen screens] objectAtIndex:0] visibleFrame];
  return int(main_screen_height - (visible.origin.y + visible.size.height));
}


/*
 * width of work area of menubar-containing display
 */
int Fl::w() {
  return int([[[NSScreen screens] objectAtIndex:0] visibleFrame].size.width);
}


/*
 * height of work area of menubar-containing display
 */
int Fl::h() {
  return int([[[NSScreen screens] objectAtIndex:0] visibleFrame].size.height);
}

// computes the work area of the nth screen (screen #0 has the menubar)
void Fl_X::screen_work_area(int &X, int &Y, int &W, int &H, int n)
{
  fl_open_display();
  NSRect r = [[[NSScreen screens] objectAtIndex:n] visibleFrame];
  X   = int(r.origin.x);
  Y   = main_screen_height - int(r.origin.y + r.size.height);
  W   = int(r.size.width);
  H   = int(r.size.height);
}

/*
 * get the current mouse pointer world coordinates
 */
void Fl::get_mouse(int &x, int &y) 
{
  fl_open_display();
  NSPoint pt = [NSEvent mouseLocation];
  x = int(pt.x);
  y = int(main_screen_height - pt.y);
}


/*
 * Gets called when a window is created or resized, or moved into/out a retina display
 * (with Mac OS 10.11 also when deminiaturized)
 */    
static void handleUpdateEvent( Fl_Window *window ) 
{
  if ( !window ) return;
  Fl_X *i = Fl_X::i( window );
  [(FLView*)[fl_xid(window) contentView] did_view_resolution_change];
  i->wait_for_expose = 0;
  if ( i->region ) {
    XDestroyRegion(i->region);
    i->region = 0;
  }
  window->clear_damage(FL_DAMAGE_ALL);
  i->flush();
  window->clear_damage();
}     


int Fl_X::fake_X_wm(const Fl_Window* w,int &X,int &Y, int &bt,int &bx, int &by) {
  int W, H, xoff, yoff, dx, dy;
  int ret = bx = by = bt = 0;
  if (w->border() && !w->parent()) {
    if (w->maxw != w->minw || w->maxh != w->minh) {
      ret = 2;
    } else {
      ret = 1;
    }
    get_window_frame_sizes(bx, by, bt);
  }
  // The coordinates of the whole window, including non-client area
  xoff = bx;
  yoff = by + bt;
  dx = 2*bx;
  dy = 2*by + bt;
  X = w->x()-xoff;
  Y = w->y()-yoff;
  W = w->w()+dx;
  H = w->h()+dy;
  
  if (w->parent()) return 0;
  
  // Proceed to positioning the window fully inside the screen, if possible
  
  // let's get a little elaborate here. Mac OS X puts a lot of stuff on the desk
  // that we want to avoid when positioning our window, namely the Dock and the
  // top menu bar (and even more stuff in 10.4 Tiger). So we will go through the
  // list of all available screens and find the one that this window is most
  // likely to go to, and then reposition it to fit withing the 'good' area.
  //  Rect r;
  // find the screen, that the center of this window will fall into
  int R = X+W, B = Y+H; // right and bottom
  int cx = (X+R)/2, cy = (Y+B)/2; // center of window;
  NSScreen *gd = NULL;
  NSArray *a = [NSScreen screens]; int count = (int)[a count]; NSRect r; int i;
  for( i = 0; i < count; i++) {
    r = [[a objectAtIndex:i] frame];
    r.origin.y = main_screen_height - (r.origin.y + r.size.height); // use FLTK's multiscreen coordinates
    if (   cx >= r.origin.x && cx <= r.origin.x + r.size.width
        && cy >= r.origin.y && cy <= r.origin.y + r.size.height)
      break;
  }
  if (i < count) gd = [a objectAtIndex:i];
  
  // if the center doesn't fall on a screen, try the top left
  if (!gd) {
    for( i = 0; i < count; i++) {
      r = [[a objectAtIndex:i] frame];
      r.origin.y = main_screen_height - (r.origin.y + r.size.height); // use FLTK's multiscreen coordinates
      if (    X >= r.origin.x && X <= r.origin.x + r.size.width
          && Y >= r.origin.y  && Y <= r.origin.y + r.size.height)
        break;
    }
    if (i < count) gd = [a objectAtIndex:i];
  }
  // if that doesn't fall on a screen, try the top right
  if (!gd) {
    for( i = 0; i < count; i++) {
      r = [[a objectAtIndex:i] frame];
      r.origin.y = main_screen_height - (r.origin.y + r.size.height); // use FLTK's multiscreen coordinates
      if (    R >= r.origin.x && R <= r.origin.x + r.size.width
          && Y >= r.origin.y  && Y <= r.origin.y + r.size.height)
        break;
    }
    if (i < count) gd = [a objectAtIndex:i];
  }
  // if that doesn't fall on a screen, try the bottom left
  if (!gd) {
    for( i = 0; i < count; i++) {
      r = [[a objectAtIndex:i] frame];
      r.origin.y = main_screen_height - (r.origin.y + r.size.height); // use FLTK's multiscreen coordinates
      if (    X >= r.origin.x && X <= r.origin.x + r.size.width
          && Y+H >= r.origin.y  && Y+H <= r.origin.y + r.size.height)
        break;
    }
    if (i < count) gd = [a objectAtIndex:i];
  }
  // last resort, try the bottom right
  if (!gd) {
    for( i = 0; i < count; i++) {
      r = [[a objectAtIndex:i] frame];
      r.origin.y = main_screen_height - (r.origin.y + r.size.height); // use FLTK's multiscreen coordinates
      if (    R >= r.origin.x && R <= r.origin.x + r.size.width
          && Y+H >= r.origin.y  && Y+H <= r.origin.y + r.size.height)
        break;
    }
    if (i < count) gd = [a objectAtIndex:i];
  }
  // if we still have not found a screen, we will use the main
  // screen, the one that has the application menu bar.
  if (!gd) gd = [a objectAtIndex:0];
  if (gd) {
    r = [gd visibleFrame];
    r.origin.y = main_screen_height - (r.origin.y + r.size.height); // use FLTK's multiscreen coordinates
    if ( R > r.origin.x + r.size.width ) X -= int(R - (r.origin.x + r.size.width));
    if ( B > r.size.height + r.origin.y ) Y -= int(B - (r.size.height + r.origin.y));
    if ( X < r.origin.x ) X = int(r.origin.x);
    if ( Y < r.origin.y ) Y = int(r.origin.y);
  }
  
  // Return the client area's top left corner in (X,Y)
  X+=xoff;
  Y+=yoff;
  
  return ret;
}


Fl_Window *fl_dnd_target_window = 0;

static void  q_set_window_title(NSWindow *nsw, const char * name, const char *mininame) {
  CFStringRef title = CFStringCreateWithCString(NULL, (name ? name : ""), kCFStringEncodingUTF8);
  if(!title) { // fallback when name contains malformed UTF-8
    int l = strlen(name);
    unsigned short* utf16 = new unsigned short[l + 1];
    l = fl_utf8toUtf16(name, l, utf16, l + 1);
    title = CFStringCreateWithCharacters(NULL, utf16, l);
    delete[] utf16;
    }
  [nsw setTitle:(NSString*)title];
  CFRelease(title);
  if (mininame && strlen(mininame)) {
    CFStringRef minititle = CFStringCreateWithCString(NULL, mininame, kCFStringEncodingUTF8);
    if (minititle) {
      [nsw setMiniwindowTitle:(NSString*)minititle];
      CFRelease(minititle);
    }
  }
}

/**                 How FLTK handles Mac OS text input
 
 Let myview be the instance of the FLView class that has the keyboard focus. FLView is an FLTK-defined NSView subclass
 that implements the NSTextInputClient protocol to properly handle text input. It also implements the old NSTextInput
 protocol to run with OS <= 10.4. The few NSTextInput protocol methods that differ in signature from the NSTextInputClient 
 protocol transmit the received message to the corresponding NSTextInputClient method.

 Keyboard input sends keyDown: and performKeyEquivalent: messages to myview. The latter occurs for keys such as
 ForwardDelete, arrows and F1, and when the Ctrl or Cmd modifiers are used. Other key presses send keyDown: messages.
 The keyDown: method calls [myview process_keydown:theEvent] that is equivalent to
 [[myview inputContext] handleEvent:theEvent], and triggers system processing of keyboard events.
 The performKeyEquivalent: method directly calls Fl::handle(FL_KEYBOARD, focus-window)
 when the Ctrl or Cmd modifiers are used. If not, it also calls [[myview inputContext] handleEvent:theEvent].
 The performKeyEquivalent: method returns YES when the keystroke has been handled and NO otherwise, which allows
 shortcuts of the system menu to be processed. Three sorts of messages are then sent back by the system to myview: 
 doCommandBySelector:, setMarkedText: and insertText:. All 3 messages eventually produce Fl::handle(FL_KEYBOARD, win) calls.
 The doCommandBySelector: message allows to process events such as new-line, forward and backward delete, arrows, 
 escape, tab, F1. The message setMarkedText: is sent when marked text, that is, temporary text that gets replaced later 
 by some other text, is inserted. This happens when a dead key is pressed, and also 
 when entering complex scripts (e.g., Chinese). Fl_X::next_marked_length gives the byte
 length of marked text before the FL_KEYBOARD event is processed. Fl::compose_state gives this length after this processing.
 Message insertText: is sent to enter text in the focused widget. If there's marked text, Fl::compose_state is > 0, and this
 marked text gets replaced by the inserted text. If there's no marked text, the new text is inserted at the insertion point. 
 When the character palette is used to enter text, the system sends an insertText: message to myview. 
 The in_key_event field of the FLView class allows to differentiate keyboard from palette inputs.
 
 During processing of the handleEvent message, inserted and marked strings are concatenated in a single string
 inserted in a single FL_KEYBOARD event after return from handleEvent. The need_handle member variable of FLView allows 
 to determine when setMarkedText or insertText strings have been sent during handleEvent processing and must trigger 
 an FL_KEYBOARD event. Concatenating two insertText operations or an insertText followed by a setMarkedText is possible. 
 In contrast, setMarkedText followed by insertText or by another setMarkedText isn't correct if concatenated in a single 
 string. Thus, in such case, the setMarkedText and the next operation produce each an FL_KEYBOARD event. 
 
 OS >= 10.7 contains a feature where pressing and holding certain keys opens a menu window that shows a list 
 of possible accented variants of this key. The selectedRange field of the FLView class and the selectedRange, insertText:
 and setMarkedText: methods of the NSTextInputClient protocol are used to support this feature.
 The notion of selected text (!= marked text) is monitored by the selectedRange field. 
 The -(NSRange)[FLView selectedRange] method is used to control whether an FLTK widget opens accented character windows 
 by returning .location = NSNotFound to disable that, or returning the value of the selectedRange field to enable the feature.
 When selectedRange.location >= 0, the value of selectedRange.length is meaningful. 0 means no text is currently selected, 
 > 0 means this number of characters before the insertion point are selected. The insertText: method does
 selectedRange = NSMakeRange(100, 0); to indicate no text is selected. The setMarkedText: method does   
 selectedRange = NSMakeRange(100, newSelection.length); to indicate that this length of text is selected.

 With OS <= 10.5, the NSView class does not implement the inputContext message. [myview process_keydown:theEvent] is
 equivalent to [[FLTextInputContext singleInstance] handleEvent:theEvent].
 Method +[FLTextInputContext singleInstance] returns an instance of class FLTextInputContext that possesses
 a handleEvent: method. The class FLTextView implements the so-called view's "field editor". This editor is an instance
 of the FLTextView class allocated by the -(id)[FLWindowDelegate windowWillReturnFieldEditor: toObject:] method.
 The -(BOOL)[FLTextInputContext handleEvent:] method emulates the missing 10.6 -(BOOL)[NSTextInputContext handleEvent:]
 by sending the interpretKeyEvents: message to the FLTextView object. The system sends back doCommandBySelector: and
 insertText: messages to the FLTextView object that are transmitted unchanged to myview to be processed as with OS >= 10.6. 
 The system also sends setMarkedText: messages directly to myview.
   
 There is furthermore an oddity of dead key processing with OS <= 10.5. It occurs when a dead key followed by a non-accented  
 key are pressed. Say, for example, that keys '^' followed by 'p' are pressed on a French or German keyboard. Resulting 
 messages are: [myview setMarkedText:@"^"], [myview insertText:@"^"], [myview insertText:@"p"], [FLTextView insertText:@"^p"]. 
 The 2nd '^' replaces the marked 1st one, followed by p^p. The resulting text in the widget is "^p^p" instead of the 
 desired "^p". To avoid that, the FLTextView object is deactivated by the insertText: message and reactivated after 
 the handleEvent: message has been processed.

 NSEvent's during a character composition sequence:
 - keyDown with deadkey -> [[theEvent characters] length] is 0
 - keyUp -> [theEvent characters] contains the deadkey
 - keyDown with next key -> [theEvent characters] contains the composed character
 - keyUp -> [theEvent characters] contains the standard character
 */

static void cocoaKeyboardHandler(NSEvent *theEvent)
{
  NSUInteger mods;
  // get the modifiers
  mods = [theEvent modifierFlags];
  // get the key code
  UInt32 keyCode = 0, maskedKeyCode = 0;
  unsigned short sym = 0;
  keyCode = [theEvent keyCode];
  // extended keyboards can also send sequences on key-up to generate Kanji etc. codes.
  // Some observed prefixes are 0x81 to 0x83, followed by an 8 bit keycode.
  // In this mode, there seem to be no key-down codes
  // printf("%08x %08x %08x\n", keyCode, mods, key);
  maskedKeyCode = keyCode & 0x7f;
  mods_to_e_state( mods ); // process modifier keys
  if (!macKeyLookUp) macKeyLookUp = fl_compute_macKeyLookUp();
  sym = macKeyLookUp[maskedKeyCode];
  if (sym < 0xff00) { // a "simple" key
    // find the result of this key without modifier
    NSString *sim = [theEvent charactersIgnoringModifiers];
    UniChar one;
    CFStringGetCharacters((CFStringRef)sim, CFRangeMake(0, 1), &one);
    // charactersIgnoringModifiers doesn't ignore shift, remove it when it's on
    if(one >= 'A' && one <= 'Z') one += 32;
    if (one > 0 && one <= 0x7f && (sym<'0' || sym>'9') ) sym = one;
  }
  Fl::e_keysym = Fl::e_original_keysym = sym;
  /*NSLog(@"cocoaKeyboardHandler: keycode=%08x keysym=%08x mods=%08x symbol=%@ (%@)",
   keyCode, sym, mods, [theEvent characters], [theEvent charactersIgnoringModifiers]);*/
  // If there is text associated with this key, it will be filled in later.
  Fl::e_length = 0;
  Fl::e_text = (char*)"";
}

@interface FLTextInputContext : NSObject // "emulates" NSTextInputContext before OS 10.6
+ (void)initialize;
+ (FLTextInputContext*)singleInstance;
-(BOOL)handleEvent:(NSEvent*)theEvent;
@end
static FLTextInputContext* fltextinputcontext_instance = nil;
@implementation FLTextInputContext
+ (void)initialize {
  fltextinputcontext_instance = [[FLTextInputContext alloc] init];
}
+ (FLTextInputContext*)singleInstance {
  return fltextinputcontext_instance;
}
-(BOOL)handleEvent:(NSEvent*)theEvent {
  FLTextView *edit = [FLTextView singleInstance];
  [edit setActive:YES];
  [edit interpretKeyEvents:[NSArray arrayWithObject:theEvent]];
  [edit setActive:YES];
  return YES;
}
@end

/* Implementation note for the support of layer-backed views.
 MacOS 10.14 Mojave changes the way all drawing to displays is performed:
 all NSView objects become layer-backed, that is, the drawing is done by
 Core Animation to a CALayer object whose content is then displayed by the NSView.
 The global variable views_use_CA is set to YES when such change applies,
 that is, for apps running under 10.14 and linked to SDK 10.14.
 When views_use_CA is NO, views are not supposed to be layer-backed.
 
 Each layer-backed non-OpenGL window has a single FLViewLayer object which itself has an associated CALayer.
 FLViewLayer implements displayLayer:. Consequently, FLViewLayer objects are drawn
 by the displayLayer: method. An FLViewLayer manages also a member variable
 CGContextRef layer_data, a bitmap context the size of the view (double on Retina).
 All Quartz drawings go to this bitmap. updateLayer finishes by using an image copy
 of the bitmap as the layer's contents. That step fills the window.
 FLViewLayer implements viewFrameDidChange which deletes the bitmap and zeros layer_data.
 This ensures the bitmap is recreated when the window is resized.
 viewFrameDidChange is also called when the window flips between low/high resolution displays.
 
 Each layer-backed OpenGL window has an associated FLGLViewLayer object, derived from FLView.
 FLGLViewLayer objects are drawn by the displayLayer: method which calls drawRect:
 which draws the GL scene.
 */

#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_8
static CGContextRef prepare_bitmap_for_layer(int w, int h ) {
  CGColorSpaceRef cspace = CGColorSpaceCreateDeviceRGB();
  CGContextRef gc = CGBitmapContextCreate(NULL,  w,  h, 8, 4 * w, cspace, kCGImageAlphaPremultipliedFirst);
  CGColorSpaceRelease(cspace);
  CGContextClearRect(gc, CGRectMake(0,0,w,h));
  return gc;
}

@interface FLGLViewLayer : FLView // for layer-backed GL windows
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_12
< CALayerDelegate >
#endif
- (void)displayLayer:(CALayer *)layer;
- (void)drawRect:(NSRect)rect;
- (BOOL)wantsLayer;
- (BOOL)did_view_resolution_change;
@end

@implementation FLGLViewLayer
- (void)displayLayer:(CALayer *)layer {
  [self drawRect:[self frame]];
}
- (void)drawRect:(NSRect)rect {
  fl_lock_function();
  Fl_Window *window = [(FLWindow*)[self window] getFl_Window];
  Fl_X *i = Fl_X::i( window );
  if (!Fl::use_high_res_GL() && fl_mac_os_version < 101401) [self layer].contentsScale = 1.;
  [self did_view_resolution_change];
  window->clear_damage(FL_DAMAGE_ALL);
  i->flush();
  window->clear_damage();
  if (window->parent() && fl_mac_os_version < 101401) window->redraw(); // useful during resize of GL subwindow
  fl_unlock_function();
}
-(BOOL)wantsLayer {
  return YES;
}
- (BOOL)did_view_resolution_change {
  BOOL retval = [super did_view_resolution_change];
  if (retval && Fl::use_high_res_GL()) {
    Fl_Window *window = [(FLWindow*)[self window] getFl_Window];
    Fl_X *i = Fl_X::i( window );
    [self layer].contentsScale = i->mapped_to_retina() ? 2. : 1.;
    window->redraw(); // necessary with 10.14.2 public beta 3
  }
  return retval;
}
@end


@implementation FLViewLayer
- (BOOL)wantsLayer {
  return YES;
}
- (void)displayLayer:(CALayer *)layer {
  // called if views are layered (but not for GL) : all drawing to window goes through this
  Fl_Window *window = [(FLWindow*)[self window] getFl_Window];
  Fl_X *i = Fl_X::i( window );
  if (!layer_data) { // runs when window is created, resized, changed screen resolution
    NSRect r = [self frame];
    layer.bounds = NSRectToCGRect(r);
    [self did_view_resolution_change];
    i->wait_for_expose = 0;
    if (i->mapped_to_retina()) {
      r.size.width *= 2; r.size.height *= 2;
      layer.contentsScale = 2.;
    } else layer.contentsScale = 1.;
    layer_data = prepare_bitmap_for_layer(r.size.width, r.size.height);
    Fl_X *i = Fl_X::i(window);
    if ( i->region ) {
      XDestroyRegion(i->region);
      i->region = 0;
    }
    window->clear_damage(FL_DAMAGE_ALL);
  }
  if (window->damage()) {
    through_drawRect = YES;
    i->flush();
    Fl_X::q_release_context();
    through_drawRect = NO;
    window->clear_damage();
    if (layer_data) {
      CGImageRef cgimg = CGBitmapContextCreateImage(layer_data);  // requires 10.4
      layer.contents = (id)cgimg;
      CGImageRelease(cgimg);
    }
  }
}
- (BOOL)did_view_resolution_change {
  BOOL retval = [super did_view_resolution_change];
  if (retval) {
    [self viewFrameDidChange];
    [self displayLayer:[self layer]]; // useful for Mandelbrot to recreate the layer's bitmap
  }
  return retval;
}
-(void)viewFrameDidChange
{
  CGContextRelease(layer_data);
  layer_data = NULL;
}
-(void)dealloc {
  CGContextRelease(layer_data);
  [super dealloc];
}
@end
#endif //>= MAC_OS_X_VERSION_10_8

@implementation FLView
- (BOOL)did_view_resolution_change {
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
  if (fl_mac_os_version >= 100700) { // determine whether window is mapped to a retina display
    Fl_Window *window = [(FLWindow*)[self window] getFl_Window];
    Fl_X *i = Fl_X::i( window );
    bool previous = i->mapped_to_retina();
    NSSize s = [self convertSizeToBacking:NSMakeSize(10, 10)]; // 10.7
    i->mapped_to_retina( int(s.width + 0.5) > 10 );
    BOOL retval = (i->wait_for_expose == 0 && previous != i->mapped_to_retina());
    if (retval) i->changed_resolution(true);
    return retval;
  }
#endif
  return NO;
}

- (BOOL)process_keydown:(NSEvent*)theEvent
{
  id o = fl_mac_os_version >= 100600 ? [self performSelector:@selector(inputContext)] : [FLTextInputContext singleInstance];
  return [o handleEvent:theEvent];
}
- (id)initWithFrame:(NSRect)frameRect
{
  static NSInteger counter = 0;
  self = [super initWithFrame:frameRect];
  if (self) {
    in_key_event = NO;
    identifier = ++counter;
    }
  return self;
}
- (void)drawRect:(NSRect)rect
{
  fl_lock_function();
  FLWindow *cw = (FLWindow*)[self window];
  Fl_Window *w = [cw getFl_Window];
  through_drawRect = YES;
  handleUpdateEvent(w);
  through_drawRect = NO;
  fl_unlock_function();
}

- (BOOL)acceptsFirstResponder
{   
  return [[self window] parentWindow] ? NO : YES; // 10.2
}
- (BOOL)performKeyEquivalent:(NSEvent*)theEvent
{   
  //NSLog(@"performKeyEquivalent:");
  fl_lock_function();
  cocoaKeyboardHandler(theEvent);
  BOOL handled;
  NSUInteger mods = [theEvent modifierFlags];
  Fl_Window *w = [(FLWindow*)[theEvent window] getFl_Window];
  if ( (mods & NSControlKeyMask) || (mods & NSCommandKeyMask) ) {
    NSString *s = [theEvent characters];
    if ( (mods & NSShiftKeyMask) && (mods & NSCommandKeyMask) ) {
      s = [s uppercaseString]; // US keyboards return lowercase letter in s if cmd-shift-key is hit
      }
    [FLView prepareEtext:s];
    Fl::compose_state = 0;
    handled = Fl::handle(FL_KEYBOARD, w);
  }
  else {
    in_key_event = YES;
    need_handle = NO;
    handled = [self process_keydown:theEvent];
    if (need_handle) handled = Fl::handle(FL_KEYBOARD, w);
    in_key_event = NO;
    }
  fl_unlock_function();
  return handled;
}
- (BOOL)acceptsFirstMouse:(NSEvent*)theEvent
{   
  Fl_Window *w = [(FLWindow*)[theEvent window] getFl_Window];
  Fl_Window *first = Fl::first_window();
  return (first == w || !first->modal());
}
- (void)resetCursorRects {
  Fl_Window *w = [(FLWindow*)[self window] getFl_Window];
  Fl_X *i = Fl_X::i(w);
  if (!i) return;  // fix for STR #3128
  // We have to have at least one cursor rect for invalidateCursorRectsForView
  // to work, hence the "else" clause.
  if (i->cursor)
    [self addCursorRect:[self visibleRect] cursor:(NSCursor*)i->cursor];
  else
    [self addCursorRect:[self visibleRect] cursor:[NSCursor arrowCursor]];
}
- (void)mouseUp:(NSEvent *)theEvent {
  cocoaMouseHandler(theEvent);
}
- (void)rightMouseUp:(NSEvent *)theEvent {
  cocoaMouseHandler(theEvent);
}
- (void)otherMouseUp:(NSEvent *)theEvent {
  cocoaMouseHandler(theEvent);
}
- (void)mouseDown:(NSEvent *)theEvent {
  cocoaMouseHandler(theEvent);
}
- (void)rightMouseDown:(NSEvent *)theEvent {
  cocoaMouseHandler(theEvent);
}
- (void)otherMouseDown:(NSEvent *)theEvent {
  cocoaMouseHandler(theEvent);
}
- (void)mouseMoved:(NSEvent *)theEvent {
  cocoaMouseHandler(theEvent);
}
- (void)mouseDragged:(NSEvent *)theEvent {
  cocoaMouseHandler(theEvent);
}
- (void)rightMouseDragged:(NSEvent *)theEvent {
  cocoaMouseHandler(theEvent);
}
- (void)otherMouseDragged:(NSEvent *)theEvent {
  cocoaMouseHandler(theEvent);
}
- (void)scrollWheel:(NSEvent *)theEvent {
  cocoaMouseWheelHandler(theEvent);
}
- (void)magnifyWithEvent:(NSEvent *)theEvent {
  cocoaMagnifyHandler(theEvent);
}
- (void)keyDown:(NSEvent *)theEvent {
  //NSLog(@"keyDown:%@",[theEvent characters]);
  fl_lock_function();
  Fl_Window *window = [(FLWindow*)[theEvent window] getFl_Window];
  Fl::first_window(window);
  cocoaKeyboardHandler(theEvent);
  in_key_event = YES;
  Fl_Widget *f = Fl::focus();
  if (f && f->as_gl_window()) { // ignore text input methods for GL windows
    need_handle = YES;
    [FLView prepareEtext:[theEvent characters]];
  } else {
    need_handle = NO;
    [self process_keydown:theEvent];
  }
  if (need_handle) Fl::handle(FL_KEYBOARD, window);
  in_key_event = NO;
  fl_unlock_function();
}
- (void)keyUp:(NSEvent *)theEvent {
  //NSLog(@"keyUp:%@",[theEvent characters]);
  fl_lock_function();
  Fl_Window *window = (Fl_Window*)[(FLWindow*)[theEvent window] getFl_Window];
  Fl::first_window(window);
  cocoaKeyboardHandler(theEvent);
  NSString *s = [theEvent characters];
  if ([s length] >= 1) [FLView prepareEtext:[s substringToIndex:1]];
  Fl::handle(FL_KEYUP,window);
  fl_unlock_function();
}
- (void)flagsChanged:(NSEvent *)theEvent {
  //NSLog(@"flagsChanged: ");
  fl_lock_function();
  static UInt32 prevMods = 0;
  NSUInteger mods = [theEvent modifierFlags];
  Fl_Window *window = (Fl_Window*)[(FLWindow*)[theEvent window] getFl_Window];
  UInt32 tMods = prevMods ^ mods;
  int sendEvent = 0;
  if ( tMods )
  {
    unsigned short keycode = [theEvent keyCode];
    if (!macKeyLookUp) macKeyLookUp = fl_compute_macKeyLookUp();
    Fl::e_keysym = Fl::e_original_keysym = macKeyLookUp[keycode & 0x7f];
    if ( Fl::e_keysym ) 
      sendEvent = ( prevMods<mods ) ? FL_KEYBOARD : FL_KEYUP;
    Fl::e_length = 0;
    Fl::e_text = (char*)"";
    prevMods = mods;
  }
  mods_to_e_state( mods );
  if (sendEvent) Fl::handle(sendEvent,window);
  fl_unlock_function();
}
- (NSDragOperation)draggingEntered:(id < NSDraggingInfo >)sender
{
  fl_lock_function();
  Fl_Window *target = [(FLWindow*)[self window] getFl_Window];
  update_e_xy_and_e_xy_root([self window]);
  fl_dnd_target_window = target;
  int ret = Fl::handle( FL_DND_ENTER, target );
  breakMacEventLoop();
  fl_unlock_function();
  Fl::flush();
  return ret ? NSDragOperationCopy : NSDragOperationNone;
}
- (NSDragOperation)draggingUpdated:(id < NSDraggingInfo >)sender
{
  fl_lock_function();
  Fl_Window *target = [(FLWindow*)[self window] getFl_Window];
  update_e_xy_and_e_xy_root([self window]);
  fl_dnd_target_window = target;
  int ret = Fl::handle( FL_DND_DRAG, target );
  breakMacEventLoop();
  fl_unlock_function();
  // if the DND started in the same application, Fl::dnd() will not return until 
  // the the DND operation is finished. The call below causes the drop indicator
  // to be draw correctly (a full event handling would be better...)
  Fl::flush();
  return ret ? NSDragOperationCopy : NSDragOperationNone;
}
- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender 
{
  static char *DragData = NULL;
  fl_lock_function();
  Fl_Window *target = [(FLWindow*)[self window] getFl_Window];
  if ( !Fl::handle( FL_DND_RELEASE, target ) ) { 
    breakMacEventLoop();
    fl_unlock_function();
    return NO;
  }
  NSPasteboard *pboard;
  // NSDragOperation sourceDragMask;
  // sourceDragMask = [sender draggingSourceOperationMask];
  pboard = [sender draggingPasteboard];
  update_e_xy_and_e_xy_root([self window]);
  if (DragData) { free(DragData); DragData = NULL; }
  if ( [[pboard types] containsObject:NSFilenamesPboardType] ) {
    CFArrayRef files = (CFArrayRef)[pboard propertyListForType:NSFilenamesPboardType];
    CFStringRef all = CFStringCreateByCombiningStrings(NULL, files, CFSTR("\n"));
    int l = CFStringGetMaximumSizeForEncoding(CFStringGetLength(all), kCFStringEncodingUTF8);
    DragData = (char *)malloc(l + 1);
    CFStringGetCString(all, DragData, l + 1, kCFStringEncodingUTF8);
    CFRelease(all);
  }
  else if ( [[pboard types] containsObject:UTF8_pasteboard_type] ) {
    NSData *data = [pboard dataForType:UTF8_pasteboard_type];
    DragData = (char *)malloc([data length] + 1);
    [data getBytes:DragData];
    DragData[[data length]] = 0;
    convert_crlf(DragData, strlen(DragData));
  }
  else {
    breakMacEventLoop();
    fl_unlock_function();
    return NO;
  }
  Fl::e_text = DragData;
  Fl::e_length = strlen(DragData);
  int old_event = Fl::e_number;
  Fl::belowmouse()->handle(Fl::e_number = FL_PASTE);
  Fl::e_number = old_event;
  if (DragData) { free(DragData); DragData = NULL; }
  Fl::e_text = NULL;
  Fl::e_length = 0;
  fl_dnd_target_window = NULL;
  breakMacEventLoop();
  fl_unlock_function();
  return YES;
}
- (void)draggingExited:(id < NSDraggingInfo >)sender
{
  fl_lock_function();
  if ( fl_dnd_target_window ) {
    Fl::handle( FL_DND_LEAVE, fl_dnd_target_window );
    fl_dnd_target_window = 0;
  }
  fl_unlock_function();
}
- (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)isLocal
{
  return NSDragOperationGeneric;
}

+ (void)prepareEtext:(NSString*)aString {
  // fills Fl::e_text with UTF-8 encoded aString using an adequate memory allocation
  static char *received_utf8 = NULL;
  static int lreceived = 0;
  char *p = (char*)[aString UTF8String];
  int l = strlen(p);
  if (l > 0) {
    if (lreceived == 0) {
      received_utf8 = (char*)malloc(l + 1);
      lreceived = l;
    }
    else if (l > lreceived) {
      received_utf8 = (char*)realloc(received_utf8, l + 1);
      lreceived = l;
    }
    strcpy(received_utf8, p);
    Fl::e_text = received_utf8;
  }
  Fl::e_length = l;
}

+ (void)concatEtext:(NSString*)aString {
  // extends Fl::e_text with aString
  NSString *newstring = [[NSString stringWithUTF8String:Fl::e_text] stringByAppendingString:aString];
  [FLView prepareEtext:newstring];
}

- (void)doCommandBySelector:(SEL)aSelector {
  NSString *s = [[NSApp currentEvent] characters];
  //NSLog(@"doCommandBySelector:%s text='%@'",sel_getName(aSelector), s);
  s = [s substringFromIndex:[s length] - 1];
  [FLView prepareEtext:s]; // use the last character of the event; necessary for deadkey + Tab
  Fl_Window *target = [(FLWindow*)[self window] getFl_Window];
  Fl::handle(FL_KEYBOARD, target);
}

- (void)insertText:(id)aString {
  [self insertText:aString replacementRange:NSMakeRange(NSNotFound, 0)];
}

- (void)insertText:(id)aString replacementRange:(NSRange)replacementRange {
  NSString *received;
  if ([aString isKindOfClass:[NSAttributedString class]]) {
    received = [(NSAttributedString*)aString string];
  } else {
    received = (NSString*)aString;
  }
  /*NSLog(@"insertText='%@' l=%d Fl::compose_state=%d range=%d,%d",
	received,strlen([received UTF8String]),Fl::compose_state,replacementRange.location,replacementRange.length);*/
  fl_lock_function();
  Fl_Window *target = [(FLWindow*)[self window] getFl_Window];
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  if (fl_mac_os_version >= 101400 && replacementRange.length > 0) {
    // occurs after a key was pressed and maintained and an auxiliary window appeared
    // prevents marking dead key from deactivation
    [[self inputContext] discardMarkedText];
  }
#endif
  while (replacementRange.length--) { // delete replacementRange.length characters before insertion point
    int saved_keysym = Fl::e_keysym;
    Fl::e_keysym = FL_BackSpace;
    Fl::handle(FL_KEYBOARD, target);
    Fl::e_keysym = saved_keysym;
    }
  if (in_key_event && Fl_X::next_marked_length && Fl::e_length) {
    // if setMarkedText + insertText is sent during handleEvent, text cannot be concatenated in single FL_KEYBOARD event
    Fl::handle(FL_KEYBOARD, target);
    Fl::e_length = 0;
    }
  if (in_key_event && Fl::e_length) [FLView concatEtext:received];
  else [FLView prepareEtext:received];
  Fl_X::next_marked_length = 0;
  // We can get called outside of key events (e.g., from the character palette, from CJK text input). 
  BOOL palette = !(in_key_event || Fl::compose_state);
  if (palette) Fl::e_keysym = 0;
  // YES if key has text attached
  BOOL has_text_key = Fl::e_keysym <= '~' || Fl::e_keysym == FL_Iso_Key ||
                      (Fl::e_keysym >= FL_KP && Fl::e_keysym <= FL_KP_Last && Fl::e_keysym != FL_KP_Enter);
  // insertText sent during handleEvent of a key without text cannot be processed in a single FL_KEYBOARD event.
  // Occurs with deadkey followed by non-text key
  if (!in_key_event || !has_text_key) {
    Fl::handle(FL_KEYBOARD, target);
    Fl::e_length = 0;
    }
  else need_handle = YES;
  selectedRange = NSMakeRange(100, 0); // 100 is an arbitrary value
  // for some reason, with the palette, the window does not redraw until the next mouse move or button push
  // sending a 'redraw()' or 'awake()' does not solve the issue!
  if (palette) Fl::flush();
  if (fl_mac_os_version < 100600) [[FLTextView singleInstance] setActive:NO];
  fl_unlock_function();
}

- (void)setMarkedText:(id)aString selectedRange:(NSRange)newSelection  {
  [self setMarkedText:aString selectedRange:newSelection replacementRange:NSMakeRange(NSNotFound, 0)];
}

- (void)setMarkedText:(id)aString selectedRange:(NSRange)newSelection replacementRange:(NSRange)replacementRange {
  NSString *received;
  if ([aString isKindOfClass:[NSAttributedString class]]) {
    received = [(NSAttributedString*)aString string];
  } else {
    received = (NSString*)aString;
  }
  fl_lock_function();
  /*NSLog(@"setMarkedText:%@ l=%d newSelection=%d,%d Fl::compose_state=%d replacement=%d,%d", 
	received, strlen([received UTF8String]), newSelection.location, newSelection.length, Fl::compose_state,
	replacementRange.location, replacementRange.length);*/
  Fl_Window *target = [(FLWindow*)[self window] getFl_Window];
  while (replacementRange.length--) { // delete replacementRange.length characters before insertion point
    Fl::e_keysym = FL_BackSpace;
    Fl::compose_state = 0;
    Fl_X::next_marked_length = 0;
    Fl::handle(FL_KEYBOARD, target);
    Fl::e_keysym = 'a'; // pretend a letter key was hit
  }
  if (in_key_event && Fl_X::next_marked_length && Fl::e_length) {
    // if setMarkedText + setMarkedText is sent during handleEvent, text cannot be concatenated in single FL_KEYBOARD event
    Fl::handle(FL_KEYBOARD, target);
    Fl::e_length = 0;
  }
  if (in_key_event && Fl::e_length) [FLView concatEtext:received];
  else [FLView prepareEtext:received];
  Fl_X::next_marked_length = strlen([received UTF8String]);
  if (!in_key_event) Fl::handle( FL_KEYBOARD, target);
  else need_handle = YES;
  selectedRange = NSMakeRange(100, newSelection.length);
  fl_unlock_function();
}

- (void)unmarkText {
  fl_lock_function();
  Fl::reset_marked_text();
  fl_unlock_function();
  //NSLog(@"unmarkText");
}

- (NSRange)selectedRange {
  Fl_Widget *w = Fl::focus();
  if (w && w->use_accents_menu()) return selectedRange;
  return NSMakeRange(NSNotFound, 0);
}

- (NSRange)markedRange {
  //NSLog(@"markedRange=%d %d", Fl::compose_state > 0?0:NSNotFound, Fl::compose_state);
  return NSMakeRange(Fl::compose_state > 0?0:NSNotFound, Fl::compose_state);
}

- (BOOL)hasMarkedText {
  //NSLog(@"hasMarkedText %s", Fl::compose_state > 0?"YES":"NO");
  return (Fl::compose_state > 0);
}

- (NSAttributedString *)attributedSubstringFromRange:(NSRange)aRange {
  return [self attributedSubstringForProposedRange:aRange actualRange:NULL];
}
- (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)aRange actualRange:(NSRangePointer)actualRange {
  //NSLog(@"attributedSubstringFromRange: %d %d",aRange.location,aRange.length);
  return nil;
}

- (NSArray *)validAttributesForMarkedText {
  return nil;
}

- (NSRect)firstRectForCharacterRange:(NSRange)aRange {
  return [self firstRectForCharacterRange:aRange actualRange:NULL];
}
- (NSRect)firstRectForCharacterRange:(NSRange)aRange actualRange:(NSRangePointer)actualRange {
  //NSLog(@"firstRectForCharacterRange %d %d actualRange=%p",aRange.location, aRange.length,actualRange);
  NSRect glyphRect;
  fl_lock_function();
  Fl_Widget *focus = Fl::focus();
  Fl_Window *wfocus = [(FLWindow*)[self window] getFl_Window];
  if (!focus) focus = wfocus;
  glyphRect.size.width = 0;
  
  int x, y, height;
  if (Fl_X::insertion_point_location(&x, &y, &height)) {
    glyphRect.origin.x = (CGFloat)x;
    glyphRect.origin.y = (CGFloat)y;
  } else {
    if (focus->as_window()) {
      glyphRect.origin.x = 0;
      glyphRect.origin.y = focus->h();
      }
    else {
      glyphRect.origin.x = focus->x();
      glyphRect.origin.y = focus->y() + focus->h();
      }
    height = 12;
  }
  glyphRect.size.height = height;
  Fl_Window *win = focus->as_window();
  if (!win) win = focus->window();
  while (win != NULL && win != wfocus) {
    glyphRect.origin.x += win->x();
    glyphRect.origin.y += win->y();
    win = win->window();
  }
  // Convert the rect to screen coordinates
  glyphRect.origin.y = wfocus->h() - glyphRect.origin.y;
  glyphRect.origin = [(FLWindow*)[self window] convertBaseToScreen:glyphRect.origin];
  if (actualRange) *actualRange = aRange;
  fl_unlock_function();
  return glyphRect;
}

- (NSUInteger)characterIndexForPoint:(NSPoint)aPoint {
  return 0;
}

- (NSInteger)windowLevel {
  return [[self window] level];
}

- (
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
   NSInteger
#else
   long
#endif
)conversationIdentifier {
  return identifier;
}
@end


NSOpenGLPixelFormat* Fl_X::mode_to_NSOpenGLPixelFormat(int m, const int *alistp)
{
  NSOpenGLPixelFormatAttribute attribs[32];
  int n = 0;
  // AGL-style code remains commented out for comparison
  if (!alistp) {
    if (m & FL_INDEX) {
      //list[n++] = AGL_BUFFER_SIZE; list[n++] = 8;
    } else {
      //list[n++] = AGL_RGBA;
      //list[n++] = AGL_GREEN_SIZE;
      //list[n++] = (m & FL_RGB8) ? 8 : 1;
      attribs[n++] = NSOpenGLPFAColorSize;
      attribs[n++] = (NSOpenGLPixelFormatAttribute)((m & FL_RGB8) ? 32 : 1);
      if (m & FL_ALPHA) {
        //list[n++] = AGL_ALPHA_SIZE;
        attribs[n++] = NSOpenGLPFAAlphaSize;
        attribs[n++] = (NSOpenGLPixelFormatAttribute)((m & FL_RGB8) ? 8 : 1);
      }
      if (m & FL_ACCUM) {
        //list[n++] = AGL_ACCUM_GREEN_SIZE; list[n++] = 1;
        attribs[n++] = NSOpenGLPFAAccumSize;
        attribs[n++] = (NSOpenGLPixelFormatAttribute)1;
        if (m & FL_ALPHA) {
          //list[n++] = AGL_ACCUM_ALPHA_SIZE; list[n++] = 1;
        }
      }
    }
    if (m & FL_DOUBLE) {
      //list[n++] = AGL_DOUBLEBUFFER;
      attribs[n++] = NSOpenGLPFADoubleBuffer;
    }
    if (m & FL_DEPTH) {
      //list[n++] = AGL_DEPTH_SIZE; list[n++] = 24;
      attribs[n++] = NSOpenGLPFADepthSize;
      attribs[n++] = (NSOpenGLPixelFormatAttribute)24;
    }
    if (m & FL_STENCIL) {
      //list[n++] = AGL_STENCIL_SIZE; list[n++] = 1;
      attribs[n++] = NSOpenGLPFAStencilSize;
      attribs[n++] = (NSOpenGLPixelFormatAttribute)1;
    }
    if (m & FL_STEREO) {
      //list[n++] = AGL_STEREO;
      attribs[n++] = NSOpenGLPFAStereo;
    }
    if ((m & FL_MULTISAMPLE) && fl_mac_os_version >= 100400) {
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4
      attribs[n++] = NSOpenGLPFAMultisample, // 10.4
#endif
      attribs[n++] = NSOpenGLPFASampleBuffers; attribs[n++] = (NSOpenGLPixelFormatAttribute)1;
      attribs[n++] = NSOpenGLPFASamples; attribs[n++] = (NSOpenGLPixelFormatAttribute)4;
    }
#if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7
#define NSOpenGLPFAOpenGLProfile      (NSOpenGLPixelFormatAttribute)99
#define kCGLPFAOpenGLProfile          NSOpenGLPFAOpenGLProfile
#define NSOpenGLProfileVersionLegacy  (NSOpenGLPixelFormatAttribute)0x1000
#define NSOpenGLProfileVersion3_2Core  (NSOpenGLPixelFormatAttribute)0x3200
#define kCGLOGLPVersion_Legacy        NSOpenGLProfileVersionLegacy
#endif
    if (fl_mac_os_version >= 100700) {
      attribs[n++] = NSOpenGLPFAOpenGLProfile;
      attribs[n++] =  (m & FL_OPENGL3) ? NSOpenGLProfileVersion3_2Core : NSOpenGLProfileVersionLegacy;
    }
  } else {
    while (alistp[n] && n < 30) {
      if (alistp[n] == kCGLPFAOpenGLProfile) {
        if (fl_mac_os_version < 100700) {
          if (alistp[n+1] != kCGLOGLPVersion_Legacy) return nil;
          n += 2;
          continue;
        }
      }
      attribs[n] = (NSOpenGLPixelFormatAttribute)alistp[n];
      n++;
    }
  }
  attribs[n] = (NSOpenGLPixelFormatAttribute)0;
  NSOpenGLPixelFormat *pixform = [[NSOpenGLPixelFormat alloc] initWithAttributes:attribs];
  /*GLint color,alpha,accum,depth;
  [pixform getValues:&color forAttribute:NSOpenGLPFAColorSize forVirtualScreen:0];
  [pixform getValues:&alpha forAttribute:NSOpenGLPFAAlphaSize forVirtualScreen:0];
  [pixform getValues:&accum forAttribute:NSOpenGLPFAAccumSize forVirtualScreen:0];
  [pixform getValues:&depth forAttribute:NSOpenGLPFADepthSize forVirtualScreen:0];
  NSLog(@"color=%d alpha=%d accum=%d depth=%d",color,alpha,accum,depth);*/
  return pixform;
}

NSOpenGLContext* Fl_X::create_GLcontext_for_window(NSOpenGLPixelFormat *pixelformat,
                                              NSOpenGLContext *shared_ctx, Fl_Window *window)
{
  NSOpenGLContext *context = [[NSOpenGLContext alloc] initWithFormat:pixelformat shareContext:shared_ctx];
  if (context) {
    NSView *view = [fl_xid(window) contentView];
    if (fl_mac_os_version >= 100700 && Fl::use_high_res_GL()) {
      //replaces  [view setWantsBestResolutionOpenGLSurface:YES]  without compiler warning
      typedef void (*bestResolutionIMP)(id, SEL, BOOL);
      static bestResolutionIMP addr = (bestResolutionIMP)[NSView instanceMethodForSelector:@selector(setWantsBestResolutionOpenGLSurface:)];
      addr(view, @selector(setWantsBestResolutionOpenGLSurface:), YES);
    }
    [context setView:view];
  }
  return context;
}

void Fl_X::GLcontext_update(NSOpenGLContext* ctxt)
{
  [ctxt update];
}

void Fl_X::GLcontext_flushbuffer(NSOpenGLContext* ctxt)
{
  [ctxt flushBuffer];
}

void Fl_X::GLcontext_release(NSOpenGLContext* ctxt)
{
  [ctxt release];
}

void Fl_X::GL_cleardrawable(void)
{
  [[NSOpenGLContext currentContext] clearDrawable];
}

void Fl_X::GLcontext_makecurrent(NSOpenGLContext* ctxt)
{
  [ctxt makeCurrentContext];
}

void Fl_Window::fullscreen_x() {
  _set_fullscreen();
  if (fl_mac_os_version < 101000) {
    // On OS X < 10.6, it is necessary to recreate the window. This is done with hide+show.
    // The alternative procedure isn't stable until MacOS 10.10
    hide();
    show();
  } else {
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
    [i->xid setStyleMask:NSBorderlessWindowMask]; //10.6
#endif
    [i->xid setLevel:NSStatusWindowLevel];
    int X,Y,W,H;
    Fl::screen_xywh(X, Y, W, H, x(), y(), w(), h());
    resize(X, Y, W, H);
  }
  Fl::handle(FL_FULLSCREEN, this);
}

void Fl_Window::fullscreen_off_x(int X, int Y, int W, int H) {
  _clear_fullscreen();
  if (fl_mac_os_version < 101000) {
    hide();
    resize(X, Y, W, H);
    show();
  } else {
    NSUInteger winstyle = (border() ?
                           (NSTitledWindowMask | NSClosableWindowMask | NSResizableWindowMask) : NSBorderlessWindowMask);
    if (!modal()) winstyle |= NSMiniaturizableWindowMask;
    NSInteger level = NSNormalWindowLevel;
    if (modal()) level = modal_window_level();
    else if (non_modal()) level = non_modal_window_level();
    [i->xid setLevel:level];
    resize(X, Y, W, H);
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
    [i->xid setStyleMask:winstyle]; //10.6
#endif
  }
  Fl::handle(FL_FULLSCREEN, this);
}

/*
 * Initialize the given port for redraw and call the window's flush() to actually draw the content
 */ 
void Fl_X::flush()
{
  if (w->as_gl_window()) {
    w->flush();
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_8
  } else if (views_use_CA) {
    if (!through_drawRect) {
      FLViewLayer *view = (FLViewLayer*)[fl_xid(w) contentView];
      [view displayLayer:[view layer]];
    } else
      w->flush();
#endif
  } else {
    make_current_counts = 1;
    if (!through_drawRect) [[xid contentView] lockFocus];
    through_Fl_X_flush = YES;
    w->flush();
    through_Fl_X_flush = NO;
    if (!through_drawRect) [[xid contentView] unlockFocus];
    make_current_counts = 0;
    Fl_X::q_release_context();
  }
}

/*
 * go ahead, create that (sub)window
 */
void Fl_X::make(Fl_Window* w)
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    Fl_Group::current(0);
    fl_open_display();
    NSInteger winlevel = NSNormalWindowLevel;
    NSUInteger winstyle;
    if (w->parent()) {
      w->border(0);
      fl_show_iconic = 0;
    }
    if (w->border()) winstyle = NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask;
    else winstyle = NSBorderlessWindowMask;
    if (fl_show_iconic && !w->parent()) { // prevent window from being out of work area when created iconized
      int sx, sy, sw, sh;
      Fl::screen_work_area (sx, sy, sw, sh, w->x(), w->y());
      if (w->x() < sx) w->x(sx);
      if (w->y() < sy) w->y(sy);
    }
    int xp = w->x();
    int yp = w->y();
    int wp = w->w();
    int hp = w->h();
    if (w->size_range_set) {
      if ( w->minh != w->maxh || w->minw != w->maxw) {
        if (w->border()) winstyle |= NSResizableWindowMask;
      }
    } else {
      if (w->resizable()) {
        Fl_Widget *o = w->resizable();
        int minw = o->w(); if (minw > 100) minw = 100;
        int minh = o->h(); if (minh > 100) minh = 100;
        w->size_range(w->w() - o->w() + minw, w->h() - o->h() + minh, 0, 0);
        if (w->border()) winstyle |= NSResizableWindowMask;
      } else {
        w->size_range(w->w(), w->h(), w->w(), w->h());
      }
    }
    int xwm = xp, ywm = yp, bt, bx, by;
    
    if (!fake_X_wm(w, xwm, ywm, bt, bx, by)) {
      // menu windows and tooltips
      if (w->modal()||w->tooltip_window()) {
        winlevel = modal_window_level();
      }
    }
    if (w->modal()) {
      winstyle &= ~NSMiniaturizableWindowMask;
      winlevel = modal_window_level();
    }
    else if (w->non_modal()) {
      winlevel = non_modal_window_level();
    }
    
    if (by+bt) {
      wp += 2*bx;
      hp += 2*by+bt;
    }
    if (w->force_position()) {
      if (!Fl::grab()) {
        xp = xwm; yp = ywm;
        w->x(xp);w->y(yp);
      }
      xp -= bx;
      yp -= by+bt;
    }
  
    Fl_X* x = new Fl_X;
    x->other_xid = 0; // room for doublebuffering image map. On OS X this is only used by overlay windows
    x->region = 0;
    x->subRect(0);
    x->cursor = NULL;
    x->gc = 0;
    x->mapped_to_retina(false);
    x->changed_resolution(false);
    x->in_windowDidResize(false);
  
    NSRect crect;
    if (w->fullscreen_active()) {
      int top, bottom, left, right;
      int sx, sy, sw, sh, X, Y, W, H;

      top = w->fullscreen_screen_top;
      bottom = w->fullscreen_screen_bottom;
      left = w->fullscreen_screen_left;
      right = w->fullscreen_screen_right;

      if ((top < 0) || (bottom < 0) || (left < 0) || (right < 0)) {
        top = Fl::screen_num(w->x(), w->y(), w->w(), w->h());
        bottom = top;
        left = top;
        right = top;
      }

      Fl::screen_xywh(sx, sy, sw, sh, top);
      Y = sy;
      Fl::screen_xywh(sx, sy, sw, sh, bottom);
      H = sy + sh - Y;
      Fl::screen_xywh(sx, sy, sw, sh, left);
      X = sx;
      Fl::screen_xywh(sx, sy, sw, sh, right);
      W = sx + sw - X;

      w->resize(X, Y, W, H);

      winstyle = NSBorderlessWindowMask;
      winlevel = NSStatusWindowLevel;
    }
    crect.origin.x = w->x(); // correct origin set later for subwindows
    crect.origin.y = main_screen_height - (w->y() + w->h());
    crect.size.width=w->w(); 
    crect.size.height=w->h();
    FLWindow *cw = [[FLWindow alloc] initWithFl_W:w 
				      contentRect:crect  
					styleMask:winstyle];
    [cw setFrameOrigin:crect.origin];
    if (!w->parent()) {
      [cw setHasShadow:YES];
      [cw setAcceptsMouseMovedEvents:YES];
    }
    if (w->shape_data_) {
      [cw setOpaque:NO]; // shaped windows must be non opaque
      [cw setBackgroundColor:[NSColor clearColor]]; // and with transparent background color
      }
    x->xid = cw;
    x->w = w; w->i = x;
    x->wait_for_expose = 1;
    if (!w->parent()) {
      x->next = Fl_X::first;
      Fl_X::first = x;
    } else if (Fl_X::first) {
      x->next = Fl_X::first->next;
      Fl_X::first->next = x;
    }
    else {
      x->next = NULL;
      Fl_X::first = x;
    }
  FLView *myview;
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_8
  if (views_use_CA) {
    myview = w->as_gl_window() ? [FLGLViewLayer alloc] : [FLViewLayer alloc];
  } else
#endif
    myview = [FLView alloc];
  myview = [myview initWithFrame:crect];
    [cw setContentView:myview];
    [myview release];
    [cw setLevel:winlevel];
    
    q_set_window_title(cw, w->label(), w->iconlabel());
    if (!w->force_position()) {
      if (w->modal()) {
        [cw center];
      } else if (w->non_modal()) {
        [cw center];
      } else {
        static NSPoint delta = NSZeroPoint;
        delta = [cw cascadeTopLeftFromPoint:delta];
      }
      crect = [cw frame]; // synchronize FLTK's and the system's window coordinates
      w->x(int(crect.origin.x));
      w->y(int(main_screen_height - (crect.origin.y + w->h())));
    }
    if(w->menu_window()) { // make menu windows slightly transparent
      [cw setAlphaValue:0.97];
    }
    // Install DnD handlers 
    [myview registerForDraggedTypes:[NSArray arrayWithObjects:UTF8_pasteboard_type,  NSFilenamesPboardType, nil]];
  
    if (w->size_range_set) w->size_range_();
    
    if ( w->border() || (!w->modal() && !w->tooltip_window()) ) {
      Fl_Tooltip::enter(0);
    }

    if (w->modal()) Fl::modal_ = w; 

    w->set_visible();
    if ( w->border() || (!w->modal() && !w->tooltip_window()) ) Fl::handle(FL_FOCUS, w);
    [cw setDelegate:[FLWindowDelegate singleInstance]];
  if (fl_show_iconic) {
    fl_show_iconic = 0;
    w->handle(FL_SHOW); // create subwindows if any
    [cw recursivelySendToSubwindows:@selector(display)];  // draw the window and its subwindows before its icon is computed
    [cw miniaturize:nil];
  } else if (w->parent()) { // a subwindow
    [cw setIgnoresMouseEvents:YES]; // needs OS X 10.2
    // next 2 statements so a subwindow doesn't leak out of its parent window
    [cw setOpaque:NO];
    [cw setBackgroundColor:[NSColor clearColor]]; // transparent background color
    [cw setSubwindowFrame];
    // needed if top window was first displayed miniaturized
    FLWindow *pxid = fl_xid(w->top_window());
    [pxid makeFirstResponder:[pxid contentView]];
  } else { // a top-level window
    [cw makeKeyAndOrderFront:nil];
  }
  
    int old_event = Fl::e_number;
    w->handle(Fl::e_number = FL_SHOW);
    Fl::e_number = old_event;
    
    // if (w->modal()) { Fl::modal_ = w; fl_fix_focus(); }
    [pool release];
}


/*
 * Tell the OS what window sizes we want to allow
 */
void Fl_Window::size_range_() {
  int bx, by, bt;
  get_window_frame_sizes(bx, by, bt);
  size_range_set = 1;
  NSSize minSize = NSMakeSize(minw, minh + bt);
  NSSize maxSize = NSMakeSize(maxw?maxw:32000, maxh?maxh + bt:32000);
  if (i && i->xid) {
    [i->xid setMinSize:minSize];
    [i->xid setMaxSize:maxSize];
  }
}

void Fl_Window::wait_for_expose()
{
    if (fl_mac_os_version < 101300) {
        [fl_xid(this) recursivelySendToSubwindows:@selector(waitForExpose)];
    } else {
      while (dropped_files_list) {
        drain_dropped_files_list();
      }
      [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:nil
                            inMode:NSDefaultRunLoopMode dequeue:NO];
    }
}

/*
 * returns pointer to the filename, or null if name ends with ':'
 */
const char *fl_filename_name( const char *name ) 
{
  const char *p, *q;
  if (!name) return (0);
  for ( p = q = name ; *p ; ) {
    if ( ( p[0] == ':' ) && ( p[1] == ':' ) ) {
      q = p+2;
      p++;
    }
    else if (p[0] == '/') {
      q = p + 1;
    }
    p++;
  }
  return q;
}


/*
 * set the window title bar name
 */
void Fl_Window::label(const char *name, const char *mininame) {
  Fl_Widget::label(name);
  iconlabel_ = mininame;
  if (shown() || i) {
    q_set_window_title(i->xid, name, mininame);
  }
}


/*
 * make a window visible
 */
void Fl_Window::show() {
  image(Fl::scheme_bg_);
  if (Fl::scheme_bg_) {
    labeltype(FL_NORMAL_LABEL);
    align(FL_ALIGN_CENTER | FL_ALIGN_INSIDE | FL_ALIGN_CLIP);
  } else {
    labeltype(FL_NO_LABEL);
  }
  Fl_Tooltip::exit(this);
  Fl_X *top = NULL;
  if (parent()) top = top_window()->i;
  if (!shown() && (!parent() || (top && ![top->xid isMiniaturized]))) {
    Fl_X::make(this);
  } else {
    if ( !parent() ) {
      if ([i->xid isMiniaturized]) {
        i->w->redraw();
        [i->xid deminiaturize:nil];
      }
      if (!fl_capture) {
        [i->xid makeKeyAndOrderFront:nil];
      }
    }
    else set_visible();
  }
}


/*
 * resize a window
 */
void Fl_Window::resize(int X,int Y,int W,int H) {
  int bx, by, bt;
  Fl_Window *parent;
  if (W<=0) W = 1; // OS X does not like zero width windows
  if (H<=0) H = 1;
  int is_a_resize = (W != w() || H != h());
  //  printf("Fl_Window::resize(X=%d, Y=%d, W=%d, H=%d), is_a_resize=%d, resize_from_system=%p, this=%p\n",
  //         X, Y, W, H, is_a_resize, resize_from_system, this);
  if (X != x() || Y != y()) set_flag(FORCE_POSITION);
  else if (!is_a_resize) {
    resize_from_system = 0;
    return;
    }
  if ( (resize_from_system!=this) && shown()) {
    if (is_a_resize) {
      if (resizable()) {
        if (W<minw) minw = W; // user request for resize takes priority
        if (maxw && W>maxw) maxw = W; // over a previously set size_range
        if (H<minh) minh = H;
        if (maxh && H>maxh) maxh = H;
        size_range(minw, minh, maxw, maxh);
      } else {
        size_range(W, H, W, H);
      }
      Fl_Group::resize(X,Y,W,H);
      // transmit changes in FLTK coords to cocoa
      get_window_frame_sizes(bx, by, bt);
      bx = X; by = Y;
      parent = window();
      while (parent) {
        bx += parent->x();
        by += parent->y();
        parent = parent->window();
      }
      NSRect r = NSMakeRect(bx, main_screen_height - (by + H), W, H + ( (border()&&!fullscreen_active())?bt:0 ));
      if (visible_r()) [fl_xid(this) setFrame:r display:YES];
    } else {
      bx = X; by = Y;
      parent = window();
      while (parent) {
        bx += parent->x();
        by += parent->y();
        parent = parent->window();
      }
      NSPoint pt = NSMakePoint(bx, main_screen_height - (by + H));
      if (visible_r()) [fl_xid(this) setFrameOrigin:pt]; // set cocoa coords to FLTK position
    }
  }
  else {
    resize_from_system = 0;
    if (is_a_resize) {
      Fl_Group::resize(X,Y,W,H);
      if (shown()) {
        redraw();
      }
    } else {
      x(X); y(Y);
    }
  }
}


/*
 * make all drawing go into this window (called by subclass flush() impl.)
 
 This can be called in 3 different instances:
 
 1) When a window is created or resized.
 The system sends the drawRect: message to the window's view after having prepared the current 
 graphics context to draw to this view. Processing of drawRect: sets variable through_drawRect 
 to YES and calls handleUpdateEvent() that calls Fl_X::flush(). Fl_X::flush() sets through_Fl_X_flush 
 to YES and calls Fl_Window::flush() that calls Fl_Window::make_current() that
 uses the window's graphics context. The window's draw() function is then executed.
 
 2) At each round of the FLTK event loop.
 Fl::flush() is called, that calls Fl_X::flush() on each window that needs drawing. Variable 
 through_Fl_X_flush is set to YES. Fl_X::flush() locks the focus to the view and calls Fl_Window::flush()
 that calls Fl_Window::make_current() which uses the window's graphics context.
 Fl_Window::flush() then runs the window's draw() function.
 
 3) An FLTK application can call Fl_Window::make_current() at any time before it draws to a window.
 This occurs for instance in the idle callback function of the mandelbrot test program. Variable 
 through_Fl_X_flush is NO. Under Mac OS 10.4 and higher, the window's graphics context is obtained.
 Under Mac OS 10.3 a new graphics context adequate for the window is created. 
 Subsequent drawing requests go to this window. CAUTION: it's not possible to call Fl::wait(),
 Fl::check() nor Fl::ready() while in the draw() function of a widget. Use an idle callback instead.
 */
void Fl_Window::make_current() 
{
  if (make_current_counts > 1 && !views_use_CA) return;
  if (make_current_counts) make_current_counts++;
  if (views_use_CA && !through_drawRect) { // detect direct calls from the app
    damage(FL_DAMAGE_CHILD); // make next draws to this window displayed at next event loop
  }
  Fl_X::q_release_context();
  fl_window = i->xid;
  Fl_X::set_high_resolution( i->mapped_to_retina() );
  current_ = this;
//NSLog(@"region-count=%d damage=%u",i->region?i->region->count:0, damage());

#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_8
  if (views_use_CA) {
    i->gc = ((FLViewLayer*)[fl_window contentView])->layer_data;
#  ifdef FLTK_HAVE_CAIRO
    // make sure the GC starts with an identity transformation matrix as do native Cocoa GC's
    // because cairo may have changed it
    CGAffineTransform mat = CGContextGetCTM(i->gc);
    if (!CGAffineTransformIsIdentity(mat)) { // 10.4
      CGContextConcatCTM(i->gc, CGAffineTransformInvert(mat));
    }
#  endif
  } else
#endif
  {
    NSGraphicsContext *nsgc;
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4
    if (fl_mac_os_version >= 100400)
      nsgc = [fl_window graphicsContext]; // 10.4
    else
#endif
      nsgc = through_Fl_X_flush ? [NSGraphicsContext currentContext] : [NSGraphicsContext graphicsContextWithWindow:fl_window];
    i->gc = (CGContextRef)[nsgc graphicsPort];
  }

  fl_gc = i->gc;
  CGContextSaveGState(fl_gc); // native context
  if (views_use_CA && i->mapped_to_retina()) CGContextScaleCTM(fl_gc, 2,2);
  // antialiasing must be deactivated because it applies to rectangles too
  // and escapes even clipping!!!
  // it gets activated when needed (e.g., draw text)
  CGContextSetShouldAntialias(fl_gc, false);  
  CGFloat hgt = [[fl_window contentView] frame].size.height;
  CGContextTranslateCTM(fl_gc, 0.5, hgt-0.5f);
  CGContextScaleCTM(fl_gc, 1.0f, -1.0f); // now 0,0 is top-left point of the window
  // for subwindows, limit drawing to inside of parent window
  // half pixel offset is necessary for clipping as done by fl_cgrectmake_cocoa()
  if (i->subRect()) CGContextClipToRect(fl_gc, CGRectOffset(*(i->subRect()), -0.5, -0.5));
  
// this is the context with origin at top left of (sub)window
  CGContextSaveGState(fl_gc);
#if defined(FLTK_USE_CAIRO)
  if (Fl::cairo_autolink_context()) Fl::cairo_make_current(this); // capture gc changes automatically to update the cairo context adequately
#endif
  fl_clip_region( 0 );
  
#if defined(FLTK_USE_CAIRO)
  // update the cairo_t context
  if (Fl::cairo_autolink_context()) Fl::cairo_make_current(this);
#endif
}

// helper function to manage the current CGContext fl_gc
extern void fl_quartz_restore_line_style_();

// FLTK has only one global graphics state. This function copies the FLTK state into the
// current Quartz context
void Fl_X::q_fill_context() {
  if (!fl_gc) return;
  if ( ! fl_window) { // a bitmap context
    CGFloat hgt = CGBitmapContextGetHeight(fl_gc);
    CGAffineTransform at = CGContextGetCTM(fl_gc);
    CGFloat offset = 0.5;
    if (at.a != 1 && at.a == at.d && at.b == 0 && at.c == 0) {
      hgt /= at.a;
      offset /= at.a;
    }
    CGContextTranslateCTM(fl_gc, offset, hgt-offset);
    CGContextScaleCTM(fl_gc, 1.0f, -1.0f); // now 0,0 is top-left point of the context
    }
  fl_color(fl_graphics_driver->color());
  fl_quartz_restore_line_style_();
}

// The only way to reset clipping to its original state is to pop the current graphics
// state and restore the global state.
void Fl_X::q_clear_clipping() {
  if (!fl_gc) return;
  CGContextRestoreGState(fl_gc);
  CGContextSaveGState(fl_gc);
}

// Give the Quartz context back to the system
void Fl_X::q_release_context(Fl_X *x) {
  if (x && x->gc!=fl_gc) return;
  if (!fl_gc) return;
  CGContextRestoreGState(fl_gc); // match the CGContextSaveGState's of make_current
  CGContextRestoreGState(fl_gc);
  Fl_X::set_high_resolution(false);
  CGContextFlush(fl_gc);
  fl_gc = 0;
#if defined(FLTK_USE_CAIRO)
  if (Fl::cairo_autolink_context()) Fl::cairo_make_current((Fl_Window*) 0); // capture gc changes automatically to update the cairo context adequately
#endif
}

void Fl_X::q_begin_image(CGRect &rect, int cx, int cy, int w, int h) {
  CGContextSaveGState(fl_gc);
  CGRect r2 = rect;
  r2.origin.x -= 0.5f;
  r2.origin.y -= 0.5f;
  CGContextClipToRect(fl_gc, r2);
  // move graphics context to origin of vertically reversed image
  // The 0.5 here cancels the 0.5 offset present in Quartz graphics contexts.
  // Thus, image and surface pixels are in phase if there's no scaling.
  // Below, we handle x2 and /2 scalings that occur when drawing to
  // a double-resolution bitmap, and when drawing a double-resolution bitmap to display.
  CGContextTranslateCTM(fl_gc, rect.origin.x - cx - 0.5, rect.origin.y - cy + h - 0.5);
  CGContextScaleCTM(fl_gc, 1, -1);
  CGAffineTransform at = CGContextGetCTM(fl_gc);
  if (at.a == at.d && at.b == 0 && at.c == 0) { // proportional scaling, no rotation
    // phase image with display pixels
    CGFloat deltax = 0, deltay = 0;
    if (at.a == 2) { // make .tx and .ty have even values
      deltax = (at.tx/2 - round(at.tx/2));
      deltay = (at.ty/2 - round(at.ty/2));
    } else if (at.a == 0.5) {
      if (Fl_Display_Device::high_resolution()) { // make .tx and .ty have int or half-int values
        deltax = -(at.tx*2 - round(at.tx*2));
        deltay = (at.ty*2 - round(at.ty*2));
      } else { // make .tx and .ty have integral values
        deltax = (at.tx - round(at.tx))*2;
        deltay = (at.ty - round(at.ty))*2;
      }
    }
    CGContextTranslateCTM(fl_gc, -deltax, -deltay);
  }
  rect.origin.x = rect.origin.y = 0;
  rect.size.width = w;
  rect.size.height = h;
}

void Fl_X::q_end_image() {
  CGContextRestoreGState(fl_gc);
}

void Fl_X::set_high_resolution(bool new_val)
{
  Fl_Display_Device::high_res_window_ = new_val;
}

void Fl_Copy_Surface::complete_copy_pdf_and_tiff()
{
  CGContextRestoreGState(gc);
  CGContextEndPage(gc);
  CGContextRelease(gc);
  NSPasteboard *clip = [NSPasteboard generalPasteboard];
  [clip declareTypes:[NSArray arrayWithObjects:PDF_pasteboard_type, TIFF_pasteboard_type, nil] owner:nil];
  [clip setData:(NSData*)pdfdata forType:PDF_pasteboard_type];
  //second, transform this PDF to a bitmap image and put it as tiff in clipboard
  NSImage *image = [[NSImage alloc] initWithData:(NSData*)pdfdata];
  CFRelease(pdfdata);
  [clip setData:[image TIFFRepresentation] forType:TIFF_pasteboard_type];
  [image release];
}

////////////////////////////////////////////////////////////////
// Copy & Paste fltk implementation.
////////////////////////////////////////////////////////////////

static size_t convert_crlf(char * s, size_t len)
{
  // turn \r characters into \n and "\r\n" sequences into \n:
  char *p;
  size_t l = len;
  while ((p = strchr(s, '\r'))) {
    if (*(p+1) == '\n') {
      memmove(p, p+1, l-(p-s));
      len--; l--;
    } else *p = '\n';
    l -= p-s;
    s = p + 1;
  }
  return len;
}

// clipboard variables definitions :
char *fl_selection_buffer[2] = {NULL, NULL};
int fl_selection_length[2] = {0, 0};
static int fl_selection_buffer_length[2];

extern void fl_trigger_clipboard_notify(int source);

void fl_clipboard_notify_change() {
  // No need to do anything here...
}

static void clipboard_check(void)
{
  static NSInteger oldcount = -1;
  NSInteger newcount = [[NSPasteboard generalPasteboard] changeCount];
  if (newcount == oldcount) return;
  oldcount = newcount;
  fl_trigger_clipboard_notify(1);
}

static void resize_selection_buffer(int len, int clipboard) {
  if (len <= fl_selection_buffer_length[clipboard])
    return;
  delete[] fl_selection_buffer[clipboard];
  fl_selection_buffer[clipboard] = new char[len+100];
  fl_selection_buffer_length[clipboard] = len+100;
}

/*
 * create a selection
 * stuff: pointer to selected data
 * len: size of selected data
 * type: always "plain/text" for now
 */
void Fl::copy(const char *stuff, int len, int clipboard, const char *type) {
  if (!stuff || len<0) return;
  if (clipboard >= 2)
    clipboard = 1; // Only on X11 do multiple clipboards make sense.

  resize_selection_buffer(len+1, clipboard);
  memcpy(fl_selection_buffer[clipboard], stuff, len);
  fl_selection_buffer[clipboard][len] = 0; // needed for direct paste
  fl_selection_length[clipboard] = len;
  if (clipboard) {
    CFDataRef text = CFDataCreate(kCFAllocatorDefault, (UInt8*)fl_selection_buffer[1], len);
    if (text==NULL) return; // there was a pb creating the object, abort.
    NSPasteboard *clip = [NSPasteboard generalPasteboard];
    [clip declareTypes:[NSArray arrayWithObject:UTF8_pasteboard_type] owner:nil];
    [clip setData:(NSData*)text forType:UTF8_pasteboard_type];
    CFRelease(text);
  }
}

static int get_plain_text_from_clipboard(int clipboard)
{
  NSInteger length = 0;
  NSPasteboard *clip = [NSPasteboard generalPasteboard];
  NSString *found = [clip availableTypeFromArray:[NSArray arrayWithObjects:UTF8_pasteboard_type, @"public.utf16-plain-text", @"com.apple.traditional-mac-plain-text", nil]];
  if (found) {
    NSData *data = [clip dataForType:found];
    if (data) {
      NSInteger len;
      char *aux_c = NULL;
      if (![found isEqualToString:UTF8_pasteboard_type]) {
	NSString *auxstring;
	auxstring = (NSString *)CFStringCreateWithBytes(NULL, 
							(const UInt8*)[data bytes], 
							[data length],
							[found isEqualToString:@"public.utf16-plain-text"] ? kCFStringEncodingUnicode : kCFStringEncodingMacRoman,
							false);
	aux_c = strdup([auxstring UTF8String]);
	[auxstring release];
	len = strlen(aux_c) + 1;
      }
      else len = [data length] + 1;
      resize_selection_buffer(len, clipboard);
      if (![found isEqualToString:UTF8_pasteboard_type]) {
        strcpy(fl_selection_buffer[clipboard], aux_c);
        free(aux_c);
      }
      else {
        [data getBytes:fl_selection_buffer[clipboard]];
      }
      fl_selection_buffer[clipboard][len - 1] = 0;
      length = convert_crlf(fl_selection_buffer[clipboard], len - 1); // turn all \r characters into \n:
      Fl::e_clipboard_type = Fl::clipboard_plain_text;
    }
  }    
  return length;
}

static Fl_Image* get_image_from_clipboard(Fl_Widget *receiver)
{
  NSPasteboard *clip = [NSPasteboard generalPasteboard];
  NSArray *present = [clip types]; // types in pasteboard in order of decreasing preference
  NSArray  *possible = [NSArray arrayWithObjects:TIFF_pasteboard_type, PDF_pasteboard_type, PICT_pasteboard_type, nil];
  NSString *found = nil;
  NSUInteger rank;
  for (NSUInteger i = 0; (!found) && i < [possible count]; i++) {
    for (rank = 0; rank < [present count]; rank++) { // find first of possible types present in pasteboard
      if ([[present objectAtIndex:rank] isEqualToString:[possible objectAtIndex:i]]) {
        found = [present objectAtIndex:rank];
        break;
      }
    }
  }
  if (!found) return NULL;
  NSData *data = [clip dataForType:found];
  if (!data) return NULL;
  NSBitmapImageRep *bitmap = nil;
  if ([found isEqualToString:TIFF_pasteboard_type]) {
    bitmap = [[NSBitmapImageRep alloc] initWithData:data];
  }
  else if ([found isEqualToString:PDF_pasteboard_type] || [found isEqualToString:PICT_pasteboard_type]) {
    NSImage *nsimg = [[NSImage alloc] initWithData:data];
    [nsimg lockFocus];
    bitmap = [[NSBitmapImageRep alloc] initWithFocusedViewRect:NSMakeRect(0, 0, [nsimg size].width, [nsimg size].height)];
    [nsimg unlockFocus];
    [nsimg release];
  }
  if (!bitmap) return NULL;
  int bytesPerPixel([bitmap bitsPerPixel]/8);
  int bpr([bitmap bytesPerRow]);
  int bpp([bitmap bytesPerPlane]);
  int hh(bpp/bpr);
  int ww(bpr/bytesPerPixel);
  uchar *imagedata = new uchar[bpr * hh];
  memcpy(imagedata, [bitmap bitmapData], bpr * hh);
  Fl_RGB_Image *image = new Fl_RGB_Image(imagedata, ww, hh, bytesPerPixel);
  image->alloc_array = 1;
  [bitmap release];
  Fl::e_clipboard_type = Fl::clipboard_image;
  return image;
}

// Call this when a "paste" operation happens:
void Fl::paste(Fl_Widget &receiver, int clipboard, const char *type) {
  if (type[0] == 0) type = Fl::clipboard_plain_text;
  if (clipboard) {
    Fl::e_clipboard_type = "";
    if (strcmp(type, Fl::clipboard_plain_text) == 0) {
      fl_selection_length[1] = get_plain_text_from_clipboard(1);
    }
    else if (strcmp(type, Fl::clipboard_image) == 0) {
      Fl::e_clipboard_data = get_image_from_clipboard(&receiver);
      if (Fl::e_clipboard_data) {
        int done = receiver.handle(FL_PASTE);
        Fl::e_clipboard_type = "";
        if (done == 0) {
          delete (Fl_Image*)Fl::e_clipboard_data;
          Fl::e_clipboard_data = NULL;
        }
      }
      return;
    }
    else
      fl_selection_length[1] = 0;
  }
  Fl::e_text = fl_selection_buffer[clipboard];
  Fl::e_length = fl_selection_length[clipboard];
  if (!Fl::e_length) Fl::e_text = (char *)"";
  receiver.handle(FL_PASTE);
}

int Fl::clipboard_contains(const char *type) {
  NSString *found = nil;
  if (strcmp(type, Fl::clipboard_plain_text) == 0) {
    found = [[NSPasteboard generalPasteboard] availableTypeFromArray:[NSArray arrayWithObjects:UTF8_pasteboard_type, @"public.utf16-plain-text", @"com.apple.traditional-mac-plain-text", nil]];
    }
  else if (strcmp(type, Fl::clipboard_image) == 0) {
    found = [[NSPasteboard generalPasteboard] availableTypeFromArray:[NSArray arrayWithObjects:TIFF_pasteboard_type, PDF_pasteboard_type, PICT_pasteboard_type, nil]];
    }
  return found != nil;
}

void Fl_X::destroy() {
  if (xid) {
    [xid close];
  }
  delete subRect();
}

void Fl_X::map() {
  if (w && xid && ![xid parentWindow]) { // 10.2
    // after a subwindow has been unmapped, it has lost its parent window and its frame may be wrong
    [xid setSubwindowFrame];
  }
  if (cursor) {
    [(NSCursor*)cursor release];
    cursor = NULL;
  }
}

void Fl_X::unmap() {
  if (w && xid) {
    if (w->parent()) [[xid parentWindow] removeChildWindow:xid]; // necessary with at least 10.5
    [xid orderOut:nil];
  }
}

// intersects current and x,y,w,h rectangle and returns result as a new Fl_Region
Fl_Region Fl_X::intersect_region_and_rect(Fl_Region current, int x,int y,int w, int h)
{
  if (current == NULL) return XRectangleRegion(x,y,w,h);
  CGRect r = fl_cgrectmake_cocoa(x, y, w, h);
  Fl_Region outr = (Fl_Region)malloc(sizeof(*outr));
  outr->count = current->count;
  outr->rects =(CGRect*)malloc(outr->count * sizeof(CGRect));
  int j = 0;
  for(int i = 0; i < current->count; i++) {
    CGRect test = CGRectIntersection(current->rects[i], r);
    if (!CGRectIsEmpty(test)) outr->rects[j++] = test;
  }
  if (j) {
    outr->count = j;
    outr->rects = (CGRect*)realloc(outr->rects, outr->count * sizeof(CGRect));
  }
  else {
    XDestroyRegion(outr);
    outr = XRectangleRegion(0,0,0,0);
  }
  return outr;
}

void Fl_X::collapse() {
  [xid miniaturize:nil];
}

static NSImage *CGBitmapContextToNSImage(CGContextRef c)
// the returned NSImage is autoreleased
{
  NSImage* image;
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  if (fl_mac_os_version >= 100600) {
    CGImageRef cgimg = CGBitmapContextCreateImage(c);  // requires 10.4
    image = [[NSImage alloc] initWithCGImage:cgimg size:NSZeroSize]; // requires 10.6
    CFRelease(cgimg);
  }
  else 
#endif
    {
      NSBitmapImageRep *imagerep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL
									   pixelsWide:CGBitmapContextGetWidth(c)
									   pixelsHigh:CGBitmapContextGetHeight(c)
									bitsPerSample:8
								      samplesPerPixel:4
									     hasAlpha:YES
									     isPlanar:NO
								       colorSpaceName:NSDeviceRGBColorSpace
									  bytesPerRow:CGBitmapContextGetBytesPerRow(c)
									 bitsPerPixel:CGBitmapContextGetBitsPerPixel(c)];
      memcpy([imagerep bitmapData], CGBitmapContextGetData(c), [imagerep bytesPerRow] * [imagerep pixelsHigh]);
      image = [[NSImage alloc] initWithSize:NSMakeSize([imagerep pixelsWide], [imagerep pixelsHigh])];
      [image addRepresentation:imagerep];
      [imagerep release];
    }
  return [image autorelease];
}

int Fl_X::set_cursor(Fl_Cursor c)
{
  if (cursor) {
    [(NSCursor*)cursor release];
    cursor = NULL;
  }

  switch (c) {
  case FL_CURSOR_ARROW:   cursor = [NSCursor arrowCursor]; break;
  case FL_CURSOR_CROSS:   cursor = [NSCursor crosshairCursor]; break;
  case FL_CURSOR_INSERT:  cursor = [NSCursor IBeamCursor]; break;
  case FL_CURSOR_HAND:    cursor = [NSCursor pointingHandCursor]; break;
  case FL_CURSOR_MOVE:    cursor = [NSCursor openHandCursor]; break;
  case FL_CURSOR_NS:      cursor = [NSCursor resizeUpDownCursor]; break;
  case FL_CURSOR_WE:      cursor = [NSCursor resizeLeftRightCursor]; break;
  case FL_CURSOR_N:       cursor = [NSCursor resizeUpCursor]; break;
  case FL_CURSOR_E:       cursor = [NSCursor resizeRightCursor]; break;
  case FL_CURSOR_W:       cursor = [NSCursor resizeLeftCursor]; break;
  case FL_CURSOR_S:       cursor = [NSCursor resizeDownCursor]; break;
  default:
    return 0;
  }

  [(NSCursor*)cursor retain];

  [(NSWindow*)xid invalidateCursorRectsForView:[(NSWindow*)xid contentView]];

  return 1;
}

int Fl_X::set_cursor(const Fl_RGB_Image *image, int hotx, int hoty) {
  if (cursor) {
    [(NSCursor*)cursor release];
    cursor = NULL;
  }

  if ((hotx < 0) || (hotx >= image->w()))
    return 0;
  if ((hoty < 0) || (hoty >= image->h()))
    return 0;

  // OS X >= 10.6 can create a NSImage from a CGImage, but we need to
  // support older versions, hence this pesky handling.

  NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc]
                              initWithBitmapDataPlanes:NULL
                              pixelsWide:image->w()
                              pixelsHigh:image->h()
                              bitsPerSample:8
                              samplesPerPixel:image->d()
                              hasAlpha:!(image->d() & 1)
                              isPlanar:NO
                              colorSpaceName:(image->d()<=2) ? NSDeviceWhiteColorSpace : NSDeviceRGBColorSpace
                              bytesPerRow:(image->w() * image->d())
                              bitsPerPixel:(image->d()*8)];

  // Alpha needs to be premultiplied for this format

  const uchar *i = (const uchar*)*image->data();
  const int extra_data = image->ld() ? (image->ld() - image->w() * image->d()) : 0;
  unsigned char *o = [bitmap bitmapData];
  for (int y = 0;y < image->h();y++) {
    if (!(image->d() & 1)) {
      for (int x = 0;x < image->w();x++) {
        unsigned int alpha;
        if (image->d() == 4) {
          alpha = i[3];
          *o++ = (unsigned char)((unsigned int)*i++ * alpha / 255);
          *o++ = (unsigned char)((unsigned int)*i++ * alpha / 255);
        }

        alpha = i[1];
        *o++ = (unsigned char)((unsigned int)*i++ * alpha / 255);
        *o++ = alpha;
        i++;
  }
    } else {
      // No alpha, so we can just copy everything directly.
      int len = image->w() * image->d();
      memcpy(o, i, len);
      o += len;
      i += len;
    }
    i += extra_data;
  }

  NSImage *nsimage = [[NSImage alloc]
                      initWithSize:NSMakeSize(image->w(), image->h())];

  [nsimage addRepresentation:bitmap];

  cursor = [[NSCursor alloc]
            initWithImage:nsimage
            hotSpot:NSMakePoint(hotx, hoty)];

  [(NSWindow*)xid invalidateCursorRectsForView:[(NSWindow*)xid contentView]];

  [bitmap release];
  [nsimage release];

  return 1;
}

@interface FLaboutItemTarget : NSObject 
{
}
- (BOOL)validateMenuItem:(NSMenuItem *)item;
- (void)showPanel;
- (void)printPanel;
- (void)terminate:(id)sender;
@end
@implementation FLaboutItemTarget
- (BOOL)validateMenuItem:(NSMenuItem *)item
{ // invalidate the Quit item of the application menu when running modal
  if (!Fl::modal() || [item action] != @selector(terminate:)) return YES;
  return NO;
}
- (void)showPanel
{
    NSDictionary *options;
    options = [NSDictionary dictionaryWithObjectsAndKeys:
	       [[[NSAttributedString alloc] 
		initWithString:[NSString stringWithFormat:@" GUI with FLTK %d.%d", 
		FL_MAJOR_VERSION, FL_MINOR_VERSION ]] autorelease], @"Credits",
                	     nil];
    [NSApp orderFrontStandardAboutPanelWithOptions:options];
}
//#include <FL/Fl_PostScript.H>
- (void)printPanel
{  
  Fl_Printer printer;
  //Fl_PostScript_File_Device printer;
  int w, h, ww, wh;
  Fl_Window *win = Fl::first_window();
  if(!win) return;
  if (win->parent()) win = win->top_window();
  if( printer.start_job(1) ) return;
  if( printer.start_page() ) return;
  fl_lock_function();
  // scale the printer device so that the window fits on the page
  float scale = 1;
  printer.printable_rect(&w, &h);
  ww = win->decorated_w();
  wh = win->decorated_h();
  if (ww>w || wh>h) {
    scale = (float)w/win->w();
    if ((float)h/wh < scale) scale = (float)h/wh;
    printer.scale(scale);
    printer.printable_rect(&w, &h);
  }
//#define ROTATE 1
#ifdef ROTATE
  printer.scale(scale * 0.8, scale * 0.8);
  printer.printable_rect(&w, &h);
  printer.origin(w/2, h/2 );
  printer.rotate(20.);
#else
  printer.origin(w/2, h/2);
#endif
  printer.print_window(win, -ww/2, -wh/2);
  //printer.print_window_part(win,0,0,win->w(),win->h(), -ww/2, -wh/2);
  printer.end_page();
  printer.end_job();
  fl_unlock_function();
}
- (void)terminate:(id)sender
{
  [NSApp terminate:sender];
}
@end


static void createAppleMenu(void)
{
  static BOOL donethat = NO;
  if (donethat) return;
  donethat = YES;
  NSMenu *mainmenu, *services = nil, *appleMenu;
  NSMenuItem *menuItem;
  NSString *title;
  
  SEL infodictSEL = (fl_mac_os_version >= 100200 ? @selector(localizedInfoDictionary) : @selector(infoDictionary));
  NSString *nsappname = [[[NSBundle mainBundle] performSelector:infodictSEL] objectForKey:@"CFBundleName"];  
  if (nsappname == nil)
    nsappname = [[NSProcessInfo processInfo] processName];
  appleMenu = [[NSMenu alloc] initWithTitle:@""];
  /* Add menu items */
  title = [NSString stringWithFormat:NSLocalizedString([NSString stringWithUTF8String:Fl_Mac_App_Menu::about],nil), nsappname];
  menuItem = [appleMenu addItemWithTitle:title action:@selector(showPanel) keyEquivalent:@""];
  FLaboutItemTarget *about = [[FLaboutItemTarget alloc] init];
  [menuItem setTarget:about];
  [appleMenu addItem:[NSMenuItem separatorItem]];
  // Print front window
  title = NSLocalizedString([NSString stringWithUTF8String:Fl_Mac_App_Menu::print], nil);
  if ([title length] > 0) {
    menuItem = [appleMenu 
		addItemWithTitle:title
		action:@selector(printPanel) 
		keyEquivalent:@""];
    [menuItem setTarget:about];
    [menuItem setEnabled:YES];
    [appleMenu addItem:[NSMenuItem separatorItem]];
    }
  if (fl_mac_os_version >= 100400) { // services+hide+quit already in menu in OS 10.3
    // Services Menu
    services = [[NSMenu alloc] initWithTitle:@""];
    menuItem = [appleMenu 
		addItemWithTitle:NSLocalizedString([NSString stringWithUTF8String:Fl_Mac_App_Menu::services], nil)
		action:nil 
		keyEquivalent:@""];
    [appleMenu setSubmenu:services forItem:menuItem];
    [appleMenu addItem:[NSMenuItem separatorItem]];
    // Hide AppName
    title = [NSString stringWithFormat:NSLocalizedString([NSString stringWithUTF8String:Fl_Mac_App_Menu::hide],nil), nsappname];
    [appleMenu addItemWithTitle:title 
			 action:@selector(hide:) 
		  keyEquivalent:@"h"];
    // Hide Others
    menuItem = [appleMenu 
		addItemWithTitle:NSLocalizedString([NSString stringWithUTF8String:Fl_Mac_App_Menu::hide_others] , nil)
		action:@selector(hideOtherApplications:) 
		keyEquivalent:@"h"];
    [menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)];
    // Show All
    [appleMenu addItemWithTitle:NSLocalizedString([NSString stringWithUTF8String:Fl_Mac_App_Menu::show] , nil)
			 action:@selector(unhideAllApplications:) keyEquivalent:@""];
    [appleMenu addItem:[NSMenuItem separatorItem]];
    // Quit AppName
    title = [NSString stringWithFormat:NSLocalizedString([NSString stringWithUTF8String:Fl_Mac_App_Menu::quit] , nil),
	     nsappname];
    menuItem = [appleMenu addItemWithTitle:title
                                    action:@selector(terminate:)
                             keyEquivalent:@"q"];
    [menuItem setTarget:about];
    }
  /* Put menu into the menubar */
  menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];
  [menuItem setSubmenu:appleMenu];
  mainmenu = [[NSMenu alloc] initWithTitle:@""];
  [mainmenu addItem:menuItem];
  if (fl_mac_os_version < 100600) {
    //	[NSApp setAppleMenu:appleMenu];
    //	to avoid compiler warning raised by use of undocumented setAppleMenu	:
    [NSApp performSelector:@selector(setAppleMenu:) withObject:appleMenu];
  }
  [NSApp setMainMenu:mainmenu];
  if (services) {
    [NSApp setServicesMenu:services];
    [services release];
    }
  [mainmenu release];
  [appleMenu release];
  [menuItem release];
}


void Fl_X::set_key_window()
{
  [xid makeKeyWindow];
}

static NSImage *imageFromText(const char *text, int *pwidth, int *pheight)
{
  const char *p, *q;
  int width = 0, height, w2, ltext = strlen(text);
  fl_font(FL_HELVETICA, 10);
  p = text;
  int nl = 0;
  while(nl < 100 && (q=strchr(p, '\n')) != NULL) { 
    nl++; 
    w2 = int(fl_width(p, q - p));
    if (w2 > width) width = w2;
    p = q + 1; 
  }
  if (text[ ltext - 1] != '\n') {
    nl++;
    w2 = int(fl_width(p));
    if (w2 > width) width = w2;
  }
  height = nl * fl_height() + 3;
  width += 6;
  Fl_Offscreen off = Fl_Quartz_Graphics_Driver::create_offscreen_with_alpha(width, height);
  fl_begin_offscreen(off);
  CGContextSetRGBFillColor( (CGContextRef)off, 0,0,0,0);
  fl_rectf(0,0,width,height);
  fl_color(FL_BLACK);
  p = text;
  int y = fl_height();
  while(TRUE) {
    q = strchr(p, '\n');
    if (q) {
      fl_draw(p, q - p, 3, y);
    } else {
      fl_draw(p, 3, y);
      break;
    }
    y += fl_height();
    p = q + 1;
  }
  fl_end_offscreen();
  NSImage* image = CGBitmapContextToNSImage( (CGContextRef)off );
  fl_delete_offscreen( off );
  *pwidth = width;
  *pheight = height;
  return image;
}

static NSImage *defaultDragImage(int *pwidth, int *pheight)
{
  const int version_threshold = 100700;
  int width, height;
  if (fl_mac_os_version >= version_threshold) {
    width = 50; height = 40;
    }
  else {
    width = 16; height = 16;
    }
  Fl_Offscreen off = Fl_Quartz_Graphics_Driver::create_offscreen_with_alpha(width, height);
  fl_begin_offscreen(off);
  if (fl_mac_os_version >= version_threshold) {
    fl_font(FL_HELVETICA, 20);
    fl_color(FL_BLACK);
    char str[4];
    int l = fl_utf8encode(0x1F69A, str); // the "Delivery truck" Unicode character from "Apple Color Emoji" font
    fl_draw(str, l, 1, 16);
    }
  else { // draw two squares
    CGContextSetRGBFillColor( (CGContextRef)off, 0,0,0,0);
    fl_rectf(0,0,width,height);
    CGContextSetRGBStrokeColor( (CGContextRef)off, 0,0,0,0.6);
    fl_rect(0,0,width,height);
    fl_rect(2,2,width-4,height-4);
  }
  fl_end_offscreen();
  NSImage* image = CGBitmapContextToNSImage( (CGContextRef)off );
  fl_delete_offscreen( off );
  *pwidth = width;
  *pheight = height;
  return image;
}

int Fl::dnd()
{
  return Fl_X::dnd(0);
}

int Fl_X::dnd(int use_selection)
{
  CFDataRef text = CFDataCreate(kCFAllocatorDefault, (UInt8*)fl_selection_buffer[0], fl_selection_length[0]);
  if (text==NULL) return false;
  NSAutoreleasePool *localPool;
  localPool = [[NSAutoreleasePool alloc] init]; 
  NSPasteboard *mypasteboard = [NSPasteboard pasteboardWithName:NSDragPboard];
  [mypasteboard declareTypes:[NSArray arrayWithObject:UTF8_pasteboard_type] owner:nil];
  [mypasteboard setData:(NSData*)text forType:UTF8_pasteboard_type];
  CFRelease(text);
  Fl_Widget *w = Fl::pushed();
  Fl_Window *win = w->top_window();
  NSView *myview = [Fl_X::i(win)->xid contentView];
  NSEvent *theEvent = [NSApp currentEvent];
  
  int width, height;
  NSImage *image;
  if (use_selection) {
    fl_selection_buffer[0][ fl_selection_length[0] ] = 0;
    image = imageFromText(fl_selection_buffer[0], &width, &height);
  } else {
    image = defaultDragImage(&width, &height);
  }
  
  static NSSize offset={0,0};
  NSPoint pt = [theEvent locationInWindow];
  pt.x -= width/2;
  pt.y -= height/2;
  [myview dragImage:image  at:pt  offset:offset 
              event:theEvent  pasteboard:mypasteboard  
             source:myview  slideBack:YES];
  if ( w ) {
    int old_event = Fl::e_number;
    w->handle(Fl::e_number = FL_RELEASE);
    Fl::e_number = old_event;
    Fl::pushed( 0 );
  }
  [localPool release];
  return true;
}

// rescales an NSBitmapImageRep
static NSBitmapImageRep *scale_nsbitmapimagerep(NSBitmapImageRep *img, float scale)
{
  int w = [img pixelsWide];
  int h = [img pixelsHigh];
  int scaled_w = int(scale * w + 0.5);
  int scaled_h = int(scale * h + 0.5);
  NSBitmapImageRep *scaled = [[NSBitmapImageRep alloc]  initWithBitmapDataPlanes:NULL
                                                                      pixelsWide:scaled_w
                                                                      pixelsHigh:scaled_h
                                                                   bitsPerSample:8
                                                                 samplesPerPixel:4
                                                                        hasAlpha:YES
                                                                        isPlanar:NO
                                                                  colorSpaceName:NSDeviceRGBColorSpace
                                                                     bytesPerRow:scaled_w*4
                                                                    bitsPerPixel:32];
  NSDictionary *dict = [NSDictionary dictionaryWithObject:scaled
                                                   forKey:NSGraphicsContextDestinationAttributeName];
  NSGraphicsContext *oldgc = [NSGraphicsContext currentContext];
  [NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithAttributes:dict]];
  [[NSColor clearColor] set];
  NSRect r = NSMakeRect(0, 0, scaled_w, scaled_h);
  NSRectFill(r);
  [img drawInRect:r];
  [NSGraphicsContext setCurrentContext:oldgc];
  [img release];
  return scaled;
}

static void write_bitmap_inside(NSBitmapImageRep *to, int to_width, NSBitmapImageRep *from,
                                int to_x, int to_y)
/* Copies in bitmap "to" the bitmap "from" with its top-left angle at coordinates to_x, to_y
 On retina displays both bitmaps have double width and height
 to_width is the width in screen units of "to". On retina, its pixel width is twice that.
 */
{
  const uchar *from_data = [from bitmapData];
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4
  if (fl_mac_os_version >= 100400) { // 10.4 required by the bitmapFormat message
    if (([to bitmapFormat] & NSAlphaFirstBitmapFormat) && !([from bitmapFormat] & NSAlphaFirstBitmapFormat) ) {
      // "to" is ARGB and "from" is RGBA --> convert "from" to ARGB
      // it is enough to read "from" starting one byte earlier, because A is always 0xFF:
      // RGBARGBA becomes (A)RGBARGB
      from_data--;
    } else if ( !([to bitmapFormat] & NSAlphaFirstBitmapFormat) && ([from bitmapFormat] & NSAlphaFirstBitmapFormat) ) {
      // "from" is ARGB and "to" is RGBA --> convert "from" to RGBA
      // it is enough to offset reading by one byte because A is always 0xFF
      // so ARGBARGB becomes RGBARGB(A) as needed
      from_data++;
    }
  }
#endif
  int to_w = (int)[to pixelsWide]; // pixel width of "to"
  int from_w = (int)[from pixelsWide]; // pixel width of "from"
  int from_h = [from pixelsHigh]; // pixel height of "from"
  int to_depth = [to samplesPerPixel], from_depth = [from samplesPerPixel];
  int depth = 0;
  if (to_depth > from_depth) depth = from_depth;
  else if (from_depth > to_depth) depth = to_depth;
  float factor = to_w / (float)to_width; // scaling factor is 1 for classic displays and 2 for retina
  to_x = factor*to_x; // transform offset from screen unit to pixels
  to_y = factor*to_y;
  // perform the copy
  uchar *tobytes = [to bitmapData] + to_y * to_w * to_depth + to_x * to_depth;
  const uchar *frombytes = from_data;
  for (int i = 0; i < from_h; i++) {
    if (depth == 0) { // depth is always 0 in case of RGBA <-> ARGB conversion
      if (i == 0 && from_data < [from bitmapData]) {
        memcpy(tobytes+1, frombytes+1, from_w * from_depth-1); // avoid reading before [from bitmapData]
        *tobytes = 0xFF; // set the very first A byte
      } else if (i == from_h - 1 && from_data > [from bitmapData]) {
        memcpy(tobytes, frombytes, from_w * from_depth - 1); // avoid reading after end of [from bitmapData]
        *(tobytes + from_w * from_depth - 1) = 0xFF; // set the very last A byte
      } else {
        memcpy(tobytes, frombytes, from_w * from_depth);
      }
    } else {
      for (int j = 0; j < from_w; j++) {
        memcpy(tobytes + j * to_depth, frombytes + j * from_depth, depth);
      }
    }
    tobytes += to_w * to_depth;
    frombytes += from_w * from_depth;
  }
}


static NSBitmapImageRep* GL_rect_to_nsbitmap(Fl_Window *win, int x, int y, int w, int h)
// captures a rectangle from a GL window and returns it as an allocated NSBitmapImageRep
// the capture has high res on retina
{
  Fl_Plugin_Manager pm("fltk:device");
  Fl_Device_Plugin *pi = (Fl_Device_Plugin*)pm.plugin("opengl.device.fltk.org");
  if (!pi) return nil;
  Fl_RGB_Image *img = pi->rectangle_capture(win, x, y, w, h);
  NSBitmapImageRep* bitmap = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL pixelsWide:img->w() pixelsHigh:img->h() bitsPerSample:8 samplesPerPixel:4 hasAlpha:YES isPlanar:NO colorSpaceName:NSDeviceRGBColorSpace bytesPerRow:4*img->w() bitsPerPixel:32];
  memset([bitmap bitmapData], 0xFF, [bitmap bytesPerPlane]);
  const uchar *from = img->array;
  for (int r = img->h() - 1; r >= 0; r--) {
    uchar *to = [bitmap bitmapData] + r * [bitmap bytesPerRow];
    for (int c = 0; c < img->w(); c++) {
      memcpy(to, from, 3);
      from += 3;
      to += 4;
    }
  }
  delete img;
  return bitmap;
}

static NSBitmapImageRep* rect_to_NSBitmapImageRep_layer(Fl_Window *win, int x, int y, int w, int h)
{ // capture window data for layer-based views because initWithFocusedViewRect: does not work for them
  NSBitmapImageRep *bitmap = nil;
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_8
  CGContextRef gc = ((FLViewLayer*)[fl_xid(win) contentView])->layer_data;
  if (!gc || y < 0) return nil;
  CGImageRef cgimg = CGBitmapContextCreateImage(gc);  // requires 10.4
  Fl_X *i = Fl_X::i( win );
  int resolution = i->mapped_to_retina() ? 2 : 1;
  if (x || y || w != win->w() || h != win->h()) {
    CGRect rect = CGRectMake(x * resolution, y * resolution, w * resolution, h * resolution);
    CGImageRef cgimg2 = CGImageCreateWithImageInRect(cgimg, rect); //10.4
    CGImageRelease(cgimg);
    cgimg = cgimg2;
  }
  bitmap = [[NSBitmapImageRep alloc] initWithCGImage:cgimg];//10.5
  CGImageRelease(cgimg);
#endif
  return bitmap;
}

static NSBitmapImageRep* rect_to_NSBitmapImageRep(Fl_Window *win, int x, int y, int w, int h)
/* Captures a rectangle from a mapped window.
 On retina displays, the resulting bitmap has 2 pixels per screen unit.
 The returned value is to be released after use
 */
{
  NSBitmapImageRep *bitmap = nil;
  NSRect rect;
  if (win->as_gl_window() && y >= 0) {
    bitmap = GL_rect_to_nsbitmap(win, x, y, w, h);
  } else if (views_use_CA) {
    bitmap = rect_to_NSBitmapImageRep_layer(win, x, y, w, h);
  } else {
    NSView *winview = nil;
    if ( through_Fl_X_flush  && Fl_Window::current() == win ) {
      rect = NSMakeRect(x - 0.5, y - 0.5, w, h);
    }
    else {
      rect = NSMakeRect(x, win->h()-(y+h), w, h);
      // lock focus to win's view
      winview = [fl_xid(win) contentView];
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4
      if (fl_mac_os_version >= 101100) [[fl_xid(win) graphicsContext] saveGraphicsState]; // necessary under 10.11
#endif
      [winview lockFocus];
    }
    // The image depth is 3 until 10.5 and 4 with 10.6 and above
    bitmap = [[NSBitmapImageRep alloc] initWithFocusedViewRect:rect];
    if ( !( through_Fl_X_flush && Fl_Window::current() == win) ) {
      [winview unlockFocus];
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4
      if (fl_mac_os_version >= 101100) [[fl_xid(win) graphicsContext] restoreGraphicsState];
#endif
    }
  }
  if (!bitmap) return nil;

  // capture also subwindows
  NSArray *children = [fl_xid(win) childWindows]; // 10.2
  NSEnumerator *enumerator = [children objectEnumerator];
  id child;
  while ((child = [enumerator nextObject]) != nil) {
    if (![child isKindOfClass:[FLWindow class]]) continue;
    Fl_Window *sub = [(FLWindow*)child getFl_Window];
    CGRect rsub = CGRectMake(sub->x(), win->h() -(sub->y()+sub->h()), sub->w(), sub->h());
    CGRect clip = CGRectMake(x, win->h()-(y+h), w, h);
    clip = CGRectIntersection(rsub, clip);
    if (CGRectIsNull(clip)) continue;
    NSBitmapImageRep *childbitmap = rect_to_NSBitmapImageRep(sub, clip.origin.x - sub->x(),
                                                             win->h() - clip.origin.y - sub->y() - clip.size.height, clip.size.width, clip.size.height);
    if (childbitmap) {
      // if bitmap is high res and childbitmap is not, childbitmap must be rescaled
      if ([bitmap pixelsWide] > w && [childbitmap pixelsWide] == clip.size.width) childbitmap = scale_nsbitmapimagerep(childbitmap, 2);
      write_bitmap_inside(bitmap, w, childbitmap,
                          clip.origin.x - x, win->h() - clip.origin.y - clip.size.height - y );
    }
    [childbitmap release];
  }
  return bitmap;
}


unsigned char *Fl_X::bitmap_from_window_rect(Fl_Window *win, int x, int y, int w, int h, int *bytesPerPixel)
/* Returns a capture of a rectangle of a mapped window as a pre-multiplied RGBA array of bytes.
 Alpha values are always 1 (except for the angles of a window title bar)
 so pre-multiplication can be ignored.
 *bytesPerPixel is set to the value 3 or 4 upon return.
 delete[] the returned pointer after use
 */
{
  NSBitmapImageRep *bitmap = rect_to_NSBitmapImageRep(win, x, y, w, h);
  if (bitmap == nil) return NULL;
  *bytesPerPixel = [bitmap bitsPerPixel]/8;
  int bpp = (int)[bitmap bytesPerPlane];
  int bpr = (int)[bitmap bytesPerRow];
  int hh = bpp/bpr; // sometimes hh = h-1 for unclear reason, and hh = 2*h with retina
  int ww = bpr/(*bytesPerPixel); // sometimes ww = w-1, and ww = 2*w with retina
  const uchar *start = [bitmap bitmapData]; // start of the bitmap data
  bool convert = false;
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4
  if (fl_mac_os_version >= 100400 && ([bitmap bitmapFormat] & NSAlphaFirstBitmapFormat)) {
    // bitmap is ARGB --> convert it to RGBA (ARGB happens with Mac OS 10.11)
    // it is enough to offset reading by one byte because A is always 0xFF
    // so ARGBARGB becomes RGBARGBA as needed
    start++;
    convert = true;
  }
#endif
  unsigned char *data;
  size_t tocopy;
  if (ww > w) { // with a retina display, we have to scale the image by a factor of 2
    uchar *data2 = [bitmap bitmapData];
    if (convert) { // duplicate the NSBitmapImageRep data taking care not to access beyond its end
      tocopy = ww*hh*4;
      data2 = new uchar[tocopy];
      memcpy(data2, start, --tocopy);
      data2[tocopy] = 0xFF; // set the last A byte
    }
    Fl_RGB_Image *rgb = new Fl_RGB_Image(data2, ww, hh, 4);
    rgb->alloc_array = (convert ? 1 : 0);
    Fl_RGB_Scaling save_scaling = Fl_Image::RGB_scaling();
    Fl_Image::RGB_scaling(FL_RGB_SCALING_BILINEAR);
    Fl_RGB_Image *rgb2 = (Fl_RGB_Image*)rgb->copy(w, h);
    Fl_Image::RGB_scaling(save_scaling);
    delete rgb;
    rgb2->alloc_array = 0;
    data = (uchar*)rgb2->array;
    delete rgb2;
  }
  else {
    data = new unsigned char[w * h *  *bytesPerPixel];
    if (w == ww) { // the NSBitmapImageRep data can be copied in one step
      tocopy = w * hh * (*bytesPerPixel);
      if (convert) { // take care not to access beyond the image end
        data[--tocopy] = 0xFF; // set the last A byte
      }
      memcpy(data, start, tocopy);
    } else {  // copy the NSBitmapImageRep data line by line
      const uchar *p = start;
      unsigned char *q = data;
      tocopy = bpr;
      for (int i = 0; i < hh; i++) {
        if (i == hh-1 && convert) tocopy--; // take care not to access beyond the image end
        memcpy(q, p, tocopy);
        p += bpr;
        q += w * (*bytesPerPixel);
      }
    }
  }
  [bitmap release];
  return data;
}


static void nsbitmapProviderReleaseData (void *info, const void *data, size_t size)
{
  [(NSBitmapImageRep*)info release];
}

CGImageRef Fl_X::CGImage_from_window_rect(Fl_Window *win, int x, int y, int w, int h)
/* Returns a capture of a rectangle of a mapped window as a CGImage.
 With retina displays, the returned image has twice the width and height.
 CFRelease the returned CGImageRef after use
 */
{
  CGImageRef img;
  NSBitmapImageRep *bitmap = rect_to_NSBitmapImageRep(win, x, y, w, h);
  if (fl_mac_os_version >= 100500) {
    img = (CGImageRef)[bitmap performSelector:@selector(CGImage)]; // requires Mac OS 10.5
    CGImageRetain(img);
    [bitmap release];
  } else {
    CGColorSpaceRef cspace = CGColorSpaceCreateDeviceRGB();
    CGDataProviderRef provider = CGDataProviderCreateWithData(bitmap, [bitmap bitmapData],
                                                              [bitmap bytesPerRow]*[bitmap pixelsHigh],
                                                              nsbitmapProviderReleaseData);
    img = CGImageCreate([bitmap pixelsWide], [bitmap pixelsHigh], 8, [bitmap bitsPerPixel], [bitmap bytesPerRow],
                        cspace,
                        [bitmap bitsPerPixel] == 32 ? kCGImageAlphaPremultipliedLast : kCGImageAlphaNone,
                        provider, NULL, false, kCGRenderingIntentDefault);
    CGColorSpaceRelease(cspace);
    CGDataProviderRelease(provider);
  }
  return img;
}

WindowRef Fl_X::window_ref() // useless with cocoa GL windows
{
  return (WindowRef)[xid windowRef];
}

// so a CGRect matches exactly what is denoted x,y,w,h for clipping purposes
CGRect fl_cgrectmake_cocoa(int x, int y, int w, int h) {
  return CGRectMake(x - 0.5, y - 0.5, w, h);
}

Window fl_xid(const Fl_Window* w)
{
  Fl_X *temp = Fl_X::i(w);
  return temp ? temp->xid : 0;
}

int Fl_Window::decorated_w()
{
  if (!shown() || parent() || !border() || !visible()) return w();
  int bx, by, bt;
  get_window_frame_sizes(bx, by, bt);
  return w() + 2 * bx;
}

int Fl_Window::decorated_h()
{
  if (!shown() || parent() || !border() || !visible()) return h();
  int bx, by, bt;
  get_window_frame_sizes(bx, by, bt);
  return h() + bt + by;
}

// clip the graphics context to rounded corners
void Fl_X::clip_to_rounded_corners(CGContextRef gc, int w, int h) {
  const CGFloat radius = 5;
  CGContextMoveToPoint(gc, 0, 0);
  CGContextAddLineToPoint(gc, 0, h - radius);
  CGContextAddArcToPoint(gc, 0, h,  radius, h, radius);
  CGContextAddLineToPoint(gc, w - radius, h);
  CGContextAddArcToPoint(gc, w, h, w, h - radius, radius);
  CGContextAddLineToPoint(gc, w, 0);
  CGContextClip(gc);
}


void *Fl_X::get_titlebar_layer(Fl_Window *win)
{
  // a compilation warning appears with SDK 10.5, so we require SDK 10.6 instead
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  return fl_mac_os_version >= 101000 ? [[[fl_xid(win) standardWindowButton:NSWindowCloseButton] superview] layer] : nil; // 10.5
#else
  return nil;
#endif
}


void Fl_X::draw_layer_to_context(void *layer, CGContextRef gc, int w, int h)
{
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  Fl_X::clip_to_rounded_corners(gc, w, h);
  CGContextSetRGBFillColor(gc, .79, .79, .79, 1.); // equiv. to FL_DARK1
  CGContextFillRect(gc, CGRectMake(0, 0, w, h));
  CGContextSaveGState(gc);
  CGContextSetShouldAntialias(gc, true);
  [(CALayer*)layer renderInContext:gc]; // 10.5
  CGContextRestoreGState(gc);
#endif
}

void Fl_Paged_Device::print_window(Fl_Window *win, int x_offset, int y_offset)
{
  if (!win->shown() || win->parent() || !win->border() || !win->visible()) {
    this->print_widget(win, x_offset, y_offset);
    return;
  }
  int bx, by, bt, bpp;
  get_window_frame_sizes(bx, by, bt);
  BOOL to_quartz =  (this->driver()->class_name() == Fl_Quartz_Graphics_Driver::class_id);
  void *layer = Fl_X::get_titlebar_layer(win);
  if (layer) { // if title bar uses a layer
    if (to_quartz) { // to Quartz printer
      CGContextSaveGState(fl_gc);
      CGContextTranslateCTM(fl_gc, x_offset - 0.5, y_offset + bt - 0.5);
      CGContextScaleCTM(fl_gc, 1, -1);
      Fl_X::draw_layer_to_context(layer, fl_gc, win->w(), bt);
      CGContextRestoreGState(fl_gc);
    }
    else { // to PostScript
      CGColorSpaceRef cspace = CGColorSpaceCreateDeviceRGB ();
      CGContextRef gc = CGBitmapContextCreate(NULL, win->w(), bt, 8, 0, cspace, kCGImageAlphaPremultipliedLast);
      CGColorSpaceRelease(cspace);
      CGContextClearRect(gc, CGRectMake(0, 0, win->w(), bt));
      Fl_X::draw_layer_to_context(layer, gc, win->w(), bt);
      Fl_RGB_Image *image = new Fl_RGB_Image((const uchar*)CGBitmapContextGetData(gc), win->w(), bt, 4,
                                             CGBitmapContextGetBytesPerRow(gc)); // 10.2
      image->draw(x_offset, y_offset); // draw title bar to PostScript
      delete image;
      CGContextRelease(gc);
    }
    this->print_widget(win, x_offset, y_offset + bt);
    return;
  }
  Fl_Display_Device::display_device()->set_current(); // send win to front and make it current
  NSString *title = [fl_xid(win) title];
  [title retain];
  [fl_xid(win) setTitle:@""]; // temporarily set a void window title
  win->show();
  fl_gc = NULL;
  Fl::check();
  // capture the window title bar with no title
  CGImageRef img = NULL;
  unsigned char *bitmap = NULL;
  if (to_quartz)
    img = Fl_X::CGImage_from_window_rect(win, 0, -bt, win->w(), bt);
  else
    bitmap = Fl_X::bitmap_from_window_rect(win, 0, -bt, win->w(), bt, &bpp);
  [fl_xid(win) setTitle:title]; // put back the window title
  this->set_current(); // back to the Fl_Paged_Device
  if (img && to_quartz) { // print the title bar
    CGRect rect = CGRectMake(x_offset, y_offset, win->w(), bt);
    Fl_X::q_begin_image(rect, 0, 0, win->w(), bt);
    CGContextDrawImage(fl_gc, rect, img);
    Fl_X::q_end_image();
    CFRelease(img);
  }
  else if(!to_quartz) {
    Fl_RGB_Image *rgb = new Fl_RGB_Image(bitmap, win->w(), bt, bpp);
    rgb->draw(x_offset, y_offset);
    delete rgb;
    delete[] bitmap;
  }
  if (win->label()) { // print the window title
    const int skip = 65; // approx width of the zone of the 3 window control buttons
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4
    if (fl_mac_os_version >= 100400 && to_quartz) { // use Cocoa string drawing with exact title bar font
      // the exact font is LucidaGrande 13 pts (and HelveticaNeueDeskInterface-Regular with 10.10)
      NSGraphicsContext *current = [NSGraphicsContext currentContext];
      [NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithGraphicsPort:fl_gc flipped:YES]];//10.4
      NSDictionary *attr = [NSDictionary dictionaryWithObject:[NSFont titleBarFontOfSize:0] 
						       forKey:NSFontAttributeName];
      NSSize size = [title sizeWithAttributes:attr];
      int x = x_offset + win->w()/2 - size.width/2;
      if (x < x_offset+skip) x = x_offset+skip;
      NSRect r = NSMakeRect(x, y_offset+bt/2+4, win->w() - skip, bt);
      [[NSGraphicsContext currentContext] setShouldAntialias:YES];
      [title drawWithRect:r options:(NSStringDrawingOptions)0 attributes:attr]; // 10.4
      [[NSGraphicsContext currentContext] setShouldAntialias:NO];
      [NSGraphicsContext setCurrentContext:current];
    }
    else
#endif
    {
      fl_font(FL_HELVETICA, 14);
      fl_color(FL_BLACK);
      int x = x_offset + win->w()/2 - fl_width(win->label())/2;
      if (x < x_offset+skip) x = x_offset+skip;
      fl_push_clip(x_offset, y_offset, win->w(), bt);
      fl_draw(win->label(), x, y_offset+bt/2+4);
      fl_pop_clip();
    }
  }
  [title release];
  this->print_widget(win, x_offset, y_offset + bt); // print the window inner part
}

void Fl_X::gl_start(NSOpenGLContext *ctxt) {
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_8
  if (views_use_CA) {
    Fl_X::q_release_context();
    [(FLViewLayer*)[fl_window contentView] viewFrameDidChange];
    [[fl_window contentView] layer].contentsScale = 1.;
  }
#endif
  [ctxt update]; // supports window resizing
}


/* Returns the address of a Carbon function after dynamically loading the Carbon library if needed.
 Supports old Mac OS X versions that may use a couple of Carbon calls:
 GetKeys used by OS X 10.3 or before (in Fl::get_key())
 PMSessionPageSetupDialog and PMSessionPrintDialog used by 10.4 or before (in Fl_Printer::start_job())
 */
void *Fl_X::get_carbon_function(const char *function_name) {
  static void *carbon = dlopen("/System/Library/Frameworks/Carbon.framework/Carbon", RTLD_LAZY);
  return (carbon ? dlsym(carbon, function_name) : NULL);
}
  
/* Returns the version of the running Mac OS as an int such as 100802 for 10.8.2
 */
int Fl_X::calc_mac_os_version() {
  if (fl_mac_os_version) return fl_mac_os_version;
  int M, m, b = 0;
  NSAutoreleasePool *localPool = [[NSAutoreleasePool alloc] init];
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_10
  if ([NSProcessInfo instancesRespondToSelector:@selector(operatingSystemVersion)]) {
    NSOperatingSystemVersion version = [[NSProcessInfo processInfo] operatingSystemVersion];
    M = version.majorVersion;
    m = version.minorVersion;
    b = version.patchVersion;
  }
  else
#endif
  {
    NSDictionary * sv = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"];
    const char *s = [[sv objectForKey:@"ProductVersion"] UTF8String];
    sscanf(s, "%d.%d.%d", &M, &m, &b);
  }
  [localPool release];
  fl_mac_os_version = M*10000 + m*100 + b;
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_14
  if (fl_mac_os_version >= 101400) views_use_CA = YES;
#endif
  //if (fl_mac_os_version >= 101300) views_use_CA = YES; // to get as with mojave
  return fl_mac_os_version;
}

#endif // __APPLE__

//
// End of "$Id$".
//