summaryrefslogtreecommitdiff
path: root/src/haiku_support.cc
blob: 28d8fae39b76f02914af5e788a3e0b8265d4e878 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
/* Haiku window system support.  Hey, Emacs, this is -*- C++ -*-
   Copyright (C) 2021-2023 Free Software Foundation, Inc.

This file is part of GNU Emacs.

GNU Emacs is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.

GNU Emacs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.  */

#include <config.h>
#include <attribute.h>

#include <app/Application.h>
#include <app/Cursor.h>
#include <app/Clipboard.h>
#include <app/Messenger.h>
#include <app/Roster.h>

#include <interface/GraphicsDefs.h>
#include <interface/InterfaceDefs.h>
#include <interface/Bitmap.h>
#include <interface/Window.h>
#include <interface/View.h>
#include <interface/Screen.h>
#include <interface/ScrollBar.h>
#include <interface/Region.h>
#include <interface/Menu.h>
#include <interface/MenuItem.h>
#include <interface/PopUpMenu.h>
#include <interface/MenuBar.h>
#include <interface/Alert.h>
#include <interface/Button.h>
#include <interface/ControlLook.h>
#include <interface/Deskbar.h>
#include <interface/ListView.h>
#include <interface/StringItem.h>
#include <interface/SplitView.h>
#include <interface/ScrollView.h>
#include <interface/StringView.h>
#include <interface/TextControl.h>
#include <interface/CheckBox.h>

#include <locale/UnicodeChar.h>

#include <game/WindowScreen.h>
#include <game/DirectWindow.h>

#include <storage/FindDirectory.h>
#include <storage/Entry.h>
#include <storage/Path.h>
#include <storage/FilePanel.h>
#include <storage/AppFileInfo.h>
#include <storage/Path.h>
#include <storage/PathFinder.h>
#include <storage/Node.h>

#include <support/Beep.h>
#include <support/DataIO.h>
#include <support/Locker.h>
#include <support/ObjectList.h>

#include <translation/TranslatorRoster.h>
#include <translation/TranslationDefs.h>
#include <translation/TranslationUtils.h>

#include <kernel/OS.h>
#include <kernel/fs_attr.h>
#include <kernel/scheduler.h>

#include <private/interface/ToolTip.h>
#include <private/interface/WindowPrivate.h>

#include <cmath>
#include <cstring>
#include <cstdint>
#include <cstdio>
#include <csignal>
#include <cfloat>

#ifdef USE_BE_CAIRO
#include <cairo.h>
#endif

#include "haiku_support.h"

/* Some messages that Emacs sends to itself.  */
enum
  {
    SCROLL_BAR_UPDATE	     = 3000,
    WAIT_FOR_RELEASE	     = 3001,
    RELEASE_NOW		     = 3002,
    CANCEL_DROP		     = 3003,
    SHOW_MENU_BAR	     = 3004,
    BE_MENU_BAR_OPEN	     = 3005,
    QUIT_APPLICATION	     = 3006,
    REPLAY_MENU_BAR	     = 3007,
    FONT_FAMILY_SELECTED     = 3008,
    FONT_STYLE_SELECTED	     = 3009,
    FILE_PANEL_SELECTION     = 3010,
    QUIT_PREVIEW_DIALOG	     = 3011,
    SET_FONT_INDICES	     = 3012,
    SET_PREVIEW_DIALOG	     = 3013,
    UPDATE_PREVIEW_DIALOG    = 3014,
    SEND_MOVE_FRAME_EVENT    = 3015,
    SET_DISABLE_ANTIALIASING = 3016,
  };

/* X11 keysyms that we use.  */
enum
  {
    KEY_BACKSPACE	  = 0xff08,
    KEY_TAB		  = 0xff09,
    KEY_RETURN		  = 0xff0d,
    KEY_PAUSE		  = 0xff13,
    KEY_ESCAPE		  = 0xff1b,
    KEY_DELETE		  = 0xffff,
    KEY_HOME		  = 0xff50,
    KEY_LEFT_ARROW	  = 0xff51,
    KEY_UP_ARROW	  = 0xff52,
    KEY_RIGHT_ARROW	  = 0xff53,
    KEY_DOWN_ARROW	  = 0xff54,
    KEY_PAGE_UP		  = 0xff55,
    KEY_PAGE_DOWN	  = 0xff56,
    KEY_END		  = 0xff57,
    KEY_PRINT		  = 0xff61,
    KEY_INSERT		  = 0xff63,
    /* This is used to indicate the first function key.  */
    KEY_F1		  = 0xffbe,
    /* These are found on some multilingual keyboards.  */
    KEY_HANGUL		  = 0xff31,
    KEY_HANGUL_HANJA	  = 0xff34,
    KEY_HIRIGANA_KATAGANA = 0xff27,
    KEY_ZENKAKU_HANKAKU	  = 0xff2a,
  };

struct font_selection_dialog_message
{
  /* Whether or not font selection was canceled.  */
  bool_bf cancel : 1;

  /* Whether or not a size was explicitly specified.  */
  bool_bf size_specified : 1;

  /* Whether or not antialiasing should be disabled.  */
  bool_bf disable_antialias : 1;

  /* The index of the selected font family.  */
  int family_idx;

  /* The index of the selected font style.  */
  int style_idx;

  /* The selected font size.  */
  int size;
};

/* The color space of the main screen.  B_NO_COLOR_SPACE means it has
   not yet been computed.  */
static color_space dpy_color_space = B_NO_COLOR_SPACE;

/* The keymap, or NULL if it has not been initialized.  */
static key_map *key_map;

/* Indices of characters into the keymap.  */
static char *key_chars;

/* Lock around keymap data, since it's touched from different
   threads.  */
static BLocker key_map_lock;

/* The locking semantics of BWindows running in multiple threads are
   so complex that child frame state (which is the only state that is
   shared between different BWindows at runtime) does best with a
   single global lock.  */
static BLocker child_frame_lock;

/* Variable where the popup menu thread returns the chosen menu
   item.  */
static BMessage volatile *popup_track_message;

/* Variable in which alert dialog threads return the selected button
   number.  */
static int32 volatile alert_popup_value;

/* The view that has the passive grab.  */
static void *grab_view;

/* The locker for that variable.  */
static BLocker grab_view_locker;

/* Whether or not a drag-and-drop operation is in progress.  */
static bool drag_and_drop_in_progress;

/* Many places require us to lock the child frame data, and then lock
   the locker of some random window.  Unfortunately, locking such a
   window might be delayed due to an arriving message, which then
   calls a callback inside that window that tries to lock the child
   frame data but doesn't finish since the child frame lock is already
   held, not letting the code that held the child frame lock proceed,
   thereby causing a deadlock.

   Rectifying that problem is simple: all code in a looper callback
   must lock the child frame data with this macro instead.

   IOW, if some other code is already running with the child frame
   lock held, don't interfere: wait until it's finished before
   continuing.  */
#define CHILD_FRAME_LOCK_INSIDE_LOOPER_CALLBACK		\
  if (child_frame_lock.LockWithTimeout (200) != B_OK)	\
    {							\
      /* The Haiku equivalent of XPutBackEvent.  */	\
      if (CurrentMessage ())				\
	PostMessage (CurrentMessage ());		\
    }							\
  else

/* This could be a private API, but it's used by (at least) the Qt
   port, so it's probably here to stay.  */
extern status_t get_subpixel_antialiasing (bool *);

/* The ID of the thread the BApplication is running in.  */
static thread_id app_thread;

_Noreturn void
gui_abort (const char *msg)
{
  fprintf (stderr, "Abort in GUI code: %s\n", msg);
  fprintf (stderr, "Under Haiku, Emacs cannot recover from errors in GUI code\n");
  fprintf (stderr, "App Server disconnects usually manifest as bitmap "
	   "initialization failures or lock failures.");
  abort ();
}

struct be_popup_menu_data
{
  int x, y;
  BPopUpMenu *menu;
};

static int32
be_popup_menu_thread_entry (void *thread_data)
{
  struct be_popup_menu_data *data;
  struct haiku_dummy_event dummy;
  BMenuItem *it;

  data = (struct be_popup_menu_data *) thread_data;

  it = data->menu->Go (BPoint (data->x, data->y));

  if (it)
    popup_track_message = it->Message ();
  else
    popup_track_message = NULL;

  haiku_write (DUMMY_EVENT, &dummy);
  return 0;
}

/* Convert a raw character RAW produced by the keycode KEY into a key
   symbol and place it in KEYSYM.

   If RAW cannot be converted into a keysym, value is 0.  If RAW can
   be converted into a keysym, but it should be ignored, value is -1.

   Any other value means success, and that the keysym should be used
   instead of mapping the keycode into a character.  */

static int
keysym_from_raw_char (int32 raw, int32 key, unsigned *code)
{
  switch (raw)
    {
    case B_BACKSPACE:
      *code = KEY_BACKSPACE;
      break;
    case B_RETURN:
      *code = KEY_RETURN;
      break;
    case B_TAB:
      *code = KEY_TAB;
      break;
    case B_ESCAPE:
      *code = KEY_ESCAPE;
      break;
    case B_LEFT_ARROW:
      *code = KEY_LEFT_ARROW;
      break;
    case B_RIGHT_ARROW:
      *code = KEY_RIGHT_ARROW;
      break;
    case B_UP_ARROW:
      *code = KEY_UP_ARROW;
      break;
    case B_DOWN_ARROW:
      *code = KEY_DOWN_ARROW;
      break;
    case B_INSERT:
      *code = KEY_INSERT;
      break;
    case B_DELETE:
      *code = KEY_DELETE;
      break;
    case B_HOME:
      *code = KEY_HOME;
      break;
    case B_END:
      *code = KEY_END;
      break;
    case B_PAGE_UP:
      *code = KEY_PAGE_UP;
      break;
    case B_PAGE_DOWN:
      *code = KEY_PAGE_DOWN;
      break;

    case B_FUNCTION_KEY:
      *code = KEY_F1 + key - 2;

      if (*code - KEY_F1 == 12)
	*code = KEY_PRINT;
      else if (*code - KEY_F1 == 13)
	/* Okay, Scroll Lock is a bit too much: keyboard.c doesn't
	   know about it yet, and it shouldn't, since that's a
	   modifier key.

	   *code = KEY_SCROLL_LOCK; */
	return -1;
      else if (*code - KEY_F1 == 14)
	*code = KEY_PAUSE;

      break;

    case B_HANGUL:
      *code = KEY_HANGUL;
      break;
    case B_HANGUL_HANJA:
      *code = KEY_HANGUL_HANJA;
      break;
    case B_KATAKANA_HIRAGANA:
      *code = KEY_HIRIGANA_KATAGANA;
      break;
    case B_HANKAKU_ZENKAKU:
      *code = KEY_ZENKAKU_HANKAKU;
      break;

    default:
      return 0;
    }

  return 1;
}

static void
map_key (char *chars, int32 offset, uint32_t *c)
{
  int size = chars[offset++];
  switch (size)
    {
    case 0:
      break;

    case 1:
      *c = chars[offset];
      break;

    default:
      {
        char str[5];
        int i = (size <= 4) ? size : 4;
        strncpy (str, &(chars[offset]), i);
        str[i] = '0';
	*c = BUnicodeChar::FromUTF8 ((char *) &str);
	break;
      }
    }
}

static void
map_shift (uint32_t kc, uint32_t *ch)
{
  if (!key_map_lock.Lock ())
    gui_abort ("Failed to lock keymap");
  if (!key_map)
    get_key_map (&key_map, &key_chars);
  if (!key_map)
    return;
  if (kc >= 128)
    return;

  int32_t m = key_map->shift_map[kc];
  map_key (key_chars, m, ch);
  key_map_lock.Unlock ();
}

static void
map_caps (uint32_t kc, uint32_t *ch)
{
  if (!key_map_lock.Lock ())
    gui_abort ("Failed to lock keymap");
  if (!key_map)
    get_key_map (&key_map, &key_chars);
  if (!key_map)
    return;
  if (kc >= 128)
    return;

  int32_t m = key_map->caps_map[kc];
  map_key (key_chars, m, ch);
  key_map_lock.Unlock ();
}

static void
map_caps_shift (uint32_t kc, uint32_t *ch)
{
  if (!key_map_lock.Lock ())
    gui_abort ("Failed to lock keymap");
  if (!key_map)
    get_key_map (&key_map, &key_chars);
  if (!key_map)
    return;
  if (kc >= 128)
    return;

  int32_t m = key_map->caps_shift_map[kc];
  map_key (key_chars, m, ch);
  key_map_lock.Unlock ();
}

static void
map_normal (uint32_t kc, uint32_t *ch)
{
  if (!key_map_lock.Lock ())
    gui_abort ("Failed to lock keymap");
  if (!key_map)
    get_key_map (&key_map, &key_chars);
  if (!key_map)
    return;
  if (kc >= 128)
    return;

  int32_t m = key_map->normal_map[kc];
  map_key (key_chars, m, ch);
  key_map_lock.Unlock ();
}

static BRect
get_zoom_rect (BWindow *window)
{
  BScreen screen;
  BDeskbar deskbar;
  BRect screen_frame;
  BRect frame;
  BRect deskbar_frame;
  BRect window_frame;
  BRect decorator_frame;

  if (!screen.IsValid ())
    gui_abort ("Failed to calculate screen rect");

  screen_frame = frame = screen.Frame ();
  deskbar_frame = deskbar.Frame ();

  if (!(modifiers () & B_SHIFT_KEY) && !deskbar.IsAutoHide ())
    {
      switch (deskbar.Location ())
	{
	case B_DESKBAR_TOP:
	  frame.top = deskbar_frame.bottom + 2;
	  break;

	case B_DESKBAR_BOTTOM:
	case B_DESKBAR_LEFT_BOTTOM:
	case B_DESKBAR_RIGHT_BOTTOM:
	  frame.bottom = deskbar_frame.top - 2;
	  break;

	case B_DESKBAR_LEFT_TOP:
	  if (!deskbar.IsExpanded ())
	    frame.top = deskbar_frame.bottom + 2;
	  else if (!deskbar.IsAlwaysOnTop ()
		   && !deskbar.IsAutoRaise ())
	    frame.left = deskbar_frame.right + 2;
	  break;

	default:
	  if (deskbar.IsExpanded ()
	      && !deskbar.IsAlwaysOnTop ()
	      && !deskbar.IsAutoRaise ())
	    frame.right = deskbar_frame.left - 2;
	}
    }

  if (window)
    {
      window_frame = window->Frame ();
      decorator_frame = window->DecoratorFrame ();

      frame.top += (window_frame.top
		    - decorator_frame.top);
      frame.bottom -= (decorator_frame.bottom
		       - window_frame.bottom);
      frame.left += (window_frame.left
		     - decorator_frame.left);
      frame.right -= (decorator_frame.right
		      - window_frame.right);

      if (frame.top > deskbar_frame.bottom
	  || frame.bottom < deskbar_frame.top)
	{
	  frame.left = screen_frame.left + (window_frame.left
					    - decorator_frame.left);
	  frame.right = screen_frame.right - (decorator_frame.right
					      - window_frame.right);
	}
    }

  return frame;
}

/* Invisible window used to get B_SCREEN_CHANGED events.  */
class EmacsScreenChangeMonitor : public BWindow
{
  BRect previous_screen_frame;

public:
  EmacsScreenChangeMonitor (void) : BWindow (BRect (-100, -100, 0, 0), "",
					     B_NO_BORDER_WINDOW_LOOK,
					     B_FLOATING_ALL_WINDOW_FEEL,
					     B_AVOID_FRONT | B_AVOID_FOCUS)
  {
    BScreen screen (this);

    if (!screen.IsValid ())
      return;

    previous_screen_frame = screen.Frame ();

    /* Immediately show this window upon creation.  It will not steal
       the focus or become visible.  */
    Show ();

    if (!LockLooper ())
      return;

    Hide ();
    UnlockLooper ();
  }

  void
  DispatchMessage (BMessage *msg, BHandler *handler)
  {
    struct haiku_screen_changed_event rq;
    BRect frame;

    if (msg->what == B_SCREEN_CHANGED)
      {
	if (msg->FindInt64 ("when", &rq.when) != B_OK)
	  rq.when = 0;

	if (msg->FindRect ("frame", &frame) != B_OK
	    || frame != previous_screen_frame)
	  {
	    haiku_write (SCREEN_CHANGED_EVENT, &rq);

	    if (frame.IsValid ())
	      previous_screen_frame = frame;
	  }
      }

    BWindow::DispatchMessage (msg, handler);
  }
};

class Emacs : public BApplication
{
public:
  BMessage settings;
  bool settings_valid_p;
  EmacsScreenChangeMonitor *monitor;

  Emacs (void) : BApplication ("application/x-vnd.GNU-emacs"),
		 settings_valid_p (false)
  {
    BPath settings_path;

    if (find_directory (B_USER_SETTINGS_DIRECTORY, &settings_path) != B_OK)
      return;

    settings_path.Append (PACKAGE_NAME);

    BEntry entry (settings_path.Path ());
    BFile settings_file (&entry, B_READ_ONLY | B_CREATE_FILE);

    if (settings.Unflatten (&settings_file) != B_OK)
      return;

    settings_valid_p = true;
    monitor = new EmacsScreenChangeMonitor;
  }

  ~Emacs (void)
  {
    if (monitor->LockLooper ())
      monitor->Quit ();
    else
      delete monitor;
  }

  void
  AboutRequested (void)
  {
    BAlert *about = new BAlert (PACKAGE_NAME,
				PACKAGE_STRING
				"\nThe extensible, self-documenting, real-time display editor.",
				"Close");
    about->Go ();
  }

  bool
  QuitRequested (void)
  {
    struct haiku_app_quit_requested_event rq;
    struct haiku_session_manager_reply reply;
    int32 reply_type;

    haiku_write (APP_QUIT_REQUESTED_EVENT, &rq);

    if (read_port (port_emacs_to_session_manager,
		   &reply_type, &reply, sizeof reply) < B_OK)
      /* Return true so the system kills us, since there's no real
	 alternative if this read fails.  */
      return true;

    return reply.quit_reply;
  }

  void
  MessageReceived (BMessage *msg)
  {
    struct haiku_clipboard_changed_event rq;

    if (msg->what == QUIT_APPLICATION)
      Quit ();
    else if (msg->what == B_CLIPBOARD_CHANGED)
      haiku_write (CLIPBOARD_CHANGED_EVENT, &rq);
    else if (msg->what == B_KEY_MAP_LOADED)
      {
	/* Install the new keymap.  Or rather, clear key_map -- Emacs
	   will fetch it again from the main thread the next time it
	   is needed.  */
	if (key_map_lock.Lock ())
	  {
	    if (key_map)
	      free (key_map);

	    if (key_chars)
	      free (key_chars);

	    key_map = NULL;
	    key_chars = NULL;
	    key_map_lock.Unlock ();
	  }
      }
    else
      BApplication::MessageReceived (msg);
  }
};

class EmacsWindow : public BWindow
{
public:
  struct child_frame
  {
    struct child_frame *next;
    int xoff, yoff;
    EmacsWindow *window;
  } *subset_windows;

  EmacsWindow *parent;
  BRect pre_fullscreen_rect;
  BRect pre_zoom_rect;
  int x_before_zoom;
  int y_before_zoom;
  bool shown_flag;
  volatile bool was_shown_p;
  bool menu_bar_active_p;
  bool override_redirect_p;
  window_look pre_override_redirect_look;
  window_feel pre_override_redirect_feel;
  uint32 pre_override_redirect_workspaces;
  int window_id;
  bool *menus_begun;
  enum haiku_z_group z_group;
  bool tooltip_p;
  enum haiku_fullscreen_mode fullscreen_mode;

  EmacsWindow () : BWindow (BRect (0, 0, 0, 0), "", B_TITLED_WINDOW_LOOK,
			    B_NORMAL_WINDOW_FEEL, B_NO_SERVER_SIDE_WINDOW_MODIFIERS),
		   subset_windows (NULL),
		   parent (NULL),
		   x_before_zoom (INT_MIN),
		   y_before_zoom (INT_MIN),
		   shown_flag (false),
		   was_shown_p (false),
		   menu_bar_active_p (false),
		   override_redirect_p (false),
		   menus_begun (NULL),
		   z_group (Z_GROUP_NONE),
		   tooltip_p (false),
		   fullscreen_mode (FULLSCREEN_MODE_NONE)
  {
    /* This pulse rate is used by scroll bars for repeating a button
       action while a button is held down.  */
    SetPulseRate (30000);
  }

  ~EmacsWindow ()
  {
    if (!child_frame_lock.Lock ())
      gui_abort ("Failed to lock child frame state lock");
    struct child_frame *next;
    for (struct child_frame *f = subset_windows; f; f = next)
      {
	if (f->window->LockLooper ())
	  gui_abort ("Failed to lock looper for unparent");
	f->window->Unparent ();
	f->window->UnlockLooper ();
	next = f->next;
	delete f;
      }

    if (this->parent)
      UnparentAndUnlink ();
    child_frame_lock.Unlock ();
  }

  void
  RecomputeFeel (void)
  {
    if (override_redirect_p || tooltip_p)
      SetFeel (kMenuWindowFeel);
    else if (parent)
      SetFeel (B_FLOATING_SUBSET_WINDOW_FEEL);
    else if (z_group == Z_GROUP_ABOVE)
      SetFeel (B_FLOATING_ALL_WINDOW_FEEL);
    else
      SetFeel (B_NORMAL_WINDOW_FEEL);
  }

  void
  UpwardsSubset (EmacsWindow *w)
  {
    for (; w; w = w->parent)
      AddToSubset (w);
  }

  void
  UpwardsSubsetChildren (EmacsWindow *w)
  {
    if (!LockLooper ())
      gui_abort ("Failed to lock looper for subset");
    if (!child_frame_lock.Lock ())
      gui_abort ("Failed to lock child frame state lock");
    UpwardsSubset (w);
    for (struct child_frame *f = subset_windows; f;
	 f = f->next)
      f->window->UpwardsSubsetChildren (w);
    child_frame_lock.Unlock ();
    UnlockLooper ();
  }

  void
  UpwardsUnSubset (EmacsWindow *w)
  {
    for (; w; w = w->parent)
      RemoveFromSubset (w);
  }

  void
  UpwardsUnSubsetChildren (EmacsWindow *w)
  {
    if (!LockLooper ())
      gui_abort ("Failed to lock looper for unsubset");
    if (!child_frame_lock.Lock ())
      gui_abort ("Failed to lock child frame state lock");
    UpwardsUnSubset (w);
    for (struct child_frame *f = subset_windows; f;
	 f = f->next)
      f->window->UpwardsUnSubsetChildren (w);
    child_frame_lock.Unlock ();
    UnlockLooper ();
  }

  void
  Unparent (void)
  {
    EmacsWindow *parent;

    if (!child_frame_lock.Lock ())
      gui_abort ("Failed to lock child frame state lock");

    parent = this->parent;
    this->parent = NULL;
    RecomputeFeel ();
    UpwardsUnSubsetChildren (parent);
    this->RemoveFromSubset (this);
    child_frame_lock.Unlock ();
  }

  void
  UnparentAndUnlink (void)
  {
    if (!child_frame_lock.Lock ())
      gui_abort ("Failed to lock child frame state lock");
    this->parent->UnlinkChild (this);
    this->Unparent ();
    child_frame_lock.Unlock ();
  }

  void
  UnlinkChild (EmacsWindow *window)
  {
    struct child_frame *last = NULL;
    struct child_frame *tem = subset_windows;

    for (; tem; last = tem, tem = tem->next)
      {
	if (tem->window == window)
	  {
	    if (last)
	      last->next = tem->next;
	    else
	      subset_windows = tem->next;
	    delete tem;
	    return;
	  }
      }

    gui_abort ("Failed to unlink child frame");
  }

  void
  ParentTo (EmacsWindow *window)
  {
    if (!child_frame_lock.Lock ())
      gui_abort ("Failed to lock child frame state lock");

    if (this->parent)
      UnparentAndUnlink ();

    this->parent = window;
    RecomputeFeel ();
    this->AddToSubset (this);
    if (!IsHidden () && this->parent)
      UpwardsSubsetChildren (parent);
    window->LinkChild (this);

    child_frame_lock.Unlock ();
  }

  void
  LinkChild (EmacsWindow *window)
  {
    struct child_frame *f = new struct child_frame;

    for (struct child_frame *f = subset_windows; f;
	 f = f->next)
      {
	if (window == f->window)
	  gui_abort ("Trying to link a child frame that is already present");
      }

    f->window = window;
    f->next = subset_windows;
    f->xoff = -1;
    f->yoff = -1;

    subset_windows = f;
  }

  void
  MoveToIncludingFrame (int x, int y)
  {
    BRect decorator, frame;

    decorator = DecoratorFrame ();
    frame = Frame ();

    MoveTo (x + frame.left - decorator.left,
	    y + frame.top - decorator.top);
  }

  void
  DoMove (struct child_frame *f)
  {
    BRect frame = this->Frame ();
    f->window->MoveToIncludingFrame (frame.left + f->xoff,
				     frame.top + f->yoff);
  }

  void
  DoUpdateWorkspace (struct child_frame *f)
  {
    f->window->SetWorkspaces (this->Workspaces ());
  }

  void
  MoveChild (EmacsWindow *window, int xoff, int yoff,
	     int weak_p)
  {
    if (!child_frame_lock.Lock ())
      gui_abort ("Failed to lock child frame state lock");

    for (struct child_frame *f = subset_windows; f;
	 f = f->next)
      {
	if (window == f->window)
	  {
	    f->xoff = xoff;
	    f->yoff = yoff;
	    if (!weak_p)
	      DoMove (f);

	    child_frame_lock.Unlock ();
	    return;
	  }
      }

    child_frame_lock.Unlock ();
    gui_abort ("Trying to move a child frame that doesn't exist");
  }

  void
  WindowActivated (bool activated)
  {
    struct haiku_activation_event rq;
    rq.window = this;
    rq.activated_p = activated;

    haiku_write (ACTIVATION, &rq);
  }

  void
  MessageReceived (BMessage *msg)
  {
    if (msg->WasDropped ())
      {
	BPoint whereto;
	int64 threadid;
	struct haiku_drag_and_drop_event rq;

	if (msg->FindInt64 ("emacs:thread_id", &threadid) == B_OK
	    && threadid == find_thread (NULL))
	  return;

	whereto = msg->DropPoint ();

	this->ConvertFromScreen (&whereto);

	rq.window = this;
	rq.message = DetachCurrentMessage ();
	rq.x = whereto.x;
	rq.y = whereto.y;

	haiku_write (DRAG_AND_DROP_EVENT, &rq);
      }
    else if (msg->GetPointer ("menuptr"))
      {
	struct haiku_menu_bar_select_event rq;

	rq.window = this;
	rq.ptr = (void *) msg->GetPointer ("menuptr");

	haiku_write (MENU_BAR_SELECT_EVENT, &rq);
      }
    else
      BWindow::MessageReceived (msg);
  }

  void
  DispatchMessage (BMessage *msg, BHandler *handler)
  {
    if (msg->what == B_KEY_DOWN || msg->what == B_KEY_UP)
      {
	struct haiku_key_event rq;

	/* Pass through key events to the regular dispatch mechanism
	   if the menu bar active, so that key navigation can work.  */
	if (menu_bar_active_p)
	  {
	    BWindow::DispatchMessage (msg, handler);
	    return;
	  }

	rq.window = this;

	int32 raw, key;
	int ret;
	msg->FindInt32 ("raw_char", &raw);
	msg->FindInt32 ("key", &key);
	msg->FindInt64 ("when", &rq.time);

	rq.modifiers = 0;
	uint32_t mods = modifiers ();

	if (mods & B_SHIFT_KEY)
	  rq.modifiers |= HAIKU_MODIFIER_SHIFT;

	if (mods & B_CONTROL_KEY)
	  rq.modifiers |= HAIKU_MODIFIER_CTRL;

	if (mods & B_COMMAND_KEY)
	  rq.modifiers |= HAIKU_MODIFIER_ALT;

	if (mods & B_OPTION_KEY)
	  rq.modifiers |= HAIKU_MODIFIER_SUPER;

	ret = keysym_from_raw_char (raw, key, &rq.keysym);

	if (!ret)
	  rq.keysym = 0;

	if (ret < 0)
	  return;

	rq.multibyte_char = 0;

	if (!rq.keysym)
	  {
	    if (mods & B_SHIFT_KEY)
	      {
		if (mods & B_CAPS_LOCK)
		  map_caps_shift (key, &rq.multibyte_char);
		else
		  map_shift (key, &rq.multibyte_char);
	      }
	    else
	      {
		if (mods & B_CAPS_LOCK)
		  map_caps (key, &rq.multibyte_char);
		else
		  map_normal (key, &rq.multibyte_char);
	      }
	  }

	haiku_write (msg->what == B_KEY_DOWN ? KEY_DOWN : KEY_UP, &rq);
      }
    else if (msg->what == B_MOUSE_WHEEL_CHANGED)
      {
	struct haiku_wheel_move_event rq;
	rq.window = this;
	rq.modifiers = 0;

	uint32_t mods = modifiers ();

	if (mods & B_SHIFT_KEY)
	  rq.modifiers |= HAIKU_MODIFIER_SHIFT;

	if (mods & B_CONTROL_KEY)
	  rq.modifiers |= HAIKU_MODIFIER_CTRL;

	if (mods & B_COMMAND_KEY)
	  rq.modifiers |= HAIKU_MODIFIER_ALT;

	if (mods & B_OPTION_KEY)
	  rq.modifiers |= HAIKU_MODIFIER_SUPER;

	float dx, dy;
	if (msg->FindFloat ("be:wheel_delta_x", &dx) == B_OK &&
	    msg->FindFloat ("be:wheel_delta_y", &dy) == B_OK)
	  {
	    rq.delta_x = dx;
	    rq.delta_y = dy;

	    haiku_write (WHEEL_MOVE_EVENT, &rq);
	  };
      }
    else if (msg->what == SEND_MOVE_FRAME_EVENT)
      FrameMoved (Frame ().LeftTop ());
    else if (msg->what == B_SCREEN_CHANGED)
      {
	if (fullscreen_mode != FULLSCREEN_MODE_NONE)
	  SetFullscreen (fullscreen_mode);

	BWindow::DispatchMessage (msg, handler);
      }
    else
      BWindow::DispatchMessage (msg, handler);
  }

  void
  MenusBeginning (void)
  {
    struct haiku_menu_bar_state_event rq;

    rq.window = this;
    if (!menus_begun)
      haiku_write (MENU_BAR_OPEN, &rq);
    else
      *menus_begun = true;

    menu_bar_active_p = true;
  }

  void
  MenusEnded ()
  {
    struct haiku_menu_bar_state_event rq;
    rq.window = this;

    haiku_write (MENU_BAR_CLOSE, &rq);
    menu_bar_active_p = false;
  }

  void
  FrameResized (float newWidth, float newHeight)
  {
    struct haiku_resize_event rq;
    rq.window = this;
    rq.width = newWidth + 1.0f;
    rq.height = newHeight + 1.0f;

    haiku_write (FRAME_RESIZED, &rq);
    BWindow::FrameResized (newWidth, newHeight);
  }

  void
  FrameMoved (BPoint new_position)
  {
    struct haiku_move_event rq;
    BRect frame, decorator_frame;
    struct child_frame *f;

    if (fullscreen_mode == FULLSCREEN_MODE_WIDTH
	&& new_position.x != 0)
      {
	MoveTo (0, new_position.y);
	return;
      }

    if (fullscreen_mode == FULLSCREEN_MODE_HEIGHT
	&& new_position.y != 0)
      {
	MoveTo (new_position.x, 0);
	return;
      }

    rq.window = this;
    rq.x = std::lrint (new_position.x);
    rq.y = std::lrint (new_position.y);

    frame = Frame ();
    decorator_frame = DecoratorFrame ();

    rq.decorator_width
      = std::lrint (frame.left - decorator_frame.left);
    rq.decorator_height
      = std::lrint (frame.top - decorator_frame.top);

    haiku_write (MOVE_EVENT, &rq);

    CHILD_FRAME_LOCK_INSIDE_LOOPER_CALLBACK
      {
	for (f = subset_windows; f; f = f->next)
	  DoMove (f);
	child_frame_lock.Unlock ();

	BWindow::FrameMoved (new_position);
      }
  }

  void
  WorkspacesChanged (uint32_t old, uint32_t n)
  {
    struct child_frame *f;

    CHILD_FRAME_LOCK_INSIDE_LOOPER_CALLBACK
      {
	for (f = subset_windows; f; f = f->next)
	  DoUpdateWorkspace (f);

	child_frame_lock.Unlock ();
      }
  }

  void
  EmacsMoveTo (int x, int y)
  {
    if (!child_frame_lock.Lock ())
      gui_abort ("Failed to lock child frame state lock");

    if (!this->parent)
      this->MoveToIncludingFrame (x, y);
    else
      this->parent->MoveChild (this, x, y, 0);
    child_frame_lock.Unlock ();
  }

  bool
  QuitRequested ()
  {
    struct haiku_quit_requested_event rq;
    rq.window = this;
    haiku_write (QUIT_REQUESTED, &rq);
    return false;
  }

  void
  Minimize (bool minimized_p)
  {
    struct haiku_iconification_event rq;

    rq.window = this;
    rq.iconified_p = !parent && minimized_p;
    haiku_write (ICONIFICATION, &rq);

    BWindow::Minimize (minimized_p);
  }

  void
  EmacsHide (void)
  {
    if (this->IsHidden ())
      return;
    if (!child_frame_lock.Lock ())
      gui_abort ("Failed to lock child frame state lock");

    Hide ();
    if (this->parent)
      UpwardsUnSubsetChildren (this->parent);

    child_frame_lock.Unlock ();
  }

  void
  EmacsShow (void)
  {
    if (!this->IsHidden ())
      return;

    if (!child_frame_lock.Lock ())
      gui_abort ("Failed to lock child frame state lock");

    if (!was_shown_p)
      {
	/* This window is being shown for the first time, which means
	   Show will unlock the looper.  In this case, it should be
	   locked again, since the looper is unlocked when the window
	   is first created.  */

	if (!LockLooper ())
	  gui_abort ("Failed to lock looper during first window show");
	was_shown_p = true;
      }

    if (this->parent)
      shown_flag = 1;
    Show ();
    if (this->parent)
      UpwardsSubsetChildren (this->parent);

    child_frame_lock.Unlock ();
  }

  BRect
  ClearFullscreen (enum haiku_fullscreen_mode target_mode)
  {
    BRect original_frame;

    switch (fullscreen_mode)
      {
      case FULLSCREEN_MODE_MAXIMIZED:
	original_frame = pre_zoom_rect;

	if (target_mode == FULLSCREEN_MODE_NONE)
	  BWindow::Zoom (pre_zoom_rect.LeftTop (),
			 BE_RECT_WIDTH (pre_zoom_rect) - 1,
			 BE_RECT_HEIGHT (pre_zoom_rect) - 1);
	break;

      case FULLSCREEN_MODE_BOTH:
      case FULLSCREEN_MODE_HEIGHT:
      case FULLSCREEN_MODE_WIDTH:
	original_frame = pre_fullscreen_rect;
	SetFlags (Flags () & ~(B_NOT_MOVABLE
			       | B_NOT_ZOOMABLE
			       | B_NOT_RESIZABLE));

	if (target_mode != FULLSCREEN_MODE_NONE)
	  goto out;

	MoveTo (pre_fullscreen_rect.LeftTop ());
	ResizeTo (BE_RECT_WIDTH (pre_fullscreen_rect) - 1,
		  BE_RECT_HEIGHT (pre_fullscreen_rect) - 1);
	break;

      case FULLSCREEN_MODE_NONE:
	original_frame = Frame ();
	break;
      }

  out:
    fullscreen_mode = FULLSCREEN_MODE_NONE;
    return original_frame;
  }

  BRect
  FullscreenRectForMode (enum haiku_fullscreen_mode mode)
  {
    BScreen screen (this);
    BRect frame;

    if (!screen.IsValid ())
      return BRect (0, 0, 0, 0);

    frame = screen.Frame ();

    if (mode == FULLSCREEN_MODE_HEIGHT)
      frame.right -= BE_RECT_WIDTH (frame) / 2;
    else if (mode == FULLSCREEN_MODE_WIDTH)
      frame.bottom -= BE_RECT_HEIGHT (frame) / 2;

    return frame;
  }

  void
  SetFullscreen (enum haiku_fullscreen_mode mode)
  {
    BRect zoom_rect, frame;

    frame = ClearFullscreen (mode);

    switch (mode)
      {
      case FULLSCREEN_MODE_MAXIMIZED:
	pre_zoom_rect = frame;
	zoom_rect = get_zoom_rect (this);
	BWindow::Zoom (zoom_rect.LeftTop (),
		       BE_RECT_WIDTH (zoom_rect) - 1,
		       BE_RECT_HEIGHT (zoom_rect) - 1);
	break;

      case FULLSCREEN_MODE_BOTH:
	SetFlags (Flags () | B_NOT_MOVABLE);
	FALLTHROUGH;

      case FULLSCREEN_MODE_HEIGHT:
      case FULLSCREEN_MODE_WIDTH:
	SetFlags (Flags () | B_NOT_ZOOMABLE | B_NOT_RESIZABLE);
	pre_fullscreen_rect = frame;
	zoom_rect = FullscreenRectForMode (mode);
	ResizeTo (BE_RECT_WIDTH (zoom_rect) - 1,
		  BE_RECT_HEIGHT (zoom_rect) - 1);
	MoveTo (zoom_rect.left, zoom_rect.top);
	break;

      case FULLSCREEN_MODE_NONE:
	break;
      }

    fullscreen_mode = mode;
  }

  void
  Zoom (BPoint origin, float width, float height)
  {
    struct haiku_zoom_event rq;

    rq.window = this;
    rq.fullscreen_mode = fullscreen_mode;
    haiku_write (ZOOM_EVENT, &rq);
  }

  void
  OffsetChildRect (BRect *r, EmacsWindow *c)
  {
    if (!child_frame_lock.Lock ())
      gui_abort ("Failed to lock child frame state lock");

    for (struct child_frame *f; f; f = f->next)
      if (f->window == c)
	{
	  r->top -= f->yoff;
	  r->bottom -= f->yoff;
	  r->left -= f->xoff;
	  r->right -= f->xoff;
	  child_frame_lock.Unlock ();
	  return;
	}

    child_frame_lock.Lock ();
    gui_abort ("Trying to calculate offsets for a child frame that doesn't exist");
  }
};

class EmacsMenuBar : public BMenuBar
{
  bool tracking_p;

public:
  EmacsMenuBar () : BMenuBar (BRect (0, 0, 0, 0), NULL)
  {
  }

  void
  AttachedToWindow (void)
  {
    BWindow *window = Window ();

    window->SetKeyMenuBar (this);
  }

  void
  FrameResized (float newWidth, float newHeight)
  {
    struct haiku_menu_bar_resize_event rq;
    rq.window = this->Window ();
    rq.height = std::lrint (newHeight + 1);
    rq.width = std::lrint (newWidth + 1);

    haiku_write (MENU_BAR_RESIZE, &rq);
    BMenuBar::FrameResized (newWidth, newHeight);
  }

  void
  MouseDown (BPoint point)
  {
    struct haiku_menu_bar_click_event rq;
    EmacsWindow *ew = (EmacsWindow *) Window ();

    rq.window = ew;
    rq.x = std::lrint (point.x);
    rq.y = std::lrint (point.y);

    if (!ew->menu_bar_active_p)
      haiku_write (MENU_BAR_CLICK, &rq);
    else
      BMenuBar::MouseDown (point);
  }

  void
  MouseMoved (BPoint point, uint32 transit, const BMessage *msg)
  {
    struct haiku_menu_bar_left_event rq;

    if (transit == B_EXITED_VIEW)
      {
	rq.x = std::lrint (point.x);
	rq.y = std::lrint (point.y);
	rq.window = this->Window ();

	haiku_write (MENU_BAR_LEFT, &rq);
      }

    BMenuBar::MouseMoved (point, transit, msg);
  }

  void
  MessageReceived (BMessage *msg)
  {
    BRect frame;
    BPoint pt, l;
    EmacsWindow *window;
    bool menus_begun;

    if (msg->what == SHOW_MENU_BAR)
      {
	window = (EmacsWindow *) Window ();
	frame = Frame ();
	pt = frame.LeftTop ();
	l = pt;
	menus_begun = false;
	Parent ()->ConvertToScreen (&pt);

	window->menus_begun = &menus_begun;
	set_mouse_position (pt.x, pt.y);
	BMenuBar::MouseDown (l);
	window->menus_begun = NULL;

	if (!menus_begun)
	  msg->SendReply (msg);
	else
	  msg->SendReply (BE_MENU_BAR_OPEN);
      }
    else if (msg->what == REPLAY_MENU_BAR)
      {
	window = (EmacsWindow *) Window ();
	menus_begun = false;
	window->menus_begun = &menus_begun;

	if (msg->FindPoint ("emacs:point", &pt) == B_OK)
	  BMenuBar::MouseDown (pt);

	window->menus_begun = NULL;

	if (!menus_begun)
	  msg->SendReply (msg);
	else
	  msg->SendReply (BE_MENU_BAR_OPEN);
      }
    else
      BMenuBar::MessageReceived (msg);
  }
};

class EmacsView : public BView
{
public:
  int looper_locked_count;
  BRegion sb_region;
  BRegion invalid_region;

  BView *offscreen_draw_view;
  BBitmap *offscreen_draw_bitmap_1;
  BBitmap *copy_bitmap;

#ifdef USE_BE_CAIRO
  cairo_surface_t *cr_surface;
  cairo_t *cr_context;
  BLocker cr_surface_lock;
#endif

  BMessage *wait_for_release_message;
  int64 grabbed_buttons;
  BScreen screen;
  bool use_frame_synchronization;

  EmacsView () : BView (BRect (0, 0, 0, 0), "Emacs",
			B_FOLLOW_NONE, B_WILL_DRAW),
		 looper_locked_count (0),
		 offscreen_draw_view (NULL),
		 offscreen_draw_bitmap_1 (NULL),
		 copy_bitmap (NULL),
#ifdef USE_BE_CAIRO
		 cr_surface (NULL),
		 cr_context (NULL),
#endif
		 wait_for_release_message (NULL),
		 grabbed_buttons (0),
		 use_frame_synchronization (false)
  {

  }

  ~EmacsView ()
  {
    if (wait_for_release_message)
      {
	wait_for_release_message->SendReply (wait_for_release_message);
	delete wait_for_release_message;
      }

    TearDownDoubleBuffering ();

    if (!grab_view_locker.Lock ())
      gui_abort ("Couldn't lock grab view locker");
    if (grab_view == this)
      grab_view = NULL;
    grab_view_locker.Unlock ();
  }

  void
  SetFrameSynchronization (bool sync)
  {
    if (LockLooper ())
      {
	use_frame_synchronization = sync;
	UnlockLooper ();
      }
  }

  void
  MessageReceived (BMessage *msg)
  {
    uint32 buttons;
    BLooper *looper = Looper ();

    if (msg->what == WAIT_FOR_RELEASE)
      {
	if (wait_for_release_message)
	  gui_abort ("Wait for release message already exists");

	GetMouse (NULL, &buttons, false);

	if (!buttons)
	  msg->SendReply (msg);
	else
	  wait_for_release_message = looper->DetachCurrentMessage ();
      }
    else if (msg->what == RELEASE_NOW)
      {
	if (wait_for_release_message)
	  wait_for_release_message->SendReply (msg);

	delete wait_for_release_message;
	wait_for_release_message = NULL;
      }
    else
      BView::MessageReceived (msg);
  }

#ifdef USE_BE_CAIRO
  void
  DetachCairoSurface (void)
  {
    if (!cr_surface_lock.Lock ())
      gui_abort ("Could not lock cr surface during detachment");
    if (!cr_surface)
      gui_abort ("Trying to detach window cr surface when none exists");
    cairo_destroy (cr_context);
    cairo_surface_destroy (cr_surface);
    cr_surface = NULL;
    cr_context = NULL;
    cr_surface_lock.Unlock ();
  }

  void
  AttachCairoSurface (void)
  {
    if (!cr_surface_lock.Lock ())
      gui_abort ("Could not lock cr surface during attachment");
    if (cr_surface)
      gui_abort ("Trying to attach cr surface when one already exists");
    BRect bounds = offscreen_draw_bitmap_1->Bounds ();

    cr_surface = cairo_image_surface_create_for_data
      ((unsigned char *) offscreen_draw_bitmap_1->Bits (),
       CAIRO_FORMAT_ARGB32, BE_RECT_WIDTH (bounds),
       BE_RECT_HEIGHT (bounds),
       offscreen_draw_bitmap_1->BytesPerRow ());
    if (!cr_surface)
      gui_abort ("Cr surface allocation failed for double-buffered view");

    cr_context = cairo_create (cr_surface);
    if (!cr_context)
      gui_abort ("cairo_t allocation failed for double-buffered view");
    cr_surface_lock.Unlock ();
  }
#endif

  void
  TearDownDoubleBuffering (void)
  {
    if (offscreen_draw_view)
      {
	if (Window ())
	  ClearViewBitmap ();
	if (copy_bitmap)
	  {
	    delete copy_bitmap;
	    copy_bitmap = NULL;
	  }
	if (!looper_locked_count)
	  if (!offscreen_draw_view->LockLooper ())
	    gui_abort ("Failed to lock offscreen draw view");
#ifdef USE_BE_CAIRO
	if (cr_surface)
	  DetachCairoSurface ();
#endif
	offscreen_draw_view->RemoveSelf ();
	delete offscreen_draw_view;
	offscreen_draw_view = NULL;
	delete offscreen_draw_bitmap_1;
	offscreen_draw_bitmap_1 = NULL;
      }
   }

  void
  AfterResize (void)
  {
    if (offscreen_draw_view)
      {
	if (!LockLooper ())
	  gui_abort ("Failed to lock looper after resize");

	if (!offscreen_draw_view->LockLooper ())
	  gui_abort ("Failed to lock offscreen draw view after resize");
#ifdef USE_BE_CAIRO
	DetachCairoSurface ();
#endif
	offscreen_draw_view->RemoveSelf ();
	delete offscreen_draw_bitmap_1;
	offscreen_draw_bitmap_1 = new BBitmap (Frame (), B_RGBA32, 1);
	if (offscreen_draw_bitmap_1->InitCheck () != B_OK)
	  gui_abort ("Offscreen draw bitmap initialization failed");

	BRect frame = Frame ();

	offscreen_draw_view->MoveTo (frame.left, frame.top);
	offscreen_draw_view->ResizeTo (BE_RECT_WIDTH (frame),
				       BE_RECT_HEIGHT (frame));
	offscreen_draw_bitmap_1->AddChild (offscreen_draw_view);
#ifdef USE_BE_CAIRO
	AttachCairoSurface ();
#endif

	if (looper_locked_count)
	  offscreen_draw_bitmap_1->Lock ();

	UnlockLooper ();
      }
  }

  void
  Draw (BRect expose_bounds)
  {
    struct haiku_expose_event rq;
    EmacsWindow *w = (EmacsWindow *) Window ();

    if (w->shown_flag && offscreen_draw_view)
      {
	PushState ();
	SetDrawingMode (B_OP_ERASE);
	FillRect (Frame ());
	PopState ();
	return;
      }

    if (!offscreen_draw_view)
      {
	if (sb_region.Contains (std::lrint (expose_bounds.left),
				std::lrint (expose_bounds.top)) &&
	    sb_region.Contains (std::lrint (expose_bounds.right),
				std::lrint (expose_bounds.top)) &&
	    sb_region.Contains (std::lrint (expose_bounds.left),
				std::lrint (expose_bounds.bottom)) &&
	    sb_region.Contains (std::lrint (expose_bounds.right),
				std::lrint (expose_bounds.bottom)))
	  return;

	rq.x = std::floor (expose_bounds.left);
	rq.y = std::floor (expose_bounds.top);
	rq.width = std::ceil (expose_bounds.right - expose_bounds.left + 1);
	rq.height = std::ceil (expose_bounds.bottom - expose_bounds.top + 1);
	if (!rq.width)
	  rq.width = 1;
	if (!rq.height)
	  rq.height = 1;
	rq.window = this->Window ();

	haiku_write (FRAME_EXPOSED, &rq);
      }
  }

  void
  FlipBuffers (void)
  {
    EmacsWindow *w;
    if (!LockLooper ())
      gui_abort ("Failed to lock looper during buffer flip");
    if (!offscreen_draw_view)
      gui_abort ("Failed to lock offscreen view during buffer flip");

    offscreen_draw_view->Sync ();
    w = (EmacsWindow *) Window ();
    w->shown_flag = 0;

    if (copy_bitmap &&
	copy_bitmap->Bounds () != offscreen_draw_bitmap_1->Bounds ())
      {
	delete copy_bitmap;
	copy_bitmap = NULL;
      }
    if (!copy_bitmap)
      {
	copy_bitmap = new BBitmap (offscreen_draw_bitmap_1);
	SetViewBitmap (copy_bitmap, Frame (),
		       Frame (), B_FOLLOW_NONE, 0);
      }
    else
      copy_bitmap->ImportBits (offscreen_draw_bitmap_1);

    if (copy_bitmap->InitCheck () != B_OK)
      gui_abort ("Failed to init copy bitmap during buffer flip");

    /* Wait for VBLANK.  If responding to the invalidation or buffer
       flipping takes longer than the blanking period, we lose.  */
    if (use_frame_synchronization)
      screen.WaitForRetrace ();

    Invalidate (&invalid_region);
    invalid_region.MakeEmpty ();
    UnlockLooper ();
    return;
  }

  void
  SetUpDoubleBuffering (void)
  {
    if (!LockLooper ())
      gui_abort ("Failed to lock self setting up double buffering");
    if (offscreen_draw_view)
      gui_abort ("Failed to lock offscreen view setting up double buffering");

    offscreen_draw_bitmap_1 = new BBitmap (Frame (), B_RGBA32, 1);
    if (offscreen_draw_bitmap_1->InitCheck () != B_OK)
      gui_abort ("Failed to init offscreen bitmap");
#ifdef USE_BE_CAIRO
    AttachCairoSurface ();
#endif
    offscreen_draw_view = new BView (Frame (), NULL, B_FOLLOW_NONE, B_WILL_DRAW);
    offscreen_draw_bitmap_1->AddChild (offscreen_draw_view);

    if (looper_locked_count)
      {
	if (!offscreen_draw_bitmap_1->Lock ())
	  gui_abort ("Failed to lock bitmap after double buffering was set up");
      }

    invalid_region.MakeEmpty ();
    UnlockLooper ();
    Invalidate ();
  }

  void
  MouseMoved (BPoint point, uint32 transit, const BMessage *drag_msg)
  {
    struct haiku_mouse_motion_event rq;
    int64 threadid;
    EmacsWindow *window;

    window = (EmacsWindow *) Window ();

    if (transit == B_EXITED_VIEW)
      rq.just_exited_p = true;
    else
      rq.just_exited_p = false;

    rq.x = point.x;
    rq.y = point.y;
    rq.window = window;
    rq.time = system_time ();

    if (drag_msg && (drag_msg->IsSourceRemote ()
		     || drag_msg->FindInt64 ("emacs:thread_id",
					     &threadid) != B_OK
		     || threadid != find_thread (NULL)))
      rq.dnd_message = true;
    else
      rq.dnd_message = false;

    if (!grab_view_locker.Lock ())
      gui_abort ("Couldn't lock grab view locker");

    if (grab_view && this != grab_view)
      {
	grab_view_locker.Unlock ();
	return;
      }

    grab_view_locker.Unlock ();

    haiku_write (MOUSE_MOTION, &rq);
  }

  void
  BasicMouseDown (BPoint point, BView *scroll_bar, BMessage *message)
  {
    struct haiku_button_event rq;
    int64 when;
    int32 mods, buttons, button;

    if (message->FindInt64 ("when", &when) != B_OK
	|| message->FindInt32 ("modifiers", &mods) != B_OK
	|| message->FindInt32 ("buttons", &buttons) != B_OK)
      return;

    /* Find which button was pressed by comparing the previous button
       mask to the current one.  This assumes that B_MOUSE_DOWN will
       be sent for each button press.  */
    button = buttons & ~grabbed_buttons;
    grabbed_buttons = buttons;

    if (!scroll_bar)
      {
	if (!grab_view_locker.Lock ())
	  gui_abort ("Couldn't lock grab view locker");
	grab_view = this;
	grab_view_locker.Unlock ();
      }

    rq.window = this->Window ();
    rq.scroll_bar = scroll_bar;

    if (button == B_PRIMARY_MOUSE_BUTTON)
      rq.btn_no = 0;
    else if (button == B_SECONDARY_MOUSE_BUTTON)
      rq.btn_no = 2;
    else if (button == B_TERTIARY_MOUSE_BUTTON)
      rq.btn_no = 1;
    else
      /* We don't know which button was pressed.  This usually happens
	 when a B_MOUSE_UP is sent to a view that didn't receive a
	 corresponding B_MOUSE_DOWN event, so simply ignore the
	 message.  */
      return;

    rq.x = point.x;
    rq.y = point.y;
    rq.modifiers = 0;

    if (mods & B_SHIFT_KEY)
      rq.modifiers |= HAIKU_MODIFIER_SHIFT;

    if (mods & B_CONTROL_KEY)
      rq.modifiers |= HAIKU_MODIFIER_CTRL;

    if (mods & B_COMMAND_KEY)
      rq.modifiers |= HAIKU_MODIFIER_ALT;

    if (mods & B_OPTION_KEY)
      rq.modifiers |= HAIKU_MODIFIER_SUPER;

    if (!scroll_bar)
      SetMouseEventMask (B_POINTER_EVENTS, (B_LOCK_WINDOW_FOCUS
					    | B_NO_POINTER_HISTORY));

    rq.time = when;
    haiku_write (BUTTON_DOWN, &rq);
  }

  void
  MouseDown (BPoint point)
  {
    BMessage *msg;
    BLooper *looper;

    looper = Looper ();
    msg = (looper
	   ? looper->CurrentMessage ()
	   : NULL);

    if (msg)
      BasicMouseDown (point, NULL, msg);
  }

  void
  BasicMouseUp (BPoint point, BView *scroll_bar, BMessage *message)
  {
    struct haiku_button_event rq;
    int64 when;
    int32 mods, button, buttons;

    if (message->FindInt64 ("when", &when) != B_OK
	|| message->FindInt32 ("modifiers", &mods) != B_OK
	|| message->FindInt32 ("buttons", &buttons) != B_OK)
      return;

    if (!scroll_bar)
      {
	if (!grab_view_locker.Lock ())
	  gui_abort ("Couldn't lock grab view locker");
	if (!buttons)
	  grab_view = NULL;
	grab_view_locker.Unlock ();
      }

    button = (grabbed_buttons & ~buttons);
    grabbed_buttons = buttons;

    if (wait_for_release_message)
      {
	if (!grabbed_buttons)
	  {
	    wait_for_release_message->SendReply (wait_for_release_message);
	    delete wait_for_release_message;
	    wait_for_release_message = NULL;
	  }

	return;
      }

    rq.window = this->Window ();
    rq.scroll_bar = scroll_bar;

    if (button == B_PRIMARY_MOUSE_BUTTON)
      rq.btn_no = 0;
    else if (button == B_SECONDARY_MOUSE_BUTTON)
      rq.btn_no = 2;
    else if (button == B_TERTIARY_MOUSE_BUTTON)
      rq.btn_no = 1;
    else
      return;

    rq.x = point.x;
    rq.y = point.y;

    rq.modifiers = 0;
    if (mods & B_SHIFT_KEY)
      rq.modifiers |= HAIKU_MODIFIER_SHIFT;

    if (mods & B_CONTROL_KEY)
      rq.modifiers |= HAIKU_MODIFIER_CTRL;

    if (mods & B_COMMAND_KEY)
      rq.modifiers |= HAIKU_MODIFIER_ALT;

    if (mods & B_OPTION_KEY)
      rq.modifiers |= HAIKU_MODIFIER_SUPER;

    rq.time = when;
    haiku_write (BUTTON_UP, &rq);
  }

  void
  MouseUp (BPoint point)
  {
    BMessage *msg;
    BLooper *looper;

    looper = Looper ();
    msg = (looper
	   ? looper->CurrentMessage ()
	   : NULL);

    if (msg)
      BasicMouseUp (point, NULL, msg);
  }
};

class EmacsScrollBar : public BScrollBar
{
public:
  int dragging;
  bool horizontal;
  enum haiku_scroll_bar_part current_part;
  float old_value;
  scroll_bar_info info;

  /* How many button events were passed to the parent without
     release.  */
  int handle_button_count;
  bool in_overscroll;
  bool can_overscroll;
  bool maybe_overscroll;
  BPoint last_overscroll;
  int last_reported_overscroll_value;
  int max_value, real_max_value;
  int overscroll_start_value;
  bigtime_t repeater_start;
  EmacsView *parent;

  EmacsScrollBar (int x, int y, int x1, int y1, bool horizontal_p,
		  EmacsView *parent)
    : BScrollBar (BRect (x, y, x1, y1), NULL, NULL, 0, 0, horizontal_p ?
		  B_HORIZONTAL : B_VERTICAL),
      dragging (0),
      handle_button_count (0),
      in_overscroll (false),
      can_overscroll (false),
      maybe_overscroll (false),
      parent (parent)
  {
    BView *vw = (BView *) this;
    vw->SetResizingMode (B_FOLLOW_NONE);
    horizontal = horizontal_p;
    get_scroll_bar_info (&info);
    SetSteps (5000, 10000);
  }

  void
  MessageReceived (BMessage *msg)
  {
    int32 portion, range, dragging, value;
    float proportion;

    if (msg->what == SCROLL_BAR_UPDATE)
      {
	portion = msg->GetInt32 ("emacs:portion", 0);
	range = msg->GetInt32 ("emacs:range", 0);
	dragging = msg->GetInt32 ("emacs:dragging", 0);
	proportion = ((range <= 0 || portion <= 0)
		      ? 1.0f : (float) portion / range);
	value = msg->GetInt32 ("emacs:units", 0);
	can_overscroll = msg->GetBool ("emacs:overscroll", false);

	if (value < 0)
	  value = 0;

	if (dragging != 1)
	  {
	    if (in_overscroll || dragging != -1)
	      {
		/* Set the value to the smallest possible one.
		   Otherwise, the call to SetRange could lead to
		   spurious updates.  */
		old_value = 0;
		SetValue (0);

		/* Unlike on Motif, PORTION isn't included in the total
		   range of the scroll bar.  */

		SetRange (0, range - portion);
		SetProportion (proportion);
		max_value = range - portion;
		real_max_value = range;

		if (in_overscroll || value > max_value)
		  value = max_value;

		old_value = roundf (value);
		SetValue (old_value);
	      }
	    else
	      {
		value = Value ();

		old_value = 0;
		SetValue (0);
		SetRange (0, range - portion);
		SetProportion (proportion);
		old_value = value;
		SetValue (value);
		max_value = range - portion;
		real_max_value = range;
	      }
	  }
      }

    BScrollBar::MessageReceived (msg);
  }

  void
  Pulse (void)
  {
    struct haiku_scroll_bar_part_event rq;
    BPoint point;
    uint32 buttons;

    if (!dragging)
      {
	SetFlags (Flags () & ~B_PULSE_NEEDED);
	return;
      }

    if (repeater_start < system_time ())
      {
	GetMouse (&point, &buttons, false);

	if (ButtonRegionFor (current_part).Contains (point))
	  {
	    rq.scroll_bar = this;
	    rq.window = Window ();
	    rq.part = current_part;
	    haiku_write (SCROLL_BAR_PART_EVENT, &rq);
	  }
      }

    BScrollBar::Pulse ();
  }

  void
  ValueChanged (float new_value)
  {
    struct haiku_scroll_bar_value_event rq;

    new_value = Value ();

    if (dragging)
      {
	if (new_value != old_value)
	  {
	    if (dragging > 1)
	      {
		SetValue (old_value);
		SetFlags (Flags () | B_PULSE_NEEDED);
	      }
	    else
	      dragging++;
	  }

	return;
      }

    if (new_value != old_value)
      {
	rq.scroll_bar = this;
	rq.window = Window ();
	rq.position = new_value;
	old_value = new_value;

	haiku_write (SCROLL_BAR_VALUE_EVENT, &rq);
      }
  }

  BRegion
  ButtonRegionFor (enum haiku_scroll_bar_part button)
  {
    BRegion region;
    BRect bounds;
    BRect rect;
    float button_size;

    bounds = Bounds ();
    bounds.InsetBy (0.0, 0.0);

    if (horizontal)
      button_size = bounds.Height () + 1.0f;
    else
      button_size = bounds.Width () + 1.0f;

    rect = BRect (bounds.left, bounds.top,
		  bounds.left + button_size - 1.0f,
		  bounds.top + button_size - 1.0f);

    if (button == HAIKU_SCROLL_BAR_UP_BUTTON)
      {
	if (!horizontal)
	  {
	    region.Include (rect);
	    if (info.double_arrows)
	      region.Include (rect.OffsetToCopy (bounds.left,
						 bounds.bottom - 2 * button_size + 1));
	  }
	else
	  {
	    region.Include (rect);
	    if (info.double_arrows)
	      region.Include (rect.OffsetToCopy (bounds.right - 2 * button_size,
						 bounds.top));
	  }
      }
    else
      {
	if (!horizontal)
	  {
	    region.Include (rect.OffsetToCopy (bounds.left, bounds.bottom - button_size));

	    if (info.double_arrows)
	      region.Include (rect.OffsetByCopy (0.0, button_size));
	  }
	else
	  {
	    region.Include (rect.OffsetToCopy (bounds.right - button_size, bounds.top));

	    if (info.double_arrows)
	      region.Include (rect.OffsetByCopy (button_size, 0.0));
	  }
      }

    return region;
  }

  void
  MouseDown (BPoint pt)
  {
    struct haiku_scroll_bar_drag_event rq;
    struct haiku_scroll_bar_part_event part;
    BRegion r;
    BLooper *looper;
    BMessage *message;
    int32 buttons, mods;

    looper = Looper ();
    message = NULL;

    if (!looper)
      GetMouse (&pt, (uint32 *) &buttons, false);
    else
      {
	message = looper->CurrentMessage ();

	if (!message || message->FindInt32 ("buttons", &buttons) != B_OK)
	  GetMouse (&pt, (uint32 *) &buttons, false);
      }

    if (message && (message->FindInt32 ("modifiers", &mods)
		    == B_OK)
	&& mods & B_CONTROL_KEY)
      {
	/* Allow C-mouse-3 to split the window on a scroll bar.   */
	handle_button_count += 1;
	SetMouseEventMask (B_POINTER_EVENTS, (B_SUSPEND_VIEW_FOCUS
					      | B_LOCK_WINDOW_FOCUS));
	parent->BasicMouseDown (ConvertToParent (pt), this, message);

	return;
      }

    repeater_start = system_time () + 300000;

    if (buttons == B_PRIMARY_MOUSE_BUTTON)
      {
	r = ButtonRegionFor (HAIKU_SCROLL_BAR_UP_BUTTON);

	if (r.Contains (pt))
	  {
	    part.scroll_bar = this;
	    part.window = Window ();
	    part.part = HAIKU_SCROLL_BAR_UP_BUTTON;
	    dragging = 1;
	    current_part = HAIKU_SCROLL_BAR_UP_BUTTON;

	    haiku_write (SCROLL_BAR_PART_EVENT, &part);
	    goto out;
	  }

	r = ButtonRegionFor (HAIKU_SCROLL_BAR_DOWN_BUTTON);

	if (r.Contains (pt))
	  {
	    part.scroll_bar = this;
	    part.window = Window ();
	    part.part = HAIKU_SCROLL_BAR_DOWN_BUTTON;
	    dragging = 1;
	    current_part = HAIKU_SCROLL_BAR_DOWN_BUTTON;

	    if (Value () == max_value)
	      {
		SetFlags (Flags () | B_PULSE_NEEDED);
		dragging = 2;
	      }

	    haiku_write (SCROLL_BAR_PART_EVENT, &part);
	    goto out;
	  }

	maybe_overscroll = true;
      }

    rq.dragging_p = 1;
    rq.window = Window ();
    rq.scroll_bar = this;

    SetMouseEventMask (B_POINTER_EVENTS, (B_SUSPEND_VIEW_FOCUS
					  | B_LOCK_WINDOW_FOCUS));

    haiku_write (SCROLL_BAR_DRAG_EVENT, &rq);

  out:
    BScrollBar::MouseDown (pt);
  }

  void
  MouseUp (BPoint pt)
  {
    struct haiku_scroll_bar_drag_event rq;
    BMessage *msg;
    BLooper *looper;

    in_overscroll = false;
    maybe_overscroll = false;

    if (handle_button_count)
      {
	handle_button_count--;
	looper = Looper ();
	msg = (looper
	       ? looper->CurrentMessage ()
	       : NULL);

	if (msg)
	  parent->BasicMouseUp (ConvertToParent (pt),
				this, msg);

	return;
      }

    rq.dragging_p = 0;
    rq.scroll_bar = this;
    rq.window = Window ();

    haiku_write (SCROLL_BAR_DRAG_EVENT, &rq);
    dragging = 0;

    BScrollBar::MouseUp (pt);
  }

  void
  MouseMoved (BPoint point, uint32 transit, const BMessage *msg)
  {
    struct haiku_menu_bar_left_event rq;
    struct haiku_scroll_bar_value_event value_event;
    int range, diff, value, trough_size;
    BRect bounds;
    BPoint conv;
    uint32 buttons;

    GetMouse (NULL, &buttons, false);

    if (transit == B_EXITED_VIEW)
      {
	conv = ConvertToParent (point);

	rq.x = std::lrint (conv.x);
	rq.y = std::lrint (conv.y);
	rq.window = this->Window ();

	haiku_write (MENU_BAR_LEFT, &rq);
      }

    if (in_overscroll)
      {
	if (horizontal)
	  diff = point.x - last_overscroll.x;
	else
	  diff = point.y - last_overscroll.y;

	if (diff < 0)
	  {
	    in_overscroll = false;
	    goto allow;
	  }

	range = real_max_value;
	bounds = Bounds ();
	bounds.InsetBy (1.0, 1.0);
	value = overscroll_start_value;
	trough_size = (horizontal
		       ? BE_RECT_WIDTH (bounds)
		       : BE_RECT_HEIGHT (bounds));
	trough_size -= (horizontal
			? BE_RECT_HEIGHT (bounds)
			: BE_RECT_WIDTH (bounds)) / 2;
	if (info.double_arrows)
	  trough_size -= (horizontal
			  ? BE_RECT_HEIGHT (bounds)
			  : BE_RECT_WIDTH (bounds)) / 2;

	value += ((double) range / trough_size) * diff;

	if (value != last_reported_overscroll_value)
	  {
	    last_reported_overscroll_value = value;

	    value_event.scroll_bar = this;
	    value_event.window = Window ();
	    value_event.position = value;

	    haiku_write (SCROLL_BAR_VALUE_EVENT, &value_event);
	    return;
	  }
      }
    else if (can_overscroll
	     && (buttons == B_PRIMARY_MOUSE_BUTTON)
	     && maybe_overscroll)
      {
	value = Value ();

	if (value >= max_value)
	  {
	    BScrollBar::MouseMoved (point, transit, msg);

	    if (value == Value ())
	      {
		overscroll_start_value = value;
		in_overscroll = true;
		last_overscroll = point;
		last_reported_overscroll_value = value;

		MouseMoved (point, transit, msg);
		return;
	      }
	  }
      }

  allow:
    BScrollBar::MouseMoved (point, transit, msg);
  }
};

class EmacsTitleMenuItem : public BMenuItem
{
public:
  EmacsTitleMenuItem (const char *str) : BMenuItem (str, NULL)
  {
    SetEnabled (0);
  }

  void
  DrawContent (void)
  {
    BMenu *menu = Menu ();

    menu->PushState ();
    menu->SetFont (be_bold_font);
    menu->SetHighColor (ui_color (B_MENU_ITEM_TEXT_COLOR));
    BMenuItem::DrawContent ();
    menu->PopState ();
  }
};

class EmacsMenuItem : public BMenuItem
{
public:
  int menu_bar_id;
  void *menu_ptr;
  void *wind_ptr;
  char *key;
  char *help;

  EmacsMenuItem (const char *key_label, const char *label,
		 const char *help, BMessage *message = NULL)
    : BMenuItem (label, message),
      menu_bar_id (-1),
      menu_ptr (NULL),
      wind_ptr (NULL),
      key (NULL),
      help (NULL)
  {
    if (key_label)
      key = strdup (key_label);

    if (help)
      this->help = strdup (help);
  }

  ~EmacsMenuItem ()
  {
    if (key)
      free (key);
    if (help)
      free (help);
  }

  void
  DrawContent (void)
  {
    BMenu *menu = Menu ();

    BMenuItem::DrawContent ();

    if (key)
      {
	BRect r = Frame ();
	int w;

	menu->PushState ();
	menu->ClipToRect (r);
	menu->SetFont (be_plain_font);
	w = menu->StringWidth (key);
	menu->MovePenTo (BPoint (BE_RECT_WIDTH (r) - w - 4,
				 menu->PenLocation ().y));
	menu->DrawString (key);
	menu->PopState ();
      }
  }

  void
  GetContentSize (float *w, float *h)
  {
    BMenuItem::GetContentSize (w, h);
    if (Menu () && key)
      *w += 4 + Menu ()->StringWidth (key);
  }

  void
  Highlight (bool highlight_p)
  {
    struct haiku_menu_bar_help_event rq;
    struct haiku_dummy_event dummy;
    BMenu *menu = Menu ();
    BRect r;
    BPoint pt;
    uint32 buttons;

    if (help)
      menu->SetToolTip (highlight_p ? help : NULL);
    else
      {
	rq.window = wind_ptr;
	rq.mb_idx = highlight_p ? menu_bar_id : -1;
	rq.highlight_p = highlight_p;
	rq.data = menu_ptr;

	r = Frame ();
	menu->GetMouse (&pt, &buttons);

	if (!highlight_p || r.Contains (pt))
	  {
	    if (menu_bar_id > 0)
	      haiku_write (MENU_BAR_HELP_EVENT, &rq);
	    else
	      {
		haiku_write_without_signal (MENU_BAR_HELP_EVENT, &rq, true);
		haiku_write (DUMMY_EVENT, &dummy);
	      }
	  }
      }

    BMenuItem::Highlight (highlight_p);
  }
};

class EmacsFontPreviewDialog : public BWindow
{
  BStringView text_view;
  BMessenger preview_source;
  BFont *current_font;
  bool is_visible;

  void
  DoLayout (void)
  {
    float width, height;

    text_view.GetPreferredSize (&width, &height);
    text_view.ResizeTo (width - 1, height - 1);

    SetSizeLimits (width, width, height, height);
    ResizeTo (width - 1, height - 1);
  }

  bool
  QuitRequested (void)
  {
    preview_source.SendMessage (QUIT_PREVIEW_DIALOG);

    return false;
  }

  void
  MessageReceived (BMessage *message)
  {
    int32 family, style;
    uint32 flags;
    font_family name;
    font_style sname;
    status_t rc;
    const char *size_name;
    int size;

    if (message->what == SET_FONT_INDICES)
      {
	size_name = message->FindString ("emacs:size");

	if (message->FindInt32 ("emacs:family", &family) != B_OK
	    || message->FindInt32 ("emacs:style", &style) != B_OK)
	  return;

	rc = get_font_family (family, &name, &flags);

	if (rc != B_OK)
	  return;

	rc = get_font_style (name, style, &sname, &flags);

	if (rc != B_OK)
	  return;

	if (current_font)
	  delete current_font;

	current_font = new BFont;
	current_font->SetFamilyAndStyle (name, sname);

	if (message->GetBool ("emacs:disable_antialiasing", false))
	  current_font->SetFlags (B_DISABLE_ANTIALIASING);

	if (size_name && strlen (size_name))
	  {
	    size = atoi (size_name);
	    current_font->SetSize (size);
	  }

	text_view.SetFont (current_font);
	DoLayout ();
	return;
      }

    BWindow::MessageReceived (message);
  }

public:

  EmacsFontPreviewDialog (BWindow *target)
    : BWindow (BRect (45, 45, 500, 300),
	       "Preview font",
	       B_FLOATING_WINDOW_LOOK,
	       B_MODAL_APP_WINDOW_FEEL,
	       B_NOT_ZOOMABLE | B_NOT_RESIZABLE),
      text_view (BRect (0, 0, 0, 0),
		 NULL, "The quick brown fox "
		 "jumped over the lazy dog"),
      preview_source (target),
      current_font (NULL)
  {
    AddChild (&text_view);
    DoLayout ();
  }

  ~EmacsFontPreviewDialog (void)
  {
    text_view.RemoveSelf ();

    if (current_font)
      delete current_font;
  }
};

class TripleLayoutView : public BView
{
  BScrollView *view_1;
  BView *view_2, *view_3;

  void
  FrameResized (float new_width, float new_height)
  {
    BRect frame;
    float width, height, height_1, width_1;
    float basic_height;

    frame = Frame ();

    view_2->GetPreferredSize (&width, &height);
    view_3->GetPreferredSize (&width_1, &height_1);

    basic_height = height + height_1;

    view_1->MoveTo (0, 0);
    view_1->ResizeTo (BE_RECT_WIDTH (frame),
		      BE_RECT_HEIGHT (frame) - basic_height);
    view_2->MoveTo (2, BE_RECT_HEIGHT (frame) - basic_height);
    view_2->ResizeTo (BE_RECT_WIDTH (frame) - 4, height);
    view_3->MoveTo (2, BE_RECT_HEIGHT (frame) - height_1);
    view_3->ResizeTo (BE_RECT_WIDTH (frame) - 4, height_1);

    BView::FrameResized (new_width, new_height);
  }

  /* This is called by the BSplitView.  */
  BSize
  MinSize (void)
  {
    float width, height;
    float width_1, height_1;
    BSize size_1;

    size_1 = view_1->MinSize ();
    view_2->GetPreferredSize (&width, &height);
    view_3->GetPreferredSize (&width_1, &height_1);

    return BSize (std::max (size_1.width,
			    std::max (width_1, width)),
		  std::max (size_1.height, height + height_1));
  }

public:
  TripleLayoutView (BScrollView *first, BView *second,
		    BView *third) : BView (NULL, B_FRAME_EVENTS),
				    view_1 (first),
				    view_2 (second),
				    view_3 (third)
  {
    FrameResized (801, 801);
  }
};

class EmacsFontSelectionDialog : public BWindow
{
  BView basic_view;
  BCheckBox antialias_checkbox;
  BCheckBox preview_checkbox;
  BSplitView split_view;
  BListView font_family_pane;
  BListView font_style_pane;
  BScrollView font_family_scroller;
  BScrollView font_style_scroller;
  TripleLayoutView style_view;
  BObjectList<BStringItem> all_families;
  BObjectList<BStringItem> all_styles;
  BButton cancel_button, ok_button;
  BTextControl size_entry;
  port_id comm_port;
  bool allow_monospace_only;
  int pending_selection_idx;
  EmacsFontPreviewDialog *preview;

  void
  ShowPreview (void)
  {
    if (!preview)
      {
	preview = new EmacsFontPreviewDialog (this);
	preview->Show ();

	UpdatePreview ();
      }
  }

  void
  UpdatePreview (void)
  {
    int family, style;
    BMessage message;
    BMessenger messenger (preview);

    family = font_family_pane.CurrentSelection ();
    style = font_style_pane.CurrentSelection ();

    message.what = SET_FONT_INDICES;
    message.AddInt32 ("emacs:family", family);
    message.AddInt32 ("emacs:style", style);

    if (antialias_checkbox.Value () == B_CONTROL_ON)
      message.AddBool ("emacs:disable_antialiasing", true);

    message.AddString ("emacs:size",
		       size_entry.Text ());

    messenger.SendMessage (&message);
  }

  void
  HidePreview (void)
  {
    if (preview)
      {
	if (preview->LockLooper ())
	  preview->Quit ();
	/* I hope this works.  */
	else
	  delete preview;

	preview = NULL;
      }
  }

  void
  UpdateStylesForIndex (int idx)
  {
    int n, i, previous_selection;
    uint32 flags;
    font_family family;
    font_style style;
    BStringItem *item;
    char *current_style;

    n = all_styles.CountItems ();
    current_style = NULL;
    previous_selection = font_style_pane.CurrentSelection ();

    if (previous_selection >= 0)
      {
	item = all_styles.ItemAt (previous_selection);
	current_style = strdup (item->Text ());
      }

    font_style_pane.MakeEmpty ();
    all_styles.MakeEmpty ();

    if (get_font_family (idx, &family, &flags) == B_OK)
      {
	n = count_font_styles (family);

	for (i = 0; i < n; ++i)
	  {
	    if (get_font_style (family, i, &style, &flags) == B_OK)
	      item = new BStringItem (style);
	    else
	      item = new BStringItem ("<error>");

	    if (current_style && pending_selection_idx < 0
		&& !strcmp (current_style, style))
	      pending_selection_idx = i;

	    font_style_pane.AddItem (item);
	    all_styles.AddItem (item);
	  }
      }

    if (pending_selection_idx >= 0)
      {
	font_style_pane.Select (pending_selection_idx);
	font_style_pane.ScrollToSelection ();
      }

    pending_selection_idx = -1;
    UpdateForSelectedStyle ();

    if (current_style)
      free (current_style);
  }

  bool
  QuitRequested (void)
  {
    struct font_selection_dialog_message rq;

    rq.cancel = true;
    write_port (comm_port, 0, &rq, sizeof rq);

    return false;
  }

  void
  UpdateForSelectedStyle (void)
  {
    int style = font_style_pane.CurrentSelection ();

    if (style < 0)
      ok_button.SetEnabled (false);
    else
      ok_button.SetEnabled (true);

    if (style >= 0 && preview)
      UpdatePreview ();
  }

  void
  MessageReceived (BMessage *msg)
  {
    const char *text;
    int idx;
    struct font_selection_dialog_message rq;

    if (msg->what == FONT_FAMILY_SELECTED)
      {
	idx = font_family_pane.CurrentSelection ();
	UpdateStylesForIndex (idx);
      }
    else if (msg->what == FONT_STYLE_SELECTED)
      UpdateForSelectedStyle ();
    else if (msg->what == B_OK
	     && font_style_pane.CurrentSelection () >= 0)
      {
	text = size_entry.Text ();

	rq.cancel = false;
	rq.family_idx = font_family_pane.CurrentSelection ();
	rq.style_idx = font_style_pane.CurrentSelection ();
	rq.size = atoi (text);
	rq.size_specified = rq.size > 0 || strlen (text);

	if (antialias_checkbox.Value () == B_CONTROL_ON)
	  rq.disable_antialias = true;
	else
	  rq.disable_antialias = false;

	write_port (comm_port, 0, &rq, sizeof rq);
      }
    else if (msg->what == B_CANCEL)
      {
	rq.cancel = true;

	write_port (comm_port, 0, &rq, sizeof rq);
      }
    else if (msg->what == SET_PREVIEW_DIALOG)
      {
	if (preview_checkbox.Value () == B_CONTROL_OFF)
	  HidePreview ();
	else
	  ShowPreview ();
      }
    else if (msg->what == QUIT_PREVIEW_DIALOG)
      {
	preview_checkbox.SetValue (B_CONTROL_OFF);
	HidePreview ();
      }
    else if (msg->what == UPDATE_PREVIEW_DIALOG)
      {
	if (preview)
	  UpdatePreview ();
      }
    else if (msg->what == SET_DISABLE_ANTIALIASING)
      {
	if (preview)
	  UpdatePreview ();
      }

    BWindow::MessageReceived (msg);
  }

public:

  ~EmacsFontSelectionDialog (void)
  {
    if (preview)
      {
	if (preview->LockLooper ())
	  preview->Quit ();
	/* I hope this works.  */
	else
	  delete preview;
      }

    font_family_pane.MakeEmpty ();
    font_style_pane.MakeEmpty ();

    font_family_pane.RemoveSelf ();
    font_style_pane.RemoveSelf ();
    antialias_checkbox.RemoveSelf ();
    preview_checkbox.RemoveSelf ();
    style_view.RemoveSelf ();
    font_family_scroller.RemoveSelf ();
    font_style_scroller.RemoveSelf ();
    cancel_button.RemoveSelf ();
    ok_button.RemoveSelf ();
    size_entry.RemoveSelf ();
    basic_view.RemoveSelf ();

    if (comm_port >= B_OK)
      delete_port (comm_port);
  }

  EmacsFontSelectionDialog (bool monospace_only,
			    int initial_family_idx,
			    int initial_style_idx,
			    int initial_size,
			    bool initial_antialias)
    : BWindow (BRect (0, 0, 500, 500),
	       "Select font from list",
	       B_TITLED_WINDOW_LOOK,
	       B_MODAL_APP_WINDOW_FEEL, 0),
      basic_view (NULL, 0),
      antialias_checkbox ("Disable antialiasing", "Disable antialiasing",
			  new BMessage (SET_DISABLE_ANTIALIASING)),
      preview_checkbox ("Show preview", "Show preview",
			new BMessage (SET_PREVIEW_DIALOG)),
      font_family_pane (BRect (0, 0, 0, 0), NULL,
			B_SINGLE_SELECTION_LIST,
			B_FOLLOW_ALL_SIDES),
      font_style_pane (BRect (0, 0, 0, 0), NULL,
		       B_SINGLE_SELECTION_LIST,
		       B_FOLLOW_ALL_SIDES),
      font_family_scroller (NULL, &font_family_pane,
			    B_FOLLOW_LEFT | B_FOLLOW_TOP,
			    0, false, true),
      font_style_scroller (NULL, &font_style_pane,
			   B_FOLLOW_ALL_SIDES,
			   B_SUPPORTS_LAYOUT, false, true),
      style_view (&font_style_scroller, &antialias_checkbox,
		  &preview_checkbox),
      all_families (20, true),
      all_styles (20, true),
      cancel_button ("Cancel", "Cancel",
		     new BMessage (B_CANCEL)),
      ok_button ("OK", "OK", new BMessage (B_OK)),
      size_entry (NULL, "Size:", NULL,
		  new BMessage (UPDATE_PREVIEW_DIALOG)),
      allow_monospace_only (monospace_only),
      pending_selection_idx (initial_style_idx),
      preview (NULL)
  {
    BStringItem *family_item;
    int i, n_families;
    font_family name;
    uint32 flags, c;
    BMessage *selection;
    BTextView *size_text;
    char format_buffer[4];

    AddChild (&basic_view);

    basic_view.AddChild (&split_view);
    basic_view.AddChild (&cancel_button);
    basic_view.AddChild (&ok_button);
    basic_view.AddChild (&size_entry);
    split_view.AddChild (&font_family_scroller, 0.7);
    split_view.AddChild (&style_view, 0.3);
    style_view.AddChild (&font_style_scroller);
    style_view.AddChild (&antialias_checkbox);
    style_view.AddChild (&preview_checkbox);

    basic_view.SetViewUIColor (B_PANEL_BACKGROUND_COLOR);
    style_view.SetViewUIColor (B_PANEL_BACKGROUND_COLOR);

    FrameResized (801, 801);
    UpdateForSelectedStyle ();

    selection = new BMessage (FONT_FAMILY_SELECTED);
    font_family_pane.SetSelectionMessage (selection);
    selection = new BMessage (FONT_STYLE_SELECTED);
    font_style_pane.SetSelectionMessage (selection);
    selection = new BMessage (B_OK);
    font_style_pane.SetInvocationMessage (selection);
    selection = new BMessage (UPDATE_PREVIEW_DIALOG);
    size_entry.SetModificationMessage (selection);

    comm_port = create_port (1, "font dialog port");

    n_families = count_font_families ();

    for (i = 0; i < n_families; ++i)
      {
	if (get_font_family (i, &name, &flags) == B_OK)
	  {
	    family_item = new BStringItem (name);

	    all_families.AddItem (family_item);
	    font_family_pane.AddItem (family_item);

	    family_item->SetEnabled (!allow_monospace_only
				     || flags & B_IS_FIXED);
	  }
	else
	  {
	    family_item = new BStringItem ("<error>");

	    all_families.AddItem (family_item);
	    font_family_pane.AddItem (family_item);
	  }
      }

    if (initial_family_idx >= 0)
      {
	font_family_pane.Select (initial_family_idx);
	font_family_pane.ScrollToSelection ();
      }

    size_text = size_entry.TextView ();

    for (c = 0; c <= 47; ++c)
      size_text->DisallowChar (c);

    for (c = 58; c <= 127; ++c)
      size_text->DisallowChar (c);

    if (initial_size > 0 && initial_size < 1000)
      {
	sprintf (format_buffer, "%d", initial_size);
	size_entry.SetText (format_buffer);
      }

    if (!initial_antialias)
      antialias_checkbox.SetValue (B_CONTROL_ON);
  }

  void
  FrameResized (float new_width, float new_height)
  {
    BRect frame;
    float ok_height, ok_width;
    float cancel_height, cancel_width;
    float size_width, size_height;
    float bone;
    int max_height;

    ok_button.GetPreferredSize (&ok_width, &ok_height);
    cancel_button.GetPreferredSize (&cancel_width,
				    &cancel_height);
    size_entry.GetPreferredSize (&size_width, &size_height);

    max_height = std::max (std::max (ok_height, cancel_height),
			   size_height);

    SetSizeLimits (cancel_width + ok_width + size_width + 6,
		   65535, max_height + 64, 65535);
    frame = Frame ();

    basic_view.ResizeTo (BE_RECT_WIDTH (frame), BE_RECT_HEIGHT (frame));
    split_view.ResizeTo (BE_RECT_WIDTH (frame) - 1,
			 BE_RECT_HEIGHT (frame) - 4 - max_height);

    bone = BE_RECT_HEIGHT (frame) - 2 - max_height / 2;

    ok_button.MoveTo ((BE_RECT_WIDTH (frame)
		       - 4 - cancel_width - ok_width),
		      bone - ok_height / 2);
    cancel_button.MoveTo (BE_RECT_WIDTH (frame) - 2 - cancel_width,
			  bone - cancel_height / 2);
    size_entry.MoveTo (2, bone - size_height / 2);

    ok_button.ResizeTo (ok_width, ok_height);
    cancel_button.ResizeTo (cancel_width, cancel_height);
    size_entry.ResizeTo (std::max (size_width,
				   BE_RECT_WIDTH (frame) / 4),
			 size_height);
  }

  void
  WaitForChoice (struct font_selection_dialog_message *msg,
		 void (*process_pending_signals_function) (void),
		 bool (*should_quit_function) (void))
  {
    int32 reply_type;
    struct object_wait_info infos[2];
    ssize_t status;

    infos[0].object = port_application_to_emacs;
    infos[0].type = B_OBJECT_TYPE_PORT;
    infos[0].events = B_EVENT_READ;

    infos[1].object = comm_port;
    infos[1].type = B_OBJECT_TYPE_PORT;
    infos[1].events = B_EVENT_READ;

    while (true)
      {
	status = wait_for_objects (infos, 2);

	if (status < B_OK)
	  continue;

	if (infos[1].events & B_EVENT_READ)
	  {
	    if (read_port (comm_port, &reply_type,
			   msg, sizeof *msg) >= B_OK)
	      return;

	    goto cancel;
	  }

	if (infos[0].events & B_EVENT_READ)
	  process_pending_signals_function ();

	if (should_quit_function ())
	  goto cancel;

	infos[0].events = B_EVENT_READ;
	infos[1].events = B_EVENT_READ;
      }

  cancel:
    msg->cancel = true;
    return;
  }

  status_t
  InitCheck (void)
  {
    return comm_port >= B_OK ? B_OK : comm_port;
  }
};

class EmacsFilePanelCallbackLooper : public BLooper
{
  port_id comm_port;

  void
  MessageReceived (BMessage *msg)
  {
    const char *str_path, *name;
    char *file_name, *str_buf;
    BEntry entry;
    BPath path;
    entry_ref ref;
    int32 old_what;

    if (msg->what == FILE_PANEL_SELECTION
	|| ((msg->FindInt32 ("old_what", &old_what) == B_OK
	     && old_what == FILE_PANEL_SELECTION)))
      {
	file_name = NULL;

	if (msg->FindRef ("refs", &ref) == B_OK
	    && entry.SetTo (&ref, 0) == B_OK
	    && entry.GetPath (&path) == B_OK)
	  {
	    str_path = path.Path ();

	    if (str_path)
	      file_name = strdup (str_path);
	  }
	else if (msg->FindRef ("directory", &ref) == B_OK
		 && entry.SetTo (&ref, 0) == B_OK
		 && entry.GetPath (&path) == B_OK)
	  {
	    name = msg->GetString ("name");
	    str_path = path.Path ();

	    if (name)
	      {
		str_buf = (char *) alloca (std::strlen (str_path)
					   + std::strlen (name) + 2);
		snprintf (str_buf, std::strlen (str_path)
			  + std::strlen (name) + 2, "%s/%s",
			  str_path, name);
		file_name = strdup (str_buf);
	      }
	  }

	write_port (comm_port, 0, &file_name, sizeof file_name);
      }

    BLooper::MessageReceived (msg);
  }

public:
  EmacsFilePanelCallbackLooper (void) : BLooper ()
  {
    comm_port = create_port (1, "file panel port");
  }

  ~EmacsFilePanelCallbackLooper (void)
  {
    delete_port (comm_port);
  }

  char *
  ReadFileName (void (*process_pending_signals_function) (void))
  {
    object_wait_info infos[2];
    ssize_t status;
    int32 reply_type;
    char *file_name;

    file_name = NULL;

    infos[0].object = port_application_to_emacs;
    infos[0].type = B_OBJECT_TYPE_PORT;
    infos[0].events = B_EVENT_READ;

    infos[1].object = comm_port;
    infos[1].type = B_OBJECT_TYPE_PORT;
    infos[1].events = B_EVENT_READ;

    while (true)
      {
	status = wait_for_objects (infos, 2);

	if (status == B_INTERRUPTED || status == B_WOULD_BLOCK)
	  continue;

	if (infos[0].events & B_EVENT_READ)
	  process_pending_signals_function ();

	if (infos[1].events & B_EVENT_READ)
	  {
	    status = read_port (comm_port,
				&reply_type, &file_name,
				sizeof file_name);

	    if (status < B_OK)
	      file_name = NULL;

	    goto out;
	  }

	infos[0].events = B_EVENT_READ;
	infos[1].events = B_EVENT_READ;
      }

  out:
    return file_name;
  }

  status_t
  InitCheck (void)
  {
    return comm_port >= B_OK ? B_OK : comm_port;
  }
};

/* A view that is added as a child of a tooltip's text view, and
   prevents motion events from reaching it (thereby moving the
   tooltip).  */
class EmacsMotionSuppressionView : public BView
{
  void
  AttachedToWindow (void)
  {
    BView *text_view, *tooltip_view;

    /* We know that this view is a child of the text view, whose
       parent is the tooltip view, and that the tooltip view has
       already set its mouse event mask.  */

    text_view = Parent ();

    if (!text_view)
      return;

    tooltip_view = text_view->Parent ();

    if (!tooltip_view)
      return;

    tooltip_view->SetEventMask (B_KEYBOARD_EVENTS, 0);
  }

public:
  EmacsMotionSuppressionView (void) : BView (BRect (-1, -1, 1, 1),
					     NULL, 0, 0)
  {
    return;
  }
};

static int32
start_running_application (void *data)
{
  Emacs *app = (Emacs *) data;

  haiku_io_init_in_app_thread ();

  if (!app->Lock ())
    gui_abort ("Failed to lock application");

  app->Run ();
  app->Unlock ();
  return 0;
}

/* Take BITMAP, a reference to a BBitmap, and return a pointer to its
   data.  */
void *
BBitmap_data (void *bitmap)
{
  return ((BBitmap *) bitmap)->Bits ();
}

/* Convert bitmap if required, placing the new bitmap in NEW_BITMAP,
   and return non-null if bitmap was successfully converted.  Bitmaps
   should be freed with `BBitmap_free'.  */
int
BBitmap_convert (void *_bitmap, void **new_bitmap)
{
  BBitmap *bitmap = (BBitmap *) _bitmap;
  if (bitmap->ColorSpace () == B_RGBA32)
    return -1;
  BRect bounds = bitmap->Bounds ();
  BBitmap *bmp = new (std::nothrow) BBitmap (bounds, B_RGBA32);
  if (!bmp || bmp->InitCheck () != B_OK)
    {
      if (bmp)
	delete bmp;
      return 0;
    }
  if (bmp->ImportBits (bitmap) != B_OK)
    {
      delete bmp;
      return 0;
    }
  *(BBitmap **) new_bitmap = bmp;
  return 1;
}

void
BBitmap_free (void *bitmap)
{
  delete (BBitmap *) bitmap;
}

/* Create new bitmap in RGB32 format, or in GRAY1 if MONO_P is
   non-zero.  */
void *
BBitmap_new (int width, int height, int mono_p)
{
  BBitmap *bn = new (std::nothrow) BBitmap (BRect (0, 0, width - 1, height - 1),
					    mono_p ? B_GRAY1 : B_RGB32);

  return bn->InitCheck () == B_OK ? (void *) bn : (void *) (delete bn, NULL);
}

void
BBitmap_dimensions (void *bitmap, int *left, int *top,
		    int *right, int *bottom,
		    int32_t *bytes_per_row, int *mono_p)
{
  BRect rect = ((BBitmap *) bitmap)->Bounds ();
  *left = rect.left;
  *top = rect.top;
  *right = rect.right;
  *bottom = rect.bottom;

  *bytes_per_row = ((BBitmap *) bitmap)->BytesPerRow ();
  *mono_p = (((BBitmap *) bitmap)->ColorSpace () == B_GRAY1);
}

static void
wait_for_exit_of_app_thread (void)
{
  status_t ret;

  be_app->PostMessage (QUIT_APPLICATION);
  wait_for_thread (app_thread, &ret);
}

/* Set up an application and return it.  If starting the application
   thread fails, abort Emacs.  */
void *
BApplication_setup (void)
{
  thread_id id;
  Emacs *app;

  if (be_app)
    return be_app;

  app = new Emacs;
  app->Unlock ();

  if ((id = spawn_thread (start_running_application, "Emacs app thread",
			  B_DEFAULT_MEDIA_PRIORITY, app)) < 0)
    gui_abort ("spawn_thread failed");

  resume_thread (id);
  app_thread = id;

  atexit (wait_for_exit_of_app_thread);
  return app;
}

/* Set up and return a window with its view put in VIEW.  */
void *
BWindow_new (void **view)
{
  BWindow *window;
  BView *vw;

  window = new (std::nothrow) EmacsWindow;
  if (!window)
    {
      *view = NULL;
      return window;
    }

  vw = new (std::nothrow) EmacsView;
  if (!vw)
    {
      *view = NULL;
      window->LockLooper ();
      window->Quit ();
      return NULL;
    }

  /* Windows are created locked by the current thread, but calling
     Show for the first time causes them to be unlocked.  To avoid a
     deadlock when a frame is created invisible in one thread, and
     another thread later tries to lock it, the window is unlocked
     here, and EmacsShow will lock it manually if it's being shown for
     the first time.  */
  window->UnlockLooper ();
  window->AddChild (vw);
  *view = vw;
  return window;
}

void
BWindow_quit (void *window)
{
  BWindow *w = (BWindow *) window;

  w->LockLooper ();
  w->Quit ();
}

/* Set WINDOW's offset to X, Y.  */
void
BWindow_set_offset (void *window, int x, int y)
{
  BWindow *wn = (BWindow *) window;
  EmacsWindow *w = dynamic_cast<EmacsWindow *> (wn);
  if (w)
    {
      if (!w->LockLooper ())
	gui_abort ("Failed to lock window looper setting offset");
      w->EmacsMoveTo (x, y);
      w->UnlockLooper ();
    }
  else
    wn->MoveTo (x, y);
}

void
BWindow_dimensions (void *window, int *width, int *height)
{
  BWindow *w = (BWindow *) window;
  BRect frame = w->Frame ();

  *width = BE_RECT_WIDTH (frame);
  *height = BE_RECT_HEIGHT (frame);
}

/* Iconify WINDOW.  */
void
BWindow_iconify (void *window)
{
  if (((BWindow *) window)->IsHidden ())
    BWindow_set_visible (window, true);
  ((BWindow *) window)->Minimize (true);
}

/* Show or hide WINDOW.  */
void
BWindow_set_visible (void *window, int visible_p)
{
  EmacsWindow *win = (EmacsWindow *) window;
  if (visible_p)
    {
      if (win->IsMinimized ())
	win->Minimize (false);
      win->EmacsShow ();
    }
  else if (!win->IsHidden ())
    {
      if (win->IsMinimized ())
	win->Minimize (false);
      win->EmacsHide ();
    }
}

/* Change the title of WINDOW to the multibyte string TITLE.  */
void
BWindow_retitle (void *window, const char *title)
{
  ((BWindow *) window)->SetTitle (title);
}

/* Resize WINDOW to WIDTH by HEIGHT.  */
void
BWindow_resize (void *window, int width, int height)
{
  ((BWindow *) window)->ResizeTo (width - 1, height - 1);
}

/* Activate WINDOW, making it the subject of keyboard focus and
   bringing it to the front of the screen.  */
void
BWindow_activate (void *window)
{
  ((BWindow *) window)->Activate ();
}

/* Return the pixel dimensions of the main screen in WIDTH and
   HEIGHT.  */
void
be_get_screen_dimensions (int *width, int *height)
{
  BScreen screen;
  BRect frame;

  if (!screen.IsValid ())
    gui_abort ("Invalid screen");

  frame = screen.Frame ();

  *width = BE_RECT_WIDTH (frame);
  *height = BE_RECT_HEIGHT (frame);
}

/* Resize VIEW to WIDTH, HEIGHT.  */
void
BView_resize_to (void *view, int width, int height)
{
  EmacsView *vw = (EmacsView *) view;
  if (!vw->LockLooper ())
    gui_abort ("Failed to lock view for resize");
  vw->ResizeTo (width, height);
  vw->AfterResize ();
  vw->UnlockLooper ();
}

void
be_delete_cursor (void *cursor)
{
  if (cursor)
    delete (BCursor *) cursor;
}

void *
be_create_cursor_from_id (int id)
{
  return new BCursor ((enum BCursorID) id);
}

void
BView_set_view_cursor (void *view, void *cursor)
{
  BView *v = (BView *) view;

  if (!v->LockLooper ())
    gui_abort ("Failed to lock view setting cursor");
  v->SetViewCursor ((BCursor *) cursor);
  v->UnlockLooper ();
}

void
BWindow_Flush (void *window)
{
  ((BWindow *) window)->Flush ();
}

/* Make a scrollbar, attach it to VIEW's window, and return it.  */
void *
be_make_scroll_bar_for_view (void *view, int horizontal_p,
			     int x, int y, int x1, int y1)
{
  EmacsScrollBar *scroll_bar;
  BView *vw = (BView *) view;

  if (!vw->LockLooper ())
    gui_abort ("Failed to lock scrollbar owner");

  scroll_bar = new EmacsScrollBar (x, y, x1, y1, horizontal_p,
				   (EmacsView *) vw);

  vw->AddChild (scroll_bar);
  vw->UnlockLooper ();

  return scroll_bar;
}

void
BScrollBar_delete (void *sb)
{
  BView *view = (BView *) sb;
  BView *pr = view->Parent ();

  if (!pr->LockLooper ())
    gui_abort ("Failed to lock scrollbar parent");
  pr->RemoveChild (view);
  pr->UnlockLooper ();

  delete (EmacsScrollBar *) sb;
}

void
BView_move_frame (void *view, int x, int y, int x1, int y1)
{
  BView *vw = (BView *) view;

  if (!vw->LockLooper ())
    gui_abort ("Failed to lock view moving frame");
  vw->MoveTo (x, y);
  vw->ResizeTo (x1 - x, y1 - y);
  vw->UnlockLooper ();
}

/* DRAGGING can either be 0 (which means to update everything), 1
   (which means to update nothing), or -1 (which means to update only
   the thumb size and range).  */

void
BView_scroll_bar_update (void *sb, int portion, int whole, int position,
			 int dragging, bool can_overscroll)
{
  BScrollBar *bar = (BScrollBar *) sb;
  BMessage msg = BMessage (SCROLL_BAR_UPDATE);
  BMessenger mr = BMessenger (bar);
  msg.AddInt32 ("emacs:range", whole);
  msg.AddInt32 ("emacs:units", position);
  msg.AddInt32 ("emacs:portion", portion);
  msg.AddInt32 ("emacs:dragging", dragging);
  msg.AddBool ("emacs:overscroll", can_overscroll);

  mr.SendMessage (&msg);
}

/* Return the default scrollbar size.  */
int
BScrollBar_default_size (int horizontal_p)
{
  return be_control_look->GetScrollBarWidth (horizontal_p
					     ? B_HORIZONTAL
					     : B_VERTICAL);
}

/* Invalidate VIEW, causing it to be drawn again.  */
void
BView_invalidate (void *view)
{
  BView *vw = (BView *) view;
  if (!vw->LockLooper ())
    gui_abort ("Couldn't lock view while invalidating it");
  vw->Invalidate ();
  vw->UnlockLooper ();
}

/* Lock VIEW in preparation for drawing operations.  This should be
   called before any attempt to draw onto VIEW or to lock it for Cairo
   drawing.  `BView_draw_unlock' should be called afterwards.

   If any drawing is going to take place, INVALID_REGION should be
   true, and X, Y, WIDTH, HEIGHT should specify a rectangle in which
   the drawing will take place.  */
void
BView_draw_lock (void *view, bool invalidate_region,
		 int x, int y, int width, int height)
{
  EmacsView *vw = (EmacsView *) view;
  if (vw->looper_locked_count)
    {
      vw->looper_locked_count++;

      if (invalidate_region && vw->offscreen_draw_view)
	vw->invalid_region.Include (BRect (x, y, x + width - 1,
					   y + height - 1));
      return;
    }
  BView *v = (BView *) find_appropriate_view_for_draw (vw);
  if (v != vw)
    {
      if (!vw->offscreen_draw_bitmap_1->Lock ())
	gui_abort ("Failed to lock offscreen bitmap while acquiring draw lock");
    }
  else if (!v->LockLooper ())
    gui_abort ("Failed to lock draw view while acquiring draw lock");

  if (v != vw && !vw->LockLooper ())
    gui_abort ("Failed to lock view while acquiring draw lock");

  if (invalidate_region && vw->offscreen_draw_view)
    vw->invalid_region.Include (BRect (x, y, x + width - 1,
				       y + height - 1));
  vw->looper_locked_count++;
}

void
BView_invalidate_region (void *view, int x, int y, int width, int height)
{
  EmacsView *vw = (EmacsView *) view;

  if (vw->offscreen_draw_view)
    vw->invalid_region.Include (BRect (x, y, x + width - 1,
				       y + height - 1));
}

void
BView_draw_unlock (void *view)
{
  EmacsView *vw = (EmacsView *) view;
  if (--vw->looper_locked_count)
    return;

  BView *v = (BView *) find_appropriate_view_for_draw (view);
  if (v == vw)
    vw->UnlockLooper ();
  else
    {
      vw->offscreen_draw_bitmap_1->Unlock ();
      vw->UnlockLooper ();
    }
}

void
BWindow_center_on_screen (void *window)
{
  BWindow *w = (BWindow *) window;
  w->CenterOnScreen ();
}

/* Import fringe bitmap (short array, low bit rightmost) BITS into
   BITMAP using the B_GRAY1 colorspace.  */
void
BBitmap_import_fringe_bitmap (void *bitmap, unsigned short *bits, int wd, int h)
{
  BBitmap *bmp = (BBitmap *) bitmap;
  unsigned char *data = (unsigned char *) bmp->Bits ();
  int i;

  for (i = 0; i < h; i++)
    {
      if (wd <= 8)
	data[0] = bits[i] & 0xff;
      else
	{
	  data[1] = bits[i] & 0xff;
	  data[0] = bits[i] >> 8;
	}

      data += bmp->BytesPerRow ();
    }
}

/* Make a scrollbar at X, Y known to the view VIEW.  */
void
BView_publish_scroll_bar (void *view, int x, int y, int width, int height)
{
  EmacsView *vw = (EmacsView *) view;
  if (vw->LockLooper ())
    {
      vw->sb_region.Include (BRect (x, y, x - 1 + width,
				    y - 1 + height));
      vw->UnlockLooper ();
    }
}

void
BView_forget_scroll_bar (void *view, int x, int y, int width, int height)
{
  EmacsView *vw = (EmacsView *) view;
  if (vw->LockLooper ())
    {
      vw->sb_region.Exclude (BRect (x, y, x - 1 + width,
				    y - 1 + height));
      vw->UnlockLooper ();
    }
}

bool
BView_inside_scroll_bar (void *view, int x, int y)
{
  EmacsView *vw = (EmacsView *) view;
  bool val;

  if (vw->LockLooper ())
    {
      val = vw->sb_region.Contains (BPoint (x, y));
      vw->UnlockLooper ();
    }
  else
    val = false;

  return val;
}

void
BView_get_mouse (void *view, int *x, int *y)
{
  BPoint l;
  BView *vw = (BView *) view;
  if (!vw->LockLooper ())
    gui_abort ("Failed to lock view in BView_get_mouse");
  vw->GetMouse (&l, NULL, 1);
  vw->UnlockLooper ();

  *x = std::lrint (l.x);
  *y = std::lrint (l.y);
}

/* Perform an in-place conversion of X and Y from VIEW's coordinate
   system to its screen's coordinate system.  */
void
BView_convert_to_screen (void *view, int *x, int *y)
{
  BPoint l = BPoint (*x, *y);
  BView *vw = (BView *) view;
  if (!vw->LockLooper ())
    gui_abort ("Failed to lock view in convert_to_screen");
  vw->ConvertToScreen (&l);
  vw->UnlockLooper ();

  *x = std::lrint (l.x);
  *y = std::lrint (l.y);
}

void
BView_convert_from_screen (void *view, int *x, int *y)
{
  BPoint l = BPoint (*x, *y);
  BView *vw = (BView *) view;
  if (!vw->LockLooper ())
    gui_abort ("Failed to lock view in convert_from_screen");
  vw->ConvertFromScreen (&l);
  vw->UnlockLooper ();

  *x = std::lrint (l.x);
  *y = std::lrint (l.y);
}

/* Decorate or undecorate WINDOW depending on DECORATE_P.  */
void
BWindow_change_decoration (void *window, int decorate_p)
{
  EmacsWindow *w = (EmacsWindow *) window;
  if (!w->LockLooper ())
    gui_abort ("Failed to lock window while changing its decorations");

  if (!w->override_redirect_p)
    {
      if (decorate_p)
	w->SetLook (B_TITLED_WINDOW_LOOK);
      else
	w->SetLook (B_NO_BORDER_WINDOW_LOOK);
    }
  else
    {
      if (decorate_p)
	w->pre_override_redirect_look = B_TITLED_WINDOW_LOOK;
      else
	w->pre_override_redirect_look = B_NO_BORDER_WINDOW_LOOK;
    }
  w->UnlockLooper ();
}

/* Decorate WINDOW appropriately for use as a tooltip.  */
void
BWindow_set_tooltip_decoration (void *window)
{
  EmacsWindow *w = (EmacsWindow *) window;
  if (!w->LockLooper ())
    gui_abort ("Failed to lock window while setting ttip decoration");
  w->tooltip_p = true;
  w->RecomputeFeel ();
  w->SetLook (B_BORDERED_WINDOW_LOOK);
  w->SetFlags (B_NOT_ZOOMABLE
	       | B_NOT_MINIMIZABLE
	       | B_AVOID_FRONT
	       | B_AVOID_FOCUS);
  w->UnlockLooper ();
}

/* Set B_AVOID_FOCUS on WINDOW if AVOID_FOCUS_P is non-nil, or clear
   it otherwise.  */
void
BWindow_set_avoid_focus (void *window, int avoid_focus_p)
{
  BWindow *w = (BWindow *) window;
  if (!w->LockLooper ())
    gui_abort ("Failed to lock window while setting avoid focus");

  if (!avoid_focus_p)
    w->SetFlags (w->Flags () & ~B_AVOID_FOCUS);
  else
    w->SetFlags (w->Flags () | B_AVOID_FOCUS);
  w->UnlockLooper ();
}

void
BView_emacs_delete (void *view)
{
  EmacsView *vw = (EmacsView *) view;
  if (!vw->LockLooper ())
    gui_abort ("Failed to lock view while deleting it");
  vw->RemoveSelf ();
  delete vw;
}

/* Create a popup menu.  */
void *
BPopUpMenu_new (const char *name)
{
  BPopUpMenu *menu = new BPopUpMenu (name);

  menu->SetRadioMode (0);
  return menu;
}

/* Add a title item to MENU.  These items cannot be highlighted or
   triggered, and their labels will display as bold text.  */
void
BMenu_add_title (void *menu, const char *text)
{
  BMenu *be_menu = (BMenu *) menu;
  EmacsTitleMenuItem *it;

  it = new EmacsTitleMenuItem (text);
  be_menu->AddItem (it);
}

/* Add an item to the menu MENU.  */
void
BMenu_add_item (void *menu, const char *label, void *ptr, bool enabled_p,
		bool marked_p, bool mbar_p, void *mbw_ptr, const char *key,
		const char *help)
{
  BMenu *m = (BMenu *) menu;
  BMessage *msg;
  if (ptr)
    msg = new BMessage ();
  EmacsMenuItem *it = new EmacsMenuItem (key, label, help, ptr ? msg : NULL);
  it->SetTarget (m->Window ());
  it->SetEnabled (enabled_p);
  it->SetMarked (marked_p);
  if (mbar_p)
    {
      it->menu_bar_id = (intptr_t) ptr;
      it->wind_ptr = mbw_ptr;
    }
  it->menu_ptr = ptr;
  if (ptr)
    msg->AddPointer ("menuptr", ptr);
  m->AddItem (it);
}

/* Add a separator to the menu MENU.  */
void
BMenu_add_separator (void *menu)
{
  BMenu *m = (BMenu *) menu;

  m->AddSeparatorItem ();
}

/* Create a submenu and attach it to MENU.  */
void *
BMenu_new_submenu (void *menu, const char *label, bool enabled_p)
{
  BMenu *m = (BMenu *) menu;
  BMenu *mn = new BMenu (label, B_ITEMS_IN_COLUMN);
  mn->SetRadioMode (0);
  BMenuItem *i = new BMenuItem (mn);
  i->SetEnabled (enabled_p);
  m->AddItem (i);
  return mn;
}

/* Create a submenu that notifies Emacs upon opening.  */
void *
BMenu_new_menu_bar_submenu (void *menu, const char *label)
{
  BMenu *m = (BMenu *) menu;
  BMenu *mn = new BMenu (label, B_ITEMS_IN_COLUMN);
  mn->SetRadioMode (0);
  BMenuItem *i = new BMenuItem (mn);
  i->SetEnabled (1);
  m->AddItem (i);
  return mn;
}

/* Run MENU, waiting for it to close, and return a pointer to the
   data of the selected item (if one exists), or NULL.  X, Y should
   be in the screen coordinate system.  */
void *
BMenu_run (void *menu, int x, int y,
	   void (*run_help_callback) (void *, void *),
	   void (*block_input_function) (void),
	   void (*unblock_input_function) (void),
	   struct timespec (*process_pending_signals_function) (void),
	   void *run_help_callback_data)
{
  BPopUpMenu *mn = (BPopUpMenu *) menu;
  enum haiku_event_type type;
  void *buf;
  void *ptr = NULL;
  struct be_popup_menu_data data;
  struct object_wait_info infos[3];
  struct haiku_menu_bar_help_event *event;
  BMessage *msg;
  ssize_t stat;
  struct timespec next_time;
  bigtime_t timeout;

  block_input_function ();
  port_popup_menu_to_emacs = create_port (1800, "popup menu port");
  data.x = x;
  data.y = y;
  data.menu = mn;
  unblock_input_function ();

  if (port_popup_menu_to_emacs < B_OK)
    return NULL;

  block_input_function ();
  mn->SetRadioMode (0);
  buf = alloca (200);

  infos[0].object = port_popup_menu_to_emacs;
  infos[0].type = B_OBJECT_TYPE_PORT;
  infos[0].events = B_EVENT_READ;

  infos[1].object = spawn_thread (be_popup_menu_thread_entry,
				  "Menu tracker", B_DEFAULT_MEDIA_PRIORITY,
				  (void *) &data);
  infos[1].type = B_OBJECT_TYPE_THREAD;
  infos[1].events = B_EVENT_INVALID;

  infos[2].object = port_application_to_emacs;
  infos[2].type = B_OBJECT_TYPE_PORT;
  infos[2].events = B_EVENT_READ;
  unblock_input_function ();

  if (infos[1].object < B_OK)
    {
      block_input_function ();
      delete_port (port_popup_menu_to_emacs);
      unblock_input_function ();
      return NULL;
    }

  block_input_function ();
  resume_thread (infos[1].object);
  unblock_input_function ();

  while (true)
    {
      next_time = process_pending_signals_function ();

      if (next_time.tv_nsec < 0)
	timeout = 10000000000;
      else
	timeout = (next_time.tv_sec * 1000000
		   + next_time.tv_nsec / 1000);

      if ((stat = wait_for_objects_etc ((object_wait_info *) &infos, 3,
					B_RELATIVE_TIMEOUT, timeout)) < B_OK)
	{
	  if (stat == B_INTERRUPTED || stat == B_TIMED_OUT
	      || stat == B_WOULD_BLOCK)
	    continue;
	  else
	    gui_abort ("Failed to wait for popup");
	}

      if (infos[0].events & B_EVENT_READ)
	{
	  while (!haiku_read_with_timeout (&type, buf, 200, 0, true))
	    {
	      switch (type)
		{
		case MENU_BAR_HELP_EVENT:
		  event = (struct haiku_menu_bar_help_event *) buf;
		  run_help_callback (event->highlight_p
				     ? event->data
				     : NULL, run_help_callback_data);
		  break;
		default:
		  gui_abort ("Unknown popup menu event");
		}
	    }
	}

      if (infos[1].events & B_EVENT_INVALID)
	{
	  block_input_function ();
	  msg = (BMessage *) popup_track_message;
	  if (popup_track_message)
	    ptr = (void *) msg->GetPointer ("menuptr");

	  delete_port (port_popup_menu_to_emacs);
	  unblock_input_function ();
	  return ptr;
	}

      infos[0].events = B_EVENT_READ;
      infos[1].events = B_EVENT_INVALID;
      infos[2].events = B_EVENT_READ;
    }
}

/* Delete the entire menu hierarchy of MENU, and then delete MENU
   itself.  */
void
BPopUpMenu_delete (void *menu)
{
  delete (BPopUpMenu *) menu;
}

/* Create a menubar, attach it to VIEW, and return it.  */
void *
BMenuBar_new (void *view)
{
  BView *vw = (BView *) view;
  EmacsMenuBar *bar = new EmacsMenuBar ();

  if (!vw->LockLooper ())
    gui_abort ("Failed to lock menu bar parent");
  vw->AddChild ((BView *) bar);
  vw->UnlockLooper ();

  return bar;
}

/* Delete MENUBAR along with all subitems. */
void
BMenuBar_delete (void *menubar)
{
  BView *vw = (BView *) menubar;
  BView *p = vw->Parent ();
  EmacsWindow *window = (EmacsWindow *) p->Window ();

  if (!p->LockLooper ())
    gui_abort ("Failed to lock menu bar parent while removing menubar");
  window->SetKeyMenuBar (NULL);
  /* MenusEnded isn't called if the menu bar is destroyed
     before it closes.  */
  window->menu_bar_active_p = false;
  vw->RemoveSelf ();
  p->UnlockLooper ();
  delete vw;
}

/* Delete all items from MENU.  */
void
BMenu_delete_all (void *menu)
{
  BMenu *mn = (BMenu *) menu;
  mn->RemoveItems (0, mn->CountItems (), true);
}

/* Delete COUNT items from MENU starting from START.  */
void
BMenu_delete_from (void *menu, int start, int count)
{
  BMenu *mn = (BMenu *) menu;
  mn->RemoveItems (start, count, true);
}

/* Count items in menu MENU.  */
int
BMenu_count_items (void *menu)
{
  return ((BMenu *) menu)->CountItems ();
}

/* Find the item in MENU at IDX.  */
void *
BMenu_item_at (void *menu, int idx)
{
  return ((BMenu *) menu)->ItemAt (idx);
}

/* Set ITEM's label to LABEL.  */
void
BMenu_item_set_label (void *item, const char *label)
{
  ((BMenuItem *) item)->SetLabel (label);
}

/* Get ITEM's menu.  */
void *
BMenu_item_get_menu (void *item)
{
  return ((BMenuItem *) item)->Submenu ();
}

/* Emit a beep noise.  */
void
haiku_ring_bell (void)
{
  beep ();
}

/* Create a BAlert with TEXT.  */
void *
BAlert_new (const char *text, enum haiku_alert_type type)
{
  return new BAlert (NULL, text, NULL, NULL, NULL, B_WIDTH_AS_USUAL,
		     (enum alert_type) type);
}

/* Add a button to ALERT and return the button.  */
void *
BAlert_add_button (void *alert, const char *text)
{
  BAlert *al = (BAlert *) alert;
  al->AddButton (text);
  return al->ButtonAt (al->CountButtons () - 1);
}

/* Make sure the leftmost button is grouped to the left hand side of
   the alert.  */
void
BAlert_set_offset_spacing (void *alert)
{
  BAlert *al = (BAlert *) alert;

  al->SetButtonSpacing (B_OFFSET_SPACING);
}

static int32
be_alert_thread_entry (void *thread_data)
{
  BAlert *alert = (BAlert *) thread_data;
  int32 value;

  if (alert->LockLooper ())
    value = alert->Go ();
  else
    value = -1;

  alert_popup_value = value;
  return 0;
}

/* Run ALERT, returning the number of the button that was selected,
   or -1 if no button was selected before the alert was closed.  */
int32
BAlert_go (void *alert,
	   void (*block_input_function) (void),
	   void (*unblock_input_function) (void),
	   void (*process_pending_signals_function) (void))
{
  struct object_wait_info infos[2];
  ssize_t stat;
  BAlert *alert_object = (BAlert *) alert;

  infos[0].object = port_application_to_emacs;
  infos[0].type = B_OBJECT_TYPE_PORT;
  infos[0].events = B_EVENT_READ;

  block_input_function ();
  /* Alerts are created locked, just like other windows.  */
  alert_object->UnlockLooper ();
  infos[1].object = spawn_thread (be_alert_thread_entry,
				  "Popup tracker",
				  B_DEFAULT_MEDIA_PRIORITY,
				  alert);
  infos[1].type = B_OBJECT_TYPE_THREAD;
  infos[1].events = B_EVENT_INVALID;
  unblock_input_function ();

  if (infos[1].object < B_OK)
    return -1;

  block_input_function ();
  resume_thread (infos[1].object);
  unblock_input_function ();

  while (true)
    {
      stat = wait_for_objects ((object_wait_info *) &infos, 2);

      if (stat == B_INTERRUPTED)
	continue;
      else if (stat < B_OK)
	gui_abort ("Failed to wait for popup dialog");

      if (infos[1].events & B_EVENT_INVALID)
	return alert_popup_value;

      if (infos[0].events & B_EVENT_READ)
	process_pending_signals_function ();

      infos[0].events = B_EVENT_READ;
      infos[1].events = B_EVENT_INVALID;
    }
}

/* Enable or disable BUTTON depending on ENABLED_P.  */
void
BButton_set_enabled (void *button, int enabled_p)
{
  ((BButton *) button)->SetEnabled (enabled_p);
}

/* Set VIEW's tooltip to TOOLTIP.  */
void
BView_set_tooltip (void *view, const char *tooltip)
{
  ((BView *) view)->SetToolTip (tooltip);
}

/* Set VIEW's tooltip to a sticky tooltip at X by Y.  */
void
be_show_sticky_tooltip (void *view, const char *tooltip_text,
			int x, int y)
{
  BToolTip *tooltip;
  BView *vw, *tooltip_view;
  BPoint point;

  vw = (BView *) view;

  if (!vw->LockLooper ())
    gui_abort ("Failed to lock view while showing sticky tooltip");

  vw->SetToolTip ((const char *) NULL);

  /* If the tooltip text is empty, then a tooltip object won't be
     created by SetToolTip.  */
  if (tooltip_text[0] == '\0')
    tooltip_text = " ";

  vw->SetToolTip (tooltip_text);

  tooltip = vw->ToolTip ();

  vw->GetMouse (&point, NULL, 1);
  point.x -= x;
  point.y -= y;

  point.x = -point.x;
  point.y = -point.y;

  /* We don't have to make the tooltip sticky since not receiving
     mouse movement is enough to prevent it from being hidden.  */
  tooltip->SetMouseRelativeLocation (point);

  /* Prevent the tooltip from moving in response to mouse
     movement.  */
  tooltip_view = tooltip->View ();

  if (tooltip_view)
    tooltip_view->AddChild (new EmacsMotionSuppressionView);

  vw->ShowToolTip (tooltip);
  vw->UnlockLooper ();
}

/* Delete ALERT.  */
void
BAlert_delete (void *alert)
{
  delete (BAlert *) alert;
}

/* Place the resolution of the monitor in DPI in X_OUT and Y_OUT.  */
void
be_get_display_resolution (double *x_out, double *y_out)
{
  BScreen s (B_MAIN_SCREEN_ID);
  monitor_info i;
  double x_inches, y_inches;
  BRect frame;

  if (!s.IsValid ())
    gui_abort ("Invalid screen for resolution checks");

  if (s.GetMonitorInfo (&i) == B_OK)
    {
      frame = s.Frame ();

      x_inches = (double) i.width * 25.4;
      y_inches = (double) i.height * 25.4;

      *x_out = (double) BE_RECT_WIDTH (frame) / x_inches;
      *y_out = (double) BE_RECT_HEIGHT (frame) / y_inches;
      return;
    }

  *x_out = 72.0;
  *y_out = 72.0;
}

/* Add WINDOW to OTHER_WINDOW's subset and parent it to
   OTHER_WINDOW.  */
void
EmacsWindow_parent_to (void *window, void *other_window)
{
  EmacsWindow *w = (EmacsWindow *) window;
  if (!w->LockLooper ())
    gui_abort ("Failed to lock window while parenting");
  w->ParentTo ((EmacsWindow *) other_window);
  w->UnlockLooper ();
}

void
EmacsWindow_unparent (void *window)
{
  EmacsWindow *w = (EmacsWindow *) window;
  if (!w->LockLooper ())
    gui_abort ("Failed to lock window while unparenting");
  w->UnparentAndUnlink ();
  w->UnlockLooper ();
}

/* Place text describing the current version of Haiku in VERSION,
   which should be a buffer LEN bytes wide.  */
void
be_get_version_string (char *version, int len)
{
  std::strncpy (version, "Unknown Haiku release", len - 1);
  version[len - 1] = '\0';

  BPath path;
  if (find_directory (B_BEOS_LIB_DIRECTORY, &path) == B_OK)
    {
      path.Append ("libbe.so");

      BAppFileInfo appFileInfo;
      version_info versionInfo;
      BFile file;
      if (file.SetTo (path.Path (), B_READ_ONLY) == B_OK
          && appFileInfo.SetTo (&file) == B_OK
          && appFileInfo.GetVersionInfo (&versionInfo,
                                         B_APP_VERSION_KIND) == B_OK
          && versionInfo.short_info[0] != '\0')
	{
	  std::strncpy (version, versionInfo.short_info, len - 1);
	  version[len - 1] = '\0';
	}
    }
}

/* Return the amount of color planes in the current display.  */
int
be_get_display_planes (void)
{
  color_space space = dpy_color_space;
  BScreen screen;

  if (space == B_NO_COLOR_SPACE)
    {
      if (!screen.IsValid ())
	gui_abort ("Invalid screen");

      space = dpy_color_space = screen.ColorSpace ();
    }

  switch (space)
    {
    case B_RGB32:
    case B_RGB24:
      return 24;
    case B_RGB16:
      return 16;
    case B_RGB15:
      return 15;
    case B_CMAP8:
    case B_GRAY8:
      return 8;
    case B_GRAY1:
      return 1;

    default:
      gui_abort ("Bad colorspace for screen");
    }

  /* https://www.haiku-os.org/docs/api/classBScreen.html
     says a valid screen can't be anything else.  */
  return -1;
}

/* Return the amount of colors the display can handle.  */
int
be_get_display_color_cells (void)
{
  BScreen screen;
  color_space space = dpy_color_space;

  if (space == B_NO_COLOR_SPACE)
    {
      if (!screen.IsValid ())
	gui_abort ("Invalid screen");

      space = dpy_color_space = screen.ColorSpace ();
    }

  switch (space)
    {
    case B_RGB32:
    case B_RGB24:
      return 16777216;
    case B_RGB16:
      return 65536;
    case B_RGB15:
      return 32768;
    case B_CMAP8:
    case B_GRAY8:
      return 256;
    case B_GRAY1:
      return 2;

    default:
      gui_abort ("Bad colorspace for screen");
    }

  return -1;
}

/* Return whether or not the current display is only capable of
   producing grayscale colors.  */
bool
be_is_display_grayscale (void)
{
  BScreen screen;
  color_space space = dpy_color_space;

  if (space == B_NO_COLOR_SPACE)
    {
      if (!screen.IsValid ())
	gui_abort ("Invalid screen");

      space = dpy_color_space = screen.ColorSpace ();
    }

  return space == B_GRAY8 || space == B_GRAY1;
}

/* Warp the pointer to X by Y.  */
void
be_warp_pointer (int x, int y)
{
  /* We're not supposed to use the following function without a
     BWindowScreen object, but in Haiku nothing actually prevents us
     from doing so.  */

  set_mouse_position (x, y);
}

/* Update the position of CHILD in WINDOW without actually moving
   it.  */
void
EmacsWindow_move_weak_child (void *window, void *child, int xoff, int yoff)
{
  EmacsWindow *w = (EmacsWindow *) window;
  EmacsWindow *c = (EmacsWindow *) child;

  if (!w->LockLooper ())
    gui_abort ("Couldn't lock window for weak move");
  w->MoveChild (c, xoff, yoff, 1);
  w->UnlockLooper ();
}

/* Find an appropriate view to draw onto.  If VW is double-buffered,
   this will be the view used for double buffering instead of VW
   itself.  */
void *
find_appropriate_view_for_draw (void *vw)
{
  BView *v = (BView *) vw;
  EmacsView *ev = dynamic_cast<EmacsView *>(v);
  if (!ev)
    return v;

  return ev->offscreen_draw_view ? ev->offscreen_draw_view : vw;
}

/* Set up double buffering for VW.  */
void
EmacsView_set_up_double_buffering (void *vw)
{
  EmacsView *view = (EmacsView *) vw;
  if (!view->LockLooper ())
    gui_abort ("Couldn't lock view while setting up double buffering");
  if (view->offscreen_draw_view)
    {
      view->UnlockLooper ();
      return;
    }
  view->SetUpDoubleBuffering ();
  view->UnlockLooper ();
}

/* Flip and invalidate the view VW.  */
void
EmacsView_flip_and_blit (void *vw)
{
  EmacsView *view = (EmacsView *) vw;
  if (!view->offscreen_draw_view)
    return;
  if (!view->LockLooper ())
    gui_abort ("Couldn't lock view in flip_and_blit");
  view->FlipBuffers ();
  view->UnlockLooper ();
}

/* Disable double buffering for VW.  */
void
EmacsView_disable_double_buffering (void *vw)
{
  EmacsView *view = (EmacsView *) vw;
  if (!view->LockLooper ())
    gui_abort ("Couldn't lock view tearing down double buffering");
  view->TearDownDoubleBuffering ();
  view->UnlockLooper ();
}

/* Return non-0 if VW is double-buffered.  */
int
EmacsView_double_buffered_p (void *vw)
{
  EmacsView *view = (EmacsView *) vw;
  if (!view->LockLooper ())
    gui_abort ("Couldn't lock view testing double buffering status");
  int db_p = !!view->offscreen_draw_view;
  view->UnlockLooper ();
  return db_p;
}

/* Popup a file dialog.  */
char *
be_popup_file_dialog (int open_p, const char *default_dir, int must_match_p,
		      int dir_only_p, void *window, const char *save_text,
		      const char *prompt,
		      void (*process_pending_signals_function) (void))
{
  BWindow *panel_window;
  BEntry path;
  BMessage msg (FILE_PANEL_SELECTION);
  BFilePanel panel (open_p ? B_OPEN_PANEL : B_SAVE_PANEL,
		    NULL, NULL, (dir_only_p
				 ? B_DIRECTORY_NODE
				 : B_FILE_NODE | B_DIRECTORY_NODE));
  char *file_name;
  EmacsFilePanelCallbackLooper *looper;

  looper = new EmacsFilePanelCallbackLooper;

  if (looper->InitCheck () < B_OK)
    {
      delete looper;
      return NULL;
    }

  if (default_dir)
    {
      if (path.SetTo (default_dir, 0) != B_OK)
	default_dir = NULL;
    }

  panel_window = panel.Window ();

  if (default_dir)
    panel.SetPanelDirectory (&path);

  if (save_text)
    panel.SetSaveText (save_text);

  panel_window->SetTitle (prompt);
  panel_window->SetFeel (B_MODAL_APP_WINDOW_FEEL);

  panel.SetHideWhenDone (false);
  panel.SetTarget (BMessenger (looper));
  panel.SetMessage (&msg);
  panel.Show ();

  looper->Run ();
  file_name = looper->ReadFileName (process_pending_signals_function);

  if (looper->Lock ())
    looper->Quit ();

  return file_name;
}

/* Move the pointer into MBAR and start tracking.  Return whether the
   menu bar was opened correctly.  */
bool
BMenuBar_start_tracking (void *mbar)
{
  EmacsMenuBar *mb = (EmacsMenuBar *) mbar;
  BMessenger messenger (mb);
  BMessage reply;

  messenger.SendMessage (SHOW_MENU_BAR, &reply);

  return reply.what == BE_MENU_BAR_OPEN;
}

#ifdef HAVE_NATIVE_IMAGE_API
int
be_can_translate_type_to_bitmap_p (const char *mime)
{
  BTranslatorRoster *r = BTranslatorRoster::Default ();
  translator_id *ids;
  int32 id_len;

  if (r->GetAllTranslators (&ids, &id_len) != B_OK)
    return 0;

  int found_in = 0;
  int found_out = 0;

  for (int i = 0; i < id_len; ++i)
    {
      found_in = 0;
      found_out = 0;
      const translation_format *i_fmts;
      const translation_format *o_fmts;

      int32 i_count, o_count;

      if (r->GetInputFormats (ids[i], &i_fmts, &i_count) != B_OK)
	continue;

      if (r->GetOutputFormats (ids[i], &o_fmts, &o_count) != B_OK)
	continue;

      for (int x = 0; x < i_count; ++x)
	{
	  if (!strcmp (i_fmts[x].MIME, mime))
	    {
	      found_in = 1;
	      break;
	    }
	}

      for (int x = 0; x < i_count; ++x)
	{
	  if (!strcmp (o_fmts[x].MIME, "image/x-be-bitmap") ||
	      !strcmp (o_fmts[x].MIME, "image/x-vnd.Be-bitmap"))
	    {
	      found_out = 1;
	      break;
	    }
	}

      if (found_in && found_out)
	break;
    }

  delete [] ids;

  return found_in && found_out;
}

void *
be_translate_bitmap_from_file_name (const char *filename)
{
  BBitmap *bm = BTranslationUtils::GetBitmap (filename);
  return bm;
}

void *
be_translate_bitmap_from_memory (const void *buf, size_t bytes)
{
  BMemoryIO io (buf, bytes);
  BBitmap *bm = BTranslationUtils::GetBitmap (&io);
  return bm;
}
#endif

/* Return the size of BITMAP's data, in bytes.  */
size_t
BBitmap_bytes_length (void *bitmap)
{
  BBitmap *bm = (BBitmap *) bitmap;
  return bm->BitsLength ();
}

/* Show VIEW's tooltip.  */
void
BView_show_tooltip (void *view)
{
  BView *vw = (BView *) view;
  if (vw->LockLooper ())
    {
      vw->ShowToolTip (vw->ToolTip ());
      vw->UnlockLooper ();
    }
}


#ifdef USE_BE_CAIRO
/* Return VIEW's cairo context.  */
cairo_t *
EmacsView_cairo_context (void *view)
{
  EmacsView *vw = (EmacsView *) view;
  return vw->cr_context;
}

/* Transfer each clip rectangle in VIEW to the cairo context
   CTX.  */
void
BView_cr_dump_clipping (void *view, cairo_t *ctx)
{
  BView *vw = (BView *) find_appropriate_view_for_draw (view);
  BRegion cr;
  vw->GetClippingRegion (&cr);

  for (int i = 0; i < cr.CountRects (); ++i)
    {
      BRect r = cr.RectAt (i);
      cairo_rectangle (ctx, r.left, r.top,
		       BE_RECT_WIDTH (r),
		       BE_RECT_HEIGHT (r));
    }

  cairo_clip (ctx);
}

/* Lock WINDOW in preparation for drawing using Cairo.  */
void
EmacsWindow_begin_cr_critical_section (void *window)
{
  BWindow *w = (BWindow *) window;
  BView *vw = (BView *) w->FindView ("Emacs");
  EmacsView *ev = dynamic_cast <EmacsView *> (vw);
  if (ev && !ev->cr_surface_lock.Lock ())
    gui_abort ("Couldn't lock view cairo surface");
}

/* Unlock WINDOW in preparation for drawing using Cairo.  */
void
EmacsWindow_end_cr_critical_section (void *window)
{
  BWindow *w = (BWindow *) window;
  BView *vw = (BView *) w->FindView ("Emacs");
  EmacsView *ev = dynamic_cast <EmacsView *> (vw);
  if (ev)
    ev->cr_surface_lock.Unlock ();
}
#endif

/* Get the width of STR in the plain font.  */
int
be_string_width_with_plain_font (const char *str)
{
  return be_plain_font->StringWidth (str);
}

/* Get the ascent + descent of the plain font.  */
int
be_plain_font_height (void)
{
  struct font_height fheight;
  be_plain_font->GetHeight (&fheight);

  return fheight.ascent + fheight.descent;
}

/* Return the number of physical displays connected.  */
int
be_get_display_screens (void)
{
  int count = 1;
  BScreen scr;

  if (!scr.IsValid ())
    gui_abort ("Main screen vanished!");
  while (scr.SetToNext () == B_OK && scr.IsValid ())
    ++count;

  return count;
}

/* Set the minimum width the user can resize WINDOW to.  */
/* Synchronize WINDOW's connection to the App Server.  */
void
BWindow_sync (void *window)
{
  BWindow *w = (BWindow *) window;

  if (!w->LockLooper ())
    gui_abort ("Failed to lock window looper for sync");
  w->Sync ();
  w->UnlockLooper ();
}

/* Set the alignment of WINDOW's dimensions.  */
void
BWindow_set_size_alignment (void *window, int align_width, int align_height)
{
  BWindow *w = (BWindow *) window;

  if (!w->LockLooper ())
    gui_abort ("Failed to lock window looper setting alignment");
#if 0 /* Haiku does not currently implement SetWindowAlignment.  */
  if (w->SetWindowAlignment (B_PIXEL_ALIGNMENT, -1, -1, align_width,
			     align_width, -1, -1, align_height,
			     align_height) != B_NO_ERROR)
    gui_abort ("Invalid pixel alignment");
#endif
  w->UnlockLooper ();
}

void
BWindow_send_behind (void *window, void *other_window)
{
  BWindow *w = (BWindow *) window;
  BWindow *other = (BWindow *) other_window;

  if (!w->LockLooper ())
    gui_abort ("Failed to lock window in order to send it behind another");
  w->SendBehind (other);
  w->UnlockLooper ();
}

bool
BWindow_is_active (void *window)
{
  BWindow *w = (BWindow *) window;
  return w->IsActive ();
}

bool
be_use_subpixel_antialiasing (void)
{
  bool current_subpixel_antialiasing;

  if (get_subpixel_antialiasing (&current_subpixel_antialiasing) != B_OK)
    return false;

  return current_subpixel_antialiasing;
}

void
BWindow_set_override_redirect (void *window, bool override_redirect_p)
{
  EmacsWindow *w = (EmacsWindow *) window;

  if (w->LockLooper ())
    {
      if (override_redirect_p && !w->override_redirect_p)
	{
	  w->override_redirect_p = true;
	  w->pre_override_redirect_look = w->Look ();
	  w->RecomputeFeel ();
	  w->SetLook (B_NO_BORDER_WINDOW_LOOK);
	  w->pre_override_redirect_workspaces = w->Workspaces ();
	  w->SetWorkspaces (B_ALL_WORKSPACES);
	}
      else if (w->override_redirect_p)
	{
	  w->override_redirect_p = false;
	  w->SetLook (w->pre_override_redirect_look);
	  w->RecomputeFeel ();
	  w->SetWorkspaces (w->pre_override_redirect_workspaces);
	}

      w->UnlockLooper ();
    }
}

/* Find a resource by the name NAME inside the settings file.  The
   string returned is in UTF-8 encoding, and will stay allocated as
   long as the BApplication (a.k.a display) is alive.  */
const char *
be_find_setting (const char *name)
{
  Emacs *app = (Emacs *) be_app;
  const char *value;

  /* Note that this is thread-safe since the constructor of `Emacs'
     runs in the main thread.  */
  if (!app->settings_valid_p)
    return NULL;

  if (app->settings.FindString (name, 0, &value) != B_OK)
    return NULL;

  return value;
}

void
BMessage_delete (void *message)
{
  delete (BMessage *) message;
}

static int32
be_drag_message_thread_entry (void *thread_data)
{
  BMessenger *messenger;
  BMessage reply;

  messenger = (BMessenger *) thread_data;
  messenger->SendMessage (WAIT_FOR_RELEASE, &reply);

  return 0;
}

bool
be_drag_message (void *view, void *message, bool allow_same_view,
		 void (*block_input_function) (void),
		 void (*unblock_input_function) (void),
		 void (*process_pending_signals_function) (void),
		 bool (*should_quit_function) (void))
{
  EmacsView *vw = (EmacsView *) view;
  EmacsWindow *window = (EmacsWindow *) vw->Window ();
  BMessage *msg = (BMessage *) message;
  BMessage wait_for_release;
  BMessenger messenger (vw);
  BMessage cancel_message (CANCEL_DROP);
  struct object_wait_info infos[2];
  ssize_t stat;
  thread_id window_thread;

  block_input_function ();

  if (!allow_same_view)
    window_thread = window->Looper ()->Thread ();

  if (!allow_same_view
      && (msg->ReplaceInt64 ("emacs:thread_id", window_thread)
	  == B_NAME_NOT_FOUND))
    msg->AddInt64 ("emacs:thread_id", window_thread);

  if (!vw->LockLooper ())
    gui_abort ("Failed to lock view looper for drag");

  vw->DragMessage (msg, BRect (0, 0, 0, 0));
  vw->UnlockLooper ();

  infos[0].object = port_application_to_emacs;
  infos[0].type = B_OBJECT_TYPE_PORT;
  infos[0].events = B_EVENT_READ;

  infos[1].object = spawn_thread (be_drag_message_thread_entry,
				  "Drag waiter thread",
				  B_DEFAULT_MEDIA_PRIORITY,
				  (void *) &messenger);
  infos[1].type = B_OBJECT_TYPE_THREAD;
  infos[1].events = B_EVENT_INVALID;
  unblock_input_function ();

  if (infos[1].object < B_OK)
    return false;

  block_input_function ();
  resume_thread (infos[1].object);
  unblock_input_function ();

  drag_and_drop_in_progress = true;

  while (true)
    {
      block_input_function ();
      stat = wait_for_objects ((struct object_wait_info *) &infos, 2);
      unblock_input_function ();

      if (stat == B_INTERRUPTED || stat == B_TIMED_OUT
	  || stat == B_WOULD_BLOCK)
	continue;

      if (stat < B_OK)
	gui_abort ("Failed to wait for drag");

      if (infos[0].events & B_EVENT_READ)
	process_pending_signals_function ();

      if (should_quit_function ())
	{
	  /* Do the best we can to prevent something from being
	     dropped, since Haiku doesn't provide a way to actually
	     cancel drag-and-drop.  */
	  if (vw->LockLooper ())
	    {
	      vw->DragMessage (&cancel_message, BRect (0, 0, 0, 0));
	      vw->UnlockLooper ();
	    }

	  messenger.SendMessage (CANCEL_DROP);
	  drag_and_drop_in_progress = false;
	  return true;
	}

      if (infos[1].events & B_EVENT_INVALID)
	{
	  drag_and_drop_in_progress = false;
	  return false;
	}

      infos[0].events = B_EVENT_READ;
      infos[1].events = B_EVENT_INVALID;
    }
}

bool
be_drag_and_drop_in_progress (void)
{
  return drag_and_drop_in_progress;
}

/* Replay the menu bar click event EVENT.  Return whether or not the
   menu bar actually opened.  */
bool
be_replay_menu_bar_event (void *menu_bar,
			  struct haiku_menu_bar_click_event *event)
{
  BMenuBar *m = (BMenuBar *) menu_bar;
  BMessenger messenger (m);
  BMessage reply, msg (REPLAY_MENU_BAR);

  msg.AddPoint ("emacs:point", BPoint (event->x, event->y));
  messenger.SendMessage (&msg, &reply);
  return reply.what == BE_MENU_BAR_OPEN;
}

void
BWindow_set_z_group (void *window, enum haiku_z_group z_group)
{
  EmacsWindow *w = (EmacsWindow *) window;

  if (w->LockLooper ())
    {
      if (w->z_group != z_group)
	{
	  w->z_group = z_group;
	  w->RecomputeFeel ();

	  if (w->z_group == Z_GROUP_BELOW)
	    w->SetFlags (w->Flags () | B_AVOID_FRONT);
	  else
	    w->SetFlags (w->Flags () & ~B_AVOID_FRONT);
	}

      w->UnlockLooper ();
    }
}

int
be_get_ui_color (const char *name, uint32_t *color)
{
  color_which which;
  rgb_color rgb;

  which = which_ui_color (name);

  if (which == B_NO_COLOR)
    return 1;

  rgb = ui_color (which);
  *color = (rgb.blue | rgb.green << 8
	    | rgb.red << 16 | 255 << 24);

  return 0;
}

bool
be_select_font (void (*process_pending_signals_function) (void),
		bool (*should_quit_function) (void),
		haiku_font_family_or_style *family,
		haiku_font_family_or_style *style,
		int *size, bool allow_monospace_only,
		int initial_family, int initial_style,
		int initial_size, bool initial_antialias,
		bool *disable_antialias)
{
  EmacsFontSelectionDialog *dialog;
  struct font_selection_dialog_message msg;
  uint32 flags;
  font_family family_buffer;
  font_style style_buffer;

  dialog = new EmacsFontSelectionDialog (allow_monospace_only,
					 initial_family, initial_style,
					 initial_size, initial_antialias);
  dialog->CenterOnScreen ();

  if (dialog->InitCheck () < B_OK)
    {
      dialog->Quit ();
      return false;
    }

  dialog->Show ();
  dialog->WaitForChoice (&msg, process_pending_signals_function,
			 should_quit_function);

  if (!dialog->LockLooper ())
    gui_abort ("Failed to lock font selection dialog looper");
  dialog->Quit ();

  if (msg.cancel)
    return false;

  if (get_font_family (msg.family_idx,
		       &family_buffer, &flags) != B_OK
      || get_font_style (family_buffer, msg.style_idx,
			 &style_buffer, &flags) != B_OK)
    return false;

  memcpy (family, family_buffer, sizeof *family);
  memcpy (style, style_buffer, sizeof *style);
  *size = msg.size_specified ? msg.size : -1;
  *disable_antialias = msg.disable_antialias;

  return true;
}

void
BWindow_set_sticky (void *window, bool sticky)
{
  BWindow *w = (BWindow *) window;

  if (w->LockLooper ())
    {
      w->SetFlags (sticky ? (w->Flags ()
			     | B_SAME_POSITION_IN_ALL_WORKSPACES)
		   : w->Flags () & ~B_SAME_POSITION_IN_ALL_WORKSPACES);

      w->UnlockLooper ();
    }
}

status_t
be_roster_launch (const char *type, const char *file, char **cargs,
		  ptrdiff_t nargs, void *message, team_id *team_id)
{
  BEntry entry;
  entry_ref ref;

  if (type)
    {
      if (message)
	return be_roster->Launch (type, (BMessage *) message,
				  team_id);

      return be_roster->Launch (type, (nargs > INT_MAX
				       ? INT_MAX : nargs),
				cargs, team_id);
    }

  if (entry.SetTo (file) != B_OK)
    return B_ERROR;

  if (entry.GetRef (&ref) != B_OK)
    return B_ERROR;

  if (message)
    return be_roster->Launch (&ref, (BMessage *) message,
			      team_id);

  return be_roster->Launch (&ref, (nargs > INT_MAX
				   ? INT_MAX : nargs),
			    cargs, team_id);
}

void *
be_create_pixmap_cursor (void *bitmap, int x, int y)
{
  BBitmap *bm;
  BCursor *cursor;

  bm = (BBitmap *) bitmap;
  cursor = new BCursor (bm, BPoint (x, y));

  if (cursor->InitCheck () != B_OK)
    {
      delete cursor;
      return NULL;
    }

  return cursor;
}

void
be_get_window_decorator_dimensions (void *window, int *left, int *top,
				    int *right, int *bottom)
{
  BWindow *wnd;
  BRect frame, window_frame;

  wnd = (BWindow *) window;

  if (!wnd->LockLooper ())
    gui_abort ("Failed to lock window looper frame");

  frame = wnd->DecoratorFrame ();
  window_frame = wnd->Frame ();

  if (left)
    *left = window_frame.left - frame.left;

  if (top)
    *top = window_frame.top - frame.top;

  if (right)
    *right = frame.right - window_frame.right;

  if (bottom)
    *bottom = frame.bottom - window_frame.bottom;

  wnd->UnlockLooper ();
}

void
be_get_window_decorator_frame (void *window, int *left, int *top,
			       int *width, int *height)
{
  BWindow *wnd;
  BRect frame;

  wnd = (BWindow *) window;

  if (!wnd->LockLooper ())
    gui_abort ("Failed to lock window looper frame");

  frame = wnd->DecoratorFrame ();

  *left = frame.left;
  *top = frame.top;
  *width = BE_RECT_WIDTH (frame);
  *height = BE_RECT_HEIGHT (frame);

  wnd->UnlockLooper ();
}

/* Request that a MOVE_EVENT be sent for WINDOW.  This is so that
   frame offsets can be updated after a frame parameter affecting
   decorators changes.  Sending an event instead of updating the
   offsets directly avoids race conditions where events with older
   information are received after the update happens.  */
void
be_send_move_frame_event (void *window)
{
  BWindow *wnd = (BWindow *) window;
  BMessenger msg (wnd);

  msg.SendMessage (SEND_MOVE_FRAME_EVENT);
}

void
be_lock_window (void *window)
{
  BWindow *wnd = (BWindow *) window;

  if (!wnd->LockLooper ())
    gui_abort ("Failed to lock window looper");
}

void
be_unlock_window (void *window)
{
  BWindow *wnd = (BWindow *) window;

  wnd->UnlockLooper ();
}

void
be_set_window_fullscreen_mode (void *window, enum haiku_fullscreen_mode mode)
{
  EmacsWindow *w = (EmacsWindow *) window;

  if (!w->LockLooper ())
    gui_abort ("Failed to lock window to set fullscreen mode");

  w->SetFullscreen (mode);
  w->UnlockLooper ();
}

bool
be_get_explicit_workarea (int *x, int *y, int *width, int *height)
{
  BDeskbar deskbar;
  BRect zoom;
  deskbar_location location;

  location = deskbar.Location ();

  if (location != B_DESKBAR_TOP
      && location != B_DESKBAR_BOTTOM)
    return false;

  zoom = get_zoom_rect (NULL);

  *x = zoom.left;
  *y = zoom.top;
  *width = BE_RECT_WIDTH (zoom);
  *height = BE_RECT_HEIGHT (zoom);

  return true;
}

/* Clear the grab view.  This has to be called manually from some
   places, since we don't get B_MOUSE_UP messages after a popup menu
   is run.  */

void
be_clear_grab_view (void)
{
  if (grab_view_locker.Lock ())
    {
      grab_view = NULL;
      grab_view_locker.Unlock ();
    }
}

void
be_set_use_frame_synchronization (void *view, bool sync)
{
  EmacsView *vw;

  vw = (EmacsView *) view;
  vw->SetFrameSynchronization (sync);
}

status_t
be_write_node_message (const char *path, const char *name, void *message)
{
  BNode node (path);
  status_t rc;
  ssize_t flat, result;
  char *buffer;
  BMessage *msg;

  rc = node.InitCheck ();
  msg = (BMessage *) message;

  if (rc < B_OK)
    return rc;

  flat = msg->FlattenedSize ();
  if (flat < B_OK)
    return flat;

  buffer = new (std::nothrow) char[flat];
  if (!buffer)
    return B_NO_MEMORY;

  rc = msg->Flatten (buffer, flat);
  if (rc < B_OK)
    {
      delete[] buffer;
      return rc;
    }

  result = node.WriteAttr (name, B_MIME_TYPE, 0,
			   buffer, flat);
  delete[] buffer;

  if (result < B_OK)
    return result;

  if (result != flat)
    return B_ERROR;

  return B_OK;
}

void
be_send_message (const char *app_id, void *message)
{
  BMessenger messenger (app_id);

  messenger.SendMessage ((BMessage *) message);
}