summaryrefslogtreecommitdiff
path: root/indra/llwindow/llwindowsdl.cpp
blob: 255d89af77854bc532767a71bb0a9ac3038fceb0 (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
/**
 * @file llwindowsdl.cpp
 * @brief SDL implementation of LLWindow class
 * @author This module has many fathers, and it shows.
 *
 * $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 "llwindowsdl.h"

#include "llwindowcallbacks.h"
#include "llkeyboardsdl.h"

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

#ifdef LL_GLIB
#include <glib.h>
#endif

extern "C" {
# include "fontconfig/fontconfig.h"
}

#if LL_LINUX
// not necessarily available on random SDL platforms, so #if LL_LINUX
// for execv(), waitpid(), fork()
# include <unistd.h>
# include <sys/types.h>
# include <sys/wait.h>
# include <stdio.h>
#endif // LL_LINUX

extern BOOL gDebugWindowProc;

const S32 MAX_NUM_RESOLUTIONS = 200;

// static variable for ATI mouse cursor crash work-around:
static bool ATIbug = false;

//
// LLWindowSDL
//

#if LL_X11
# include <X11/Xutil.h>
#endif //LL_X11

// TOFU HACK -- (*exactly* the same hack as LLWindowMacOSX for a similar
// set of reasons): Stash a pointer to the LLWindowSDL object here and
// maintain in the constructor and destructor.  This assumes that there will
// be only one object of this class at any time.  Currently this is true.
static LLWindowSDL *gWindowImplementation = NULL;


void maybe_lock_display(void)
{
    if (gWindowImplementation && gWindowImplementation->Lock_Display) {
        gWindowImplementation->Lock_Display();
    }
}


void maybe_unlock_display(void)
{
    if (gWindowImplementation && gWindowImplementation->Unlock_Display) {
        gWindowImplementation->Unlock_Display();
    }
}


#if LL_X11
// static
Window LLWindowSDL::get_SDL_XWindowID(void)
{
    if (gWindowImplementation) {
        return gWindowImplementation->mSDL_XWindowID;
    }
    return None;
}

//static
Display* LLWindowSDL::get_SDL_Display(void)
{
    if (gWindowImplementation) {
        return gWindowImplementation->mSDL_Display;
    }
    return NULL;
}
#endif // LL_X11

#if LL_X11

// Clipboard handing via native X11, base on the implementation in Cool VL by Henri Beauchamp

namespace
{
    std::array<Atom, 3> gSupportedAtoms;

    Atom XA_CLIPBOARD;
    Atom XA_TARGETS;
    Atom PVT_PASTE_BUFFER;
    long const MAX_PASTE_BUFFER_SIZE = 16383;

    void filterSelectionRequest( XEvent aEvent )
    {
        auto *display = LLWindowSDL::getSDLDisplay();
        auto &request = aEvent.xselectionrequest;

        XSelectionEvent reply { SelectionNotify, aEvent.xany.serial, aEvent.xany.send_event, display,
                                request.requestor, request.selection, request.target,
                                request.property,request.time };

        if (request.target == XA_TARGETS)
        {
            XChangeProperty(display, request.requestor, request.property,
                            XA_ATOM, 32, PropModeReplace,
                            (unsigned char *) &gSupportedAtoms.front(), gSupportedAtoms.size());
        }
        else if (std::find(gSupportedAtoms.begin(), gSupportedAtoms.end(), request.target) !=
                 gSupportedAtoms.end())
        {
            std::string utf8;
            if (request.selection == XA_PRIMARY)
                utf8 = wstring_to_utf8str(gWindowImplementation->getPrimaryText());
            else
                utf8 = wstring_to_utf8str(gWindowImplementation->getSecondaryText());

            XChangeProperty(display, request.requestor, request.property,
                            request.target, 8, PropModeReplace,
                            (unsigned char *) utf8.c_str(), utf8.length());
        }
        else if (request.selection == XA_CLIPBOARD)
        {
            // Did not have what they wanted, so no property set
            reply.property = None;
        }
        else
            return;

        XSendEvent(request.display, request.requestor, False, NoEventMask, (XEvent *) &reply);
        XSync(display, False);
    }

    void filterSelectionClearRequest( XEvent aEvent )
    {
        auto &request = aEvent.xselectionrequest;
        if (request.selection == XA_PRIMARY)
            gWindowImplementation->clearPrimaryText();
        else if (request.selection == XA_CLIPBOARD)
            gWindowImplementation->clearSecondaryText();
    }

    int x11_clipboard_filter(void*, SDL_Event *evt)
    {
        Display *display = LLWindowSDL::getSDLDisplay();
        if (!display)
            return 1;

        if (evt->type != SDL_SYSWMEVENT)
            return 1;

        auto xevent = evt->syswm.msg->msg.x11.event;

        if (xevent.type == SelectionRequest)
            filterSelectionRequest( xevent );
        else if (xevent.type == SelectionClear)
            filterSelectionClearRequest( xevent );
        return 1;
    }

    bool grab_property(Display* display, Window window, Atom selection, Atom target)
    {
        if( !display )
            return false;

        maybe_lock_display();

        XDeleteProperty(display, window, PVT_PASTE_BUFFER);
        XFlush(display);

        XConvertSelection(display, selection, target, PVT_PASTE_BUFFER, window,  CurrentTime);

        // Unlock the connection so that the SDL event loop may function
        maybe_unlock_display();

        const auto start{ SDL_GetTicks() };
        const auto end{ start + 1000 };

        XEvent xevent {};
        bool response = false;

        do
        {
            SDL_Event event {};

            // Wait for an event
            SDL_WaitEvent(&event);

            // If the event is a window manager event
            if (event.type == SDL_SYSWMEVENT)
            {
                xevent = event.syswm.msg->msg.x11.event;

                if (xevent.type == SelectionNotify && xevent.xselection.requestor == window)
                    response = true;
            }
        } while (!response && SDL_GetTicks() < end );

        return response && xevent.xselection.property != None;
    }
}

void LLWindowSDL::initialiseX11Clipboard()
{
    if (!mSDL_Display)
        return;

    SDL_EventState(SDL_SYSWMEVENT, SDL_ENABLE);
    SDL_SetEventFilter(x11_clipboard_filter, nullptr);

    maybe_lock_display();

    XA_CLIPBOARD = XInternAtom(mSDL_Display, "CLIPBOARD", False);

    gSupportedAtoms[0] = XInternAtom(mSDL_Display, "UTF8_STRING", False);
    gSupportedAtoms[1] = XInternAtom(mSDL_Display, "COMPOUND_TEXT", False);
    gSupportedAtoms[2] = XA_STRING;

    // TARGETS atom
    XA_TARGETS = XInternAtom(mSDL_Display, "TARGETS", False);

    // SL_PASTE_BUFFER atom
    PVT_PASTE_BUFFER = XInternAtom(mSDL_Display, "FS_PASTE_BUFFER", False);

    maybe_unlock_display();
}

bool LLWindowSDL::getSelectionText( Atom aSelection, Atom aType, LLWString &text )
{
    if( !mSDL_Display )
        return false;

    if( !grab_property(mSDL_Display, mSDL_XWindowID, aSelection,aType ) )
        return false;

    maybe_lock_display();

    Atom type;
    int format{};
    unsigned long len{},remaining {};
    unsigned char* data = nullptr;
    int res = XGetWindowProperty(mSDL_Display, mSDL_XWindowID,
                                 PVT_PASTE_BUFFER, 0, MAX_PASTE_BUFFER_SIZE, False,
                                 AnyPropertyType, &type, &format, &len,
                                 &remaining, &data);
    if (data && len)
    {
        text = LLWString(
                utf8str_to_wstring(reinterpret_cast< char const *>( data ) )
        );
        XFree(data);
    }

    maybe_unlock_display();
    return res == Success;
}

bool LLWindowSDL::getSelectionText(Atom selection, LLWString& text)
{
    if (!mSDL_Display)
        return false;

    maybe_lock_display();

    Window owner = XGetSelectionOwner(mSDL_Display, selection);
    if (owner == None)
    {
        if (selection == XA_PRIMARY)
        {
            owner = DefaultRootWindow(mSDL_Display);
            selection = XA_CUT_BUFFER0;
        }
        else
        {
            maybe_unlock_display();
            return false;
        }
    }

    maybe_unlock_display();

    for( Atom atom : gSupportedAtoms )
    {
        if(getSelectionText(selection, atom, text ) )
            return true;
    }

    return false;
}

bool LLWindowSDL::setSelectionText(Atom selection, const LLWString& text)
{
    maybe_lock_display();

    if (selection == XA_PRIMARY)
    {
        std::string utf8 = wstring_to_utf8str(text);
        XStoreBytes(mSDL_Display, utf8.c_str(), utf8.length() + 1);
        mPrimaryClipboard = text;
    }
    else
        mSecondaryClipboard = text;

    XSetSelectionOwner(mSDL_Display, selection, mSDL_XWindowID, CurrentTime);

    auto owner = XGetSelectionOwner(mSDL_Display, selection);

    maybe_unlock_display();

    return owner == mSDL_XWindowID;
}

Display* LLWindowSDL::getSDLDisplay()
{
    if (gWindowImplementation)
        return gWindowImplementation->mSDL_Display;
    return nullptr;
}

#endif


LLWindowSDL::LLWindowSDL(LLWindowCallbacks* callbacks,
                         const std::string& title, S32 x, S32 y, S32 width,
                         S32 height, U32 flags,
                         BOOL fullscreen, BOOL clearBg,
                         BOOL disable_vsync, BOOL use_gl,
                         BOOL ignore_pixel_depth, U32 fsaa_samples)
        : LLWindow(callbacks, fullscreen, flags),
        Lock_Display(NULL),
        //Unlock_Display(NULL), mGamma(1.0f)
        Unlock_Display(NULL), mGamma(1.0f)
{
    // Initialize the keyboard
    gKeyboard = new LLKeyboardSDL();
    gKeyboard->setCallbacks(callbacks);
    // Note that we can't set up key-repeat until after SDL has init'd video

    // Ignore use_gl for now, only used for drones on PC
    mWindow = NULL;
    mContext = {};
    mNeedsResize = FALSE;
    mOverrideAspectRatio = 0.f;
    mGrabbyKeyFlags = 0;
    mReallyCapturedCount = 0;
    mHaveInputFocus = -1;
    mIsMinimized = -1;
    mFSAASamples = fsaa_samples;

#if LL_X11
    mSDL_XWindowID = None;
    mSDL_Display = NULL;
#endif // LL_X11

    // Assume 4:3 aspect ratio until we know better
    mOriginalAspectRatio = 1024.0 / 768.0;

    if (title.empty())
        mWindowTitle = "SDL Window";  // *FIX: (?)
    else
        mWindowTitle = title;

    // Create the GL context and set it up for windowed or fullscreen, as appropriate.
    if(createContext(x, y, width, height, 32, fullscreen, disable_vsync))
    {
        gGLManager.initGL();

        //start with arrow cursor
        initCursors();
        setCursor( UI_CURSOR_ARROW );
    }

    stop_glerror();

    // Stash an object pointer for OSMessageBox()
    gWindowImplementation = this;

#if LL_X11
    mFlashing = FALSE;
    initialiseX11Clipboard();
#endif // LL_X11

    mKeyVirtualKey = 0;
    mKeyModifiers = KMOD_NONE;
}

static SDL_Surface *Load_BMP_Resource(const char *basename)
{
    const int PATH_BUFFER_SIZE=1000;
    char path_buffer[PATH_BUFFER_SIZE]; /* Flawfinder: ignore */

    // Figure out where our BMP is living on the disk
    snprintf(path_buffer, PATH_BUFFER_SIZE-1, "%s%sres-sdl%s%s",
             gDirUtilp->getAppRODataDir().c_str(),
             gDirUtilp->getDirDelimiter().c_str(),
             gDirUtilp->getDirDelimiter().c_str(),
             basename);
    path_buffer[PATH_BUFFER_SIZE-1] = '\0';

    return SDL_LoadBMP(path_buffer);
}

#if LL_X11
// This is an XFree86/XOrg-specific hack for detecting the amount of Video RAM
// on this machine.  It works by searching /var/log/var/log/Xorg.?.log or
// /var/log/XFree86.?.log for a ': (VideoRAM ?|Memory): (%d+) kB' regex, where
// '?' is the X11 display number derived from $DISPLAY
static int x11_detect_VRAM_kb_fp(FILE *fp, const char *prefix_str)
{
    const int line_buf_size = 1000;
    char line_buf[line_buf_size];
    while (fgets(line_buf, line_buf_size, fp))
    {
        //LL_DEBUGS() << "XLOG: " << line_buf << LL_ENDL;

        // Why the ad-hoc parser instead of using a regex?  Our
        // favourite regex implementation - libboost_regex - is
        // quite a heavy and troublesome dependency for the client, so
        // it seems a shame to introduce it for such a simple task.
        // *FIXME: libboost_regex is a dependency now anyway, so we may
        // as well use it instead of this hand-rolled nonsense.
        const char *part1_template = prefix_str;
        const char part2_template[] = " kB";
        char *part1 = strstr(line_buf, part1_template);
        if (part1) // found start of matching line
        {
            part1 = &part1[strlen(part1_template)]; // -> after
            char *part2 = strstr(part1, part2_template);
            if (part2) // found end of matching line
            {
                // now everything between part1 and part2 is
                // supposed to be numeric, describing the
                // number of kB of Video RAM supported
                int rtn = 0;
                for (; part1 < part2; ++part1)
                {
                    if (*part1 < '0' || *part1 > '9')
                    {
                        // unexpected char, abort parse
                        rtn = 0;
                        break;
                    }
                    rtn *= 10;
                    rtn += (*part1) - '0';
                }
                if (rtn > 0)
                {
                    // got the kB number.  return it now.
                    return rtn;
                }
            }
        }
    }
    return 0; // 'could not detect'
}

static int x11_detect_VRAM_kb()
{
    std::string x_log_location("/var/log/");
    std::string fname;
    int rtn = 0; // 'could not detect'
    int display_num = 0;
    FILE *fp;
    char *display_env = getenv("DISPLAY"); // e.g. :0 or :0.0 or :1.0 etc
    // parse DISPLAY number so we can go grab the right log file
    if (display_env[0] == ':' &&
        display_env[1] >= '0' && display_env[1] <= '9')
    {
        display_num = display_env[1] - '0';
    }

    // *TODO: we could be smarter and see which of Xorg/XFree86 has the
    // freshest time-stamp.

    // Try Xorg log first
    fname = x_log_location;
    fname += "Xorg.";
    fname += ('0' + display_num);
    fname += ".log";
    fp = fopen(fname.c_str(), "r");
    if (fp)
    {
        LL_INFOS() << "Looking in " << fname
                   << " for VRAM info..." << LL_ENDL;
        rtn = x11_detect_VRAM_kb_fp(fp, ": VideoRAM: ");
        fclose(fp);
        if (0 == rtn)
        {
            fp = fopen(fname.c_str(), "r");
            if (fp)
            {
                rtn = x11_detect_VRAM_kb_fp(fp, ": Video RAM: ");
                fclose(fp);
                if (0 == rtn)
                {
                    fp = fopen(fname.c_str(), "r");
                    if (fp)
                    {
                        rtn = x11_detect_VRAM_kb_fp(fp, ": Memory: ");
                        fclose(fp);
                    }
                }
            }
        }
    }
    else
    {
        LL_INFOS() << "Could not open " << fname
                   << " - skipped." << LL_ENDL;
        // Try old XFree86 log otherwise
        fname = x_log_location;
        fname += "XFree86.";
        fname += ('0' + display_num);
        fname += ".log";
        fp = fopen(fname.c_str(), "r");
        if (fp)
        {
            LL_INFOS() << "Looking in " << fname
                       << " for VRAM info..." << LL_ENDL;
            rtn = x11_detect_VRAM_kb_fp(fp, ": VideoRAM: ");
            fclose(fp);
            if (0 == rtn)
            {
                fp = fopen(fname.c_str(), "r");
                if (fp)
                {
                    rtn = x11_detect_VRAM_kb_fp(fp, ": Memory: ");
                    fclose(fp);
                }
            }
        }
        else
        {
            LL_INFOS() << "Could not open " << fname
                       << " - skipped." << LL_ENDL;
        }
    }
    return rtn;
}
#endif // LL_X11

void LLWindowSDL::setTitle(const std::string title)
{
    SDL_SetWindowTitle( mWindow, title.c_str() );
}

void LLWindowSDL::tryFindFullscreenSize( int &width, int &height )
{
    LL_INFOS() << "createContext: setting up fullscreen " << width << "x" << height << LL_ENDL;

    // If the requested width or height is 0, find the best default for the monitor.
    if((width == 0) || (height == 0))
    {
        // Scan through the list of modes, looking for one which has:
        //      height between 700 and 800
        //      aspect ratio closest to the user's original mode
        S32 resolutionCount = 0;
        LLWindowResolution *resolutionList = getSupportedResolutions(resolutionCount);

        if(resolutionList != NULL)
        {
            F32 closestAspect = 0;
            U32 closestHeight = 0;
            U32 closestWidth = 0;
            int i;

            LL_INFOS() << "createContext: searching for a display mode, original aspect is " << mOriginalAspectRatio << LL_ENDL;

            for(i=0; i < resolutionCount; i++)
            {
                F32 aspect = (F32)resolutionList[i].mWidth / (F32)resolutionList[i].mHeight;

                LL_INFOS() << "createContext: width " << resolutionList[i].mWidth << " height " << resolutionList[i].mHeight << " aspect " << aspect << LL_ENDL;

                if( (resolutionList[i].mHeight >= 700) && (resolutionList[i].mHeight <= 800) &&
                    (fabs(aspect - mOriginalAspectRatio) < fabs(closestAspect - mOriginalAspectRatio)))
                {
                    LL_INFOS() << " (new closest mode) " << LL_ENDL;

                    // This is the closest mode we've seen yet.
                    closestWidth = resolutionList[i].mWidth;
                    closestHeight = resolutionList[i].mHeight;
                    closestAspect = aspect;
                }
            }

            width = closestWidth;
            height = closestHeight;
        }
    }

    if((width == 0) || (height == 0))
    {
        // Mode search failed for some reason.  Use the old-school default.
        width = 1024;
        height = 768;
    }
}

BOOL LLWindowSDL::createContext(int x, int y, int width, int height, int bits, BOOL fullscreen, BOOL disable_vsync)
{
    //bool          glneedsinit = false;

    LL_INFOS() << "createContext, fullscreen=" << fullscreen <<
               " size=" << width << "x" << height << LL_ENDL;

    // captures don't survive contexts
    mGrabbyKeyFlags = 0;
    mReallyCapturedCount = 0;

    std::initializer_list<std::tuple< char const*, char const * > > hintList =
            {
                    {SDL_HINT_VIDEO_X11_NET_WM_BYPASS_COMPOSITOR,"0"},
                    {SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH,"1"},
            };

    for( auto hint: hintList )
    {
        SDL_SetHint( std::get<0>(hint), std::get<1>(hint));
    }

    std::initializer_list<std::tuple<uint32_t, char const*, bool>> initList=
            { {SDL_INIT_VIDEO,"SDL_INIT_VIDEO", true},
              {SDL_INIT_AUDIO,"SDL_INIT_AUDIO", false},
              {SDL_INIT_GAMECONTROLLER,"SDL_INIT_GAMECONTROLLER", false},
              {SDL_INIT_SENSOR,"SDL_INIT_SENSOR", false}
            };

    for( auto subSystem : initList)
    {
        if( SDL_InitSubSystem( std::get<0>(subSystem) ) < 0 )
        {
            LL_WARNS() << "SDL_InitSubSystem for " << std::get<1>(subSystem) << " failed " << SDL_GetError() << LL_ENDL;

            if( std::get<2>(subSystem))
                setupFailure("SDL_Init() failure", "error", OSMB_OK);

        }
    }

    SDL_version c_sdl_version;
    SDL_VERSION(&c_sdl_version);
    LL_INFOS() << "Compiled against SDL "
               << int(c_sdl_version.major) << "."
               << int(c_sdl_version.minor) << "."
               << int(c_sdl_version.patch) << LL_ENDL;
    SDL_version r_sdl_version;
    SDL_GetVersion(&r_sdl_version);
    LL_INFOS() << " Running against SDL "
               << int(r_sdl_version.major) << "."
               << int(r_sdl_version.minor) << "."
               << int(r_sdl_version.patch) << LL_ENDL;

    if (width == 0)
        width = 1024;
    if (height == 0)
        width = 768;

    mFullscreen = fullscreen;

    int sdlflags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE;

    if( mFullscreen )
    {
        sdlflags |= SDL_WINDOW_FULLSCREEN;
        tryFindFullscreenSize( width, height );
    }

    mSDLFlags = sdlflags;

    GLint redBits{8}, greenBits{8}, blueBits{8}, alphaBits{8};

    GLint depthBits{(bits <= 16) ? 16 : 24}, stencilBits{8};

    if (getenv("LL_GL_NO_STENCIL"))
        stencilBits = 0;

    SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, alphaBits);
    SDL_GL_SetAttribute(SDL_GL_RED_SIZE,   redBits);
    SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, greenBits);
    SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE,  blueBits);
    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, depthBits );

    // We need stencil support for a few (minor) things.
    if (stencilBits)
        SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, stencilBits);
    // *FIX: try to toggle vsync here?

    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

    if (mFSAASamples > 0)
    {
        SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
        SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, mFSAASamples);
    }

    SDL_GL_SetAttribute(SDL_GL_SHARE_WITH_CURRENT_CONTEXT, 1);
    mWindow = SDL_CreateWindow( mWindowTitle.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, mSDLFlags );

    if( mWindow )
    {
        mContext = SDL_GL_CreateContext( mWindow );

        if( mContext == 0 )
        {
            LL_WARNS() << "Cannot create GL context " << SDL_GetError() << LL_ENDL;
            setupFailure("GL Context creation error creation error", "Error", OSMB_OK);
            return FALSE;
        }
        // SDL_GL_SetSwapInterval(1);
        mSurface = SDL_GetWindowSurface( mWindow );
    }


    if( mFullscreen )
    {
        if (mSurface)
        {
            mFullscreen = TRUE;
            mFullscreenWidth = mSurface->w;
            mFullscreenHeight = mSurface->h;
            mFullscreenBits    = mSurface->format->BitsPerPixel;
            mFullscreenRefresh = -1;

            LL_INFOS() << "Running at " << mFullscreenWidth
                       << "x"   << mFullscreenHeight
                       << "x"   << mFullscreenBits
                       << " @ " << mFullscreenRefresh
                       << LL_ENDL;
        }
        else
        {
            LL_WARNS() << "createContext: fullscreen creation failure. SDL: " << SDL_GetError() << LL_ENDL;
            // No fullscreen support
            mFullscreen = FALSE;
            mFullscreenWidth   = -1;
            mFullscreenHeight  = -1;
            mFullscreenBits    = -1;
            mFullscreenRefresh = -1;

            std::string error = llformat("Unable to run fullscreen at %d x %d.\nRunning in window.", width, height);
            OSMessageBox(error, "Error", OSMB_OK);
            return FALSE;
        }
    }
    else
    {
        if (!mWindow)
        {
            LL_WARNS() << "createContext: window creation failure. SDL: " << SDL_GetError() << LL_ENDL;
            setupFailure("Window creation error", "Error", OSMB_OK);
            return FALSE;
        }
    }

    // Set the application icon.
    SDL_Surface *bmpsurface;
    bmpsurface = Load_BMP_Resource("ll_icon.BMP");
    if (bmpsurface)
    {
        SDL_SetWindowIcon(mWindow, bmpsurface);
        SDL_FreeSurface(bmpsurface);
        bmpsurface = NULL;
    }

    // Detect video memory size.
# if LL_X11
    gGLManager.mVRAM = x11_detect_VRAM_kb() / 1024;
    if (gGLManager.mVRAM != 0)
    {
        LL_INFOS() << "X11 log-parser detected " << gGLManager.mVRAM << "MB VRAM." << LL_ENDL;
    } else
# endif // LL_X11
    {
        // fallback to letting SDL detect VRAM.
        // note: I've not seen SDL's detection ever actually find
        // VRAM != 0, but if SDL *does* detect it then that's a bonus.
        gGLManager.mVRAM = 0;
        if (gGLManager.mVRAM != 0)
        {
            LL_INFOS() << "SDL detected " << gGLManager.mVRAM << "MB VRAM." << LL_ENDL;
        }
    }
    // If VRAM is not detected, that is handled later

    // *TODO: Now would be an appropriate time to check for some
    // explicitly unsupported cards.
    //const char* RENDERER = (const char*) glGetString(GL_RENDERER);

    SDL_GL_GetAttribute(SDL_GL_RED_SIZE, &redBits);
    SDL_GL_GetAttribute(SDL_GL_GREEN_SIZE, &greenBits);
    SDL_GL_GetAttribute(SDL_GL_BLUE_SIZE, &blueBits);
    SDL_GL_GetAttribute(SDL_GL_ALPHA_SIZE, &alphaBits);
    SDL_GL_GetAttribute(SDL_GL_DEPTH_SIZE, &depthBits);
    SDL_GL_GetAttribute(SDL_GL_STENCIL_SIZE, &stencilBits);

    LL_INFOS() << "GL buffer:" << LL_ENDL;
    LL_INFOS() << "  Red Bits " << S32(redBits) << LL_ENDL;
    LL_INFOS() << "  Green Bits " << S32(greenBits) << LL_ENDL;
    LL_INFOS() << "  Blue Bits " << S32(blueBits) << LL_ENDL;
    LL_INFOS() << "  Alpha Bits " << S32(alphaBits) << LL_ENDL;
    LL_INFOS() << "  Depth Bits " << S32(depthBits) << LL_ENDL;
    LL_INFOS() << "  Stencil Bits " << S32(stencilBits) << LL_ENDL;

    GLint colorBits = redBits + greenBits + blueBits + alphaBits;
    // fixme: actually, it's REALLY important for picking that we get at
    // least 8 bits each of red,green,blue.  Alpha we can be a bit more
    // relaxed about if we have to.
    if (colorBits < 32)
    {
        close();
        setupFailure(
                "Second Life requires True Color (32-bit) to run in a window.\n"
                "Please go to Control Panels -> Display -> Settings and\n"
                "set the screen to 32-bit color.\n"
                "Alternately, if you choose to run fullscreen, Second Life\n"
                "will automatically adjust the screen each time it runs.",
                "Error",
                OSMB_OK);
        return FALSE;
    }

#if LL_X11
    /* Grab the window manager specific information */
    SDL_SysWMinfo info;
    SDL_VERSION(&info.version);
    if ( SDL_GetWindowWMInfo(mWindow, &info) )
    {
        /* Save the information for later use */
        if ( info.subsystem == SDL_SYSWM_X11 )
        {
            mSDL_Display = info.info.x11.display;
            mSDL_XWindowID = info.info.x11.window;
        }
        else
        {
            LL_WARNS() << "We're not running under X11?  Wild."
                       << LL_ENDL;
        }
    }
    else
    {
        LL_WARNS() << "We're not running under any known WM.  Wild."
                   << LL_ENDL;
    }
#endif // LL_X11


    SDL_StartTextInput();
    //make sure multisampling is disabled by default
    glDisable(GL_MULTISAMPLE_ARB);

    // Don't need to get the current gamma, since there's a call that restores it to the system defaults.
    return TRUE;
}


// changing fullscreen resolution, or switching between windowed and fullscreen mode.
BOOL LLWindowSDL::switchContext(BOOL fullscreen, const LLCoordScreen &size, BOOL disable_vsync, const LLCoordScreen * const posp)
{
    const BOOL needsRebuild = TRUE;  // Just nuke the context and start over.
    BOOL result = true;

    LL_INFOS() << "switchContext, fullscreen=" << fullscreen << LL_ENDL;
    stop_glerror();
    if(needsRebuild)
    {
        destroyContext();
        result = createContext(0, 0, size.mX, size.mY, 0, fullscreen, disable_vsync);
        if (result)
        {
            gGLManager.initGL();

            //start with arrow cursor
            initCursors();
            setCursor( UI_CURSOR_ARROW );
        }
    }

    stop_glerror();

    return result;
}

void LLWindowSDL::destroyContext()
{
    LL_INFOS() << "destroyContext begins" << LL_ENDL;

    SDL_StopTextInput();
#if LL_X11
    mSDL_Display = NULL;
    mSDL_XWindowID = None;
    Lock_Display = NULL;
    Unlock_Display = NULL;
#endif // LL_X11

    // Clean up remaining GL state before blowing away window
    LL_INFOS() << "shutdownGL begins" << LL_ENDL;
    gGLManager.shutdownGL();
    LL_INFOS() << "SDL_QuitSS/VID begins" << LL_ENDL;
    SDL_QuitSubSystem(SDL_INIT_VIDEO);  // *FIX: this might be risky...

    mWindow = NULL;
}

LLWindowSDL::~LLWindowSDL()
{
    quitCursors();
    destroyContext();

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

    gWindowImplementation = NULL;
}


void LLWindowSDL::show()
{
    // *FIX: What to do with SDL?
}

void LLWindowSDL::hide()
{
    // *FIX: What to do with SDL?
}

//virtual
void LLWindowSDL::minimize()
{
    // *FIX: What to do with SDL?
}

//virtual
void LLWindowSDL::restore()
{
    // *FIX: What to do with SDL?
}


// close() destroys all OS-specific code associated with a window.
// Usually called from LLWindowManager::destroyWindow()
void LLWindowSDL::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 LLWindowSDL::isValid()
{
    return (mWindow != NULL);
}

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

    // *FIX: This isn't really right...
    // Then what is?
    if (mWindow)
    {
        result = TRUE;
    }

    return(result);
}

BOOL LLWindowSDL::getMinimized()
{
    BOOL result = FALSE;

    if (mWindow && (1 == mIsMinimized))
    {
        result = TRUE;
    }
    return(result);
}

BOOL LLWindowSDL::getMaximized()
{
    BOOL result = FALSE;

    if (mWindow)
    {
        // TODO
    }

    return(result);
}

BOOL LLWindowSDL::maximize()
{
    // TODO
    return FALSE;
}

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

BOOL LLWindowSDL::getPosition(LLCoordScreen *position)
{
    // *FIX: can anything be done with this?
    position->mX = 0;
    position->mY = 0;
    return TRUE;
}

BOOL LLWindowSDL::getSize(LLCoordScreen *size)
{
    if (mSurface)
    {
        size->mX = mSurface->w;
        size->mY = mSurface->h;
        return (TRUE);
    }

    return (FALSE);
}

BOOL LLWindowSDL::getSize(LLCoordWindow *size)
{
    if (mSurface)
    {
        size->mX = mSurface->w;
        size->mY = mSurface->h;
        return (TRUE);
    }

    return (FALSE);
}

BOOL LLWindowSDL::setPosition(const LLCoordScreen position)
{
    if(mWindow)
    {
        // *FIX: (?)
        //MacMoveWindow(mWindow, position.mX, position.mY, false);
    }

    return TRUE;
}

template< typename T > bool setSizeImpl( const T& newSize, SDL_Window *pWin )
{
    if( !pWin )
        return false;

    auto nFlags = SDL_GetWindowFlags( pWin );

    if( nFlags & SDL_WINDOW_MAXIMIZED )
        SDL_RestoreWindow( pWin );


    SDL_SetWindowSize( pWin, newSize.mX, newSize.mY );
    SDL_Event event;
    event.type = SDL_WINDOWEVENT;
    event.window.event = SDL_WINDOWEVENT_RESIZED;
    event.window.windowID = SDL_GetWindowID( pWin );
    event.window.data1 = newSize.mX;
    event.window.data2 = newSize.mY;
    SDL_PushEvent( &event );

    return true;
}

BOOL LLWindowSDL::setSizeImpl(const LLCoordScreen size)
{
    return ::setSizeImpl( size, mWindow );
}

BOOL LLWindowSDL::setSizeImpl(const LLCoordWindow size)
{
    return ::setSizeImpl( size, mWindow );
}


void LLWindowSDL::swapBuffers()
{
    if (mWindow)
    {
        SDL_GL_SwapWindow( mWindow );
    }
}

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

void LLWindowSDL::setFSAASamples(const U32 samples)
{
    mFSAASamples = samples;
}

F32 LLWindowSDL::getGamma()
{
    return 1/mGamma;
}

BOOL LLWindowSDL::restoreGamma()
{
    //CGDisplayRestoreColorSyncSettings();
    // SDL_SetGamma(1.0f, 1.0f, 1.0f);
    return true;
}

BOOL LLWindowSDL::setGamma(const F32 gamma)
{
    mGamma = gamma;
    if (mGamma == 0) mGamma = 0.1f;
    mGamma = 1/mGamma;
    // SDL_SetGamma(mGamma, mGamma, mGamma);
    return true;
}

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



// Constrains the mouse to the window.
void LLWindowSDL::setMouseClipping( BOOL b )
{
    //SDL_WM_GrabInput(b ? SDL_GRAB_ON : SDL_GRAB_OFF);
}

// virtual
void LLWindowSDL::setMinSize(U32 min_width, U32 min_height, bool enforce_immediately)
{
    LLWindow::setMinSize(min_width, min_height, enforce_immediately);

#if LL_X11
    // Set the minimum size limits for X11 window
    // so the window manager doesn't allow resizing below those limits.
    XSizeHints* hints = XAllocSizeHints();
    hints->flags |= PMinSize;
    hints->min_width = mMinWindowWidth;
    hints->min_height = mMinWindowHeight;

    XSetWMNormalHints(mSDL_Display, mSDL_XWindowID, hints);

    XFree(hints);
#endif
}

BOOL LLWindowSDL::setCursorPosition(const LLCoordWindow position)
{
    BOOL result = TRUE;
    LLCoordScreen screen_pos;

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

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

    // do the actual forced cursor move.
    SDL_WarpMouseInWindow(mWindow, screen_pos.mX, screen_pos.mY);

    //LL_INFOS() << llformat("llcw %d,%d -> scr %d,%d", position.mX, position.mY, screen_pos.mX, screen_pos.mY) << LL_ENDL;

    return result;
}

BOOL LLWindowSDL::getCursorPosition(LLCoordWindow *position)
{
    //Point cursor_point;
    LLCoordScreen screen_pos;

    //GetMouse(&cursor_point);
    int x, y;
    SDL_GetMouseState(&x, &y);

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

    return convertCoords(screen_pos, position);
}


F32 LLWindowSDL::getNativeAspectRatio()
{
    // MBW -- there are a couple of bad assumptions here.  One is that the display list won't include
    //      ridiculous resolutions nobody would ever use.  The other is that the list is in order.

    // New assumptions:
    // - pixels are square (the only reasonable choice, really)
    // - The user runs their display at a native resolution, so the resolution of the display
    //    when the app is launched has an aspect ratio that matches the monitor.

    //RN: actually, the assumption that there are no ridiculous resolutions (above the display's native capabilities) has
    // been born out in my experience.
    // Pixels are often not square (just ask the people who run their LCDs at 1024x768 or 800x600 when running fullscreen, like me)
    // The ordering of display list is a blind assumption though, so we should check for max values
    // Things might be different on the Mac though, so I'll defer to MBW

    // 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 LLWindowSDL::getPixelAspectRatio()
{
    F32 pixel_aspect = 1.f;
    if (getFullscreen())
    {
        LLCoordScreen screen_size;
        if (getSize(&screen_size))
        {
            pixel_aspect = getNativeAspectRatio() * (F32)screen_size.mY / (F32)screen_size.mX;
        }
    }

    return pixel_aspect;
}


// This is to support 'temporarily windowed' mode so that
// dialogs are still usable in fullscreen.
void LLWindowSDL::beforeDialog()
{
    bool running_x11 = false;
#if LL_X11
    running_x11 = (mSDL_XWindowID != None);
#endif //LL_X11

    LL_INFOS() << "LLWindowSDL::beforeDialog()" << LL_ENDL;

    if (SDLReallyCaptureInput(FALSE)) // must ungrab input so popup works!
    {
        if (mFullscreen)
        {
            // need to temporarily go non-fullscreen; bless SDL
            // for providing a SDL_WM_ToggleFullScreen() - though
            // it only works in X11
            if (running_x11 && mWindow)
            {
                SDL_SetWindowFullscreen( mWindow, 0 );
            }
        }
    }

#if LL_X11
    if (mSDL_Display)
    {
        // Everything that we/SDL asked for should happen before we
        // potentially hand control over to GTK.
        maybe_lock_display();
        XSync(mSDL_Display, False);
        maybe_unlock_display();
    }
#endif // LL_X11

    maybe_lock_display();
}

void LLWindowSDL::afterDialog()
{
    bool running_x11 = false;
#if LL_X11
    running_x11 = (mSDL_XWindowID != None);
#endif //LL_X11

    LL_INFOS() << "LLWindowSDL::afterDialog()" << LL_ENDL;

    maybe_unlock_display();

    if (mFullscreen)
    {
        // need to restore fullscreen mode after dialog - only works
        // in X11
        if (running_x11 && mWindow)
        {
            SDL_SetWindowFullscreen( mWindow, 0 );
        }
    }
}


#if LL_X11
// set/reset the XWMHints flag for 'urgency' that usually makes the icon flash
void LLWindowSDL::x11_set_urgent(BOOL urgent)
{
    if (mSDL_Display && !mFullscreen)
    {
        XWMHints *wm_hints;

        LL_INFOS() << "X11 hint for urgency, " << urgent << LL_ENDL;

        maybe_lock_display();
        wm_hints = XGetWMHints(mSDL_Display, mSDL_XWindowID);
        if (!wm_hints)
            wm_hints = XAllocWMHints();

        if (urgent)
            wm_hints->flags |= XUrgencyHint;
        else
            wm_hints->flags &= ~XUrgencyHint;

        XSetWMHints(mSDL_Display, mSDL_XWindowID, wm_hints);
        XFree(wm_hints);
        XSync(mSDL_Display, False);
        maybe_unlock_display();
    }
}
#endif // LL_X11

void LLWindowSDL::flashIcon(F32 seconds)
{
    if (getMinimized())
    {
#if !LL_X11
        LL_INFOS() << "Stub LLWindowSDL::flashIcon(" << seconds << ")" << LL_ENDL;
#else
        LL_INFOS() << "X11 LLWindowSDL::flashIcon(" << seconds << ")" << LL_ENDL;

        F32 remaining_time = mFlashTimer.getRemainingTimeF32();
        if (remaining_time < seconds)
            remaining_time = seconds;
        mFlashTimer.reset();
        mFlashTimer.setTimerExpirySec(remaining_time);

        x11_set_urgent(TRUE);
        mFlashing = TRUE;
#endif // LL_X11
    }
}

BOOL LLWindowSDL::isClipboardTextAvailable()
{
    return mSDL_Display && XGetSelectionOwner(mSDL_Display, XA_CLIPBOARD) != None;
}

BOOL LLWindowSDL::pasteTextFromClipboard(LLWString &dst)
{
    return getSelectionText(XA_CLIPBOARD, dst);
}

BOOL LLWindowSDL::copyTextToClipboard(const LLWString &s)
{
    return setSelectionText(XA_CLIPBOARD, s);
}

BOOL LLWindowSDL::isPrimaryTextAvailable()
{
    LLWString text;
    return getSelectionText(XA_PRIMARY, text) && !text.empty();
}

BOOL LLWindowSDL::pasteTextFromPrimary(LLWString &dst)
{
    return getSelectionText(XA_PRIMARY, dst);
}

BOOL LLWindowSDL::copyTextToPrimary(const LLWString &s)
{
    return setSelectionText(XA_PRIMARY, s);
}

LLWindow::LLWindowResolution* LLWindowSDL::getSupportedResolutions(S32 &num_resolutions)
{
    if (!mSupportedResolutions)
    {
        mSupportedResolutions = new LLWindowResolution[MAX_NUM_RESOLUTIONS];
        mNumSupportedResolutions = 0;

        // <FS:ND> Use display no from mWindow/mSurface here?
        int max = SDL_GetNumDisplayModes(0);
        max = llclamp( max, 0, MAX_NUM_RESOLUTIONS );

        for( int i =0; i < max; ++i )
        {
            SDL_DisplayMode mode = { SDL_PIXELFORMAT_UNKNOWN, 0, 0, 0, 0 };
            if (SDL_GetDisplayMode( 0 , i, &mode) != 0)
            {
                continue;
            }

            int w = mode.w;
            int h = mode.h;
            if ((w >= 800) && (h >= 600))
            {
                // make sure we don't add the same resolution multiple times!
                if ( (mNumSupportedResolutions == 0) ||
                     ((mSupportedResolutions[mNumSupportedResolutions-1].mWidth != w) &&
                      (mSupportedResolutions[mNumSupportedResolutions-1].mHeight != h)) )
                {
                    mSupportedResolutions[mNumSupportedResolutions].mWidth = w;
                    mSupportedResolutions[mNumSupportedResolutions].mHeight = h;
                    mNumSupportedResolutions++;
                }
            }
        }
    }

    num_resolutions = mNumSupportedResolutions;
    return mSupportedResolutions;
}

BOOL LLWindowSDL::convertCoords(LLCoordGL from, LLCoordWindow *to)
{
    if (!to)
        return FALSE;

    to->mX = from.mX;
    to->mY = mSurface->h - from.mY - 1;

    return TRUE;
}

BOOL LLWindowSDL::convertCoords(LLCoordWindow from, LLCoordGL* to)
{
    if (!to)
        return FALSE;

    to->mX = from.mX;
    to->mY = mSurface->h - from.mY - 1;

    return TRUE;
}

BOOL LLWindowSDL::convertCoords(LLCoordScreen from, LLCoordWindow* to)
{
    if (!to)
        return FALSE;

    // In the fullscreen case, window and screen coordinates are the same.
    to->mX = from.mX;
    to->mY = from.mY;
    return (TRUE);
}

BOOL LLWindowSDL::convertCoords(LLCoordWindow from, LLCoordScreen *to)
{
    if (!to)
        return FALSE;

    // In the fullscreen case, window and screen coordinates are the same.
    to->mX = from.mX;
    to->mY = from.mY;
    return (TRUE);
}

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

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

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

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




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

    OSMessageBox(text, caption, type);
}

BOOL LLWindowSDL::SDLReallyCaptureInput(BOOL capture)
{
    // note: this used to be safe to call nestedly, but in the
    // end that's not really a wise usage pattern, so don't.

    if (capture)
        mReallyCapturedCount = 1;
    else
        mReallyCapturedCount = 0;

    bool wantGrab;
    if (mReallyCapturedCount <= 0) // uncapture
    {
        wantGrab = false;
    } else // capture
    {
        wantGrab = true;
    }

    if (mReallyCapturedCount < 0) // yuck, imbalance.
    {
        mReallyCapturedCount = 0;
        LL_WARNS() << "ReallyCapture count was < 0" << LL_ENDL;
    }

    bool newGrab = wantGrab;

#if LL_X11
    if (!mFullscreen) /* only bother if we're windowed anyway */
    {
        if (mSDL_Display)
        {
            /* we dirtily mix raw X11 with SDL so that our pointer
               isn't (as often) constrained to the limits of the
               window while grabbed, which feels nicer and
               hopefully eliminates some reported 'sticky pointer'
               problems.  We use raw X11 instead of
               SDL_WM_GrabInput() because the latter constrains
               the pointer to the window and also steals all
               *keyboard* input from the window manager, which was
               frustrating users. */
            int result;
            if (wantGrab == true)
            {
                maybe_lock_display();
                result = XGrabPointer(mSDL_Display, mSDL_XWindowID,
                                      True, 0, GrabModeAsync,
                                      GrabModeAsync,
                                      None, None, CurrentTime);
                maybe_unlock_display();
                if (GrabSuccess == result)
                    newGrab = true;
                else
                    newGrab = false;
            }
            else
            {
                newGrab = false;

                maybe_lock_display();
                XUngrabPointer(mSDL_Display, CurrentTime);
                // Make sure the ungrab happens RIGHT NOW.
                XSync(mSDL_Display, False);
                maybe_unlock_display();
            }
        }
    }
#endif // LL_X11
    // return boolean success for whether we ended up in the desired state
    return capture == newGrab;
}

U32 LLWindowSDL::SDLCheckGrabbyKeys(U32 keysym, BOOL gain)
{
    /* part of the fix for SL-13243: Some popular window managers like
       to totally eat alt-drag for the purposes of moving windows.  We
       spoil their day by acquiring the exclusive X11 mouse lock for as
       long as ALT is held down, so the window manager can't easily
       see what's happening.  Tested successfully with Metacity.
       And... do the same with CTRL, for other darn WMs.  We don't
       care about other metakeys as SL doesn't use them with dragging
       (for now). */

    /* We maintain a bitmap of critical keys which are up and down
       instead of simply key-counting, because SDL sometimes reports
       misbalanced keyup/keydown event pairs to us for whatever reason. */

    U32 mask = 0;
    switch (keysym)
    {
        case SDLK_LALT:
            mask = 1U << 0; break;
        case SDLK_RALT:
            mask = 1U << 1; break;
        case SDLK_LCTRL:
            mask = 1U << 2; break;
        case SDLK_RCTRL:
            mask = 1U << 3; break;
        default:
            break;
    }

    if (gain)
        mGrabbyKeyFlags |= mask;
    else
        mGrabbyKeyFlags &= ~mask;

    //LL_INFOS() << "mGrabbyKeyFlags=" << mGrabbyKeyFlags << LL_ENDL;

    /* 0 means we don't need to mousegrab, otherwise grab. */
    return mGrabbyKeyFlags;
}


void check_vm_bloat()
{
#if LL_LINUX
    // watch our own VM and RSS sizes, warn if we bloated rapidly
    static const std::string STATS_FILE = "/proc/self/stat";
    FILE *fp = fopen(STATS_FILE.c_str(), "r");
    if (fp)
    {
        static long long last_vm_size = 0;
        static long long last_rss_size = 0;
        const long long significant_vm_difference = 250 * 1024*1024;
        const long long significant_rss_difference = 50 * 1024*1024;
        long long this_vm_size = 0;
        long long this_rss_size = 0;

        ssize_t res;
        size_t dummy;
        char *ptr = NULL;
        for (int i=0; i<22; ++i) // parse past the values we don't want
        {
            res = getdelim(&ptr, &dummy, ' ', fp);
            if (-1 == res)
            {
                LL_WARNS() << "Unable to parse " << STATS_FILE << LL_ENDL;
                goto finally;
            }
            free(ptr);
            ptr = NULL;
        }
        // 23rd space-delimited entry is vsize
        res = getdelim(&ptr, &dummy, ' ', fp);
        llassert(ptr);
        if (-1 == res)
        {
            LL_WARNS() << "Unable to parse " << STATS_FILE << LL_ENDL;
            goto finally;
        }
        this_vm_size = atoll(ptr);
        free(ptr);
        ptr = NULL;
        // 24th space-delimited entry is RSS
        res = getdelim(&ptr, &dummy, ' ', fp);
        llassert(ptr);
        if (-1 == res)
        {
            LL_WARNS() << "Unable to parse " << STATS_FILE << LL_ENDL;
            goto finally;
        }
        this_rss_size = getpagesize() * atoll(ptr);
        free(ptr);
        ptr = NULL;

        LL_INFOS() << "VM SIZE IS NOW " << (this_vm_size/(1024*1024)) << " MB, RSS SIZE IS NOW " << (this_rss_size/(1024*1024)) << " MB" << LL_ENDL;

        if (llabs(last_vm_size - this_vm_size) >
            significant_vm_difference)
        {
            if (this_vm_size > last_vm_size)
            {
                LL_WARNS() << "VM size grew by " << (this_vm_size - last_vm_size)/(1024*1024) << " MB in last frame" << LL_ENDL;
            }
            else
            {
                LL_INFOS() << "VM size shrank by " << (last_vm_size - this_vm_size)/(1024*1024) << " MB in last frame" << LL_ENDL;
            }
        }

        if (llabs(last_rss_size - this_rss_size) >
            significant_rss_difference)
        {
            if (this_rss_size > last_rss_size)
            {
                LL_WARNS() << "RSS size grew by " << (this_rss_size - last_rss_size)/(1024*1024) << " MB in last frame" << LL_ENDL;
            }
            else
            {
                LL_INFOS() << "RSS size shrank by " << (last_rss_size - this_rss_size)/(1024*1024) << " MB in last frame" << LL_ENDL;
            }
        }

        last_rss_size = this_rss_size;
        last_vm_size = this_vm_size;

        finally:
        if (NULL != ptr)
        {
            free(ptr);
            ptr = NULL;
        }
        fclose(fp);
    }
#endif // LL_LINUX
}


// virtual
void LLWindowSDL::processMiscNativeEvents()
{
#if LL_GLIB
    // Pump until we've nothing left to do or passed 1/15th of a
    // second pumping for this frame.
    static LLTimer pump_timer;
    pump_timer.reset();
    pump_timer.setTimerExpirySec(1.0f / 15.0f);
    do
    {
        g_main_context_iteration(g_main_context_default(), FALSE);
    } while( g_main_context_pending(g_main_context_default()) && !pump_timer.hasExpired());
#endif

    // hack - doesn't belong here - but this is just for debugging
    if (getenv("LL_DEBUG_BLOAT"))
    {
        check_vm_bloat();
    }
}

void LLWindowSDL::gatherInput()
{
    const Uint32 CLICK_THRESHOLD = 300;  // milliseconds
    static int leftClick = 0;
    static int rightClick = 0;
    static Uint32 lastLeftDown = 0;
    static Uint32 lastRightDown = 0;
    SDL_Event event;

    // Handle all outstanding SDL events
    while (SDL_PollEvent(&event))
    {
        switch (event.type)
        {
            case SDL_MOUSEWHEEL:
                if( event.wheel.y != 0 )
                    mCallbacks->handleScrollWheel(this, -event.wheel.y);
                break;

            case SDL_MOUSEMOTION:
            {
                LLCoordWindow winCoord(event.button.x, event.button.y);
                LLCoordGL openGlCoord;
                convertCoords(winCoord, &openGlCoord);
                MASK mask = gKeyboard->currentMask(TRUE);
                mCallbacks->handleMouseMove(this, openGlCoord, mask);
                break;
            }

            case SDL_TEXTINPUT:
            {
                auto string = utf8str_to_utf16str( event.text.text );
                mKeyModifiers = gKeyboard->currentMask( FALSE );
                mInputType = "textinput";
                for( auto key: string )
                {
                    mKeyVirtualKey = key;

                    if( (MASK_CONTROL|MASK_ALT)&mKeyModifiers )
                        gKeyboard->handleKeyDown(mKeyVirtualKey, mKeyModifiers );
                    else
                        handleUnicodeUTF16( key, mKeyModifiers );
                }
                break;
            }

            case SDL_KEYDOWN:
                mKeyVirtualKey = event.key.keysym.sym;
                mKeyModifiers = event.key.keysym.mod;
                mInputType = "keydown";

                // treat all possible Enter/Return keys the same
                if (mKeyVirtualKey == SDLK_RETURN2 || mKeyVirtualKey == SDLK_KP_ENTER)
                {
                    mKeyVirtualKey = SDLK_RETURN;
                }

                gKeyboard->handleKeyDown(mKeyVirtualKey, mKeyModifiers );

                // <FS:ND> Slightly hacky :| To make the viewer honor enter (eg to accept form input) we've to not only send handleKeyDown but also send a
                // invoke handleUnicodeUTF16 in case the user hits return.
                // Note that we cannot blindly use handleUnicodeUTF16 for each SDL_KEYDOWN. Doing so will create bogus keyboard input (like % for cursor left).
                if( mKeyVirtualKey == SDLK_RETURN )
                {
                    // fix return key not working when capslock, scrolllock or numlock are enabled
                    mKeyModifiers &= (~(KMOD_NUM | KMOD_CAPS | KMOD_MODE | KMOD_SCROLL));
                    handleUnicodeUTF16( mKeyVirtualKey, mKeyModifiers );
                }

                // part of the fix for SL-13243
                if (SDLCheckGrabbyKeys(event.key.keysym.sym, TRUE) != 0)
                    SDLReallyCaptureInput(TRUE);

                break;

            case SDL_KEYUP:
                mKeyVirtualKey = event.key.keysym.sym;
                mKeyModifiers = event.key.keysym.mod;
                mInputType = "keyup";

                // treat all possible Enter/Return keys the same
                if (mKeyVirtualKey == SDLK_RETURN2 || mKeyVirtualKey == SDLK_KP_ENTER)
                {
                    mKeyVirtualKey = SDLK_RETURN;
                }

                if (SDLCheckGrabbyKeys(mKeyVirtualKey, FALSE) == 0)
                    SDLReallyCaptureInput(FALSE); // part of the fix for SL-13243

                gKeyboard->handleKeyUp(mKeyVirtualKey,mKeyModifiers);
                break;

            case SDL_MOUSEBUTTONDOWN:
            {
                bool isDoubleClick = false;
                LLCoordWindow winCoord(event.button.x, event.button.y);
                LLCoordGL openGlCoord;
                convertCoords(winCoord, &openGlCoord);
                MASK mask = gKeyboard->currentMask(TRUE);

                if (event.button.button == SDL_BUTTON_LEFT)   // SDL doesn't manage double clicking...
                {
                    Uint32 now = SDL_GetTicks();
                    if ((now - lastLeftDown) > CLICK_THRESHOLD)
                        leftClick = 1;
                    else
                    {
                        if (++leftClick >= 2)
                        {
                            leftClick = 0;
                            isDoubleClick = true;
                        }
                    }
                    lastLeftDown = now;
                }
                else if (event.button.button == SDL_BUTTON_RIGHT)
                {
                    Uint32 now = SDL_GetTicks();
                    if ((now - lastRightDown) > CLICK_THRESHOLD)
                        rightClick = 1;
                    else
                    {
                        if (++rightClick >= 2)
                        {
                            rightClick = 0;
                            isDoubleClick = true;
                        }
                    }
                    lastRightDown = now;
                }

                if (event.button.button == SDL_BUTTON_LEFT)  // left
                {
                    if (isDoubleClick)
                        mCallbacks->handleDoubleClick(this, openGlCoord, mask);
                    else
                        mCallbacks->handleMouseDown(this, openGlCoord, mask);
                }

                else if (event.button.button == SDL_BUTTON_RIGHT)  // right
                {
                    mCallbacks->handleRightMouseDown(this, openGlCoord, mask);
                }

                else if (event.button.button == SDL_BUTTON_MIDDLE)  // middle
                {
                    mCallbacks->handleMiddleMouseDown(this, openGlCoord, mask);
                }
                else if (event.button.button == 4)  // mousewheel up...thanks to X11 for making SDL consider these "buttons".
                    mCallbacks->handleScrollWheel(this, -1);
                else if (event.button.button == 5)  // mousewheel down...thanks to X11 for making SDL consider these "buttons".
                    mCallbacks->handleScrollWheel(this, 1);

                break;
            }

            case SDL_MOUSEBUTTONUP:
            {
                LLCoordWindow winCoord(event.button.x, event.button.y);
                LLCoordGL openGlCoord;
                convertCoords(winCoord, &openGlCoord);
                MASK mask = gKeyboard->currentMask(TRUE);

                if (event.button.button == SDL_BUTTON_LEFT)  // left
                    mCallbacks->handleMouseUp(this, openGlCoord, mask);
                else if (event.button.button == SDL_BUTTON_RIGHT)  // right
                    mCallbacks->handleRightMouseUp(this, openGlCoord, mask);
                else if (event.button.button == SDL_BUTTON_MIDDLE)  // middle
                    mCallbacks->handleMiddleMouseUp(this, openGlCoord, mask);
                // don't handle mousewheel here...

                break;
            }

            case SDL_WINDOWEVENT:  // *FIX: handle this?
            {
                if( event.window.event == SDL_WINDOWEVENT_RESIZED
                    /* || event.window.event == SDL_WINDOWEVENT_SIZE_CHANGED*/ ) // <FS:ND> SDL_WINDOWEVENT_SIZE_CHANGED is followed by SDL_WINDOWEVENT_RESIZED, so handling one shall be enough
                {
                    LL_INFOS() << "Handling a resize event: " << event.window.data1 << "x" << event.window.data2 << LL_ENDL;

                    S32 width = llmax(event.window.data1, (S32)mMinWindowWidth);
                    S32 height = llmax(event.window.data2, (S32)mMinWindowHeight);
                    mSurface = SDL_GetWindowSurface( mWindow );

                    // *FIX: I'm not sure this is necessary!
                    // <FS:ND> I think is is not
                    // SDL_SetWindowSize(mWindow, width, height);
                    //

                    mCallbacks->handleResize(this, width, height);
                }
                else if( event.window.event == SDL_WINDOWEVENT_FOCUS_GAINED ) // <FS:ND> What about SDL_WINDOWEVENT_ENTER (mouse focus)
                {
                    // We have to do our own state massaging because SDL
                    // can send us two unfocus events in a row for example,
                    // which confuses the focus code [SL-24071].
                    mHaveInputFocus = true;

                    mCallbacks->handleFocus(this);
                }
                else if( event.window.event == SDL_WINDOWEVENT_FOCUS_LOST ) // <FS:ND> What about SDL_WINDOWEVENT_LEAVE (mouse focus)
                {
                    // We have to do our own state massaging because SDL
                    // can send us two unfocus events in a row for example,
                    // which confuses the focus code [SL-24071].
                    mHaveInputFocus = false;

                    mCallbacks->handleFocusLost(this);
                }
                else if( event.window.event == SDL_WINDOWEVENT_MINIMIZED ||
                         event.window.event == SDL_WINDOWEVENT_MAXIMIZED ||
                         event.window.event == SDL_WINDOWEVENT_RESTORED ||
                         event.window.event == SDL_WINDOWEVENT_EXPOSED ||
                         event.window.event == SDL_WINDOWEVENT_SHOWN )
                {
                    mIsMinimized = (event.window.event == SDL_WINDOWEVENT_MINIMIZED);

                    mCallbacks->handleActivate(this, !mIsMinimized);
                    LL_INFOS() << "SDL deiconification state switched to " << mIsMinimized << LL_ENDL;
                }

                break;
            }
            case SDL_QUIT:
                if(mCallbacks->handleCloseRequest(this))
                {
                    // Get the app to initiate cleanup.
                    mCallbacks->handleQuit(this);
                    // The app is responsible for calling destroyWindow when done with GL
                }
                break;
            default:
                //LL_INFOS() << "Unhandled SDL event type " << event.type << LL_ENDL;
                break;
        }
    }

    updateCursor();

#if LL_X11
    // This is a good time to stop flashing the icon if our mFlashTimer has
    // expired.
    if (mFlashing && mFlashTimer.hasExpired())
    {
        x11_set_urgent(FALSE);
        mFlashing = FALSE;
    }
#endif // LL_X11
}

static SDL_Cursor *makeSDLCursorFromBMP(const char *filename, int hotx, int hoty)
{
    SDL_Cursor *sdlcursor = NULL;
    SDL_Surface *bmpsurface;

    // Load cursor pixel data from BMP file
    bmpsurface = Load_BMP_Resource(filename);
    if (bmpsurface && bmpsurface->w%8==0)
    {
        SDL_Surface *cursurface;
        LL_DEBUGS() << "Loaded cursor file " << filename << " "
                    << bmpsurface->w << "x" << bmpsurface->h << LL_ENDL;
        cursurface = SDL_CreateRGBSurface (SDL_SWSURFACE,
                                           bmpsurface->w,
                                           bmpsurface->h,
                                           32,
                                           SDL_SwapLE32(0xFFU),
                                           SDL_SwapLE32(0xFF00U),
                                           SDL_SwapLE32(0xFF0000U),
                                           SDL_SwapLE32(0xFF000000U));
        SDL_FillRect(cursurface, NULL, SDL_SwapLE32(0x00000000U));

        // Blit the cursor pixel data onto a 32-bit RGBA surface so we
        // only have to cope with processing one type of pixel format.
        if (0 == SDL_BlitSurface(bmpsurface, NULL,
                                 cursurface, NULL))
        {
            // n.b. we already checked that width is a multiple of 8.
            const int bitmap_bytes = (cursurface->w * cursurface->h) / 8;
            unsigned char *cursor_data = new unsigned char[bitmap_bytes];
            unsigned char *cursor_mask = new unsigned char[bitmap_bytes];
            memset(cursor_data, 0, bitmap_bytes);
            memset(cursor_mask, 0, bitmap_bytes);
            int i,j;
            // Walk the RGBA cursor pixel data, extracting both data and
            // mask to build SDL-friendly cursor bitmaps from.  The mask
            // is inferred by color-keying against 200,200,200
            for (i=0; i<cursurface->h; ++i) {
                for (j=0; j<cursurface->w; ++j) {
                    U8 *pixelp =
                            ((U8*)cursurface->pixels)
                            + cursurface->pitch * i
                            + j*cursurface->format->BytesPerPixel;
                    U8 srcred = pixelp[0];
                    U8 srcgreen = pixelp[1];
                    U8 srcblue = pixelp[2];
                    BOOL mask_bit = (srcred != 200)
                                    || (srcgreen != 200)
                                    || (srcblue != 200);
                    BOOL data_bit = mask_bit && (srcgreen <= 80);//not 0x80
                    unsigned char bit_offset = (cursurface->w/8) * i
                                               + j/8;
                    cursor_data[bit_offset] |= (data_bit) << (7 - (j&7));
                    cursor_mask[bit_offset] |= (mask_bit) << (7 - (j&7));
                }
            }
            sdlcursor = SDL_CreateCursor((Uint8*)cursor_data,
                                         (Uint8*)cursor_mask,
                                         cursurface->w, cursurface->h,
                                         hotx, hoty);
            delete[] cursor_data;
            delete[] cursor_mask;
        } else {
            LL_WARNS() << "CURSOR BLIT FAILURE, cursurface: " << cursurface << LL_ENDL;
        }
        SDL_FreeSurface(cursurface);
        SDL_FreeSurface(bmpsurface);
    } else {
        LL_WARNS() << "CURSOR LOAD FAILURE " << filename << LL_ENDL;
    }

    return sdlcursor;
}

void LLWindowSDL::updateCursor()
{
    if (ATIbug) {
        // cursor-updating is very flaky when this bug is
        // present; do nothing.
        return;
    }

    if (mCurrentCursor != mNextCursor)
    {
        if (mNextCursor < UI_CURSOR_COUNT)
        {
            SDL_Cursor *sdlcursor = mSDLCursors[mNextCursor];
            // Try to default to the arrow for any cursors that
            // did not load correctly.
            if (!sdlcursor && mSDLCursors[UI_CURSOR_ARROW])
                sdlcursor = mSDLCursors[UI_CURSOR_ARROW];
            if (sdlcursor)
                SDL_SetCursor(sdlcursor);
        } else {
            LL_WARNS() << "Tried to set invalid cursor number " << mNextCursor << LL_ENDL;
        }
        mCurrentCursor = mNextCursor;
    }
}

void LLWindowSDL::initCursors()
{
    int i;
    // Blank the cursor pointer array for those we may miss.
    for (i=0; i<UI_CURSOR_COUNT; ++i)
    {
        mSDLCursors[i] = NULL;
    }
    // Pre-make an SDL cursor for each of the known cursor types.
    // We hardcode the hotspots - to avoid that we'd have to write
    // a .cur file loader.
    // NOTE: SDL doesn't load RLE-compressed BMP files.
    mSDLCursors[UI_CURSOR_ARROW] = makeSDLCursorFromBMP("llarrow.BMP",0,0);
    mSDLCursors[UI_CURSOR_WAIT] = makeSDLCursorFromBMP("wait.BMP",12,15);
    mSDLCursors[UI_CURSOR_HAND] = makeSDLCursorFromBMP("hand.BMP",7,10);
    mSDLCursors[UI_CURSOR_IBEAM] = makeSDLCursorFromBMP("ibeam.BMP",15,16);
    mSDLCursors[UI_CURSOR_CROSS] = makeSDLCursorFromBMP("cross.BMP",16,14);
    mSDLCursors[UI_CURSOR_SIZENWSE] = makeSDLCursorFromBMP("sizenwse.BMP",14,17);
    mSDLCursors[UI_CURSOR_SIZENESW] = makeSDLCursorFromBMP("sizenesw.BMP",17,17);
    mSDLCursors[UI_CURSOR_SIZEWE] = makeSDLCursorFromBMP("sizewe.BMP",16,14);
    mSDLCursors[UI_CURSOR_SIZENS] = makeSDLCursorFromBMP("sizens.BMP",17,16);
    mSDLCursors[UI_CURSOR_SIZEALL] = makeSDLCursorFromBMP("sizeall.BMP", 17, 17);
    mSDLCursors[UI_CURSOR_NO] = makeSDLCursorFromBMP("llno.BMP",8,8);
    mSDLCursors[UI_CURSOR_WORKING] = makeSDLCursorFromBMP("working.BMP",12,15);
    mSDLCursors[UI_CURSOR_TOOLGRAB] = makeSDLCursorFromBMP("lltoolgrab.BMP",2,13);
    mSDLCursors[UI_CURSOR_TOOLLAND] = makeSDLCursorFromBMP("lltoolland.BMP",1,6);
    mSDLCursors[UI_CURSOR_TOOLFOCUS] = makeSDLCursorFromBMP("lltoolfocus.BMP",8,5);
    mSDLCursors[UI_CURSOR_TOOLCREATE] = makeSDLCursorFromBMP("lltoolcreate.BMP",7,7);
    mSDLCursors[UI_CURSOR_ARROWDRAG] = makeSDLCursorFromBMP("arrowdrag.BMP",0,0);
    mSDLCursors[UI_CURSOR_ARROWCOPY] = makeSDLCursorFromBMP("arrowcop.BMP",0,0);
    mSDLCursors[UI_CURSOR_ARROWDRAGMULTI] = makeSDLCursorFromBMP("llarrowdragmulti.BMP",0,0);
    mSDLCursors[UI_CURSOR_ARROWCOPYMULTI] = makeSDLCursorFromBMP("arrowcopmulti.BMP",0,0);
    mSDLCursors[UI_CURSOR_NOLOCKED] = makeSDLCursorFromBMP("llnolocked.BMP",8,8);
    mSDLCursors[UI_CURSOR_ARROWLOCKED] = makeSDLCursorFromBMP("llarrowlocked.BMP",0,0);
    mSDLCursors[UI_CURSOR_GRABLOCKED] = makeSDLCursorFromBMP("llgrablocked.BMP",2,13);
    mSDLCursors[UI_CURSOR_TOOLTRANSLATE] = makeSDLCursorFromBMP("lltooltranslate.BMP",0,0);
    mSDLCursors[UI_CURSOR_TOOLROTATE] = makeSDLCursorFromBMP("lltoolrotate.BMP",0,0);
    mSDLCursors[UI_CURSOR_TOOLSCALE] = makeSDLCursorFromBMP("lltoolscale.BMP",0,0);
    mSDLCursors[UI_CURSOR_TOOLCAMERA] = makeSDLCursorFromBMP("lltoolcamera.BMP",7,5);
    mSDLCursors[UI_CURSOR_TOOLPAN] = makeSDLCursorFromBMP("lltoolpan.BMP",7,5);
    mSDLCursors[UI_CURSOR_TOOLZOOMIN] = makeSDLCursorFromBMP("lltoolzoomin.BMP",7,5);
    mSDLCursors[UI_CURSOR_TOOLZOOMOUT] = makeSDLCursorFromBMP("lltoolzoomout.BMP", 7, 5);
    mSDLCursors[UI_CURSOR_TOOLPICKOBJECT3] = makeSDLCursorFromBMP("toolpickobject3.BMP",0,0);
    mSDLCursors[UI_CURSOR_TOOLPLAY] = makeSDLCursorFromBMP("toolplay.BMP",0,0);
    mSDLCursors[UI_CURSOR_TOOLPAUSE] = makeSDLCursorFromBMP("toolpause.BMP",0,0);
    mSDLCursors[UI_CURSOR_TOOLMEDIAOPEN] = makeSDLCursorFromBMP("toolmediaopen.BMP",0,0);
    mSDLCursors[UI_CURSOR_PIPETTE] = makeSDLCursorFromBMP("lltoolpipette.BMP",2,28);
    mSDLCursors[UI_CURSOR_TOOLSIT] = makeSDLCursorFromBMP("toolsit.BMP",20,15);
    mSDLCursors[UI_CURSOR_TOOLBUY] = makeSDLCursorFromBMP("toolbuy.BMP",20,15);
    mSDLCursors[UI_CURSOR_TOOLOPEN] = makeSDLCursorFromBMP("toolopen.BMP",20,15);
    mSDLCursors[UI_CURSOR_TOOLPATHFINDING] = makeSDLCursorFromBMP("lltoolpathfinding.BMP", 16, 16);
    mSDLCursors[UI_CURSOR_TOOLPATHFINDING_PATH_START] = makeSDLCursorFromBMP("lltoolpathfindingpathstart.BMP", 16, 16);
    mSDLCursors[UI_CURSOR_TOOLPATHFINDING_PATH_START_ADD] = makeSDLCursorFromBMP("lltoolpathfindingpathstartadd.BMP", 16, 16);
    mSDLCursors[UI_CURSOR_TOOLPATHFINDING_PATH_END] = makeSDLCursorFromBMP("lltoolpathfindingpathend.BMP", 16, 16);
    mSDLCursors[UI_CURSOR_TOOLPATHFINDING_PATH_END_ADD] = makeSDLCursorFromBMP("lltoolpathfindingpathendadd.BMP", 16, 16);
    mSDLCursors[UI_CURSOR_TOOLNO] = makeSDLCursorFromBMP("llno.BMP",8,8);

    if (getenv("LL_ATI_MOUSE_CURSOR_BUG") != NULL) {
        LL_INFOS() << "Disabling cursor updating due to LL_ATI_MOUSE_CURSOR_BUG" << LL_ENDL;
        ATIbug = true;
    }
}

void LLWindowSDL::quitCursors()
{
    int i;
    if (mWindow)
    {
        for (i=0; i<UI_CURSOR_COUNT; ++i)
        {
            if (mSDLCursors[i])
            {
                SDL_FreeCursor(mSDLCursors[i]);
                mSDLCursors[i] = NULL;
            }
        }
    } else {
        // SDL doesn't refcount cursors, so if the window has
        // already been destroyed then the cursors have gone with it.
        LL_INFOS() << "Skipping quitCursors: mWindow already gone." << LL_ENDL;
        for (i=0; i<UI_CURSOR_COUNT; ++i)
            mSDLCursors[i] = NULL;
    }
}

void LLWindowSDL::captureMouse()
{
    // SDL already enforces the semantics that captureMouse is
    // used for, i.e. that we continue to get mouse events as long
    // as a button is down regardless of whether we left the
    // window, and in a less obnoxious way than SDL_WM_GrabInput
    // which would confine the cursor to the window too.

    LL_DEBUGS() << "LLWindowSDL::captureMouse" << LL_ENDL;
}

void LLWindowSDL::releaseMouse()
{
    // see LWindowSDL::captureMouse()

    LL_DEBUGS() << "LLWindowSDL::releaseMouse" << LL_ENDL;
}

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

void LLWindowSDL::showCursor()
{
    if(mCursorHidden)
    {
        // LL_INFOS() << "showCursor: showing" << LL_ENDL;
        mCursorHidden = FALSE;
        mHideCursorPermanent = FALSE;
        SDL_ShowCursor(1);
    }
    else
    {
        // LL_INFOS() << "showCursor: already visible" << LL_ENDL;
    }
}

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

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

//
// LLSplashScreenSDL - I don't think we'll bother to implement this; it's
// fairly obsolete at this point.
//
LLSplashScreenSDL::LLSplashScreenSDL()
{
}

LLSplashScreenSDL::~LLSplashScreenSDL()
{
}

void LLSplashScreenSDL::showImpl()
{
}

void LLSplashScreenSDL::updateImpl(const std::string& mesg)
{
}

void LLSplashScreenSDL::hideImpl()
{
}

S32 OSMessageBoxSDL(const std::string& text, const std::string& caption, U32 type)
{
    SDL_MessageBoxData oData = { SDL_MESSAGEBOX_INFORMATION, nullptr, caption.c_str(), text.c_str(), 0, nullptr, nullptr };
    SDL_MessageBoxButtonData btnOk[] = {{SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT, OSBTN_OK, "OK" }};
    SDL_MessageBoxButtonData btnOkCancel [] =  {{SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT, OSBTN_OK, "OK" }, {SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT, OSBTN_CANCEL, "Cancel"} };
    SDL_MessageBoxButtonData btnYesNo[] = { {SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT, OSBTN_YES, "Yes" }, {SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT, OSBTN_NO, "No"} };

    switch (type)
    {
        default:
        case OSMB_OK:
            oData.flags = SDL_MESSAGEBOX_WARNING;
            oData.buttons = btnOk;
            oData.numbuttons = 1;
            break;
        case OSMB_OKCANCEL:
            oData.flags = SDL_MESSAGEBOX_INFORMATION;
            oData.buttons = btnOkCancel;
            oData.numbuttons = 2;
            break;
        case OSMB_YESNO:
            oData.flags = SDL_MESSAGEBOX_INFORMATION;
            oData.buttons = btnYesNo;
            oData.numbuttons = 2;
            break;
    }

    int btn{0};
    if( 0 == SDL_ShowMessageBox( &oData, &btn ) )
        return btn;
    return OSBTN_CANCEL;
}

BOOL LLWindowSDL::dialogColorPicker( F32 *r, F32 *g, F32 *b)
{
    return (FALSE);
}

/*
        Make the raw keyboard data available - used to poke through to LLQtWebKit so
        that Qt/Webkit has access to the virtual keycodes etc. that it needs
*/
LLSD LLWindowSDL::getNativeKeyData()
{
    LLSD result = LLSD::emptyMap();

    U32 modifiers = 0; // pretend-native modifiers... oh what a tangled web we weave!

    // we go through so many levels of device abstraction that I can't really guess
    // what a plugin under GDK under Qt under SL under SDL under X11 considers
    // a 'native' modifier mask.  this has been sort of reverse-engineered... they *appear*
    // to match GDK consts, but that may be co-incidence.
    modifiers |= (mKeyModifiers & KMOD_LSHIFT) ? 0x0001 : 0;
    modifiers |= (mKeyModifiers & KMOD_RSHIFT) ? 0x0001 : 0;// munge these into the same shift
    modifiers |= (mKeyModifiers & KMOD_CAPS)   ? 0x0002 : 0;
    modifiers |= (mKeyModifiers & KMOD_LCTRL)  ? 0x0004 : 0;
    modifiers |= (mKeyModifiers & KMOD_RCTRL)  ? 0x0004 : 0;// munge these into the same ctrl
    modifiers |= (mKeyModifiers & KMOD_LALT)   ? 0x0008 : 0;// untested
    modifiers |= (mKeyModifiers & KMOD_RALT)   ? 0x0008 : 0;// untested
    // *todo: test ALTs - I don't have a case for testing these.  Do you?
    // *todo: NUM? - I don't care enough right now (and it's not a GDK modifier).

    result["virtual_key"] = (S32)mKeyVirtualKey;
    result["virtual_key_win"] = (S32)LLKeyboardSDL::mapSDL2toWin( mKeyVirtualKey );
    result["modifiers"] = (S32)modifiers;
    result["input_type"] = mInputType;
    return result;
}

#if LL_LINUX || LL_SOLARIS
// extracted from spawnWebBrowser for clarity and to eliminate
//  compiler confusion regarding close(int fd) vs. LLWindow::close()
void exec_cmd(const std::string& cmd, const std::string& arg)
{
    char* const argv[] = {(char*)cmd.c_str(), (char*)arg.c_str(), NULL};
    fflush(NULL);
    pid_t pid = fork();
    if (pid == 0)
    { // child
        // disconnect from stdin/stdout/stderr, or child will
        // keep our output pipe undesirably alive if it outlives us.
        // close(0);
        // close(1);
        // close(2);
        // <FS:TS> Reopen stdin, stdout, and stderr to /dev/null.
        //         It's good practice to always have those file
        //         descriptors open to something, lest the exec'd
        //         program actually try to use them.
        FILE *result;
        result = freopen("/dev/null","r",stdin);
        if (result == NULL)
        {
            LL_WARNS() << "Error reopening stdin for web browser: "
                       << strerror(errno) << LL_ENDL;
        }
        result = freopen("/dev/null","w",stdout);
        if (result == NULL)
        {
            LL_WARNS() << "Error reopening stdout for web browser: "
                       << strerror(errno) << LL_ENDL;
        }
        result = freopen("/dev/null","w",stderr);
        if (result == NULL)
        {
            LL_WARNS() << "Error reopening stderr for web browser: "
                       << strerror(errno) << LL_ENDL;
        }
        // end ourself by running the command
        execv(cmd.c_str(), argv);   /* Flawfinder: ignore */
        // if execv returns at all, there was a problem.
        LL_WARNS() << "execv failure when trying to start " << cmd << LL_ENDL;
        _exit(1); // _exit because we don't want atexit() clean-up!
    } else {
        if (pid > 0)
        {
            // parent - wait for child to die
            int childExitStatus;
            waitpid(pid, &childExitStatus, 0);
        } else {
            LL_WARNS() << "fork failure." << LL_ENDL;
        }
    }
}
#endif

// Open a URL with the user's default web browser.
// Must begin with protocol identifier.
void LLWindowSDL::spawnWebBrowser(const std::string& escaped_url, bool async)
{
    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;
    }

    LL_INFOS() << "spawn_web_browser: " << escaped_url << LL_ENDL;

#if LL_LINUX
# if LL_X11
    if (mSDL_Display)
    {
        maybe_lock_display();
        // Just in case - before forking.
        XSync(mSDL_Display, False);
        maybe_unlock_display();
    }
# endif // LL_X11

    std::string cmd, arg;
    cmd  = gDirUtilp->getAppRODataDir();
    cmd += gDirUtilp->getDirDelimiter();
    cmd += "etc";
    cmd += gDirUtilp->getDirDelimiter();
    cmd += "launch_url.sh";
    arg = escaped_url;
    exec_cmd(cmd, arg);
#endif // LL_LINUX

    LL_INFOS() << "spawn_web_browser returning." << LL_ENDL;
}

void LLWindowSDL::openFile(const std::string& file_name)
{
    spawnWebBrowser("file://"+file_name,TRUE);
}

void *LLWindowSDL::getPlatformWindow()
{
    return NULL;
}

void LLWindowSDL::bringToFront()
{
    // This is currently used when we are 'launched' to a specific
    // map position externally.
    LL_INFOS() << "bringToFront" << LL_ENDL;
#if LL_X11
    if (mSDL_Display && !mFullscreen)
    {
        maybe_lock_display();
        XRaiseWindow(mSDL_Display, mSDL_XWindowID);
        XSync(mSDL_Display, False);
        maybe_unlock_display();
    }
#endif // LL_X11
}

//static
std::vector<std::string> LLWindowSDL::getDynamicFallbackFontList()
{
    // Use libfontconfig to find us a nice ordered list of fallback fonts
    // specific to this system.
    std::string final_fallback("/usr/share/fonts/truetype/kochi/kochi-gothic.ttf");
    const int max_font_count_cutoff = 40; // fonts are expensive in the current system, don't enumerate an arbitrary number of them
    // Our 'ideal' font properties which define the sorting results.
    // slant=0 means Roman, index=0 means the first face in a font file
    // (the one we actually use), weight=80 means medium weight,
    // spacing=0 means proportional spacing.
    std::string sort_order("slant=0:index=0:weight=80:spacing=0");
    // elide_unicode_coverage removes fonts from the list whose unicode
    // range is covered by fonts earlier in the list.  This usually
    // removes ~90% of the fonts as redundant (which is great because
    // the font list can be huge), but might unnecessarily reduce the
    // renderable range if for some reason our FreeType actually fails
    // to use some of the fonts we want it to.
    const bool elide_unicode_coverage = true;
    std::vector<std::string> rtns;
    FcFontSet *fs = NULL;
    FcPattern *sortpat = NULL;

    LL_INFOS() << "Getting system font list from FontConfig..." << LL_ENDL;

    // If the user has a system-wide language preference, then favor
    // fonts from that language group.  This doesn't affect the types
    // of languages that can be displayed, but ensures that their
    // preferred language is rendered from a single consistent font where
    // possible.
    FL_Locale *locale = NULL;
    FL_Success success = FL_FindLocale(&locale, FL_MESSAGES);
    if (success != 0)
    {
        if (success >= 2 && locale->lang) // confident!
        {
            LL_INFOS("AppInit") << "Language " << locale->lang << LL_ENDL;
            LL_INFOS("AppInit") << "Location " << locale->country << LL_ENDL;
            LL_INFOS("AppInit") << "Variant " << locale->variant << LL_ENDL;

            LL_INFOS() << "Preferring fonts of language: "
                       << locale->lang
                       << LL_ENDL;
            sort_order = "lang=" + std::string(locale->lang) + ":"
                         + sort_order;
        }
    }
    FL_FreeLocale(&locale);

    if (!FcInit())
    {
        LL_WARNS() << "FontConfig failed to initialize." << LL_ENDL;
        rtns.push_back(final_fallback);
        return rtns;
    }

    sortpat = FcNameParse((FcChar8*) sort_order.c_str());
    if (sortpat)
    {
        // Sort the list of system fonts from most-to-least-desirable.
        FcResult result;
        fs = FcFontSort(NULL, sortpat, elide_unicode_coverage,
                        NULL, &result);
        FcPatternDestroy(sortpat);
    }

    int found_font_count = 0;
    if (fs)
    {
        // Get the full pathnames to the fonts, where available,
        // which is what we really want.
        found_font_count = fs->nfont;
        for (int i=0; i<fs->nfont; ++i)
        {
            FcChar8 *filename;
            if (FcResultMatch == FcPatternGetString(fs->fonts[i],
                                                    FC_FILE, 0,
                                                    &filename)
                && filename)
            {
                rtns.push_back(std::string((const char*)filename));
                if (rtns.size() >= max_font_count_cutoff)
                    break; // hit limit
            }
        }
        FcFontSetDestroy (fs);
    }

    LL_DEBUGS() << "Using font list: " << LL_ENDL;
    for (std::vector<std::string>::iterator it = rtns.begin();
         it != rtns.end();
         ++it)
    {
        LL_DEBUGS() << "  file: " << *it << LL_ENDL;
    }
    LL_INFOS() << "Using " << rtns.size() << "/" << found_font_count << " system fonts." << LL_ENDL;

    rtns.push_back(final_fallback);
    return rtns;
}


void* LLWindowSDL::createSharedContext()
{
    auto *pContext = SDL_GL_CreateContext(mWindow);
    if ( pContext)
    {
        SDL_GL_SetSwapInterval(0);
        SDL_GL_MakeCurrent(mWindow, mContext);

        LLCoordScreen size;
        if (getSize(&size))
            setSize(size);

        LL_DEBUGS() << "Creating shared OpenGL context successful!" << LL_ENDL;

        return (void*)pContext;
    }

    LL_WARNS() << "Creating shared OpenGL context failed!" << LL_ENDL;

    return nullptr;
}

void LLWindowSDL::makeContextCurrent(void* contextPtr)
{
    LL_PROFILER_GPU_CONTEXT;
    SDL_GL_MakeCurrent( mWindow, contextPtr );
}

void LLWindowSDL::destroySharedContext(void* contextPtr)
{
    SDL_GL_DeleteContext( contextPtr );
}

void LLWindowSDL::toggleVSync(bool enable_vsync)
{
}

U32 LLWindowSDL::getAvailableVRAMMegabytes()
{
    return 4096;
}