summaryrefslogtreecommitdiff
path: root/indra/llwindow/llwindowmacosx.cpp
blob: 41665419aad3b97c39f6c75748567c47f2e4981c (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
/**
 * @file llwindowmacosx.cpp
 * @brief Platform-dependent implementation of llwindow
 *
 * $LicenseInfo:firstyear=2001&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2010, Linden Research, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License only.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */

#include "linden_common.h"

#include "llwindowmacosx.h"

#include "llkeyboardmacosx.h"
#include "llwindowcallbacks.h"
#include "llpreeditor.h"

#include "llerror.h"
#include "llgl.h"
#include "llstring.h"
#include "lldir.h"
#include "indra_constants.h"

#include <OpenGL/OpenGL.h>
#include <Carbon/Carbon.h>
#include <CoreServices/CoreServices.h>
#include <CoreGraphics/CGDisplayConfiguration.h>

#include <IOKit/IOCFPlugIn.h>
#include <IOKit/IOKitLib.h>
#include <IOKit/IOMessage.h>
#include <IOKit/hid/IOHIDUsageTables.h>
#include <IOKit/hid/IOHIDLib.h>
#include <IOKit/usb/IOUSBLib.h>

extern BOOL gDebugWindowProc;
BOOL gHiDPISupport = TRUE;

const S32	BITS_PER_PIXEL = 32;
const S32	MAX_NUM_RESOLUTIONS = 32;

const S32   DEFAULT_REFRESH_RATE = 60;

namespace
{
    NSKeyEventRef mRawKeyEvent = NULL;
}
//
// LLWindowMacOSX
//

BOOL LLWindowMacOSX::sUseMultGL = FALSE;

// Cross-platform bits:

BOOL check_for_card(const char* RENDERER, const char* bad_card)
{
	if (!strnicmp(RENDERER, bad_card, strlen(bad_card)))
	{
		std::string buffer = llformat(
			"Your video card appears to be a %s, which Second Life does not support.\n"
			"\n"
			"Second Life requires a video card with 32 Mb of memory or more, as well as\n"
			"multitexture support.  We explicitly support nVidia GeForce 2 or better, \n"
			"and ATI Radeon 8500 or better.\n"
			"\n"
			"If you own a supported card and continue to receive this message, try \n"
			"updating to the latest video card drivers. Otherwise look in the\n"
			"secondlife.com support section or e-mail technical support\n"
			"\n"
			"You can try to run Second Life, but it will probably crash or run\n"
			"very slowly.  Try anyway?",
			bad_card);
		S32 button = OSMessageBox(buffer.c_str(), "Unsupported video card", OSMB_YESNO);
		if (OSBTN_YES == button)
		{
			return FALSE;
		}
		else
		{
			return TRUE;
		}
	}

	return FALSE;
}

// Switch to determine whether we capture all displays, or just the main one.
// We may want to base this on the setting of _DEBUG...

#define CAPTURE_ALL_DISPLAYS 0
//static double getDictDouble (CFDictionaryRef refDict, CFStringRef key);
static long getDictLong (CFDictionaryRef refDict, CFStringRef key);

// MBW -- HACK ALERT
// On the Mac, to put up an OS dialog in full screen mode, we must first switch OUT of full screen mode.
// The proper way to do this is to bracket the dialog with calls to beforeDialog() and afterDialog(), but these
// require a pointer to the LLWindowMacOSX object.  Stash it here and maintain in the constructor and destructor.
// This assumes that there will be only one object of this class at any time.  Hopefully this is true.
static LLWindowMacOSX *gWindowImplementation = NULL;

LLWindowMacOSX::LLWindowMacOSX(LLWindowCallbacks* callbacks,
							   const std::string& title, const std::string& name, S32 x, S32 y, S32 width,
							   S32 height, U32 flags,
							   BOOL fullscreen, BOOL clearBg,
							   BOOL enable_vsync, BOOL use_gl,
							   BOOL ignore_pixel_depth,
							   U32 fsaa_samples)
	: LLWindow(NULL, fullscreen, flags)
{
	// *HACK: During window construction we get lots of OS events for window
	// reshape, activate, etc. that the viewer isn't ready to handle.
	// Route them to a dummy callback structure until the end of constructor.
	LLWindowCallbacks null_callbacks;
	mCallbacks = &null_callbacks;

	// Voodoo for calling cocoa from carbon (see llwindowmacosx-objc.mm).
	setupCocoa();

	// Initialize the keyboard
	gKeyboard = new LLKeyboardMacOSX();
	gKeyboard->setCallbacks(callbacks);

	// Ignore use_gl for now, only used for drones on PC
	mWindow = NULL;
	mContext = NULL;
	mPixelFormat = NULL;
	mDisplay = CGMainDisplayID();
	mSimulatedRightClick = FALSE;
	mLastModifiers = 0;
	mHandsOffEvents = FALSE;
	mCursorDecoupled = FALSE;
	mCursorLastEventDeltaX = 0;
	mCursorLastEventDeltaY = 0;
	mCursorIgnoreNextDelta = FALSE;
	mNeedsResize = FALSE;
	mOverrideAspectRatio = 0.f;
	mMaximized = FALSE;
	mMinimized = FALSE;
	mLanguageTextInputAllowed = FALSE;
	mPreeditor = NULL;
	mFSAASamples = fsaa_samples;
	mForceRebuild = FALSE;

	// Get the original aspect ratio of the main device.
	mOriginalAspectRatio = (double)CGDisplayPixelsWide(mDisplay) / (double)CGDisplayPixelsHigh(mDisplay);

	// Stash the window title
	mWindowTitle = title;
	//mWindowTitle[0] = title.length();

	mDragOverrideCursor = -1;

	// Set up global event handlers (the fullscreen case needs this)
	//InstallStandardEventHandler(GetApplicationEventTarget());

	// Stash an object pointer for OSMessageBox()
	gWindowImplementation = this;
	// Create the GL context and set it up for windowed or fullscreen, as appropriate.
	if(createContext(x, y, width, height, 32, fullscreen, enable_vsync))
	{
		if(mWindow != NULL)
		{
			makeWindowOrderFront(mWindow);
		}

		if (!gGLManager.initGL())
		{
			setupFailure(
				"Second Life is unable to run because your video card drivers\n"
				"are out of date or unsupported. Please make sure you have\n"
				"the latest video card drivers installed.\n"
				"If you continue to receive this message, contact customer service.",
				"Error",
				OSMB_OK);
			return;
		}

        //start with arrow cursor
		initCursors();
		setCursor( UI_CURSOR_ARROW );
		
		allowLanguageTextInput(NULL, FALSE);
	}

	mCallbacks = callbacks;
	stop_glerror();
	
	
}

// These functions are used as wrappers for our internal event handling callbacks.
// It's a good idea to wrap these to avoid reworking more code than we need to within LLWindow.

bool callKeyUp(NSKeyEventRef event, unsigned short key, unsigned int mask)
{
    mRawKeyEvent = event;
	bool retVal = gKeyboard->handleKeyUp(key, mask);
    mRawKeyEvent = NULL;
    return retVal;
}

bool callKeyDown(NSKeyEventRef event, unsigned short key, unsigned int mask, wchar_t character)
{
    //if (mask!=MASK_NONE)
    {
        if((key == gKeyboard->inverseTranslateKey('Z')) && (character == 'y'))
        {
            key = gKeyboard->inverseTranslateKey('Y');
        }
        else if ((key == gKeyboard->inverseTranslateKey('Y')) && (character == 'z'))
        {
            key = gKeyboard->inverseTranslateKey('Z');
        }
    }

    mRawKeyEvent = event;
	bool retVal = gKeyboard->handleKeyDown(key, mask);
    mRawKeyEvent = NULL;
    return retVal;
}

void callResetKeys()
{
	gKeyboard->resetKeys();
}

bool callUnicodeCallback(wchar_t character, unsigned int mask)
{
    NativeKeyEventData eventData;
    
    memset(&eventData, 0, sizeof(NativeKeyEventData));
    
    eventData.mKeyEvent = NativeKeyEventData::KEYCHAR;
    eventData.mEventType = 0;
    eventData.mEventModifiers = mask;
    eventData.mEventKeyCode = 0;
    eventData.mEventChars = character;
    eventData.mEventUnmodChars = character;
    eventData.mEventRepeat = false;
    
    mRawKeyEvent = &eventData;
    
    bool result = gWindowImplementation->getCallbacks()->handleUnicodeChar(character, mask);
    mRawKeyEvent = NULL;
    return result;
}

void callFocus()
{
	if (gWindowImplementation)
	{
		gWindowImplementation->getCallbacks()->handleFocus(gWindowImplementation);
	}
}

void callFocusLost()
{
	if (gWindowImplementation)
	{
		gWindowImplementation->getCallbacks()->handleFocusLost(gWindowImplementation);
	}
}

void callRightMouseDown(float *pos, MASK mask)
{
    if (gWindowImplementation->allowsLanguageInput())
    {
        gWindowImplementation->interruptLanguageTextInput();
    }
    
	LLCoordGL		outCoords;
	outCoords.mX = ll_round(pos[0]);
	outCoords.mY = ll_round(pos[1]);
	gWindowImplementation->getCallbacks()->handleRightMouseDown(gWindowImplementation, outCoords, gKeyboard->currentMask(TRUE));
}

void callRightMouseUp(float *pos, MASK mask)
{
    if (gWindowImplementation->allowsLanguageInput())
    {
        gWindowImplementation->interruptLanguageTextInput();
    }
    
	LLCoordGL		outCoords;
	outCoords.mX = ll_round(pos[0]);
	outCoords.mY = ll_round(pos[1]);
	gWindowImplementation->getCallbacks()->handleRightMouseUp(gWindowImplementation, outCoords, gKeyboard->currentMask(TRUE));
}

void callLeftMouseDown(float *pos, MASK mask)
{
    if (gWindowImplementation->allowsLanguageInput())
    {
        gWindowImplementation->interruptLanguageTextInput();
    }
    
	LLCoordGL		outCoords;
	outCoords.mX = ll_round(pos[0]);
	outCoords.mY = ll_round(pos[1]);
	gWindowImplementation->getCallbacks()->handleMouseDown(gWindowImplementation, outCoords, gKeyboard->currentMask(TRUE));
}

void callLeftMouseUp(float *pos, MASK mask)
{
    if (gWindowImplementation->allowsLanguageInput())
    {
        gWindowImplementation->interruptLanguageTextInput();
    }
    
	LLCoordGL		outCoords;
	outCoords.mX = ll_round(pos[0]);
	outCoords.mY = ll_round(pos[1]);
	gWindowImplementation->getCallbacks()->handleMouseUp(gWindowImplementation, outCoords, gKeyboard->currentMask(TRUE));
	
}

void callDoubleClick(float *pos, MASK mask)
{
    if (gWindowImplementation->allowsLanguageInput())
    {
        gWindowImplementation->interruptLanguageTextInput();
    }
    
	LLCoordGL	outCoords;
	outCoords.mX = ll_round(pos[0]);
	outCoords.mY = ll_round(pos[1]);
	gWindowImplementation->getCallbacks()->handleDoubleClick(gWindowImplementation, outCoords, gKeyboard->currentMask(TRUE));
}

void callResize(unsigned int width, unsigned int height)
{
	if (gWindowImplementation != NULL)
	{
		gWindowImplementation->getCallbacks()->handleResize(gWindowImplementation, width, height);
	}
}

void callMouseMoved(float *pos, MASK mask)
{
	LLCoordGL		outCoords;
	outCoords.mX = ll_round(pos[0]);
	outCoords.mY = ll_round(pos[1]);
	float deltas[2];
	gWindowImplementation->getMouseDeltas(deltas);
	outCoords.mX += deltas[0];
	outCoords.mY += deltas[1];
	gWindowImplementation->getCallbacks()->handleMouseMove(gWindowImplementation, outCoords, gKeyboard->currentMask(TRUE));
	//gWindowImplementation->getCallbacks()->handleScrollWheel(gWindowImplementation, 0);
}

void callMouseDragged(float *pos, MASK mask)
{
    LLCoordGL		outCoords;
    outCoords.mX = ll_round(pos[0]);
    outCoords.mY = ll_round(pos[1]);
    float deltas[2];
    gWindowImplementation->getMouseDeltas(deltas);
    outCoords.mX += deltas[0];
    outCoords.mY += deltas[1];
    gWindowImplementation->getCallbacks()->handleMouseDragged(gWindowImplementation, outCoords, gKeyboard->currentMask(TRUE));
}

void callScrollMoved(float deltaX, float deltaY)
{
	if ( gWindowImplementation && gWindowImplementation->getCallbacks() )
	{
		gWindowImplementation->getCallbacks()->handleScrollHWheel(gWindowImplementation, deltaX);
		gWindowImplementation->getCallbacks()->handleScrollWheel(gWindowImplementation, deltaY);
	}
}

void callMouseExit()
{
	gWindowImplementation->getCallbacks()->handleMouseLeave(gWindowImplementation);
}

void callWindowFocus()
{
   if ( gWindowImplementation && gWindowImplementation->getCallbacks() )
	{
		gWindowImplementation->getCallbacks()->handleFocus (gWindowImplementation);
	}
	else
	{
		LL_WARNS("COCOA") << "Window Implementation or callbacks not yet initialized." << LL_ENDL;
	}


}

void callWindowUnfocus()
{
	if ( gWindowImplementation && gWindowImplementation->getCallbacks() )
	{
		gWindowImplementation->getCallbacks()->handleFocusLost(gWindowImplementation);
	}
}

void callWindowHide()
{	
	if ( gWindowImplementation && gWindowImplementation->getCallbacks() )
	{
		gWindowImplementation->getCallbacks()->handleActivate(gWindowImplementation, false);
	}
}

void callWindowUnhide()
{	
	if ( gWindowImplementation && gWindowImplementation->getCallbacks() )
	{
		gWindowImplementation->getCallbacks()->handleActivate(gWindowImplementation, true);
	}
}

void callWindowDidChangeScreen()
{
	if ( gWindowImplementation && gWindowImplementation->getCallbacks() )
	{
		gWindowImplementation->getCallbacks()->handleWindowDidChangeScreen(gWindowImplementation);
	}
}

void callDeltaUpdate(float *delta, MASK mask)
{
	gWindowImplementation->updateMouseDeltas(delta);
}

void callOtherMouseDown(float *pos, MASK mask, int button)
{
	LLCoordGL		outCoords;
	outCoords.mX = ll_round(pos[0]);
	outCoords.mY = ll_round(pos[1]);
	float deltas[2];
	gWindowImplementation->getMouseDeltas(deltas);
	outCoords.mX += deltas[0];
	outCoords.mY += deltas[1];

    if (button == 2)
    {
        gWindowImplementation->getCallbacks()->handleMiddleMouseDown(gWindowImplementation, outCoords, mask);
    }
    else
    {
        gWindowImplementation->getCallbacks()->handleOtherMouseDown(gWindowImplementation, outCoords, mask, button + 1);
    }
}

void callOtherMouseUp(float *pos, MASK mask, int button)
{
	LLCoordGL outCoords;
	outCoords.mX = ll_round(pos[0]);
	outCoords.mY = ll_round(pos[1]);
	float deltas[2];
	gWindowImplementation->getMouseDeltas(deltas);
	outCoords.mX += deltas[0];
    outCoords.mY += deltas[1];
    if (button == 2)
    {
        gWindowImplementation->getCallbacks()->handleMiddleMouseUp(gWindowImplementation, outCoords, mask);
    }
    else
    {
        gWindowImplementation->getCallbacks()->handleOtherMouseUp(gWindowImplementation, outCoords, mask, button + 1);
    }
}

void callModifier(MASK mask)
{
	gKeyboard->handleModifier(mask);
}

void callHandleDragEntered(std::string url)
{
	gWindowImplementation->handleDragNDrop(url, LLWindowCallbacks::DNDA_START_TRACKING);
}

void callHandleDragExited(std::string url)
{
	gWindowImplementation->handleDragNDrop(url, LLWindowCallbacks::DNDA_STOP_TRACKING);
}

void callHandleDragUpdated(std::string url)
{
	gWindowImplementation->handleDragNDrop(url, LLWindowCallbacks::DNDA_TRACK);
}

void callHandleDragDropped(std::string url)
{
	gWindowImplementation->handleDragNDrop(url, LLWindowCallbacks::DNDA_DROPPED);
}

void callQuitHandler()
{
	if (gWindowImplementation)
	{
		if(gWindowImplementation->getCallbacks()->handleCloseRequest(gWindowImplementation))
		{
			gWindowImplementation->getCallbacks()->handleQuit(gWindowImplementation);
		}
	}
}

void getPreeditSelectionRange(int *position, int *length)
{
	if (gWindowImplementation->getPreeditor())
	{
		gWindowImplementation->getPreeditor()->getSelectionRange(position, length);
	}
}

void getPreeditMarkedRange(int *position, int *length)
{
	if (gWindowImplementation->getPreeditor())
	{
		gWindowImplementation->getPreeditor()->getPreeditRange(position, length);
	}
}

void setPreeditMarkedRange(int position, int length)
{
	if (gWindowImplementation->getPreeditor())
	{
		gWindowImplementation->getPreeditor()->markAsPreedit(position, length);
	}
}

bool handleUnicodeCharacter(wchar_t c)
{
    bool success = false;
	if (gWindowImplementation->getPreeditor())
	{
        success = gWindowImplementation->getPreeditor()->handleUnicodeCharHere(c);
	}
    
    return success;
}

void resetPreedit()
{
	if (gWindowImplementation->getPreeditor())
	{
		gWindowImplementation->getPreeditor()->resetPreedit();
	}
}

// For reasons of convenience, handle IME updates here.
// This largely mirrors the old implementation, only sans the carbon parameters.
void setMarkedText(unsigned short *unitext, unsigned int *selectedRange, unsigned int *replacementRange, long text_len, attributedStringInfo segments)
{
	if (gWindowImplementation->getPreeditor())
	{
		LLPreeditor *preeditor = gWindowImplementation->getPreeditor();
		preeditor->resetPreedit();
		// This should be a viable replacement for the kEventParamTextInputSendReplaceRange parameter.
		if (replacementRange[0] < replacementRange[1])
		{
			const LLWString& text = preeditor->getPreeditString();
			const S32 location = wstring_wstring_length_from_utf16_length(text, 0, replacementRange[0]);
			const S32 length = wstring_wstring_length_from_utf16_length(text, location, replacementRange[1]);
			preeditor->markAsPreedit(location, length);
		}
		
		LLWString fix_str = utf16str_to_wstring(llutf16string(unitext, text_len));
		
		S32 caret_position = fix_str.length();
		
		preeditor->updatePreedit(fix_str, segments.seg_lengths, segments.seg_standouts, caret_position);
	}
}

void getPreeditLocation(float *location, unsigned int length)
{
	if (gWindowImplementation->getPreeditor())
	{
		LLPreeditor *preeditor = gWindowImplementation->getPreeditor();
		LLCoordGL coord;
		LLCoordScreen screen;
		LLRect rect;
		
		preeditor->getPreeditLocation(length, &coord, &rect, NULL);
		
		float c[4] = {float(coord.mX), float(coord.mY), 0, 0};
		
		convertRectToScreen(gWindowImplementation->getWindow(), c);
		
		location[0] = c[0];
		location[1] = c[1];
	}
}

void LLWindowMacOSX::updateMouseDeltas(float* deltas)
{
	if (mCursorDecoupled)
	{
		mCursorLastEventDeltaX = ll_round(deltas[0]);
		mCursorLastEventDeltaY = ll_round(-deltas[1]);
		
		if (mCursorIgnoreNextDelta)
		{
			mCursorLastEventDeltaX = 0;
			mCursorLastEventDeltaY = 0;
			mCursorIgnoreNextDelta = FALSE;
		}
	} else {
		mCursorLastEventDeltaX = 0;
		mCursorLastEventDeltaY = 0;
	}
}

void LLWindowMacOSX::getMouseDeltas(float* delta)
{
	delta[0] = mCursorLastEventDeltaX;
	delta[1] = mCursorLastEventDeltaY;
}

BOOL LLWindowMacOSX::createContext(int x, int y, int width, int height, int bits, BOOL fullscreen, BOOL enable_vsync)
{
	mFullscreen = fullscreen;
	
	if (mWindow == NULL)
	{
		mWindow = getMainAppWindow();
	}

	if(mContext == NULL)
	{
		// Our OpenGL view is already defined within SecondLife.xib.
		// Get the view instead.
		mGLView = createOpenGLView(mWindow, mFSAASamples, enable_vsync);
		mContext = getCGLContextObj(mGLView);
		gGLManager.mVRAM = getVramSize(mGLView);

        if(!mPixelFormat)
        {
            CGLPixelFormatAttribute attribs[] =
            {
                kCGLPFANoRecovery,
                kCGLPFADoubleBuffer,
                kCGLPFAClosestPolicy,
                kCGLPFAAccelerated,
                kCGLPFAMultisample,
                kCGLPFASampleBuffers, static_cast<CGLPixelFormatAttribute>((mFSAASamples > 0 ? 1 : 0)),
                kCGLPFASamples, static_cast<CGLPixelFormatAttribute>(mFSAASamples),
                kCGLPFAStencilSize, static_cast<CGLPixelFormatAttribute>(8),
                kCGLPFADepthSize, static_cast<CGLPixelFormatAttribute>(24),
                kCGLPFAAlphaSize, static_cast<CGLPixelFormatAttribute>(8),
                kCGLPFAColorSize, static_cast<CGLPixelFormatAttribute>(24),
                kCGLPFAOpenGLProfile, static_cast<CGLPixelFormatAttribute>(kCGLOGLPVersion_GL4_Core),
                static_cast<CGLPixelFormatAttribute>(0)
            };

            GLint numPixelFormats;
            CGLChoosePixelFormat (attribs, &mPixelFormat, &numPixelFormats);
            
            if(mPixelFormat == NULL) {
                CGLChoosePixelFormat (attribs, &mPixelFormat, &numPixelFormats);
            }
        }

	}
	
	// This sets up our view to recieve text from our non-inline text input window.
	setupInputWindow(mWindow, mGLView);
	
	// Hook up the context to a drawable

	if(mContext != NULL)
	{
		
		
		U32 err = CGLSetCurrentContext(mContext);
		if (err != kCGLNoError)
		{
			setupFailure("Can't activate GL rendering context", "Error", OSMB_OK);
			return FALSE;
		}
	}

    mRefreshRate = CGDisplayModeGetRefreshRate(CGDisplayCopyDisplayMode(mDisplay));
    if(mRefreshRate == 0)
    {
        //consider adding more appropriate fallback later
        mRefreshRate = DEFAULT_REFRESH_RATE;
    }

	// Disable vertical sync for swap
    toggleVSync(enable_vsync);

	//enable multi-threaded OpenGL
	if (sUseMultGL)
	{
		CGLError cgl_err;
		CGLContextObj ctx = CGLGetCurrentContext();

		cgl_err =  CGLEnable( ctx, kCGLCEMPEngine);

		if (cgl_err != kCGLNoError )
		{
			LL_INFOS("GLInit") << "Multi-threaded OpenGL not available." << LL_ENDL;
		}
		else
		{
            LL_INFOS("GLInit") << "Multi-threaded OpenGL enabled." << LL_ENDL;
		}
	}
	makeFirstResponder(mWindow, mGLView);
    
	return TRUE;
}


// We only support OS X 10.7's fullscreen app mode which is literally a full screen window that fills a virtual desktop.
// This makes this method obsolete.
BOOL LLWindowMacOSX::switchContext(BOOL fullscreen, const LLCoordScreen &size, BOOL enable_vsync, const LLCoordScreen * const posp)
{
	return FALSE;
}

void LLWindowMacOSX::destroyContext()
{
	if (!mContext)
	{
		// We don't have a context
		return;
	}
	// Unhook the GL context from any drawable it may have
	if(mContext != NULL)
	{
		LL_DEBUGS("Window") << "destroyContext: unhooking drawable " << LL_ENDL;
		CGLSetCurrentContext(NULL);
	}

	// Clean up remaining GL state before blowing away window
	gGLManager.shutdownGL();

	// Clean up the pixel format
	if(mPixelFormat != NULL)
	{
		CGLDestroyPixelFormat(mPixelFormat);
		mPixelFormat = NULL;
	}

	// Clean up the GL context
	if(mContext != NULL)
	{
		CGLDestroyContext(mContext);
	}
	
	// Destroy our LLOpenGLView
	if(mGLView != NULL)
	{
		removeGLView(mGLView);
		mGLView = NULL;
	}
	
	// Close the window
	if(mWindow != NULL)
	{
        NSWindowRef dead_window = mWindow;
        mWindow = NULL;
		closeWindow(dead_window);
	}

}

LLWindowMacOSX::~LLWindowMacOSX()
{
	destroyContext();

	if(mSupportedResolutions != NULL)
	{
		delete []mSupportedResolutions;
	}

	gWindowImplementation = NULL;

}


void LLWindowMacOSX::show()
{
}

void LLWindowMacOSX::hide()
{
	setMouseClipping(FALSE);
}

//virtual
void LLWindowMacOSX::minimize()
{
	setMouseClipping(FALSE);
	showCursor();
}

//virtual
void LLWindowMacOSX::restore()
{
	show();
}


// close() destroys all OS-specific code associated with a window.
// Usually called from LLWindowManager::destroyWindow()
void LLWindowMacOSX::close()
{
	// Is window is already closed?
	//	if (!mWindow)
	//	{
	//		return;
	//	}

	// Make sure cursor is visible and we haven't mangled the clipping state.
	setMouseClipping(FALSE);
	showCursor();

	destroyContext();
}

BOOL LLWindowMacOSX::isValid()
{
	if(mFullscreen)
	{
		return(TRUE);
	}

	return (mWindow != NULL);
}

BOOL LLWindowMacOSX::getVisible()
{
	BOOL result = FALSE;

	if(mFullscreen)
	{
		result = TRUE;
	}if (mWindow)
	{
			result = TRUE;
	}

	return(result);
}

BOOL LLWindowMacOSX::getMinimized()
{
	return mMinimized;
}

BOOL LLWindowMacOSX::getMaximized()
{
	return mMaximized;
}

BOOL LLWindowMacOSX::maximize()
{
	if (mWindow && !mMaximized)
	{
	}

	return mMaximized;
}

BOOL LLWindowMacOSX::getFullscreen()
{
	return mFullscreen;
}

void LLWindowMacOSX::gatherInput()
{
	updateCursor();
}

BOOL LLWindowMacOSX::getPosition(LLCoordScreen *position)
{
	S32 err = -1;

	if(mFullscreen)
	{
		position->mX = 0;
		position->mY = 0;
		err = noErr;
	}
	else if(mWindow)
	{
		const CGPoint & pos = getContentViewBoundsPosition(mWindow);

		position->mX = pos.x;
		position->mY = pos.y;

		err = noErr;
	}
	else
	{
		LL_ERRS() << "LLWindowMacOSX::getPosition(): no window and not fullscreen!" << LL_ENDL;
	}

	return (err == noErr);
}

BOOL LLWindowMacOSX::getSize(LLCoordScreen *size)
{
	S32 err = -1;

	if(mFullscreen)
	{
		size->mX = mFullscreenWidth;
		size->mY = mFullscreenHeight;
		err = noErr;
	}
	else if(mWindow)
	{
		const CGSize & sz = gHiDPISupport ? getDeviceContentViewSize(mWindow, mGLView) : getContentViewBoundsSize(mWindow);

		size->mX = sz.width;
		size->mY = sz.height;
        err = noErr;
	}
	else
	{
		LL_ERRS() << "LLWindowMacOSX::getSize(): no window and not fullscreen!" << LL_ENDL;
	}

	return (err == noErr);
}

BOOL LLWindowMacOSX::getSize(LLCoordWindow *size)
{
	S32 err = -1;
	
	if(mFullscreen)
	{
		size->mX = mFullscreenWidth;
		size->mY = mFullscreenHeight;
		err = noErr;
	}
	else if(mWindow)
	{
		const CGSize & sz = gHiDPISupport ? getDeviceContentViewSize(mWindow, mGLView) : getContentViewBoundsSize(mWindow);
		
		size->mX = sz.width;
		size->mY = sz.height;
        err = noErr;
        
        
	}
	else
	{
		LL_ERRS() << "LLWindowMacOSX::getSize(): no window and not fullscreen!" << LL_ENDL;
	}
	
	return (err == noErr);
}

BOOL LLWindowMacOSX::setPosition(const LLCoordScreen position)
{
	if(mWindow)
	{
		float pos[2] = {float(position.mX), float(position.mY)};
		setWindowPos(mWindow, pos);
	}

	return TRUE;
}

BOOL LLWindowMacOSX::setSizeImpl(const LLCoordScreen size)
{
	if(mWindow)
	{
        LLCoordWindow to;
        convertCoords(size, &to);
		setWindowSize(mWindow, to.mX, to.mY);
        return TRUE;
	}

	return FALSE;
}

BOOL LLWindowMacOSX::setSizeImpl(const LLCoordWindow size)
{
	if (mWindow)
	{
        const int titlePadding = 22;
        setWindowSize(mWindow, size.mX, size.mY + titlePadding);
        return TRUE;
	}
    
	return FALSE;
}

void LLWindowMacOSX::swapBuffers()
{
	CGLFlushDrawable(mContext);
}

void LLWindowMacOSX::restoreGLContext()
{
    CGLSetCurrentContext(mContext);
}

F32 LLWindowMacOSX::getGamma()
{
	F32 result = 2.2;	// Default to something sane

	CGGammaValue redMin;
	CGGammaValue redMax;
	CGGammaValue redGamma;
	CGGammaValue greenMin;
	CGGammaValue greenMax;
	CGGammaValue greenGamma;
	CGGammaValue blueMin;
	CGGammaValue blueMax;
	CGGammaValue blueGamma;

	if(CGGetDisplayTransferByFormula(
		mDisplay,
		&redMin,
		&redMax,
		&redGamma,
		&greenMin,
		&greenMax,
		&greenGamma,
		&blueMin,
		&blueMax,
		&blueGamma) == noErr)
	{
		// So many choices...
		// Let's just return the green channel gamma for now.
		result = greenGamma;
	}

	return result;
}

U32 LLWindowMacOSX::getFSAASamples()
{
	return mFSAASamples;
}

void LLWindowMacOSX::setFSAASamples(const U32 samples)
{
	mFSAASamples = samples;
	mForceRebuild = TRUE;
}

BOOL LLWindowMacOSX::restoreGamma()
{
	CGDisplayRestoreColorSyncSettings();
	return true;
}

BOOL LLWindowMacOSX::setGamma(const F32 gamma)
{
	CGGammaValue redMin;
	CGGammaValue redMax;
	CGGammaValue redGamma;
	CGGammaValue greenMin;
	CGGammaValue greenMax;
	CGGammaValue greenGamma;
	CGGammaValue blueMin;
	CGGammaValue blueMax;
	CGGammaValue blueGamma;

	// MBW -- XXX -- Should we allow this in windowed mode?

	if(CGGetDisplayTransferByFormula(
		mDisplay,
		&redMin,
		&redMax,
		&redGamma,
		&greenMin,
		&greenMax,
		&greenGamma,
		&blueMin,
		&blueMax,
		&blueGamma) != noErr)
	{
		return false;
	}

	if(CGSetDisplayTransferByFormula(
		mDisplay,
		redMin,
		redMax,
		gamma,
		greenMin,
		greenMax,
		gamma,
		blueMin,
		blueMax,
		gamma) != noErr)
	{
		return false;
	}


	return true;
}

BOOL LLWindowMacOSX::isCursorHidden()
{
	return mCursorHidden;
}



// Constrains the mouse to the window.
void LLWindowMacOSX::setMouseClipping( BOOL b )
{
	// Just stash the requested state.  We'll simulate this when the cursor is hidden by decoupling.
	mIsMouseClipping = b;

	if(b)
	{
		//		LL_INFOS() << "setMouseClipping(TRUE)" << LL_ENDL;
	}
	else
	{
		//		LL_INFOS() << "setMouseClipping(FALSE)" << LL_ENDL;
	}

	adjustCursorDecouple();
}

BOOL LLWindowMacOSX::setCursorPosition(const LLCoordWindow position)
{
	BOOL result = FALSE;
	LLCoordScreen screen_pos;

	if (!convertCoords(position, &screen_pos))
	{
		return FALSE;
	}

	CGPoint newPosition;

	//	LL_INFOS() << "setCursorPosition(" << screen_pos.mX << ", " << screen_pos.mY << ")" << LL_ENDL;

	newPosition.x = screen_pos.mX;
	newPosition.y = screen_pos.mY;

	CGSetLocalEventsSuppressionInterval(0.0);
	if(CGWarpMouseCursorPosition(newPosition) == noErr)
	{
		result = TRUE;
	}

	// Under certain circumstances, this will trigger us to decouple the cursor.
	adjustCursorDecouple(true);

	// trigger mouse move callback
	LLCoordGL gl_pos;
	convertCoords(position, &gl_pos);
	float scale = getSystemUISize();
	gl_pos.mX *= scale;
	gl_pos.mY *= scale;
	mCallbacks->handleMouseMove(this, gl_pos, (MASK)0);

	return result;
}

BOOL LLWindowMacOSX::getCursorPosition(LLCoordWindow *position)
{
	float cursor_point[2];
	LLCoordScreen screen_pos;

	if(mWindow == NULL)
		return FALSE;
	
	getCursorPos(mWindow, cursor_point);

	if(mCursorDecoupled)
	{
		//		CGMouseDelta x, y;

		// If the cursor's decoupled, we need to read the latest movement delta as well.
		//		CGGetLastMouseDelta( &x, &y );
		//		cursor_point.h += x;
		//		cursor_point.v += y;

		// CGGetLastMouseDelta may behave strangely when the cursor's first captured.
		// Stash in the event handler instead.
		cursor_point[0] += mCursorLastEventDeltaX;
		cursor_point[1] += mCursorLastEventDeltaY;
	}

	float scale = getSystemUISize();
	position->mX = cursor_point[0] * scale;
	position->mY = cursor_point[1] * scale;

	return TRUE;
}

void LLWindowMacOSX::adjustCursorDecouple(bool warpingMouse)
{
	if(mIsMouseClipping && mCursorHidden)
	{
		if(warpingMouse)
		{
			// The cursor should be decoupled.  Make sure it is.
			if(!mCursorDecoupled)
			{
				//			LL_INFOS() << "adjustCursorDecouple: decoupling cursor" << LL_ENDL;
				CGAssociateMouseAndMouseCursorPosition(false);
				mCursorDecoupled = true;
				mCursorIgnoreNextDelta = TRUE;
			}
		}
	}
	else
	{
		// The cursor should not be decoupled.  Make sure it isn't.
		if(mCursorDecoupled)
		{
			//			LL_INFOS() << "adjustCursorDecouple: recoupling cursor" << LL_ENDL;
			CGAssociateMouseAndMouseCursorPosition(true);
			mCursorDecoupled = false;
		}
	}
}

F32 LLWindowMacOSX::getNativeAspectRatio()
{
	if (mFullscreen)
	{
		return (F32)mFullscreenWidth / (F32)mFullscreenHeight;
	}
	else
	{
		// The constructor for this class grabs the aspect ratio of the monitor before doing any resolution
		// switching, and stashes it in mOriginalAspectRatio.  Here, we just return it.

		if (mOverrideAspectRatio > 0.f)
		{
			return mOverrideAspectRatio;
		}

		return mOriginalAspectRatio;
	}
}

F32 LLWindowMacOSX::getPixelAspectRatio()
{
	//OS X always enforces a 1:1 pixel aspect ratio, regardless of video mode
	return 1.f;
}

U32 LLWindowMacOSX::getAvailableVRAMMegabytes() {
    // MTL (and MoltenVK) has some additional gpu data, such as recommendedMaxWorkingSetSize and currentAllocatedSize.
    // But these are not available for OpenGL and/or our current mimimum OS version.
    // So we will estimate.
    static const U32 mb = 1024*1024;
    // We're asked for total available gpu memory, but we only have allocation info on texture usage. So estimate by doubling that.
    static const U32 total_factor = 2; // estimated total/textures
    return gGLManager.mVRAM - (LLImageGL::getTextureBytesAllocated() * total_factor/mb);
}

//static SInt32 oldWindowLevel;

// MBW -- XXX -- There's got to be a better way than this.  Find it, please...

// Since we're no longer supporting the "typical" fullscreen mode with CGL or NSOpenGL anymore, these are unnecessary. -Geenz
void LLWindowMacOSX::beforeDialog()
{
}

void LLWindowMacOSX::afterDialog()
{
    //For fix problem with Core Flow view on OSX
    restoreGLContext();
}


void LLWindowMacOSX::flashIcon(F32 seconds)
{
	// For consistency with OS X conventions, the number of seconds given is ignored and
	// left up to the OS (which will actually bounce it for one second).
	requestUserAttention();
}

BOOL LLWindowMacOSX::isClipboardTextAvailable()
{
	return pasteBoardAvailable();
}

BOOL LLWindowMacOSX::pasteTextFromClipboard(LLWString &dst)
{
    unsigned short* pboard_data = copyFromPBoard(); // must free returned data
	llutf16string str(pboard_data);
    free(pboard_data);

	dst = utf16str_to_wstring(str);
	if (dst != L"")
	{
		return true;
	} else {
		return false;
	}
}

BOOL LLWindowMacOSX::copyTextToClipboard(const LLWString &s)
{
	BOOL result = false;
	llutf16string utf16str = wstring_to_utf16str(s);
	
	result = copyToPBoard(utf16str.data(), utf16str.length());

	return result;
}


// protected
BOOL LLWindowMacOSX::resetDisplayResolution()
{
	// This is only called from elsewhere in this class, and it's not used by the Mac implementation.
	return true;
}


LLWindow::LLWindowResolution* LLWindowMacOSX::getSupportedResolutions(S32 &num_resolutions)
{
	if (!mSupportedResolutions)
	{
		CFArrayRef modes = CGDisplayCopyAllDisplayModes(mDisplay, nullptr);

		if(modes != NULL)
		{
			CFIndex index, cnt;

			mSupportedResolutions = new LLWindowResolution[MAX_NUM_RESOLUTIONS];
			mNumSupportedResolutions = 0;

			//  Examine each mode
			cnt = CFArrayGetCount( modes );

			for ( index = 0; (index < cnt) && (mNumSupportedResolutions < MAX_NUM_RESOLUTIONS); index++ )
			{
				//  Pull the mode dictionary out of the CFArray
				CFDictionaryRef mode = (CFDictionaryRef)CFArrayGetValueAtIndex( modes, index );
				long width = getDictLong(mode, kCGDisplayWidth);
				long height = getDictLong(mode, kCGDisplayHeight);
				long bits = getDictLong(mode, kCGDisplayBitsPerPixel);

				if(bits == BITS_PER_PIXEL && width >= 800 && height >= 600)
				{
					BOOL resolution_exists = FALSE;
					for(S32 i = 0; i < mNumSupportedResolutions; i++)
					{
						if (mSupportedResolutions[i].mWidth == width &&
							mSupportedResolutions[i].mHeight == height)
						{
							resolution_exists = TRUE;
						}
					}
					if (!resolution_exists)
					{
						mSupportedResolutions[mNumSupportedResolutions].mWidth = width;
						mSupportedResolutions[mNumSupportedResolutions].mHeight = height;
						mNumSupportedResolutions++;
					}
				}
			}
            CFRelease(modes);
		}
	}

	num_resolutions = mNumSupportedResolutions;
	return mSupportedResolutions;
}

BOOL LLWindowMacOSX::convertCoords(LLCoordGL from, LLCoordWindow *to)
{
	to->mX = from.mX;
	to->mY = from.mY;
	return TRUE;
}

BOOL LLWindowMacOSX::convertCoords(LLCoordWindow from, LLCoordGL* to)
{
	to->mX = from.mX;
	to->mY = from.mY;
	return TRUE;
}

BOOL LLWindowMacOSX::convertCoords(LLCoordScreen from, LLCoordWindow* to)
{
	if(mWindow)
	{
		float mouse_point[2];

		mouse_point[0] = from.mX;
		mouse_point[1] = from.mY;
		
		convertScreenToWindow(mWindow, mouse_point);

		to->mX = mouse_point[0];
		to->mY = mouse_point[1];

		return TRUE;
	}
	return FALSE;
}

BOOL LLWindowMacOSX::convertCoords(LLCoordWindow from, LLCoordScreen *to)
{
	if(mWindow)
	{
		float mouse_point[2];

		mouse_point[0] = from.mX;
		mouse_point[1] = from.mY;
		
		convertWindowToScreen(mWindow, mouse_point);

		to->mX = mouse_point[0];
		to->mY = mouse_point[1];

		return TRUE;
	}
	return FALSE;
}

BOOL LLWindowMacOSX::convertCoords(LLCoordScreen from, LLCoordGL *to)
{
	LLCoordWindow window_coord;

	return(convertCoords(from, &window_coord) && convertCoords(window_coord, to));
}

BOOL LLWindowMacOSX::convertCoords(LLCoordGL from, LLCoordScreen *to)
{
	LLCoordWindow window_coord;

	return(convertCoords(from, &window_coord) && convertCoords(window_coord, to));
}




void LLWindowMacOSX::setupFailure(const std::string& text, const std::string& caption, U32 type)
{
	destroyContext();

	OSMessageBox(text, caption, type);
}

			// Note on event recording - QUIT is a known special case and we are choosing NOT to record it for the record and playback feature 
			// it is handled at a very low-level
const char* cursorIDToName(int id)
{
	switch (id)
	{
		case UI_CURSOR_ARROW:							return "UI_CURSOR_ARROW";
		case UI_CURSOR_WAIT:							return "UI_CURSOR_WAIT";
		case UI_CURSOR_HAND:							return "UI_CURSOR_HAND";
		case UI_CURSOR_IBEAM:							return "UI_CURSOR_IBEAM";
		case UI_CURSOR_CROSS:							return "UI_CURSOR_CROSS";
		case UI_CURSOR_SIZENWSE:						return "UI_CURSOR_SIZENWSE";
		case UI_CURSOR_SIZENESW:						return "UI_CURSOR_SIZENESW";
		case UI_CURSOR_SIZEWE:							return "UI_CURSOR_SIZEWE";
		case UI_CURSOR_SIZENS:							return "UI_CURSOR_SIZENS";
		case UI_CURSOR_SIZEALL:							return "UI_CURSOR_SIZEALL";
		case UI_CURSOR_NO:								return "UI_CURSOR_NO";
		case UI_CURSOR_WORKING:							return "UI_CURSOR_WORKING";
		case UI_CURSOR_TOOLGRAB:						return "UI_CURSOR_TOOLGRAB";
		case UI_CURSOR_TOOLLAND:						return "UI_CURSOR_TOOLLAND";
		case UI_CURSOR_TOOLFOCUS:						return "UI_CURSOR_TOOLFOCUS";
		case UI_CURSOR_TOOLCREATE:						return "UI_CURSOR_TOOLCREATE";
		case UI_CURSOR_ARROWDRAG:						return "UI_CURSOR_ARROWDRAG";
		case UI_CURSOR_ARROWCOPY:						return "UI_CURSOR_ARROWCOPY";
		case UI_CURSOR_ARROWDRAGMULTI:					return "UI_CURSOR_ARROWDRAGMULTI";
		case UI_CURSOR_ARROWCOPYMULTI:					return "UI_CURSOR_ARROWCOPYMULTI";
		case UI_CURSOR_NOLOCKED:						return "UI_CURSOR_NOLOCKED";
		case UI_CURSOR_ARROWLOCKED:						return "UI_CURSOR_ARROWLOCKED";
		case UI_CURSOR_GRABLOCKED:						return "UI_CURSOR_GRABLOCKED";
		case UI_CURSOR_TOOLTRANSLATE:					return "UI_CURSOR_TOOLTRANSLATE";
		case UI_CURSOR_TOOLROTATE:						return "UI_CURSOR_TOOLROTATE";
		case UI_CURSOR_TOOLSCALE:						return "UI_CURSOR_TOOLSCALE";
		case UI_CURSOR_TOOLCAMERA:						return "UI_CURSOR_TOOLCAMERA";
		case UI_CURSOR_TOOLPAN:							return "UI_CURSOR_TOOLPAN";
		case UI_CURSOR_TOOLZOOMIN:						return "UI_CURSOR_TOOLZOOMIN";
		case UI_CURSOR_TOOLZOOMOUT:						return "UI_CURSOR_TOOLZOOMOUT";
		case UI_CURSOR_TOOLPICKOBJECT3:					return "UI_CURSOR_TOOLPICKOBJECT3";
		case UI_CURSOR_TOOLPLAY:						return "UI_CURSOR_TOOLPLAY";
		case UI_CURSOR_TOOLPAUSE:						return "UI_CURSOR_TOOLPAUSE";
		case UI_CURSOR_TOOLMEDIAOPEN:					return "UI_CURSOR_TOOLMEDIAOPEN";
		case UI_CURSOR_PIPETTE:							return "UI_CURSOR_PIPETTE";
		case UI_CURSOR_TOOLSIT:							return "UI_CURSOR_TOOLSIT";
		case UI_CURSOR_TOOLBUY:							return "UI_CURSOR_TOOLBUY";
		case UI_CURSOR_TOOLOPEN:						return "UI_CURSOR_TOOLOPEN";
		case UI_CURSOR_TOOLPATHFINDING:					return "UI_CURSOR_PATHFINDING";
		case UI_CURSOR_TOOLPATHFINDING_PATH_START:		return "UI_CURSOR_PATHFINDING_START";
		case UI_CURSOR_TOOLPATHFINDING_PATH_START_ADD:	return "UI_CURSOR_PATHFINDING_START_ADD";
		case UI_CURSOR_TOOLPATHFINDING_PATH_END:		return "UI_CURSOR_PATHFINDING_END";
		case UI_CURSOR_TOOLPATHFINDING_PATH_END_ADD:	return "UI_CURSOR_PATHFINDING_END_ADD";
		case UI_CURSOR_TOOLNO:							return "UI_CURSOR_NO";
	}

	LL_ERRS() << "cursorIDToName: unknown cursor id" << id << LL_ENDL;

	return "UI_CURSOR_ARROW";
}

static CursorRef gCursors[UI_CURSOR_COUNT];


static void initPixmapCursor(int cursorid, int hotspotX, int hotspotY)
{
	// cursors are in <Application Bundle>/Contents/Resources/cursors_mac/UI_CURSOR_FOO.tif
	std::string fullpath = gDirUtilp->add(
		gDirUtilp->getAppRODataDir(),
		"cursors_mac",
		cursorIDToName(cursorid) + std::string(".tif"));

	gCursors[cursorid] = createImageCursor(fullpath.c_str(), hotspotX, hotspotY);
}

void LLWindowMacOSX::updateCursor()
{
	S32 result = 0;

	if (mDragOverrideCursor != -1)
	{
		// A drag is in progress...remember the requested cursor and we'll
		// restore it when it is done
		mCurrentCursor = mNextCursor;
		return;
	}
		
	if (mNextCursor == UI_CURSOR_ARROW
		&& mBusyCount > 0)
	{
		mNextCursor = UI_CURSOR_WORKING;
	}
	
    if(mCurrentCursor == mNextCursor)
    {
        if(mCursorHidden && mHideCursorPermanent && isCGCursorVisible())
        {
            hideNSCursor();            
            adjustCursorDecouple();
        }
        return;
    }

	// RN: replace multi-drag cursors with single versions
	if (mNextCursor == UI_CURSOR_ARROWDRAGMULTI)
	{
		mNextCursor = UI_CURSOR_ARROWDRAG;
	}
	else if (mNextCursor == UI_CURSOR_ARROWCOPYMULTI)
	{
		mNextCursor = UI_CURSOR_ARROWCOPY;
	}

	switch(mNextCursor)
	{
	default:
	case UI_CURSOR_ARROW:
		setArrowCursor();
		if(mCursorHidden)
		{
			// Since InitCursor resets the hide level, correct for it here.
			hideNSCursor();
		}
		break;

		// MBW -- XXX -- Some of the standard Windows cursors have no standard Mac equivalents.
		//    Find out what they look like and replicate them.

		// These are essentially correct
	case UI_CURSOR_WAIT:		/* Apple purposely doesn't allow us to set the beachball cursor manually.  Let NSApp figure out when to do this. */	break;
	case UI_CURSOR_IBEAM:		setIBeamCursor();	break;
	case UI_CURSOR_CROSS:		setCrossCursor();	break;
	case UI_CURSOR_HAND:		setPointingHandCursor();	break;
		//		case UI_CURSOR_NO:			SetThemeCursor(kThemeNotAllowedCursor);	break;
	case UI_CURSOR_ARROWCOPY:   setCopyCursor();	break;

		// Double-check these
	case UI_CURSOR_NO:
	case UI_CURSOR_SIZEWE:
	case UI_CURSOR_SIZENS:
	case UI_CURSOR_SIZENWSE:
	case UI_CURSOR_SIZENESW:
	case UI_CURSOR_WORKING:
	case UI_CURSOR_TOOLGRAB:
	case UI_CURSOR_TOOLLAND:
	case UI_CURSOR_TOOLFOCUS:
	case UI_CURSOR_TOOLCREATE:
	case UI_CURSOR_ARROWDRAG:
	case UI_CURSOR_NOLOCKED:
	case UI_CURSOR_ARROWLOCKED:
	case UI_CURSOR_GRABLOCKED:
	case UI_CURSOR_PIPETTE:
	case UI_CURSOR_TOOLTRANSLATE:
	case UI_CURSOR_TOOLROTATE:
	case UI_CURSOR_TOOLSCALE:
	case UI_CURSOR_TOOLCAMERA:
	case UI_CURSOR_TOOLPAN:
	case UI_CURSOR_TOOLZOOMIN:
	case UI_CURSOR_TOOLPICKOBJECT3:
	case UI_CURSOR_TOOLPLAY:
	case UI_CURSOR_TOOLPAUSE:
	case UI_CURSOR_TOOLMEDIAOPEN:
	case UI_CURSOR_TOOLSIT:
	case UI_CURSOR_TOOLBUY:
	case UI_CURSOR_TOOLOPEN:
	case UI_CURSOR_TOOLPATHFINDING:
	case UI_CURSOR_TOOLPATHFINDING_PATH_START:
	case UI_CURSOR_TOOLPATHFINDING_PATH_START_ADD:
	case UI_CURSOR_TOOLPATHFINDING_PATH_END:
	case UI_CURSOR_TOOLPATHFINDING_PATH_END_ADD:
	case UI_CURSOR_TOOLNO:
		result = setImageCursor(gCursors[mNextCursor]);
		break;

	}

	if(result != noErr)
	{
		setArrowCursor();
	}

	mCurrentCursor = mNextCursor;
}

ECursorType LLWindowMacOSX::getCursor() const
{
	return mCurrentCursor;
}

void LLWindowMacOSX::initCursors()
{
	initPixmapCursor(UI_CURSOR_NO, 8, 8);
	initPixmapCursor(UI_CURSOR_WORKING, 1, 1);
	initPixmapCursor(UI_CURSOR_TOOLGRAB, 2, 14);
	initPixmapCursor(UI_CURSOR_TOOLLAND, 13, 8);
	initPixmapCursor(UI_CURSOR_TOOLFOCUS, 7, 6);
	initPixmapCursor(UI_CURSOR_TOOLCREATE, 7, 7);
	initPixmapCursor(UI_CURSOR_ARROWDRAG, 1, 1);
	initPixmapCursor(UI_CURSOR_ARROWCOPY, 1, 1);
	initPixmapCursor(UI_CURSOR_NOLOCKED, 8, 8);
	initPixmapCursor(UI_CURSOR_ARROWLOCKED, 1, 1);
	initPixmapCursor(UI_CURSOR_GRABLOCKED, 2, 14);
	initPixmapCursor(UI_CURSOR_PIPETTE, 3, 29);
	initPixmapCursor(UI_CURSOR_TOOLTRANSLATE, 1, 1);
	initPixmapCursor(UI_CURSOR_TOOLROTATE, 1, 1);
	initPixmapCursor(UI_CURSOR_TOOLSCALE, 1, 1);
	initPixmapCursor(UI_CURSOR_TOOLCAMERA, 7, 6);
	initPixmapCursor(UI_CURSOR_TOOLPAN, 7, 6);
	initPixmapCursor(UI_CURSOR_TOOLZOOMIN, 7, 6);
    initPixmapCursor(UI_CURSOR_TOOLZOOMOUT, 7, 6);
	initPixmapCursor(UI_CURSOR_TOOLPICKOBJECT3, 1, 1);
	initPixmapCursor(UI_CURSOR_TOOLPLAY, 1, 1);
	initPixmapCursor(UI_CURSOR_TOOLPAUSE, 1, 1);
	initPixmapCursor(UI_CURSOR_TOOLMEDIAOPEN, 1, 1);
	initPixmapCursor(UI_CURSOR_TOOLSIT, 20, 15);
	initPixmapCursor(UI_CURSOR_TOOLBUY, 20, 15);
	initPixmapCursor(UI_CURSOR_TOOLOPEN, 20, 15);
	initPixmapCursor(UI_CURSOR_TOOLPATHFINDING, 16, 16);
	initPixmapCursor(UI_CURSOR_TOOLPATHFINDING_PATH_START, 16, 16);
	initPixmapCursor(UI_CURSOR_TOOLPATHFINDING_PATH_START_ADD, 16, 16);
	initPixmapCursor(UI_CURSOR_TOOLPATHFINDING_PATH_END, 16, 16);
	initPixmapCursor(UI_CURSOR_TOOLPATHFINDING_PATH_END_ADD, 16, 16);
	initPixmapCursor(UI_CURSOR_TOOLNO, 8, 8);

	initPixmapCursor(UI_CURSOR_SIZENWSE, 10, 10);
	initPixmapCursor(UI_CURSOR_SIZENESW, 10, 10);
	initPixmapCursor(UI_CURSOR_SIZEWE, 10, 10);
	initPixmapCursor(UI_CURSOR_SIZENS, 10, 10);
    initPixmapCursor(UI_CURSOR_SIZEALL, 10, 10);

}

void LLWindowMacOSX::captureMouse()
{
	// By registering a global CarbonEvent handler for mouse move events, we ensure that
	// mouse events are always processed.  Thus, capture and release are unnecessary.
}

void LLWindowMacOSX::releaseMouse()
{
	// By registering a global CarbonEvent handler for mouse move events, we ensure that
	// mouse events are always processed.  Thus, capture and release are unnecessary.
}

void LLWindowMacOSX::hideCursor()
{
	if(!mCursorHidden)
	{
		//		LL_INFOS() << "hideCursor: hiding" << LL_ENDL;
		mCursorHidden = TRUE;
		mHideCursorPermanent = TRUE;
		hideNSCursor();
	}
	else
	{
		//		LL_INFOS() << "hideCursor: already hidden" << LL_ENDL;
	}

	adjustCursorDecouple();
}

void LLWindowMacOSX::showCursor()
{
	if(mCursorHidden || !isCGCursorVisible())
	{
		//		LL_INFOS() << "showCursor: showing" << LL_ENDL;
		mCursorHidden = FALSE;
		mHideCursorPermanent = FALSE;
		showNSCursor();
	}
	else
	{
		//		LL_INFOS() << "showCursor: already visible" << LL_ENDL;
	}

	adjustCursorDecouple();
}

void LLWindowMacOSX::showCursorFromMouseMove()
{
	if (!mHideCursorPermanent)
	{
		showCursor();
	}
}

void LLWindowMacOSX::hideCursorUntilMouseMove()
{
	if (!mHideCursorPermanent)
	{
		hideCursor();
		mHideCursorPermanent = FALSE;
	}
}



//
// LLSplashScreenMacOSX
//
LLSplashScreenMacOSX::LLSplashScreenMacOSX()
{
	mWindow = NULL;
}

LLSplashScreenMacOSX::~LLSplashScreenMacOSX()
{
}

void LLSplashScreenMacOSX::showImpl()
{
	// This code _could_ be used to display a spash screen...
}

void LLSplashScreenMacOSX::updateImpl(const std::string& mesg)
{
	if(mWindow != NULL)
	{
		CFStringCreateWithCString(NULL, mesg.c_str(), kCFStringEncodingUTF8);
	}
}


void LLSplashScreenMacOSX::hideImpl()
{
	if(mWindow != NULL)
	{
		mWindow = NULL;
	}
}

S32 OSMessageBoxMacOSX(const std::string& text, const std::string& caption, U32 type)
{
	return showAlert(text, caption, type);
}

// Open a URL with the user's default web browser.
// Must begin with protocol identifier.
void LLWindowMacOSX::spawnWebBrowser(const std::string& escaped_url, bool async)
{
	// I'm fairly certain that this is all legitimate under Apple's currently supported APIs.
	
	bool found = false;
	S32 i;
	for (i = 0; i < gURLProtocolWhitelistCount; i++)
	{
		if (escaped_url.find(gURLProtocolWhitelist[i]) != std::string::npos)
		{
			found = true;
			break;
		}
	}

	if (!found)
	{
		LL_WARNS() << "spawn_web_browser called for url with protocol not on whitelist: " << escaped_url << LL_ENDL;
		return;
	}

	S32 result = 0;
	CFURLRef urlRef = NULL;

	LL_INFOS() << "Opening URL " << escaped_url << LL_ENDL;

	CFStringRef	stringRef = CFStringCreateWithCString(NULL, escaped_url.c_str(), kCFStringEncodingUTF8);
	if (stringRef)
	{
		// This will succeed if the string is a full URL, including the http://
		// Note that URLs specified this way need to be properly percent-escaped.
		urlRef = CFURLCreateWithString(NULL, stringRef, NULL);

		// Don't use CRURLCreateWithFileSystemPath -- only want valid URLs

		CFRelease(stringRef);
	}

	if (urlRef)
	{
		result = LSOpenCFURLRef(urlRef, NULL);

		if (result != noErr)
		{
			LL_INFOS() << "Error " << result << " on open." << LL_ENDL;
		}

		CFRelease(urlRef);
	}
	else
	{
		LL_INFOS() << "Error: couldn't create URL." << LL_ENDL;
	}
}

// String should match ndof, so string mapping code was copied as is
static char mapChar( char c )
{
    unsigned char uc = ( unsigned char ) c;
    
    switch( uc )
    {
        case '/': return '-'; // use dash instead of slash
            
        case 0x7F: return ' ';
        case 0x80: return 'A';
        case 0x81: return 'A';
        case 0x82: return 'C';
        case 0x83: return 'E';
        case 0x84: return 'N';
        case 0x85: return 'O';
        case 0x86: return 'U';
        case 0x87: return 'a';
        case 0x88: return 'a';
        case 0x89: return 'a';
        case 0x8A: return 'a';
        case 0x8B: return 'a';
        case 0x8C: return 'a';
        case 0x8D: return 'c';
        case 0x8E: return 'e';
        case 0x8F: return 'e';
        case 0x90: return ' ';
        case 0x91: return ' '; // ? '
        case 0x92: return ' '; // ? '
        case 0x93: return ' '; // ? "
        case 0x94: return ' '; // ? "
        case 0x95: return ' ';
        case 0x96: return ' ';
        case 0x97: return ' ';
        case 0x98: return ' ';
        case 0x99: return ' ';
        case 0x9A: return ' ';
        case 0x9B: return 0x27;
        case 0x9C: return 0x22;
        case 0x9D: return ' ';
        case 0x9E: return ' ';
        case 0x9F: return ' ';
        case 0xA0: return ' ';
        case 0xA1: return ' ';
        case 0xA2: return ' ';
        case 0xA3: return ' ';
        case 0xA4: return ' ';
        case 0xA5: return ' ';
        case 0xA6: return ' ';
        case 0xA7: return ' ';
        case 0xA8: return ' ';
        case 0xA9: return ' ';
        case 0xAA: return ' ';
        case 0xAB: return ' ';
        case 0xAC: return ' ';
        case 0xAD: return ' ';
        case 0xAE: return ' ';
        case 0xAF: return ' ';
        case 0xB0: return ' ';
        case 0xB1: return ' ';
        case 0xB2: return ' ';
        case 0xB3: return ' ';
        case 0xB4: return ' ';
        case 0xB5: return ' ';
        case 0xB6: return ' ';
        case 0xB7: return ' ';
        case 0xB8: return ' ';
        case 0xB9: return ' ';
        case 0xBA: return ' ';
        case 0xBB: return ' ';
        case 0xBC: return ' ';
        case 0xBD: return ' ';
        case 0xBE: return ' ';
        case 0xBF: return ' ';
        case 0xC0: return ' ';
        case 0xC1: return ' ';
        case 0xC2: return ' ';
        case 0xC3: return ' ';
        case 0xC4: return ' ';
        case 0xC5: return ' ';
        case 0xC6: return ' ';
        case 0xC7: return ' ';
        case 0xC8: return ' ';
        case 0xC9: return ' ';
        case 0xCA: return ' ';
        case 0xCB: return 'A';
        case 0xCC: return 'A';
        case 0xCD: return 'O';
        case 0xCE: return ' ';
        case 0xCF: return ' ';
        case 0xD0: return '-';
        case 0xD1: return '-';
        case 0xD2: return 0x22;
        case 0xD3: return 0x22;
        case 0xD4: return 0x27;
        case 0xD5: return 0x27;
        case 0xD6: return '-'; // use dash instead of slash
        case 0xD7: return ' ';
        case 0xD8: return 'y';
        case 0xD9: return 'Y';
        case 0xDA: return '-'; // use dash instead of slash
        case 0xDB: return ' ';
        case 0xDC: return '<';
        case 0xDD: return '>';
        case 0xDE: return ' ';
        case 0xDF: return ' ';
        case 0xE0: return ' ';
        case 0xE1: return ' ';
        case 0xE2: return ',';
        case 0xE3: return ',';
        case 0xE4: return ' ';
        case 0xE5: return 'A';
        case 0xE6: return 'E';
        case 0xE7: return 'A';
        case 0xE8: return 'E';
        case 0xE9: return 'E';
        case 0xEA: return 'I';
        case 0xEB: return 'I';
        case 0xEC: return 'I';
        case 0xED: return 'I';
        case 0xEE: return 'O';
        case 0xEF: return 'O';
        case 0xF0: return ' ';
        case 0xF1: return 'O';
        case 0xF2: return 'U';
        case 0xF3: return 'U';
        case 0xF4: return 'U';
        case 0xF5: return '|';
        case 0xF6: return ' ';
        case 0xF7: return ' ';
        case 0xF8: return ' ';
        case 0xF9: return ' ';
        case 0xFA: return '.';
        case 0xFB: return ' ';
        case 0xFC: return ' ';
        case 0xFD: return 0x22;
        case 0xFE: return ' ';
        case 0xFF: return ' ';
    }
    return c;
}

// String should match ndof for manufacturer based search to work
static void sanitizeString( char* inCStr )
{
    char* charIt = inCStr;
    while ( *charIt )
    {
        *charIt = mapChar( *charIt );
        charIt++;
    }
}

struct HidDevice
{
    long mAxis;
    long mLocalID;
    char mProduct[256];
    char mManufacturer[256];
    long mUsage;
    long mUsagePage;
};

static void populate_device_info( io_object_t io_obj_p, CFDictionaryRef device_dic, HidDevice* devicep )
{
    CFMutableDictionaryRef io_properties = nil;
    io_registry_entry_t entry1;
    io_registry_entry_t entry2;
    kern_return_t rc;

    // Mac OS X currently is not mirroring all USB properties to HID page so need to look at USB device page also
    // get dictionary for usb properties: step up two levels and get CF dictionary for USB properties
    // try to get parent1
    rc = IORegistryEntryGetParentEntry( io_obj_p, kIOServicePlane, &entry1 );
    if ( KERN_SUCCESS == rc )
    {
        rc = IORegistryEntryGetParentEntry( entry1, kIOServicePlane, &entry2 );
        
        IOObjectRelease( entry1 );
        
        if ( KERN_SUCCESS == rc )
        {
            rc = IORegistryEntryCreateCFProperties( entry2, &io_properties, kCFAllocatorDefault, kNilOptions );
            // either way, release parent2
            IOObjectRelease( entry2 );
        }
    }
    if ( KERN_SUCCESS == rc )
    {
        // IORegistryEntryCreateCFProperties() succeeded
        if ( io_properties != nil )
        {
            CFTypeRef dict_element = 0;
            // get device info
            // try hid dictionary first, if fail then go to usb dictionary
            
            
            dict_element = CFDictionaryGetValue( device_dic, CFSTR(kIOHIDProductKey) );
            if ( !dict_element )
            {
                dict_element = CFDictionaryGetValue( io_properties, CFSTR( "USB Product Name" ) );
            }
            if ( dict_element )
            {
                bool res = CFStringGetCString((CFStringRef)dict_element, devicep->mProduct, 256, kCFStringEncodingUTF8);
                sanitizeString(devicep->mProduct);
                if ( !res )
                {
                    LL_WARNS("Joystick") << "Failed to populate mProduct" << LL_ENDL;
                }
            }
            
            dict_element = CFDictionaryGetValue( device_dic, CFSTR( kIOHIDManufacturerKey ) );
            if ( !dict_element )
            {
                dict_element = CFDictionaryGetValue( io_properties, CFSTR( "USB Vendor Name" ) );
            }
            if ( dict_element )
            {
                bool res = CFStringGetCString( (CFStringRef)dict_element, devicep->mManufacturer, 256, kCFStringEncodingUTF8 );
                sanitizeString(devicep->mManufacturer);
                if ( !res )
                {
                    LL_WARNS("Joystick") << "Failed to populate mManufacturer" << LL_ENDL;
                }
            }
            
            dict_element = CFDictionaryGetValue( device_dic, CFSTR( kIOHIDLocationIDKey ) );
            if ( !dict_element )
            {
                dict_element = CFDictionaryGetValue( io_properties, CFSTR( "locationID" ) );
            }
            if ( dict_element )
            {
                bool res = CFNumberGetValue( (CFNumberRef)dict_element, kCFNumberLongType, &devicep->mLocalID );
                if ( !res )
                {
                    LL_WARNS("Joystick") << "Failed to populate mLocalID" << LL_ENDL;
                }
            }
            
            dict_element = CFDictionaryGetValue( device_dic, CFSTR( kIOHIDPrimaryUsagePageKey ) );
            if ( dict_element )
            {
                bool res = CFNumberGetValue( (CFNumberRef)dict_element, kCFNumberLongType, &devicep->mUsagePage );
                if ( !res )
                {
                    LL_WARNS("Joystick") << "Failed to populate mUsagePage" << LL_ENDL;
                }
                dict_element = CFDictionaryGetValue( device_dic, CFSTR( kIOHIDPrimaryUsageKey ) );
                if ( dict_element )
                {
                    if ( !CFNumberGetValue( (CFNumberRef)dict_element, kCFNumberLongType, &devicep->mUsage ) )
                    {
                        LL_WARNS("Joystick") << "Failed to populate mUsage" << LL_ENDL;
                    }
                }
            }
            
            //Add axis, because ndof lib checks sutability by axises as well as other elements
            devicep->mAxis = 0;
            CFTypeRef hid_elements = CFDictionaryGetValue( device_dic, CFSTR( kIOHIDElementKey ) );
            if ( hid_elements && CFGetTypeID( hid_elements ) == CFArrayGetTypeID( ) )
            {
                long count = CFArrayGetCount( (CFArrayRef) hid_elements );
                for (int i = 0; i < count; ++i)
                {
                    CFTypeRef element = CFArrayGetValueAtIndex((CFArrayRef) hid_elements, i);
                    if (element && CFGetTypeID( element ) == CFDictionaryGetTypeID( ))
                    {
                        long type = 0, usage_page = 0, usage = 0;
                        
                        CFTypeRef ref_value = CFDictionaryGetValue( (CFDictionaryRef) element, CFSTR( kIOHIDElementTypeKey ) );
                        if ( ref_value )
                        {
                            CFNumberGetValue( (CFNumberRef)ref_value, kCFNumberLongType, &type );
                        }
                        
                        ref_value = CFDictionaryGetValue( (CFDictionaryRef) element, CFSTR( kIOHIDElementUsagePageKey ) );
                        if ( ref_value )
                        {
                             CFNumberGetValue( (CFNumberRef)ref_value, kCFNumberLongType, &usage_page );
                        }
                        
                        ref_value = CFDictionaryGetValue( (CFDictionaryRef) element, CFSTR( kIOHIDElementUsageKey ) );
                        if ( ref_value )
                        {
                            CFNumberGetValue( (CFNumberRef)ref_value, kCFNumberLongType, &usage );
                        }
                        if ( type != 0
                            && type != kIOHIDElementTypeCollection
                            && usage_page == kHIDPage_GenericDesktop)
                        {
                            switch( usage )
                            {
                                case kHIDUsage_GD_X:
                                case kHIDUsage_GD_Y:
                                case kHIDUsage_GD_Z:
                                case kHIDUsage_GD_Rx:
                                case kHIDUsage_GD_Ry:
                                case kHIDUsage_GD_Rz:
                                    devicep->mAxis++;
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                }
            }
            
            CFRelease(io_properties);
        }
        else
        {
            LL_WARNS("Joystick") << "Failed to populate fields" << LL_ENDL;
        }
    }
}

HidDevice populate_device( io_object_t io_obj )
{
    void* interfacep = nullptr;
    HidDevice device;
    memset( &device, 0, sizeof( HidDevice ) );
    CFMutableDictionaryRef device_dic = 0;
    kern_return_t result = IORegistryEntryCreateCFProperties( io_obj, &device_dic, kCFAllocatorDefault, kNilOptions );
    
    if ( KERN_SUCCESS == result
        && device_dic )
    {
        IOReturn io_result = kIOReturnSuccess;
        HRESULT query_result = S_OK;
        SInt32 the_score = 0;
        IOCFPlugInInterface **the_interface = NULL;
        
        
        io_result = IOCreatePlugInInterfaceForService( io_obj, kIOHIDDeviceUserClientTypeID,
                                                        kIOCFPlugInInterfaceID, &the_interface, &the_score );
        if ( io_result == kIOReturnSuccess )
        {
            query_result = ( *the_interface )->QueryInterface( the_interface, CFUUIDGetUUIDBytes( kIOHIDDeviceInterfaceID ), ( LPVOID * ) & ( interfacep ) );
            if ( query_result != S_OK )
            {
                LL_WARNS("Joystick") << "QueryInterface failed" << LL_ENDL;
            }
            IODestroyPlugInInterface( the_interface );
        }
        else
        {
            LL_WARNS("Joystick") << "IOCreatePlugInInterfaceForService failed" << LL_ENDL;
        }
        
        if ( interfacep )
        {
            result = ( *( IOHIDDeviceInterface** )interfacep )->open( interfacep, 0 );
            
            if ( result != kIOReturnSuccess)
            {
                LL_WARNS("Joystick") << "open failed" << LL_ENDL;
            }
        }
        // extract needed fields
        populate_device_info( io_obj, device_dic, &device );
        
        // Release interface
        if ( interfacep )
        {
            ( *( IOHIDDeviceInterface** ) interfacep )->close( interfacep );
            
            ( *( IOHIDDeviceInterface** ) interfacep )->Release( interfacep );

            interfacep = NULL;
        }
        
        CFRelease( device_dic );
    }
    else
    {
        LL_WARNS("Joystick") << "populate_device failed" << LL_ENDL;
    }
    
    return device;
}

static void get_devices(std::list<HidDevice> &list_of_devices,
                          io_iterator_t inIODeviceIterator)
{
    IOReturn result = kIOReturnSuccess;    // assume success( optimist! )
    io_object_t io_obj = 0;
    
    while ( 0 != (io_obj = IOIteratorNext( inIODeviceIterator ) ) )
    {
        HidDevice device = populate_device( io_obj );
        
        //  Should match ndof
        if (device.mAxis >= 3
            || (device.mUsagePage == kHIDPage_GenericDesktop
                && (device.mUsage == kHIDUsage_GD_MultiAxisController
                    || device.mUsage == kHIDUsage_GD_GamePad
                    || device.mUsage == kHIDUsage_GD_Joystick))
            || (device.mUsagePage == kHIDPage_Game
                && device.mUsage == kHIDUsage_Game_3DGameController)
            || strstr(device.mManufacturer, "3Dconnexion"))
        {
            list_of_devices.push_back(device);
        }
        else
        {
            LL_DEBUGS("Joystick");
            list_of_devices.push_back(device);
            LL_CONT << "Device axes: " << (S32)device.mAxis
                    << " Device HIDUsepage: " << (S32)device.mUsagePage
                    << " Device HIDUsage: " << (S32)device.mUsage;
		    LL_ENDL;
		}
        
        
        // release the device object, it is no longer needed
        result = IOObjectRelease( io_obj );
        if ( KERN_SUCCESS != result )
        {
            LL_WARNS("Joystick") << "IOObjectRelease failed" << LL_ENDL;
        }
    }
}

bool LLWindowMacOSX::getInputDevices(U32 device_type_filter,
                                     std::function<bool(std::string&, LLSD&, void*)> osx_callback,
                                     void* win_callback,
                                     void* userdata)
{
    bool return_value = false;
    CFMutableDictionaryRef device_dict_ref;
    IOReturn result = kIOReturnSuccess;    // assume success( optimist! )
    
    // Set up matching dictionary to search the I/O Registry for HID devices we are interested in. Dictionary reference is NULL if error.
    
    // A dictionary to match devices to?
    device_dict_ref = IOServiceMatching( kIOHIDDeviceKey );
    
    // BUG FIX! one reference is consumed by IOServiceGetMatchingServices
    CFRetain( device_dict_ref );
    io_iterator_t io_iter = 0;
    
    // create an IO object iterator
    result = IOServiceGetMatchingServices( kIOMasterPortDefault, device_dict_ref, &io_iter );
    if ( kIOReturnSuccess != result )
    {
        LL_WARNS("Joystick") << "IOServiceGetMatchingServices failed" << LL_ENDL;
    }
    
    if ( io_iter )
    {
        // add all existing devices
        std::list<HidDevice> device_list;
        
        get_devices(device_list, io_iter);
        
        std::list<HidDevice>::iterator iter;
        
        for (iter = device_list.begin(); iter != device_list.end(); ++iter)
        {
            std::string label(iter->mProduct);
            LLSD data;
            data["manufacturer"] = std::string(iter->mManufacturer);
            data["product"] = label;
            
            if (osx_callback(label, data, userdata))
            {
                break; //found device
            }
        }
        return_value = true;
    }
        
    CFRelease( device_dict_ref );
    return return_value;
}

LLSD LLWindowMacOSX::getNativeKeyData()
{
	LLSD result = LLSD::emptyMap();

	if(mRawKeyEvent)
	{
        result["event_type"] = LLSD::Integer(mRawKeyEvent->mEventType);
        result["event_modifiers"] = LLSD::Integer(mRawKeyEvent->mEventModifiers);
        result["event_keycode"] = LLSD::Integer(mRawKeyEvent->mEventKeyCode);
        result["event_chars"] = (mRawKeyEvent->mEventChars) ? LLSD(LLSD::Integer(mRawKeyEvent->mEventChars)) : LLSD();
        result["event_umodchars"] = (mRawKeyEvent->mEventUnmodChars) ? LLSD(LLSD::Integer(mRawKeyEvent->mEventUnmodChars)) : LLSD();
        result["event_isrepeat"] = LLSD::Boolean(mRawKeyEvent->mEventRepeat);
	}

	LL_DEBUGS() << "native key data is: " << result << LL_ENDL;

	return result;
}

BOOL LLWindowMacOSX::dialogColorPicker( F32 *r, F32 *g, F32 *b)
{
	BOOL	retval = FALSE;
	OSErr	error = noErr;
	NColorPickerInfo	info;
	
	memset(&info, 0, sizeof(info));
	info.theColor.color.rgb.red = (UInt16)(*r * 65535.f);
	info.theColor.color.rgb.green = (UInt16)(*g * 65535.f);
	info.theColor.color.rgb.blue = (UInt16)(*b * 65535.f);
	info.placeWhere = kCenterOnMainScreen;

	error = NPickColor(&info);
	
	if (error == noErr)
	{
		retval = info.newColorChosen;
		if (info.newColorChosen)
		{
			*r = ((float) info.theColor.color.rgb.red) / 65535.0;
			*g = ((float) info.theColor.color.rgb.green) / 65535.0;
			*b = ((float) info.theColor.color.rgb.blue) / 65535.0;
		}
	}

	return (retval);
}

void *LLWindowMacOSX::getPlatformWindow()
{
	// NOTE: this will be NULL in fullscreen mode.  Plan accordingly.
	return (void*)mWindow;
}

// get a double value from a dictionary
/*
static double getDictDouble (CFDictionaryRef refDict, CFStringRef key)
{
	double double_value;
	CFNumberRef number_value = (CFNumberRef) CFDictionaryGetValue(refDict, key);
	if (!number_value) // if can't get a number for the dictionary
		return -1;  // fail
	if (!CFNumberGetValue(number_value, kCFNumberDoubleType, &double_value)) // or if cant convert it
		return -1; // fail
	return double_value; // otherwise return the long value
}*/

// get a long value from a dictionary
static long getDictLong (CFDictionaryRef refDict, CFStringRef key)
{
	long int_value;
	CFNumberRef number_value = (CFNumberRef) CFDictionaryGetValue(refDict, key);
	if (!number_value) // if can't get a number for the dictionary
		return -1;  // fail
	if (!CFNumberGetValue(number_value, kCFNumberLongType, &int_value)) // or if cant convert it
		return -1; // fail
	return int_value; // otherwise return the long value
}

void LLWindowMacOSX::allowLanguageTextInput(LLPreeditor *preeditor, BOOL b)
{
	if (preeditor != mPreeditor && !b)
	{
		// This condition may occur by a call to
		// setEnabled(BOOL) against LLTextEditor or LLLineEditor
		// when the control is not focused.
		// We need to silently ignore the case so that
		// the language input status of the focused control
		// is not disturbed.
		return;
	}
    
	// Take care of old and new preeditors.
	if (preeditor != mPreeditor || !b)
	{
		// We need to interrupt before updating mPreeditor,
		// so that the fix string from input method goes to
		// the old preeditor.
		if (mLanguageTextInputAllowed)
		{
			interruptLanguageTextInput();
		}
		mPreeditor = (b ? preeditor : NULL);
	}
	
	if (b == mLanguageTextInputAllowed)
	{
		return;
	}
	mLanguageTextInputAllowed = b;
    allowDirectMarkedTextInput(b, mGLView); // mLanguageTextInputAllowed and mMarkedTextAllowed should be updated at once (by Pell Smit
}

class sharedContext 
{
public:
    CGLContextObj mContext;
};

void* LLWindowMacOSX::createSharedContext()
{
    sharedContext* sc = new sharedContext();
    CGLCreateContext(mPixelFormat, mContext, &(sc->mContext));
    
    if (sUseMultGL)
    {
        CGLEnable(mContext, kCGLCEMPEngine);
    }

    return (void *)sc;
}

void LLWindowMacOSX::makeContextCurrent(void* context)
{
    CGLSetCurrentContext(((sharedContext*)context)->mContext);

    //enable multi-threaded OpenGL
	if (sUseMultGL)
	{
		CGLError cgl_err;
		CGLContextObj ctx = CGLGetCurrentContext();

		cgl_err =  CGLEnable( ctx, kCGLCEMPEngine);

		if (cgl_err != kCGLNoError )
		{
			LL_INFOS("GLInit") << "Multi-threaded OpenGL not available." << LL_ENDL;
		}
		else
		{
            LL_INFOS("GLInit") << "Multi-threaded OpenGL enabled." << LL_ENDL;
		}
	}
	
}

void LLWindowMacOSX::destroySharedContext(void* context)
{
    sharedContext* sc = (sharedContext*)context;

    CGLDestroyContext(sc->mContext);

    delete sc;
}

void LLWindowMacOSX::toggleVSync(bool enable_vsync)
{
    GLint frames_per_swap = 0;
    if (!enable_vsync)
    {
        frames_per_swap = 0;
    }
    else
    {
        frames_per_swap = 1;
    }
    
    CGLSetParameter(mContext, kCGLCPSwapInterval, &frames_per_swap);
}

void LLWindowMacOSX::interruptLanguageTextInput()
{
	commitCurrentPreedit(mGLView);
}

std::vector<std::string> LLWindowMacOSX::getDisplaysResolutionList()
{
	std::vector<std::string> resolution_list;
	
	CGDirectDisplayID display_ids[10];
	uint32_t found_displays = 0;
	CGError err = CGGetActiveDisplayList(10, display_ids, &found_displays);
	
	if (kCGErrorSuccess != err)
	{
		LL_WARNS() << "Couldn't get a list of active displays" << LL_ENDL;
		return std::vector<std::string>();
	}
	
	for (uint32_t i = 0; i < found_displays; i++)
	{
		S32 monitor_width = CGDisplayPixelsWide(display_ids[i]);
		S32 monitor_height = CGDisplayPixelsHigh(display_ids[i]);
		
		std::ostringstream sstream;
		sstream << monitor_width << "x" << monitor_height;;
		std::string res = sstream.str();
		
		resolution_list.push_back(res);
	}
	
	return resolution_list;
}

//static
std::vector<std::string> LLWindowMacOSX::getDynamicFallbackFontList()
{
	// Fonts previously in getFontListSans() have moved to fonts.xml.
	return std::vector<std::string>();
}

// static
MASK LLWindowMacOSX::modifiersToMask(S16 modifiers)
{
	MASK mask = 0;
	if(modifiers & MAC_SHIFT_KEY) { mask |= MASK_SHIFT; }
	if(modifiers & (MAC_CMD_KEY | MAC_CTRL_KEY)) { mask |= MASK_CONTROL; }
	if(modifiers & MAC_ALT_KEY) { mask |= MASK_ALT; }
	return mask;
}

F32 LLWindowMacOSX::getSystemUISize()
{
	return gHiDPISupport ? ::getDeviceUnitSize(mGLView) : LLWindow::getSystemUISize();
}

#if LL_OS_DRAGDROP_ENABLED
/*
S16 LLWindowMacOSX::dragTrackingHandler(DragTrackingMessage message, WindowRef theWindow,
						  void * handlerRefCon, DragRef drag)
{
	S16 result = 0;
	LLWindowMacOSX *self = (LLWindowMacOSX*)handlerRefCon;

	LL_DEBUGS() << "drag tracking handler, message = " << message << LL_ENDL;

	switch(message)
	{
		case kDragTrackingInWindow:
			result = self->handleDragNDrop(drag, LLWindowCallbacks::DNDA_TRACK);
		break;

		case kDragTrackingEnterHandler:
			result = self->handleDragNDrop(drag, LLWindowCallbacks::DNDA_START_TRACKING);
		break;

		case kDragTrackingLeaveHandler:
			result = self->handleDragNDrop(drag, LLWindowCallbacks::DNDA_STOP_TRACKING);
		break;

		default:
		break;
	}

	return result;
}
OSErr LLWindowMacOSX::dragReceiveHandler(WindowRef theWindow, void * handlerRefCon,
										 DragRef drag)
{
	LLWindowMacOSX *self = (LLWindowMacOSX*)handlerRefCon;
	return self->handleDragNDrop(drag, LLWindowCallbacks::DNDA_DROPPED);

}
*/
void LLWindowMacOSX::handleDragNDrop(std::string url, LLWindowCallbacks::DragNDropAction action)
{
	MASK mask = LLWindowMacOSX::modifiersToMask(getModifiers());

	float mouse_point[2];
	// This will return the mouse point in window coords
	getCursorPos(mWindow, mouse_point);
	LLCoordWindow window_coords(mouse_point[0], mouse_point[1]);
	LLCoordGL gl_pos;
	convertCoords(window_coords, &gl_pos);
	
	if(!url.empty())
	{
		LLWindowCallbacks::DragNDropResult res =
		mCallbacks->handleDragNDrop(this, gl_pos, mask, action, url);
		
		switch (res) {
			case LLWindowCallbacks::DND_NONE:		// No drop allowed
				if (action == LLWindowCallbacks::DNDA_TRACK)
				{
					mDragOverrideCursor = 0;
				}
				else {
					mDragOverrideCursor = -1;
				}
				break;
			case LLWindowCallbacks::DND_MOVE:		// Drop accepted would result in a "move" operation
				mDragOverrideCursor = UI_CURSOR_NO;
				break;
			case LLWindowCallbacks::DND_COPY:		// Drop accepted would result in a "copy" operation
				mDragOverrideCursor = UI_CURSOR_ARROWCOPY;
				break;
			default:
				mDragOverrideCursor = -1;
				break;
		}
		// This overrides the cursor being set by setCursor.
		// This is a bit of a hack workaround because lots of areas
		// within the viewer just blindly set the cursor.
		if (mDragOverrideCursor == -1)
		{
			// Restore the cursor
			ECursorType temp_cursor = mCurrentCursor;
			// get around the "setting the same cursor" code in setCursor()
			mCurrentCursor = UI_CURSOR_COUNT;
			setCursor(temp_cursor);
		}
		else {
			// Override the cursor
			switch (mDragOverrideCursor) {
				case 0:
					setArrowCursor();
					break;
				case UI_CURSOR_NO:
					setNotAllowedCursor();
				case UI_CURSOR_ARROWCOPY:
					setCopyCursor();
				default:
					break;
			};
		}
	}
}

#endif // LL_OS_DRAGDROP_ENABLED