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
|
//
// Unicode to UTF-8 conversion functions.
//
// Author: Jean-Marc Lienher ( http://oksid.ch )
// Copyright 2000-2010 by O'ksi'D.
// Copyright 2016-2026 by Bill Spitzak and others.
//
// This library is free software. Distribution and use rights are outlined in
// the file "COPYING" which should have been included with this file. If this
// file is missing or damaged, see the license at:
//
// https://www.fltk.org/COPYING.php
//
// Please see the following page on how to report bugs and issues:
//
// https://www.fltk.org/bugs.php
//
#include <FL/Fl.H>
#include "Fl_System_Driver.H"
#include <FL/filename.H>
#include <stdarg.h>
#include <FL/fl_utf8.h>
#include "utf8_internal.h"
#include <sys/stat.h>
#include <string.h>
#include <stdlib.h>
#undef fl_open
/** \addtogroup fl_unicode
@{
*/
// *** NOTE : All functions are LIMITED to 24 bits Unicode values !!! ***
// *** But only 16 bits are really used under Linux and win32 ***
#define NBC 0xFFFF + 1
static int Toupper(int ucs) {
int i;
static unsigned short *table = NULL;
if (!table) {
table = (unsigned short*) malloc(
sizeof(unsigned short) * (NBC));
for (i = 0; i < NBC; i++) {
table[i] = (unsigned short) i;
}
for (i = 0; i < NBC; i++) {
int l;
l = XUtf8Tolower(i);
if (l != i) table[l] = (unsigned short) i;
}
}
if (ucs >= NBC || ucs < 0) return ucs;
return table[ucs];
}
/**
Returns the byte length of the UTF-8 sequence, or -1.
This function is helpful for finding faulty UTF-8 style encodings. It does
not check for undefined Unicode values.
Example:
\code{.cpp}
#include <FL/fl_utf8.h>
bool test(const char *str) {
if (str == nullptr) return true;
const char *src = str;
for (int p = 0; ; p++) {
if (src == 0) return true;
int len = fl_utf8len(*src);
if (len == -1) {
printf("Invalid UTF-8 character start: 0x%02x\n", (unsigned char)*src);
return false;
} else {
while (len > 0) {
if (*src == 0) {
printf("Interrupted UTF-8 sequence at %d\n", (int)(src-str));
return false;
}
src++;
len--;
}
printf("Character %d at %d uses %d bytes\n", p, (int)(src-str), len);
}
}
}
\endcode
\param[in] c the first character in a UTF- sequence
\return the number of bytes in that sequence, or -1 if c is not a valid
character for UTF-8 style encoding.
\see fl_utf8len1
*/
int fl_utf8len(char c)
{
if (!(c & 0x80)) return 1;
if (c & 0x40) {
if (c & 0x20) {
if (c & 0x10) {
if (c & 0x08) {
if (c & 0x04) {
return 6;
}
return 5;
}
return 4;
}
return 3;
}
return 2;
}
return -1;
} // fl_utf8len
/**
Returns the byte length of the UTF-8 sequence with first byte \p c,
or -1 if \p c is not valid.
This function can be used to scan faulty UTF-8 sequences, albeit
ignoring invalid codes.
Example:
\code
#include <FL/fl_utf8.h>
char mixed_string[] = "Hello \xFF\x80 world"; // Contains invalid UTF-8
char *p = mixed_string;
while (*p) {
int len = fl_utf8len1(*p);
printf("Byte 0x%02x uses %d byte(s)\n", (unsigned char)*p, len);
p += len; // Always advances by at least 1, even for invalid bytes
}
\endcode
\param[in] c the first character in a UTF-8 sequence
\return the number of bytes in that sequence, or 1 if c is not a recognized
character for UTF-8 style encoding, so a loop can continue to scan a string.
\see fl_utf8len \see fl_utf8len
*/
int fl_utf8len1(char c)
{
if (!(c & 0x80)) return 1;
if (c & 0x40) {
if (c & 0x20) {
if (c & 0x10) {
if (c & 0x08) {
if (c & 0x04) {
return 6;
}
return 5;
}
return 4;
}
return 3;
}
return 2;
}
return 1;
} // fl_utf8len1
/**
Return the length in bytes of a UTF-8 string.
An illegal UTF-8 character is counted as 1.
Example:
\code
#include <FL/fl_utf8.h>
return fl_utf8strlen("über", 1); // returns 2, the ü is encoded 0xC3, 0xBC
\endcode
\param[in] text encoded in UTF-8
\param[in] len number of Unicode characters, -1 to test until the end of text
\return number of bytes that make up the Unicode string
\see fl_utf_nb_char(const unsigned char *buf, int len)
*/
int fl_utf8strlen(const char *text, int len)
{
if (len == -1) return (int)strlen(text);
int i, n = 0;
for (i=len; i>0; i--) {
if (*text == 0) return n; // end of string
int nc = fl_utf8len1(*text);
n += nc;
text += nc;
}
return n;
}
/**
Returns the number of Unicode chars in the UTF-8 string.
An illegal UTF-8 character is counted as 1.
Example:
\code
#include <FL/fl_utf8.h>
const char *str = "äöü"; // strlen(str) is 6
return fl_utf_nb_char(str, strlen(str)); // returns 3
\endcode
\param[in] buf text encoded in UTF-8
\param[in] len number of bytes to check. This code does not check for the
trailing NUL character of "C" style strings. -1 is *not* valid here.
\return number of characters in that sequence. If a trailing UTF-8 sequence
is not complete, the entire character is still counted.
\see fl_utf8strlen(const char *text, int len)
*/
int
fl_utf_nb_char(
const unsigned char *buf,
int len)
{
int i = 0;
int nbc = 0;
while (i < len) {
int cl = fl_utf8len((buf+i)[0]);
if (cl < 1) cl = 1;
nbc++;
i += cl;
}
return nbc;
}
/**
UTF-8 aware strncasecmp - converts to lower case Unicode and tests.
Characters are extracted as Unicode, the converted to their lower case
version, and the compared numerically. This does not take language specific
collation sequences into account. The limitations of `fl_tolower()` apply.
\code
#include <FL/fl_utf8.h>
return fl_utf_strncasecmp("über", "Über"); // returns 0
return fl_utf_strncasecmp("Meier", "Müller"); // returns a negative value
\endcode
\param s1, s2 the UTF-8 strings to compare
\param n the maximum number of UTF-8 characters to compare
\return result of comparison
\retval 0 if the strings are equal
\retval >0 if s1 is greater than s2
\retval <0 if s1 is less than s2
\see fl_tolower().
*/
int fl_utf_strncasecmp(const char *s1, const char *s2, int n)
{
int i;
for (i = 0; i < n; i++) {
int l1, l2;
unsigned int u1, u2;
if (*s1==0 && *s2==0) return 0; // all compared equal, return 0
u1 = fl_utf8decode(s1, 0, &l1);
u2 = fl_utf8decode(s2, 0, &l2);
int res = XUtf8Tolower(u1) - XUtf8Tolower(u2);
if (res) return res;
s1 += l1;
s2 += l2;
}
return 0;
}
/**
UTF-8 aware strcasecmp - converts to Unicode and tests.
\return result of comparison
\retval 0 if the strings are equal
\retval 1 if s1 is greater than s2
\retval -1 if s1 is less than s2
\see fl_utf_strncasecmp(const char *s1, const char *s2, int n)
*/
int fl_utf_strcasecmp(const char *s1, const char *s2)
{
return fl_utf_strncasecmp(s1, s2, 0x7fffffff);
}
/**
Returns the Unicode lower case value of \p ucs.
This is a relatively naive algorithm, good enough for basic Unicode string
handling. If the conversion code can't call a system native function, FLTK
will use lookup tables that are limited to the character range
from 0x0 to 0xffff. Characters with a higher value are not converted.
Perfect per-language character handling is a project larger than
FLTK itself.
\param[in] ucs Unicode 32 bit character
\return lower case version of that character in Unicode 32, or the same code
if there is no lower case version.
\see fl_toupper(unsigned int ucs), fl_utf8decode(), fl_utf8encode()
*/
int fl_tolower(unsigned int ucs)
{
return XUtf8Tolower(ucs);
}
/**
Returns the Unicode upper case value of \p ucs.
\param[in] ucs Unicode 32 bit character
\return upper case version of that character in Unicode 32, or the same code
if there is no upper case version.
\see fl_tolower(unsigned int ucs), fl_utf8decode(), fl_utf8encode()
*/
int fl_toupper(unsigned int ucs)
{
return Toupper(ucs);
}
/**
Converts the string \p str to its lower case equivalent into buf.
The destination buffer `buf` must be provided by the caller. The `buf` length
should be at least `3 * len` for 16-bit Unicode.
Example:
\code
#include <FL/fl_utf8.h>
const char *str = "ÇA VA?";
auto src_len = strlen(str)
char *buf = malloc(src_len*3 + 1);
puts(fl_utf_tolower(str, src_len, buf));
// should print "ça va?"
\endcode
\param[in] str UTF-8 string that will be converted
\param[in] len number of *bytes* to convert, must not be -1
\param[out] buf write the conversion result into this buffer
\return number of characters converted
\see fl_utf_toupper(), fl_tolower(unsigned int ucs)
*/
int fl_utf_tolower(const unsigned char *str, int len, char *buf)
{
int i;
int l = 0;
char *end = (char *)&str[len];
for (i = 0; i < len;) {
int l1, l2;
unsigned int u1;
u1 = fl_utf8decode((const char*)(str + i), end, &l1);
l2 = fl_utf8encode((unsigned int) XUtf8Tolower(u1), buf + l);
if (l1 < 1) {
i += 1;
} else {
i += l1;
}
if (l2 < 1) {
l += 1;
} else {
l += l2;
}
}
return l;
}
/**
Converts the string \p str to its upper case equivalent into buf.
The destination buffer `buf` must be provided by the caller. The `buf` length
should be at least `3 * len` for 16-bit Unicode.
\param[in] str UTF-8 string that will be converted
\param[in] len number of *bytes* to convert, must not be -1
\param[out] buf write the conversion result into this buffer
\return number of characters converted
\see fl_utf_tolower(), fl_tolower(unsigned int ucs)
*/
int fl_utf_toupper(const unsigned char *str, int len, char *buf)
{
int i;
int l = 0;
char *end = (char *)&str[len];
for (i = 0; i < len;) {
int l1, l2;
unsigned int u1;
u1 = fl_utf8decode((const char*)(str + i), end, &l1);
l2 = fl_utf8encode((unsigned int) Toupper(u1), buf + l);
if (l1 < 1) {
i += 1;
} else {
i += l1;
}
if (l2 < 1) {
l += 1;
} else {
l += l2;
}
}
return l;
}
/**
Returns true if the Unicode character \p ucs is non-spacing.
Non-spacing characters in Unicode are typically combining marks like
tilde (~), diaeresis (¨), or other marks that are added to a base
character, for instance 'a' (base character) + '¨' (combining mark) = 'ä'
(German Umlaut).
- http://unicode.org/glossary/#base_character
- http://unicode.org/glossary/#nonspacing_mark
- http://unicode.org/glossary/#combining_character
\param[in] ucs 32 bit Unicode character
\return 0 if this is a spacing character, or any other value if not
\note This function has not been verified. It's not working for ASCII
characters
*/
unsigned int fl_nonspacing(unsigned int ucs)
{
return (unsigned int) XUtf8IsNonSpacing(ucs);
}
/**
Converts UTF-8 string \p s to a local multi-byte character string.
On Linux and macOS, this returns the same string. On Windows machines,
this function will convert the string to UTF-16, and the to the current
encoding using `wcstombs()`.
\param[in] s a UTF-8 encode string
\return a string that matches the current locale of the host machine. This
is a pointer to an internal buffer that changes size as needed.
\note Do not deallocate the returned pointer. This function is not
thread safe.
*/
char * fl_utf2mbcs(const char *s)
{
return Fl::system_driver()->utf2mbcs(s);
}
/** Cross-platform function to get environment variables with a UTF-8 encoded
name or value.
This function is especially useful on the Windows platform where
non-ASCII environment variables are encoded as wide characters.
The returned value of the variable is encoded in UTF-8 as well.
On platforms other than Windows this function calls getenv directly.
The return value is returned as-is.
The return value is a pointer to an implementation defined buffer:
- an internal buffer that is (re)allocated as needed (Windows) or
- the string in the environment itself (Unix, Linux, MaOS) or
- any other implementation (other platforms).
This string must be considered read-only and must not be freed by the caller.
If the resultant string is to be used later it must be copied to a safe
place. The next call to fl_getenv() or any other environment changes may
overwrite the string.
Example:
\code
#include <FL/fl_utf8.h>
fl_putenv("cœur=frère")
return fl_getenv("cœur"); // return UTF-8 value on all platforms
\endcode
\note This function is not thread-safe.
\param[in] v the UTF-8 encoded environment variable
\return the environment variable in UTF-8 encoding, or NULL in case of error.
\see fl_putenv(const char* var)
*/
char *fl_getenv(const char* v) {
return Fl::system_driver()->getenv(v);
}
/** Cross-platform function to write environment variables with a UTF-8
encoded name or value.
This function is especially useful on the Windows platform where
non-ASCII environment variables are encoded as wide characters.
The given argument \p var must be encoded in UTF-8 in the form "name=value".
The \p 'name' part must conform to platform dependent restrictions on
environment variable names.
The string given in \p var is copied and optionally converted to the
required encoding for the platform. On platforms other than Windows
this function calls putenv directly.
The return value is zero on success and non-zero in case of error.
The value in case of error is platform specific and returned as-is.
\note The copied string is allocated on the heap and "lost" on some platforms,
i.e. calling fl_putenv() to change environment variables frequently may cause
memory leaks. There may be an option to avoid this in a future implementation.
\note This function is not thread-safe.
\param[in] var the UTF-8 encoded environment variable \p 'name=value'
\return 0 on success, non-zero in case of error.
\see fl_getenv(const char* var)
*/
int fl_putenv(const char* var) {
return Fl::system_driver()->putenv(var);
}
/** Cross-platform function to open files with a UTF-8 encoded name.
This function is especially useful on the Windows platform where the
standard open() function fails with UTF-8 encoded non-ASCII filenames.
\code
#include <FL/fl_utf8.h>
void test() {
int fd = fl_open("¡Peligro!", O_RDWR);
if (fd != -1) fl_close_fd(fd);
}
\endcode
\param[in] fname the UTF-8 encoded filename
\param[in] oflags other arguments are as in the standard open() function
\return a file descriptor upon successful completion, or -1 in case of error.
\see fl_fopen(), fl_open_ext(), fl_close_fd(int fd).
*/
int fl_open(const char* fname, int oflags, ...) {
int pmode;
va_list ap;
va_start(ap, oflags);
pmode = va_arg (ap, int);
va_end(ap);
return Fl::system_driver()->open(fname, oflags, pmode);
}
/** Cross-platform function to close a file descriptor.
\return 0 in case of success, or -1 in case of error.
*/
int fl_close_fd(int fd) {
return Fl::system_driver()->close_fd(fd);
}
/** Cross-platform function to open files with a UTF-8 encoded name.
In comparison with fl_open(), this function allows to control whether
the file is opened in binary (a.k.a. untranslated) mode. This is especially
useful on the Windows platform where files are by default opened in
text (translated) mode.
\param[in] fname the UTF-8 encoded filename
\param[in] binary if non-zero, the file is to be accessed in binary
(a.k.a. untranslated) mode.
\param[in] oflags,... these arguments are as in the standard open() function.
Setting \p oflags to zero opens the file for reading.
\return a file descriptor upon successful completion, or -1 in case of error.
\see fl_open(), fl_fopen()
*/
int fl_open_ext(const char* fname, int binary, int oflags, ...) {
int pmode;
va_list ap;
va_start(ap, oflags);
pmode = va_arg (ap, int);
va_end(ap);
return Fl::system_driver()->open_ext(fname, binary, oflags, pmode);
}
/** Cross-platform function to open files with a UTF-8 encoded name.
This function is especially useful on the Windows platform where the
standard fopen() function fails with UTF-8 encoded non-ASCII filenames.
\code
#include <FL/fl_utf8.h>
void test() {
FILE *f = fl_fopen("¡Peligro!", "rw");
if (f) fl_fclose(f);
}
\endcode
\param f the UTF-8 encoded filename
\param mode same as the second argument of the standard fopen() function
\return a FILE pointer upon successful completion, or NULL in case of error.
\sa fl_open().
*/
FILE *fl_fopen(const char* f, const char *mode) {
return Fl::system_driver()->fopen(f, mode);
}
/** Cross-platform function to run a system command with a UTF-8 encoded string.
This function is especially useful on the Windows platform where
non-ASCII program (file) names must be encoded as wide characters.
On platforms other than Windows this function calls system() directly.
\code
#include <FL/fl_utf8.h>
fl_system("echo \"Hauptstraße 2\""");
\endcode
\param[in] cmd the UTF-8 encoded command string
\return the return value of _wsystem() on Windows or system() on other platforms.
*/
int fl_system(const char* cmd)
{
return Fl::system_driver()->system(cmd);
}
/**
Calls `execvp` on all platforms.
On Windows, this converts the file and all arguments in argv into Windows
multibyte characters and calls `_wexecvp`.
\param[in] file path to the new process
\param[in] argv array of command line arguments, last array member must
be a `nullptr`.
\return the result of `execvp` call.
*/
int fl_execvp(const char *file, char *const *argv)
{
return Fl::system_driver()->execvp(file, argv);
}
/** Cross-platform function to set a files mode() with a UTF-8 encoded
name or value.
This function is especially useful on the Windows platform where the
standard chmod() function fails with UTF-8 encoded non-ASCII filenames.
\param[in] f the UTF-8 encoded filename
\param[in] mode the mode to set
\return the return value of _wchmod() on Windows or chmod() on other platforms.
*/
int fl_chmod(const char* f, int mode) {
return Fl::system_driver()->chmod(f, mode);
}
/** Cross-platform function to test a files access() with a UTF-8 encoded
name or value.
This function is especially useful on the Windows platform where the
standard access() function fails with UTF-8 encoded non-ASCII filenames.
Windows defines the mode values 0 for existence, 2 for writable, 4 for
readable, and 6 of readable and writable. On other systems, the modes
`X_OK`, `W_OK`, and `R_OK` are usually defined as 1, 2, and 4.
Upon successful completion, the value 0 is returned on all platforms.
\param[in] f the UTF-8 encoded filename
\param[in] mode the mode to test
\return the return value of _waccess() on Windows or access() on other platforms.
*/
int fl_access(const char* f, int mode) {
return Fl::system_driver()->access(f, mode);
}
/** Cross-platform function to stat() a file using a UTF-8 encoded
name or value.
This function is especially useful on the Windows platform where the
standard stat() function fails with UTF-8 encoded non-ASCII filenames.
\param[in] f the UTF-8 encoded filename
\param[out] b the stat struct to populate
\return the return value of _wstat() on Windows or stat() on other platforms.
\note the contents of `struct stat` is returned unchanged in the host format.
*/
int fl_stat(const char* f, struct stat *b) {
return Fl::system_driver()->flstat(f, b);
}
/** Cross-platform function to change the current working directory,
given as a UTF-8 encoded string.
This function is especially useful on the Windows platform where the
standard _wchdir() function needs a \p path in UTF-16 encoding.
The \p path is converted to a system specific encoding if necessary
and the system specific \p chdir(converted_path) function is called.
The function returns 0 on success and -1 on error. Depending on the
platform, \p errno \b may be set if an error occurs.
\note The possible errno values are platform specific. Refer to the
documentation of the platform specific chdir() function.
If the function is not implemented on a particular platform the
default implementation returns -1 and \p errno is \b not set.
If the \p path is \p NULL the function returns -1, but \p errno is
\b not changed. This is a convenience feature of fl_chdir() as
opposed to chdir().
\param[in] path the target directory for chdir (may be \p NULL)
\return 0 if successful, -1 on error (errno may be set)
*/
int fl_chdir(const char* path) {
if (!path)
return -1;
return Fl::system_driver()->chdir(path);
}
/** Cross-platform function to get the current working directory
as a UTF-8 encoded value.
This function is especially useful on the Windows platform where the
standard _wgetcwd() function returns UTF-16 encoded non-ASCII filenames.
If \p buf is \p NULL a buffer of size \p (len+1) is allocated, filled with
the current working directory, and returned. In this case the buffer must
be released by the caller with free() to prevent memory leaks.
\param[in] buf the buffer to populate (may be NULL)
\param[in] len the length of the buffer
\return the CWD encoded as UTF-8
*/
char *fl_getcwd(char *buf, int len) {
if (buf == NULL) {
buf = (char*)malloc(len + 1);
}
return Fl::system_driver()->getcwd(buf, len);
}
/** Cross-platform function to unlink() (that is, delete) a file using
a UTF-8 encoded filename.
This function is especially useful on the Windows platform where
the standard function expects UTF-16 encoded non-ASCII filenames.
\param fname the filename to unlink
\return the return value of _wunlink() on Windows or unlink() on other platforms.
*/
int fl_unlink(const char* fname) {
return Fl::system_driver()->unlink(fname);
}
/** Cross-platform function to create a directory with a UTF-8 encoded name.
This function is especially useful on the Windows platform where the
standard _wmkdir() function expects UTF-16 encoded non-ASCII filenames.
\param[in] f the UTF-8 encoded filename
\param[in] mode the mode of the directory
\return the return value of _wmkdir() on Windows or mkdir() on other platforms.
*/
int fl_mkdir(const char* f, int mode) {
return Fl::system_driver()->mkdir(f, mode);
}
/** Cross-platform function to remove a directory with a UTF-8 encoded
name.
This function is especially useful on the Windows platform where the
standard _wrmdir() function expects UTF-16 encoded non-ASCII filenames.
\param[in] f the UTF-8 encoded filename to remove
\return the return value of _wrmdir() on Windows or rmdir() on other platforms.
*/
int fl_rmdir(const char* f) {
return Fl::system_driver()->rmdir(f);
}
/** Cross-platform function to rename a filesystem object using
UTF-8 encoded names.
This function is especially useful on the Windows platform where the
standard _wrename() function expects UTF-16 encoded non-ASCII filenames.
\param[in] f the UTF-8 encoded filename to change
\param[in] n the new UTF-8 encoded filename to set
\return the return value of _wrename() on Windows or rename() on other platforms.
*/
int fl_rename(const char* f, const char *n) {
return Fl::system_driver()->rename(f, n);
}
/** Cross-platform function to recursively create a path in the file system.
This function creates a \p path in the file system by recursively creating
all directories.
\param[in] path a Unix style ('/' forward slashes) absolute or relative pathname
\return 1 if the path was created, 0 if creating the path failed at some point
*/
char fl_make_path( const char *path ) {
if (fl_access(path, 0)) {
const char *s = strrchr( path, '/' );
if ( !s ) return 0;
size_t len = (size_t) (s-path);
char *p = (char*)malloc( len+1 );
memcpy( p, path, len );
p[len] = 0;
fl_make_path( p );
free( p );
fl_mkdir(path, 0700);
}
return 1;
}
/** Cross-platform function to create a path for the file in the file system.
This function strips the filename from the given \p path and creates
a path in the file system by recursively creating all directories.
\param[in] path path to a file, ending in a file name. The separator between
the path and the filename must be the forward slash.
*/
void fl_make_path_for_file( const char *path ) {
const char *s = strrchr( path, '/' );
if ( !s ) return;
size_t len = (s-path);
char *p = (char*)malloc( len+1 );
memcpy( p, path, len );
p[len] = 0;
fl_make_path( p );
free( p );
} // fl_make_path_for_file()
/** Set to 1 to turn bad UTF-8 bytes into ISO-8859-1. If this is zero
they are instead turned into the Unicode REPLACEMENT CHARACTER, of
value 0xfffd.
If this is on fl_utf8decode() will correctly map most (perhaps all)
human-readable text that is in ISO-8859-1. This may allow you
to completely ignore character sets in your code because virtually
everything is either ISO-8859-1 or UTF-8.
*/
#ifndef ERRORS_TO_ISO8859_1
# define ERRORS_TO_ISO8859_1 1
#endif
/** Set to 1 to turn bad UTF-8 bytes in the 0x80-0x9f range into the
Unicode index for Microsoft's CP1252 character set. You should
also set ERRORS_TO_ISO8859_1. With this a huge amount of more
available text (such as all web pages) are correctly converted
to Unicode.
*/
#ifndef ERRORS_TO_CP1252
# define ERRORS_TO_CP1252 1
#endif
/** A number of Unicode code points are in fact illegal and should not
be produced by a UTF-8 converter. Turn this on will replace the
bytes in those encodings with errors. If you do this then converting
arbitrary 16-bit data to UTF-8 and then back is not an identity,
which will probably break a lot of software.
*/
#ifndef STRICT_RFC3629
# define STRICT_RFC3629 0
#endif
#if ERRORS_TO_CP1252
/* Codes 0x80..0x9f from the Microsoft CP1252 character set, translated
to Unicode:
*/
static unsigned short cp1252[32] = {
0x20ac, 0x0081, 0x201a, 0x0192, 0x201e, 0x2026, 0x2020, 0x2021,
0x02c6, 0x2030, 0x0160, 0x2039, 0x0152, 0x008d, 0x017d, 0x008f,
0x0090, 0x2018, 0x2019, 0x201c, 0x201d, 0x2022, 0x2013, 0x2014,
0x02dc, 0x2122, 0x0161, 0x203a, 0x0153, 0x009d, 0x017e, 0x0178
};
#endif
/**
Decode a single UTF-8 encoded character starting at \e p.
The resulting Unicode value (in the range 0-0x10ffff) is returned,
and \e len is set to the number of bytes in the UTF-8 encoding
(adding \e len to \e p will point at the next character).
If \p p points at an illegal UTF-8 encoding, including one that
would go past \e end, or where a code uses more bytes than
necessary, then *(unsigned char*)p is translated as though it is
in the Microsoft CP1252 character set and \e len is set to 1.
Treating errors this way allows this to decode almost any
ISO-8859-1 or CP1252 text that has been mistakenly placed where
UTF-8 is expected, and has proven very useful.
If you want errors to be converted to error characters (as the
standards recommend), adding a test to see if the length is
unexpectedly 1 will work:
\code
if (*p & 0x80) { // what should be a multibyte encoding
code = fl_utf8decode(p,end,&len);
if (len<2) code = 0xFFFD; // Turn errors into REPLACEMENT CHARACTER
} else { // handle the 1-byte UTF-8 encoding:
code = *p;
len = 1;
}
\endcode
Direct testing for the 1-byte case (as shown above) will also
speed up the scanning of strings where the majority of characters
are ASCII.
\param[in] p pointer to a UTF-8 encoded character
\param[in] end if set, points after the last character that may be read
\param[out] len if set, returns the length of the input UTF-8 sequence
\return 32 bit Unicode character, or Unicode REPLACEMENT CHARACTER
*/
unsigned fl_utf8decode(const char* p, const char* end, int* len)
{
unsigned char c = *(const unsigned char*)p;
if (c < 0x80) {
if (len) *len = 1;
return c;
#if ERRORS_TO_CP1252
} else if (c < 0xa0) {
if (len) *len = 1;
return cp1252[c-0x80];
#endif
} else if (c < 0xc2) {
goto FAIL;
}
if ( (end && p+1 >= end) || (p[1]&0xc0) != 0x80) goto FAIL;
if (c < 0xe0) {
if (len) *len = 2;
return
((p[0] & 0x1f) << 6) +
((p[1] & 0x3f));
} else if (c == 0xe0) {
if (((const unsigned char*)p)[1] < 0xa0) goto FAIL;
goto UTF8_3;
#if STRICT_RFC3629
} else if (c == 0xed) {
/* RFC 3629 says surrogate chars are illegal. */
if (((const unsigned char*)p)[1] >= 0xa0) goto FAIL;
goto UTF8_3;
} else if (c == 0xef) {
/* 0xfffe and 0xffff are also illegal characters */
if (((const unsigned char*)p)[1]==0xbf &&
((const unsigned char*)p)[2]>=0xbe) goto FAIL;
goto UTF8_3;
#endif
} else if (c < 0xf0) {
UTF8_3:
if ( (end && p+2 >= end) || (p[2]&0xc0) != 0x80) goto FAIL;
if (len) *len = 3;
return
((p[0] & 0x0f) << 12) +
((p[1] & 0x3f) << 6) +
((p[2] & 0x3f));
} else if (c == 0xf0) {
if (((const unsigned char*)p)[1] < 0x90) goto FAIL;
goto UTF8_4;
} else if (c < 0xf4) {
UTF8_4:
if ( (end && p+3 >= end) || (p[2]&0xc0) != 0x80 || (p[3]&0xc0) != 0x80) goto FAIL;
if (len) *len = 4;
#if STRICT_RFC3629
/* RFC 3629 says all codes ending in fffe or ffff are illegal: */
if ((p[1]&0xf)==0xf &&
((const unsigned char*)p)[2] == 0xbf &&
((const unsigned char*)p)[3] >= 0xbe) goto FAIL;
#endif
return
((p[0] & 0x07) << 18) +
((p[1] & 0x3f) << 12) +
((p[2] & 0x3f) << 6) +
((p[3] & 0x3f));
} else if (c == 0xf4) {
if (((const unsigned char*)p)[1] > 0x8f) goto FAIL; /* after 0x10ffff */
goto UTF8_4;
} else {
FAIL:
if (len) *len = 1;
#if ERRORS_TO_ISO8859_1
return c;
#else
return 0xfffd; /* Unicode REPLACEMENT CHARACTER */
#endif
}
}
/** Move \p p forward until it points to the start of a UTF-8
character. If it already points at the start of one then it
is returned unchanged. Any UTF-8 errors are treated as though each
byte of the error is an individual character.
This function is for moving a pointer that was jumped to the
middle of a string, such as when doing a binary search for
a position. You should use either this or fl_utf8back() depending
on which direction your algorithm can handle the pointer
moving. Do not use this to scan strings, use fl_utf8decode()
instead.
\param[in] p points somewhere into a UTF-8 encoded string, need not be on
a UTF-8 sequence start or end.
\param[in] start is the start of the string and is used to limit the
backwards search for the start of a UTF-8 character.
\param[in] end is the end of the string and is assumed to be a break
between characters. It is assumed to be greater than p.
\return pointer to the start of a UTF-8 sequence or pointer to terminating NUL.
*/
const char* fl_utf8fwd(const char* p, const char* start, const char* end)
{
const char* a;
int len;
/* if we are not pointing at a continuation character, we are done: */
if ((*p&0xc0) != 0x80) return p;
/* search backwards for a 0xc0 starting the character: */
for (a = p-1; ; --a) {
if (a < start) return p;
if (!(a[0]&0x80)) return p;
if ((a[0]&0x40)) break;
}
fl_utf8decode(a,end,&len);
a += len;
if (a > p) return a;
return p;
}
/** Move \p p backward until it points to the start of a UTF-8
character. If it already points at the start of one then it
is returned unchanged. Any UTF-8 errors are treated as though each
byte of the error is an individual character.
\param[in] p points somewhere into a UTF-8 encoded string, need not be on
a UTF-8 sequence start or end. If you wish to decrement a UTF-8 pointer,
pass p-1 to this.
\param[in] start is the start of the string and is used to limit the
backwards search for the start of a UTF-8 character.
\param[in] end is the end of the string and is assumed to be a break
between characters. It is assumed to be greater than p.
\return pointer to the start of a UTF-8 sequence.
*/
const char* fl_utf8back(const char* p, const char* start, const char* end)
{
const char* a;
int len;
/* if we are not pointing at a continuation character, we are done: */
if ((*p&0xc0) != 0x80) return p;
/* search backwards for a 0xc0 starting the character: */
for (a = p-1; ; --a) {
if (a < start) return p;
if (!(a[0]&0x80)) return p;
if ((a[0]&0x40)) break;
}
fl_utf8decode(a,end,&len);
if (a+len > p) return a;
return p;
}
/** Returns number of bytes that utf8encode() will use to encode the
character \p ucs.
\param[in] ucs 32-bit Unicode character
\return number of bytes for UTF-8 encoded sequence.
*/
int fl_utf8bytes(unsigned ucs) {
if (ucs < 0x000080U) {
return 1;
} else if (ucs < 0x000800U) {
return 2;
} else if (ucs < 0x010000U) {
return 3;
} else if (ucs <= 0x10ffffU) {
return 4;
} else {
return 3; /* length of the illegal character encoding */
}
}
/** Write the UTF-8 encoding of \e ucs into \e buf and return the
number of bytes written. Up to 4 bytes may be written. If you know
that \p ucs is less than 0x10000 then at most 3 bytes will be written.
If you wish to speed this up, remember that anything less than 0x80
is written as a single byte.
If ucs is greater than 0x10ffff this is an illegal character
according to RFC 3629. These are converted as though they are
0xFFFD (REPLACEMENT CHARACTER).
RFC 3629 also says many other values for \p ucs are illegal (in
the range 0xd800 to 0xdfff, or ending with 0xfffe or
0xffff). However I encode these as though they are legal, so that
utf8encode/fl_utf8decode will be the identity for all codes between 0
and 0x10ffff.
\param[in] ucs 32-bit Unicode character
\param[out] buf a buffer of at least four bytes to receive the UTF-8 byte
sequence. No terminating NUL is added.
\return number of bytes in UTF-8 sequence.
*/
int fl_utf8encode(unsigned ucs, char* buf) {
if (ucs < 0x000080U) {
buf[0] = ucs;
return 1;
} else if (ucs < 0x000800U) {
buf[0] = 0xc0 | (ucs >> 6);
buf[1] = 0x80 | (ucs & 0x3F);
return 2;
} else if (ucs < 0x010000U) {
buf[0] = 0xe0 | (ucs >> 12);
buf[1] = 0x80 | ((ucs >> 6) & 0x3F);
buf[2] = 0x80 | (ucs & 0x3F);
return 3;
} else if (ucs <= 0x0010ffffU) {
buf[0] = 0xf0 | (ucs >> 18);
buf[1] = 0x80 | ((ucs >> 12) & 0x3F);
buf[2] = 0x80 | ((ucs >> 6) & 0x3F);
buf[3] = 0x80 | (ucs & 0x3F);
return 4;
} else {
/* encode 0xfffd: */
buf[0] = (char)0xef;
buf[1] = (char)0xbf;
buf[2] = (char)0xbd;
return 3;
}
}
/** Convert a single 32-bit Unicode codepoint into an array of 16-bit
characters. These are used by some system calls, especially on Windows.
Unicode characters in the range 0x10000 to 0x10ffff are converted to
"surrogate pairs" which take two words each (in UTF-16 encoding).
Typically, setting \p dstlen to 2 will ensure that any valid Unicode
value can be converted, and setting \p dstlen to 3 or more will allow
a NULL terminated sequence to be returned.
\param[in] ucs is the value to convert.
\param[out] dst points at an array to write, and
\param[in] dstlen is the number of
locations in this array. At most \p dstlen words will be
written, and a 0 terminating word will be added if \p dstlen is
large enough. Thus this function will never overwrite the buffer
and will attempt return a zero-terminated string if space permits.
If \p dstlen is zero then \p dst can be set to NULL and no data
is written, but the length is returned.
\return The return value is the number of 16-bit words that \e would be
written to \p dst if it is large enough, not counting any terminating
zero. If the return value is greater than \p dstlen it indicates
truncation, you should then allocate a new array of size return+1
and call this again.
*/
unsigned fl_ucs_to_Utf16(const unsigned ucs, unsigned short *dst, const unsigned dstlen)
{
/* The rule for direct conversion from UCS to UTF16 is:
* - if UCS > 0x0010FFFF then UCS is invalid
* - if UCS >= 0xD800 && UCS <= 0xDFFF UCS is invalid
* - if UCS <= 0x0000FFFF then U16 = UCS, len = 1
* - else
* -- U16[0] = ((UCS - 0x00010000) >> 10) & 0x3FF + 0xD800
* -- U16[1] = (UCS & 0x3FF) + 0xDC00
* -- len = 2;
*/
unsigned count; /* Count of converted UTF16 cells */
unsigned short u16[4]; /* Alternate buffer if dst is not set */
unsigned short *out; /* points to the active buffer */
/* Ensure we have a valid buffer to write to */
if((!dstlen) || (!dst)) {
out = u16;
} else {
out = dst;
}
/* Convert from UCS to UTF16 */
if((ucs > 0x0010FFFF) || /* UCS is too large */
((ucs > 0xD7FF) && (ucs < 0xE000))) { /* UCS in invalid range */
out[0] = 0xFFFD; /* REPLACEMENT CHARACTER */
count = 1;
} else if(ucs < 0x00010000) {
out[0] = (unsigned short)ucs;
count = 1;
} else if(dstlen < 2) { /* dst is too small for the result */
out[0] = 0xFFFD; /* REPLACEMENT CHARACTER */
count = 2;
} else {
out[0] = (((ucs - 0x00010000) >> 10) & 0x3FF) + 0xD800;
out[1] = (ucs & 0x3FF) + 0xDC00;
count = 2;
}
/* NULL terminate the output, if there is space */
if(count < dstlen) { out[count] = 0; }
return count;
} /* fl_ucs_to_Utf16 */
/** Convert a UTF-8 sequence into an array of 16-bit characters. These
are used by some system calls, especially on Windows.
Errors in the UTF-8 are converted as though each byte in the
erroneous string is in the Microsoft CP1252 encoding. This allows
ISO-8859-1 text mistakenly identified as UTF-8 to be printed
correctly.
Unicode characters in the range 0x10000 to 0x10ffff are converted to
"surrogate pairs" which take two words each (this is called UTF-16
encoding).
\param[in] src points at the UTF-8, and
\param[in] srclen is the number of bytes to convert.
\param[out] dst points at an array to write, and
\param[in] dstlen is the number of
locations in this array. At most \p dstlen-1 words will be
written there, plus a 0 terminating word. Thus this function
will never overwrite the buffer and will always return a
zero-terminated string. If \p dstlen is zero then \p dst can be
null and no data is written, but the length is returned.
\return The return value is the number of 16-bit words that \e would be
written to \p dst if it were long enough, not counting the terminating
zero. If the return value is greater or equal to \p dstlen it
indicates truncation, you can then allocate a new array of size
return+1 and call this again.
*/
unsigned fl_utf8toUtf16(const char* src, unsigned srclen,
unsigned short* dst, unsigned dstlen)
{
const char* p = src;
const char* e = src+srclen;
unsigned count = 0;
if (dstlen) for (;;) {
if (p >= e) {dst[count] = 0; return count;}
if (!(*p & 0x80)) { /* ascii */
dst[count] = *p++;
} else {
int len; unsigned ucs = fl_utf8decode(p,e,&len);
p += len;
if (ucs < 0x10000) {
dst[count] = ucs;
} else {
/* make a surrogate pair: */
if (count+2 >= dstlen) {dst[count] = 0; count += 2; break;}
dst[count] = (((ucs-0x10000u)>>10)&0x3ff) | 0xd800;
dst[++count] = (ucs&0x3ff) | 0xdc00;
}
}
if (++count == dstlen) {dst[count-1] = 0; break;}
}
/* we filled dst, measure the rest: */
while (p < e) {
if (!(*p & 0x80)) p++;
else {
int len; unsigned ucs = fl_utf8decode(p,e,&len);
p += len;
if (ucs >= 0x10000) ++count;
}
++count;
}
return count;
}
/** Convert a UTF-8 sequence into an array of 1-byte characters.
If the UTF-8 decodes to a character greater than 0xff then it is
replaced with '?'.
Errors in the UTF-8 sequence are converted as individual bytes, same as
fl_utf8decode() does. This allows ISO-8859-1 text mistakenly identified
as UTF-8 to be printed correctly (and possibly CP1252 on Windows).
\param[in] src points at the UTF-8 sequence, and
\param[in] srclen is the number of bytes to convert.
\param[out] dst Up to \p dstlen bytes are written to \p dst, including a null
terminator. The return value is the number of bytes that would be
written, not counting the null terminator. If greater or equal to...
\param[in] dstlen then if you malloc a new array of size n+1 you will have
the space needed for the entire string. If \p dstlen is zero then
nothing is written and this call just measures the storage space
needed.
\return number of characters converted.
*/
unsigned fl_utf8toa(const char* src, unsigned srclen,
char* dst, unsigned dstlen)
{
const char* p = src;
const char* e = src+srclen;
unsigned count = 0;
if (dstlen) for (;;) {
unsigned char c;
if (p >= e) {dst[count] = 0; return count;}
c = *(const unsigned char*)p;
if (c < 0xC2) { /* ascii or bad code */
dst[count] = c;
p++;
} else {
int len; unsigned ucs = fl_utf8decode(p,e,&len);
p += len;
if (ucs < 0x100) dst[count] = ucs;
else dst[count] = '?';
}
if (++count >= dstlen) {dst[count-1] = 0; break;}
}
/* we filled dst, measure the rest: */
while (p < e) {
if (!(*p & 0x80)) p++;
else {
int len;
fl_utf8decode(p,e,&len);
p += len;
}
++count;
}
return count;
}
/** Convert an ISO-8859-1 (ie normal c-string) byte stream to UTF-8.
It is possible this should convert Microsoft's CP1252 to UTF-8
instead. This would translate the codes in the range 0x80-0x9f
to different characters. Currently it does not do this.
\param[out] dst Up to \p dstlen bytes are written to \p dst, including a null
terminator. The return value is the number of bytes that would be
written, not counting the null terminator. If greater or equal to...
\param[in] dstlen then if you malloc a new array of size n+1 you will have
the space needed for the entire string. If \p dstlen is zero then
nothing is written and this call just measures the storage space
needed.
\param[in] src pointer to ISO-8859-1 string.
\param[in] srclen is the number of bytes in \p src to convert.
\return Number of bytes written. If the return value equals \p srclen then
this indicates that no conversion is necessary, as only ASCII characters
are in the string.
*/
unsigned fl_utf8froma(char* dst, unsigned dstlen,
const char* src, unsigned srclen) {
const char* p = src;
const char* e = src+srclen;
unsigned count = 0;
if (dstlen) for (;;) {
unsigned char ucs;
if (p >= e) {dst[count] = 0; return count;}
ucs = *(const unsigned char*)p++;
if (ucs < 0x80U) {
dst[count++] = ucs;
if (count >= dstlen) {dst[count-1] = 0; break;}
} else { /* 2 bytes (note that CP1252 translate could make 3 bytes!) */
if (count+2 >= dstlen) {dst[count] = 0; count += 2; break;}
dst[count++] = 0xc0 | (ucs >> 6);
dst[count++] = 0x80 | (ucs & 0x3F);
}
}
/* we filled dst, measure the rest: */
while (p < e) {
unsigned char ucs = *(const unsigned char*)p++;
if (ucs < 0x80U) {
count++;
} else {
count += 2;
}
}
return count;
}
/** Examines the first \p srclen bytes in \p src and returns a verdict
on whether it is UTF-8 or not.
- Returns 0 if there is any illegal UTF-8 sequences, using the
same rules as fl_utf8decode(). Note that some UCS values considered
illegal by RFC 3629, such as 0xffff, are considered legal by this.
- Returns 1 if there are only single-byte characters (ie no bytes
have the high bit set). This is legal UTF-8, but also indicates
plain ASCII. It also returns 1 if \p srclen is zero.
- Returns 2 if there are only characters less than 0x800.
- Returns 3 if there are only characters less than 0x10000.
- Returns 4 if there are characters in the 0x10000 to 0x10ffff range.
Because there are many illegal sequences in UTF-8, it is almost
impossible for a string in another encoding to be confused with
UTF-8. This is very useful for transitioning Unix to UTF-8
filenames, you can simply test each filename with this to decide
if it is UTF-8 or in the locale encoding. My hope is that if
this is done we will be able to cleanly transition to a locale-less
encoding.
\param[in] src pointer to string of unknown encoding
\param[in] srclen number of bytes to compare, must not be -1
\return 0 if this is probably not a UTF-8 encode string
*/
int fl_utf8test(const char* src, unsigned srclen) {
int ret = 1;
const char* p = src;
const char* e = src+srclen;
while (p < e) {
if (*p & 0x80) {
int len; fl_utf8decode(p,e,&len);
if (len < 2) return 0;
if (len > ret) ret = len;
p += len;
} else {
p++;
}
}
return ret;
}
/* forward declare mk_wcwidth() as static so the name is not visible.
*/
static int mk_wcwidth(unsigned int ucs);
/* include the c source directly so its contents are only visible here
*/
#include "xutf8/mk_wcwidth.c"
/** Wrapper to adapt Markus Kuhn's implementation of wcwidth() for FLTK.
\param [in] ucs Unicode character value
\returns width of character in columns
See http://www.cl.cam.ac.uk/~mgk25/ucs/wcwidth.c for Markus Kuhn's
original implementation of wcwidth() and wcswidth()
(defined in IEEE Std 1002.1-2001) for Unicode.
\b WARNING: this function returns widths for "raw" Unicode characters.
It does not even try to map C1 control characters (0x80 to 0x9F) to
CP1252, and C0/C1 control characters and DEL will return -1.
You are advised to use fl_width(const char* src) instead.
*/
int fl_wcwidth_(unsigned int ucs) {
return mk_wcwidth(ucs);
}
/** extended wrapper around fl_wcwidth_(unsigned int ucs) function.
\param[in] src pointer to start of UTF-8 byte sequence
\returns width of character in columns
Depending on build options, this function may map C1 control
characters (0x80 to 0x9f) to CP1252, and return the width of
that character instead. This is not the same behaviour as
fl_wcwidth_(unsigned int ucs) .
Note that other control characters and DEL will still return -1,
so if you want different behaviour, you need to test for those
characters before calling fl_wcwidth(), and handle them separately.
*/
int fl_wcwidth(const char* src) {
int len = fl_utf8len(*src);
int ret = 0;
unsigned int ucs = fl_utf8decode(src, src+len, &ret);
int width = fl_wcwidth_(ucs);
return width;
}
/**
Converts a UTF-8 string into a wide character string.
This function generates 32-bit wchar_t (e.g. "ucs4" as it were) except
on Windows where it is equivalent to fl_utf8toUtf16 and returns
UTF-16.
Notice that sizeof(wchar_t) is 2 on Windows and is 4 on Linux
and most other systems. Where wchar_t is 16 bits, Unicode
characters in the range 0x10000 to 0x10ffff are converted to
"surrogate pairs" which take two words each (this is called UTF-16
encoding). If wchar_t is 32 bits this rather nasty problem is
avoided.
\note Windows includes Cygwin, i.e. compiled with Cygwin's POSIX
layer (cygwin1.dll, --enable-cygwin), either native (GDI) or X11.
\param[in] src points at the UTF-8, and
\param[in] srclen is the number of bytes to convert.
\param[out] dst points at an array to write, and
\param[in] dstlen is the number of locations in this array. At most \p dstlen-1 wchar_t will be
written there, plus a 0 terminating wchar_t.
\return The return value is the number of wchar_t that \e would be written
to \p dst if it were long enough, not counting the terminating
zero. If the return value is greater or equal to \p dstlen it
indicates truncation, you can then allocate a new array of size
return+1 and call this again.
*/
unsigned fl_utf8towc(const char* src, unsigned srclen,
wchar_t* dst, unsigned dstlen)
{
return Fl::system_driver()->utf8towc(src, srclen, dst, dstlen);
}
/** Turn "wide characters" as returned by some system calls
(especially on Windows) into UTF-8.
Up to \p dstlen bytes are written to \p dst, including a null
terminator. The return value is the number of bytes that would be
written, not counting the null terminator. If greater or equal to
\p dstlen then if you malloc a new array of size n+1 you will have
the space needed for the entire string. If \p dstlen is zero then
nothing is written and this call just measures the storage space
needed.
\p srclen is the number of words in \p src to convert. On Windows
this is not necessarily the number of characters, due to there
possibly being "surrogate pairs" in the UTF-16 encoding used.
On Unix wchar_t is 32 bits and each location is a character.
On Unix if a \p src word is greater than 0x10ffff then this is an
illegal character according to RFC 3629. These are converted as
though they are 0xFFFD (REPLACEMENT CHARACTER). Characters in the
range 0xd800 to 0xdfff, or ending with 0xfffe or 0xffff are also
illegal according to RFC 3629. However I encode these as though
they are legal, so that fl_utf8towc will return the original data.
On Windows "surrogate pairs" are converted to a single character
and UTF-8 encoded (as 4 bytes). Mismatched halves of surrogate
pairs are converted as though they are individual characters.
\param[out] dst a destination buffer provided by the caller
\param[in] dstlen size of dst buffer
\param[in] src pointer to Windows wide char string
\param[in] srclen number of characters to convert
\return number of bytes written, not including the terminating NUL
*/
unsigned fl_utf8fromwc(char* dst, unsigned dstlen, const wchar_t* src, unsigned srclen)
{
return Fl::system_driver()->utf8fromwc(dst, dstlen, src, srclen);
}
/** Return true if the "locale" seems to indicate that UTF-8 encoding
is used. If true the fl_utf8to_mb and fl_utf8from_mb don't do anything
useful.
\note <i>It is highly recommended that you change your system so this
does return true.</i> On Windows this is done by setting the
"codepage" to CP_UTF8. On Unix this is done by setting $LC_CTYPE
to a string containing the letters "utf" or "UTF" in it, or by
deleting all $LC* and $LANG environment variables. In the future
it is likely that all non-Asian Unix systems will return true,
due to the compatibility of UTF-8 with ISO-8859-1.
*/
int fl_utf8locale()
{
return Fl::system_driver()->utf8locale();
}
/** Convert the UTF-8 used by FLTK to the locale-specific encoding
used for filenames (and sometimes used for data in files).
Unfortunately due to stupid design you will have to do this as
needed for filenames. This is a bug on both Unix and Windows.
Up to \p dstlen bytes are written to \p dst, including a null
terminator. The return value is the number of bytes that would be
written, not counting the null terminator. If greater or equal to
\p dstlen then if you malloc a new array of size n+1 you will have
the space needed for the entire string. If \p dstlen is zero then
nothing is written and this call just measures the storage space
needed.
If fl_utf8locale() returns true then this does not change the data.
*/
unsigned fl_utf8to_mb(const char* src, unsigned srclen, char* dst, unsigned dstlen) {
if (fl_utf8locale()) {
/* identity transform: */
if (srclen < dstlen) {
memcpy(dst, src, srclen);
dst[srclen] = 0;
} else {
/* Buffer insufficent or buffer query */
}
return srclen;
}
return Fl::system_driver()->utf8to_mb(src, srclen, dst, dstlen);
}
/** Convert a filename from the locale-specific multibyte encoding
used by Windows to UTF-8 as used by FLTK.
Up to \p dstlen bytes are written to \p dst, including a null
terminator. The return value is the number of bytes that would be
written, not counting the null terminator. If greater or equal to
\p dstlen then if you malloc a new array of size n+1 you will have
the space needed for the entire string. If \p dstlen is zero then
nothing is written and this call just measures the storage space
needed.
On Unix or on Windows when a UTF-8 locale is in effect, this
does not change the data.
You may also want to check if fl_utf8test() returns non-zero, so that
the filesystem can store filenames in UTF-8 encoding regardless of
the locale.
*/
unsigned fl_utf8from_mb(char* dst, unsigned dstlen, const char* src, unsigned srclen) {
if (fl_utf8locale()) {
/* identity transform: */
if (srclen < dstlen) {
memcpy(dst, src, srclen);
dst[srclen] = 0;
} else {
/* Buffer insufficent or buffer query */
}
return srclen;
}
return Fl::system_driver()->utf8from_mb(dst, dstlen, src, srclen);
}
/**
Returns pointer to beginning of character after given location in UTF8 string accounting for composed characters.
Some unicode characters (examples: 👩✈️ "woman pilot", 🇸🇲 "San Marino flag") are composed of several unicode points.
They may pair two successive codepoints with U+200D (zero-width joiner) and may qualify any component with
variation selectors or Fitzpatrick emoji modifiers. Most flag emojis are composed of two successive
"regional indicator symbols", each in range [U+1F1E6 , U+1F1FF].
\param from points to a location within a UTF8 string. If this location is inside the UTF8
encoding of a codepoint or is an invalid byte, this function returns \p from + 1.
\param end points past last codepoint of the string.
\return pointer to beginning of first codepoint after possibly composed character that begins at \p from.
*/
const char *fl_utf8_next_composed_char(const char *from, const char *end) {
int skip = fl_utf8len1(*from);
if (skip <= 2) return from + skip;
unsigned u = fl_utf8decode(from, end, NULL);
if (u >= 0x1F1E6 && u <= 0x1F1FF) { // a 1st regional indicator symbol can be a flag
u = fl_utf8decode(from + skip, end, NULL);
if (u >= 0x1F1E6 && u <= 0x1F1FF) { // a 2nd regional indicator symbol gives a flag
return from + 2 * skip;
}
} else if (u == 0x1F3F4) { // “waving black flag” may start subdivision flags (e.g. 🏴)
const char *next = from + skip;
do {
u = fl_utf8decode(next, end, NULL);
next += fl_utf8len1(*next);
if (u == 0xE007F) return next; // ends with "cancel tag"
} while (u >= 0xE0020 && u <= 0xE007E); // any series of "tag components"
}
from += skip; // skip 1st codepoint
while (from < end) {
u = fl_utf8decode(from, end, NULL);
if (u == 0x200D) { // zero-width joiner
from += fl_utf8len(*from); // skip joiner
from += fl_utf8len(*from); // skip joined codepoint
} else if (u >= 0xFE00 && u <= 0xFE0F) { // a variation selector
from += fl_utf8len(*from); // skip variation selector
} else if (u >= 0x1F3FB && u <= 0x1F3FF) { // EMOJI MODIFIER FITZPATRICK
from += fl_utf8len(*from); // skip modifier
} else break;
}
return from;
}
/**
Returns pointer to beginning of character before given location in UTF8 string accounting for composed characters.
See fl_utf8_next_composed_char() for a hint about what is a composed unicode character.
\param from points to a location within a UTF8 string. If this location is inside the UTF8
encoding of a codepoint or is an invalid byte, this function returns \p from - 1.
\param begin points to start of first codepoint of the string.
\return pointer to beginning of first possibly composed character before the codepoint that begins at \p from.
*/
const char *fl_utf8_previous_composed_char(const char *from, const char *begin) {
int l = fl_utf8len(*from);
if (from <= begin || l == -1) return from - 1;
const char *keep = from + l;
from = fl_utf8back(from - 1, begin, NULL);
unsigned u = fl_utf8decode(from, keep, NULL);
if (u >= 0x1F1E6 && u <= 0x1F1FF) { // a 1st regional indicator symbol can be a flag
const char *previous = fl_utf8back(from - 1, begin, NULL);
u = fl_utf8decode(previous, keep, NULL);
if (u >= 0x1F1E6 && u <= 0x1F1FF) { // a 2nd Regional indicator symbol gives a flag
return previous;
}
} else if (u == 0xE007F) { // ends with "cancel tag"
const char *previous = from;
do {
if (previous <= begin) return begin;
previous = fl_utf8back(previous - 1, begin, NULL);
u = fl_utf8decode(previous, keep, NULL);
if (u == 0x1F3F4) return previous; // “waving black flag” starts subdivision flags
} while (u >= 0xE0020 && u <= 0xE007E); // any series of "tag components"
}
while (from >= begin) {
u = fl_utf8decode(from, keep, NULL);
if (u >= 0xFE00 && u <= 0xFE0F) { // a variation selector
from = fl_utf8back(from - 1, begin, NULL);
} else if (u >= 0x1F3FB && u <= 0x1F3FF) { // EMOJI MODIFIER FITZPATRICK
from = fl_utf8back(from - 1, begin, NULL);
} else if (from > begin) {
keep = fl_utf8back(from - 1, begin, NULL);
u = fl_utf8decode(keep, from, NULL);
if (u == 0x200D) { // zero-width joiner
from = fl_utf8back(keep - 1, begin, NULL);
continue;
}
return from;
} else break;
}
return from;
}
/** @} */
|