fl_utf.c 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986
  1. /*
  2. * "$Id: fl_utf.c 8864 2011-07-19 04:49:30Z greg.ercolano $"
  3. *
  4. * This is the utf.c file from fltk2 adapted for use in my fltk1.1 port
  5. */
  6. /* Copyright 2006-2011 by Bill Spitzak and others.
  7. *
  8. * This library is free software. Distribution and use rights are outlined in
  9. * the file "COPYING" which should have been included with this file. If this
  10. * file is missing or damaged, see the license at:
  11. *
  12. * http://www.fltk.org/COPYING.php
  13. *
  14. * Please report all bugs and problems on the following page:
  15. *
  16. * http://www.fltk.org/str.php
  17. */
  18. /* Modified to obey rfc3629, which limits unicode to 0-0x10ffff */
  19. #include <FL/fl_utf8.h>
  20. #include <string.h>
  21. #include <stdlib.h>
  22. /** \addtogroup fl_unicode
  23. @{
  24. */
  25. #if 0
  26. /**
  27. \defgroup fl_unichar Unicode Character Functions
  28. Global Functions Handling Single Unicode Characters
  29. @{ */
  30. /**
  31. Converts a Unicode character into a utf-8 sequence.
  32. \param[in] uc Unicode character
  33. \param[out] text utf-8 sequence will be written here; if this pointer is
  34. \c NULL, only the length of the utf-8 sequence is calculated
  35. \return length of the sequence in bytes
  36. */
  37. /* FL_EXPORT int fl_unichar_to_utf8(unsigned int uc, char *text); */
  38. /** @} */
  39. /**
  40. \defgroup fl_utf8 Unicode String Functions
  41. Global Functions Handling Unicode Text
  42. @{ */
  43. /**
  44. Calculate the size of a utf-8 sequence for a Unicode character.
  45. \param[in] uc Unicode character
  46. \return length of the sequence in bytes
  47. */
  48. /* FL_EXPORT int fl_utf8_size(unsigned int uc); */
  49. /** @} */
  50. #endif /* 0 */
  51. /*!Set to 1 to turn bad UTF8 bytes into ISO-8859-1. If this is to zero
  52. they are instead turned into the Unicode REPLACEMENT CHARACTER, of
  53. value 0xfffd.
  54. If this is on fl_utf8decode() will correctly map most (perhaps all)
  55. human-readable text that is in ISO-8859-1. This may allow you
  56. to completely ignore character sets in your code because virtually
  57. everything is either ISO-8859-1 or UTF-8.
  58. */
  59. #define ERRORS_TO_ISO8859_1 1
  60. /*!Set to 1 to turn bad UTF8 bytes in the 0x80-0x9f range into the
  61. Unicode index for Microsoft's CP1252 character set. You should
  62. also set ERRORS_TO_ISO8859_1. With this a huge amount of more
  63. available text (such as all web pages) are correctly converted
  64. to Unicode.
  65. */
  66. #define ERRORS_TO_CP1252 1
  67. /*!A number of Unicode code points are in fact illegal and should not
  68. be produced by a UTF-8 converter. Turn this on will replace the
  69. bytes in those encodings with errors. If you do this then converting
  70. arbitrary 16-bit data to UTF-8 and then back is not an identity,
  71. which will probably break a lot of software.
  72. */
  73. #define STRICT_RFC3629 0
  74. #if ERRORS_TO_CP1252
  75. /* Codes 0x80..0x9f from the Microsoft CP1252 character set, translated
  76. * to Unicode:
  77. */
  78. static unsigned short cp1252[32] = {
  79. 0x20ac, 0x0081, 0x201a, 0x0192, 0x201e, 0x2026, 0x2020, 0x2021,
  80. 0x02c6, 0x2030, 0x0160, 0x2039, 0x0152, 0x008d, 0x017d, 0x008f,
  81. 0x0090, 0x2018, 0x2019, 0x201c, 0x201d, 0x2022, 0x2013, 0x2014,
  82. 0x02dc, 0x2122, 0x0161, 0x203a, 0x0153, 0x009d, 0x017e, 0x0178
  83. };
  84. #endif
  85. /*! Decode a single UTF-8 encoded character starting at \e p. The
  86. resulting Unicode value (in the range 0-0x10ffff) is returned,
  87. and \e len is set to the number of bytes in the UTF-8 encoding
  88. (adding \e len to \e p will point at the next character).
  89. If \p p points at an illegal UTF-8 encoding, including one that
  90. would go past \e end, or where a code is uses more bytes than
  91. necessary, then *(unsigned char*)p is translated as though it is
  92. in the Microsoft CP1252 character set and \e len is set to 1.
  93. Treating errors this way allows this to decode almost any
  94. ISO-8859-1 or CP1252 text that has been mistakenly placed where
  95. UTF-8 is expected, and has proven very useful.
  96. If you want errors to be converted to error characters (as the
  97. standards recommend), adding a test to see if the length is
  98. unexpectedly 1 will work:
  99. \code
  100. if (*p & 0x80) { // what should be a multibyte encoding
  101. code = fl_utf8decode(p,end,&len);
  102. if (len<2) code = 0xFFFD; // Turn errors into REPLACEMENT CHARACTER
  103. } else { // handle the 1-byte utf8 encoding:
  104. code = *p;
  105. len = 1;
  106. }
  107. \endcode
  108. Direct testing for the 1-byte case (as shown above) will also
  109. speed up the scanning of strings where the majority of characters
  110. are ASCII.
  111. */
  112. unsigned fl_utf8decode(const char* p, const char* end, int* len)
  113. {
  114. unsigned char c = *(unsigned char*)p;
  115. if (c < 0x80) {
  116. if (len) *len = 1;
  117. return c;
  118. #if ERRORS_TO_CP1252
  119. } else if (c < 0xa0) {
  120. if (len) *len = 1;
  121. return cp1252[c-0x80];
  122. #endif
  123. } else if (c < 0xc2) {
  124. goto FAIL;
  125. }
  126. if ( (end && p+1 >= end) || (p[1]&0xc0) != 0x80) goto FAIL;
  127. if (c < 0xe0) {
  128. if (len) *len = 2;
  129. return
  130. ((p[0] & 0x1f) << 6) +
  131. ((p[1] & 0x3f));
  132. } else if (c == 0xe0) {
  133. if (((unsigned char*)p)[1] < 0xa0) goto FAIL;
  134. goto UTF8_3;
  135. #if STRICT_RFC3629
  136. } else if (c == 0xed) {
  137. /* RFC 3629 says surrogate chars are illegal. */
  138. if (((unsigned char*)p)[1] >= 0xa0) goto FAIL;
  139. goto UTF8_3;
  140. } else if (c == 0xef) {
  141. /* 0xfffe and 0xffff are also illegal characters */
  142. if (((unsigned char*)p)[1]==0xbf &&
  143. ((unsigned char*)p)[2]>=0xbe) goto FAIL;
  144. goto UTF8_3;
  145. #endif
  146. } else if (c < 0xf0) {
  147. UTF8_3:
  148. if ( (end && p+2 >= end) || (p[2]&0xc0) != 0x80) goto FAIL;
  149. if (len) *len = 3;
  150. return
  151. ((p[0] & 0x0f) << 12) +
  152. ((p[1] & 0x3f) << 6) +
  153. ((p[2] & 0x3f));
  154. } else if (c == 0xf0) {
  155. if (((unsigned char*)p)[1] < 0x90) goto FAIL;
  156. goto UTF8_4;
  157. } else if (c < 0xf4) {
  158. UTF8_4:
  159. if ( (end && p+3 >= end) || (p[2]&0xc0) != 0x80 || (p[3]&0xc0) != 0x80) goto FAIL;
  160. if (len) *len = 4;
  161. #if STRICT_RFC3629
  162. /* RFC 3629 says all codes ending in fffe or ffff are illegal: */
  163. if ((p[1]&0xf)==0xf &&
  164. ((unsigned char*)p)[2] == 0xbf &&
  165. ((unsigned char*)p)[3] >= 0xbe) goto FAIL;
  166. #endif
  167. return
  168. ((p[0] & 0x07) << 18) +
  169. ((p[1] & 0x3f) << 12) +
  170. ((p[2] & 0x3f) << 6) +
  171. ((p[3] & 0x3f));
  172. } else if (c == 0xf4) {
  173. if (((unsigned char*)p)[1] > 0x8f) goto FAIL; /* after 0x10ffff */
  174. goto UTF8_4;
  175. } else {
  176. FAIL:
  177. if (len) *len = 1;
  178. #if ERRORS_TO_ISO8859_1
  179. return c;
  180. #else
  181. return 0xfffd; /* Unicode REPLACEMENT CHARACTER */
  182. #endif
  183. }
  184. }
  185. /*! Move \p p forward until it points to the start of a UTF-8
  186. character. If it already points at the start of one then it
  187. is returned unchanged. Any UTF-8 errors are treated as though each
  188. byte of the error is an individual character.
  189. \e start is the start of the string and is used to limit the
  190. backwards search for the start of a utf8 character.
  191. \e end is the end of the string and is assumed to be a break
  192. between characters. It is assumed to be greater than p.
  193. This function is for moving a pointer that was jumped to the
  194. middle of a string, such as when doing a binary search for
  195. a position. You should use either this or fl_utf8back() depending
  196. on which direction your algorithim can handle the pointer
  197. moving. Do not use this to scan strings, use fl_utf8decode()
  198. instead.
  199. */
  200. const char* fl_utf8fwd(const char* p, const char* start, const char* end)
  201. {
  202. const char* a;
  203. int len;
  204. /* if we are not pointing at a continuation character, we are done: */
  205. if ((*p&0xc0) != 0x80) return p;
  206. /* search backwards for a 0xc0 starting the character: */
  207. for (a = p-1; ; --a) {
  208. if (a < start) return p;
  209. if (!(a[0]&0x80)) return p;
  210. if ((a[0]&0x40)) break;
  211. }
  212. fl_utf8decode(a,end,&len);
  213. a += len;
  214. if (a > p) return a;
  215. return p;
  216. }
  217. /*! Move \p p backward until it points to the start of a UTF-8
  218. character. If it already points at the start of one then it
  219. is returned unchanged. Any UTF-8 errors are treated as though each
  220. byte of the error is an individual character.
  221. \e start is the start of the string and is used to limit the
  222. backwards search for the start of a UTF-8 character.
  223. \e end is the end of the string and is assumed to be a break
  224. between characters. It is assumed to be greater than p.
  225. If you wish to decrement a UTF-8 pointer, pass p-1 to this.
  226. */
  227. const char* fl_utf8back(const char* p, const char* start, const char* end)
  228. {
  229. const char* a;
  230. int len;
  231. /* if we are not pointing at a continuation character, we are done: */
  232. if ((*p&0xc0) != 0x80) return p;
  233. /* search backwards for a 0xc0 starting the character: */
  234. for (a = p-1; ; --a) {
  235. if (a < start) return p;
  236. if (!(a[0]&0x80)) return p;
  237. if ((a[0]&0x40)) break;
  238. }
  239. fl_utf8decode(a,end,&len);
  240. if (a+len > p) return a;
  241. return p;
  242. }
  243. /*! Returns number of bytes that utf8encode() will use to encode the
  244. character \p ucs. */
  245. int fl_utf8bytes(unsigned ucs) {
  246. if (ucs < 0x000080U) {
  247. return 1;
  248. } else if (ucs < 0x000800U) {
  249. return 2;
  250. } else if (ucs < 0x010000U) {
  251. return 3;
  252. } else if (ucs <= 0x10ffffU) {
  253. return 4;
  254. } else {
  255. return 3; /* length of the illegal character encoding */
  256. }
  257. }
  258. /*! Write the UTF-8 encoding of \e ucs into \e buf and return the
  259. number of bytes written. Up to 4 bytes may be written. If you know
  260. that \p ucs is less than 0x10000 then at most 3 bytes will be written.
  261. If you wish to speed this up, remember that anything less than 0x80
  262. is written as a single byte.
  263. If ucs is greater than 0x10ffff this is an illegal character
  264. according to RFC 3629. These are converted as though they are
  265. 0xFFFD (REPLACEMENT CHARACTER).
  266. RFC 3629 also says many other values for \p ucs are illegal (in
  267. the range 0xd800 to 0xdfff, or ending with 0xfffe or
  268. 0xffff). However I encode these as though they are legal, so that
  269. utf8encode/fl_utf8decode will be the identity for all codes between 0
  270. and 0x10ffff.
  271. */
  272. int fl_utf8encode(unsigned ucs, char* buf) {
  273. if (ucs < 0x000080U) {
  274. buf[0] = ucs;
  275. return 1;
  276. } else if (ucs < 0x000800U) {
  277. buf[0] = 0xc0 | (ucs >> 6);
  278. buf[1] = 0x80 | (ucs & 0x3F);
  279. return 2;
  280. } else if (ucs < 0x010000U) {
  281. buf[0] = 0xe0 | (ucs >> 12);
  282. buf[1] = 0x80 | ((ucs >> 6) & 0x3F);
  283. buf[2] = 0x80 | (ucs & 0x3F);
  284. return 3;
  285. } else if (ucs <= 0x0010ffffU) {
  286. buf[0] = 0xf0 | (ucs >> 18);
  287. buf[1] = 0x80 | ((ucs >> 12) & 0x3F);
  288. buf[2] = 0x80 | ((ucs >> 6) & 0x3F);
  289. buf[3] = 0x80 | (ucs & 0x3F);
  290. return 4;
  291. } else {
  292. /* encode 0xfffd: */
  293. buf[0] = 0xefU;
  294. buf[1] = 0xbfU;
  295. buf[2] = 0xbdU;
  296. return 3;
  297. }
  298. }
  299. /*! Convert a single 32-bit Unicode codepoint into an array of 16-bit
  300. characters. These are used by some system calls, especially on Windows.
  301. \p ucs is the value to convert.
  302. \p dst points at an array to write, and \p dstlen is the number of
  303. locations in this array. At most \p dstlen words will be
  304. written, and a 0 terminating word will be added if \p dstlen is
  305. large enough. Thus this function will never overwrite the buffer
  306. and will attempt return a zero-terminated string if space permits.
  307. If \p dstlen is zero then \p dst can be set to NULL and no data
  308. is written, but the length is returned.
  309. The return value is the number of 16-bit words that \e would be written
  310. to \p dst if it is large enough, not counting any terminating
  311. zero.
  312. If the return value is greater than \p dstlen it indicates truncation,
  313. you should then allocate a new array of size return+1 and call this again.
  314. Unicode characters in the range 0x10000 to 0x10ffff are converted to
  315. "surrogate pairs" which take two words each (in UTF-16 encoding).
  316. Typically, setting \p dstlen to 2 will ensure that any valid Unicode
  317. value can be converted, and setting \p dstlen to 3 or more will allow
  318. a NULL terminated sequence to be returned.
  319. */
  320. unsigned fl_ucs_to_Utf16(const unsigned ucs, unsigned short *dst, const unsigned dstlen)
  321. {
  322. /* The rule for direct conversion from UCS to UTF16 is:
  323. * - if UCS > 0x0010FFFF then UCS is invalid
  324. * - if UCS >= 0xD800 && UCS <= 0xDFFF UCS is invalid
  325. * - if UCS <= 0x0000FFFF then U16 = UCS, len = 1
  326. * - else
  327. * -- U16[0] = ((UCS - 0x00010000) >> 10) & 0x3FF + 0xD800
  328. * -- U16[1] = (UCS & 0x3FF) + 0xDC00
  329. * -- len = 2;
  330. */
  331. unsigned count; /* Count of converted UTF16 cells */
  332. unsigned short u16[4]; /* Alternate buffer if dst is not set */
  333. unsigned short *out; /* points to the active buffer */
  334. /* Ensure we have a valid buffer to write to */
  335. if((!dstlen) || (!dst)) {
  336. out = u16;
  337. } else {
  338. out = dst;
  339. }
  340. /* Convert from UCS to UTF16 */
  341. if((ucs > 0x0010FFFF) || /* UCS is too large */
  342. ((ucs > 0xD7FF) && (ucs < 0xE000))) { /* UCS in invalid range */
  343. out[0] = 0xFFFD; /* REPLACEMENT CHARACTER */
  344. count = 1;
  345. } else if(ucs < 0x00010000) {
  346. out[0] = (unsigned short)ucs;
  347. count = 1;
  348. } else if(dstlen < 2) { /* dst is too small for the result */
  349. out[0] = 0xFFFD; /* REPLACEMENT CHARACTER */
  350. count = 2;
  351. } else {
  352. out[0] = (((ucs - 0x00010000) >> 10) & 0x3FF) + 0xD800;
  353. out[1] = (ucs & 0x3FF) + 0xDC00;
  354. count = 2;
  355. }
  356. /* NULL terminate the output, if there is space */
  357. if(count < dstlen) { out[count] = 0; }
  358. return count;
  359. } /* fl_ucs_to_Utf16 */
  360. /*! Convert a UTF-8 sequence into an array of 16-bit characters. These
  361. are used by some system calls, especially on Windows.
  362. \p src points at the UTF-8, and \p srclen is the number of bytes to
  363. convert.
  364. \p dst points at an array to write, and \p dstlen is the number of
  365. locations in this array. At most \p dstlen-1 words will be
  366. written there, plus a 0 terminating word. Thus this function
  367. will never overwrite the buffer and will always return a
  368. zero-terminated string. If \p dstlen is zero then \p dst can be
  369. null and no data is written, but the length is returned.
  370. The return value is the number of 16-bit words that \e would be written
  371. to \p dst if it were long enough, not counting the terminating
  372. zero. If the return value is greater or equal to \p dstlen it
  373. indicates truncation, you can then allocate a new array of size
  374. return+1 and call this again.
  375. Errors in the UTF-8 are converted as though each byte in the
  376. erroneous string is in the Microsoft CP1252 encoding. This allows
  377. ISO-8859-1 text mistakenly identified as UTF-8 to be printed
  378. correctly.
  379. Unicode characters in the range 0x10000 to 0x10ffff are converted to
  380. "surrogate pairs" which take two words each (this is called UTF-16
  381. encoding).
  382. */
  383. unsigned fl_utf8toUtf16(const char* src, unsigned srclen,
  384. unsigned short* dst, unsigned dstlen)
  385. {
  386. const char* p = src;
  387. const char* e = src+srclen;
  388. unsigned count = 0;
  389. if (dstlen) for (;;) {
  390. if (p >= e) {dst[count] = 0; return count;}
  391. if (!(*p & 0x80)) { /* ascii */
  392. dst[count] = *p++;
  393. } else {
  394. int len; unsigned ucs = fl_utf8decode(p,e,&len);
  395. p += len;
  396. if (ucs < 0x10000) {
  397. dst[count] = ucs;
  398. } else {
  399. /* make a surrogate pair: */
  400. if (count+2 >= dstlen) {dst[count] = 0; count += 2; break;}
  401. dst[count] = (((ucs-0x10000u)>>10)&0x3ff) | 0xd800;
  402. dst[++count] = (ucs&0x3ff) | 0xdc00;
  403. }
  404. }
  405. if (++count == dstlen) {dst[count-1] = 0; break;}
  406. }
  407. /* we filled dst, measure the rest: */
  408. while (p < e) {
  409. if (!(*p & 0x80)) p++;
  410. else {
  411. int len; unsigned ucs = fl_utf8decode(p,e,&len);
  412. p += len;
  413. if (ucs >= 0x10000) ++count;
  414. }
  415. ++count;
  416. }
  417. return count;
  418. }
  419. /**
  420. Converts a UTF-8 string into a wide character string.
  421. This function generates 32-bit wchar_t (e.g. "ucs4" as it were) except
  422. on Windows where it is equivalent to fl_utf8toUtf16 and returns
  423. UTF-16.
  424. \p src points at the UTF-8, and \p srclen is the number of bytes to
  425. convert.
  426. \p dst points at an array to write, and \p dstlen is the number of
  427. locations in this array. At most \p dstlen-1 wchar_t will be
  428. written there, plus a 0 terminating wchar_t.
  429. The return value is the number of wchar_t that \e would be written
  430. to \p dst if it were long enough, not counting the terminating
  431. zero. If the return value is greater or equal to \p dstlen it
  432. indicates truncation, you can then allocate a new array of size
  433. return+1 and call this again.
  434. Notice that sizeof(wchar_t) is 2 on Windows and is 4 on Linux
  435. and most other systems. Where wchar_t is 16 bits, Unicode
  436. characters in the range 0x10000 to 0x10ffff are converted to
  437. "surrogate pairs" which take two words each (this is called UTF-16
  438. encoding). If wchar_t is 32 bits this rather nasty problem is
  439. avoided.
  440. Note that Windows includes Cygwin, i.e. compiled with Cygwin's POSIX
  441. layer (cygwin1.dll, --enable-cygwin), either native (GDI) or X11.
  442. */
  443. unsigned fl_utf8towc(const char* src, unsigned srclen,
  444. wchar_t* dst, unsigned dstlen)
  445. {
  446. #if defined(WIN32) || defined(__CYGWIN__)
  447. return fl_utf8toUtf16(src, srclen, (unsigned short*)dst, dstlen);
  448. #else
  449. const char* p = src;
  450. const char* e = src+srclen;
  451. unsigned count = 0;
  452. if (dstlen) for (;;) {
  453. if (p >= e) {
  454. dst[count] = 0;
  455. return count;
  456. }
  457. if (!(*p & 0x80)) { /* ascii */
  458. dst[count] = *p++;
  459. } else {
  460. int len; unsigned ucs = fl_utf8decode(p,e,&len);
  461. p += len;
  462. dst[count] = (wchar_t)ucs;
  463. }
  464. if (++count == dstlen) {dst[count-1] = 0; break;}
  465. }
  466. /* we filled dst, measure the rest: */
  467. while (p < e) {
  468. if (!(*p & 0x80)) p++;
  469. else {
  470. int len; fl_utf8decode(p,e,&len);
  471. p += len;
  472. }
  473. ++count;
  474. }
  475. return count;
  476. #endif
  477. }
  478. /*! Convert a UTF-8 sequence into an array of 1-byte characters.
  479. If the UTF-8 decodes to a character greater than 0xff then it is
  480. replaced with '?'.
  481. Errors in the UTF-8 are converted as individual bytes, same as
  482. fl_utf8decode() does. This allows ISO-8859-1 text mistakenly identified
  483. as UTF-8 to be printed correctly (and possibly CP1512 on Windows).
  484. \p src points at the UTF-8, and \p srclen is the number of bytes to
  485. convert.
  486. Up to \p dstlen bytes are written to \p dst, including a null
  487. terminator. The return value is the number of bytes that would be
  488. written, not counting the null terminator. If greater or equal to
  489. \p dstlen then if you malloc a new array of size n+1 you will have
  490. the space needed for the entire string. If \p dstlen is zero then
  491. nothing is written and this call just measures the storage space
  492. needed.
  493. */
  494. unsigned fl_utf8toa(const char* src, unsigned srclen,
  495. char* dst, unsigned dstlen)
  496. {
  497. const char* p = src;
  498. const char* e = src+srclen;
  499. unsigned count = 0;
  500. if (dstlen) for (;;) {
  501. unsigned char c;
  502. if (p >= e) {dst[count] = 0; return count;}
  503. c = *(unsigned char*)p;
  504. if (c < 0xC2) { /* ascii or bad code */
  505. dst[count] = c;
  506. p++;
  507. } else {
  508. int len; unsigned ucs = fl_utf8decode(p,e,&len);
  509. p += len;
  510. if (ucs < 0x100) dst[count] = ucs;
  511. else dst[count] = '?';
  512. }
  513. if (++count >= dstlen) {dst[count-1] = 0; break;}
  514. }
  515. /* we filled dst, measure the rest: */
  516. while (p < e) {
  517. if (!(*p & 0x80)) p++;
  518. else {
  519. int len;
  520. fl_utf8decode(p,e,&len);
  521. p += len;
  522. }
  523. ++count;
  524. }
  525. return count;
  526. }
  527. /*! Turn "wide characters" as returned by some system calls
  528. (especially on Windows) into UTF-8.
  529. Up to \p dstlen bytes are written to \p dst, including a null
  530. terminator. The return value is the number of bytes that would be
  531. written, not counting the null terminator. If greater or equal to
  532. \p dstlen then if you malloc a new array of size n+1 you will have
  533. the space needed for the entire string. If \p dstlen is zero then
  534. nothing is written and this call just measures the storage space
  535. needed.
  536. \p srclen is the number of words in \p src to convert. On Windows
  537. this is not necessarily the number of characters, due to there
  538. possibly being "surrogate pairs" in the UTF-16 encoding used.
  539. On Unix wchar_t is 32 bits and each location is a character.
  540. On Unix if a \p src word is greater than 0x10ffff then this is an
  541. illegal character according to RFC 3629. These are converted as
  542. though they are 0xFFFD (REPLACEMENT CHARACTER). Characters in the
  543. range 0xd800 to 0xdfff, or ending with 0xfffe or 0xffff are also
  544. illegal according to RFC 3629. However I encode these as though
  545. they are legal, so that fl_utf8towc will return the original data.
  546. On Windows "surrogate pairs" are converted to a single character
  547. and UTF-8 encoded (as 4 bytes). Mismatched halves of surrogate
  548. pairs are converted as though they are individual characters.
  549. */
  550. unsigned fl_utf8fromwc(char* dst, unsigned dstlen,
  551. const wchar_t* src, unsigned srclen) {
  552. unsigned i = 0;
  553. unsigned count = 0;
  554. if (dstlen) for (;;) {
  555. unsigned ucs;
  556. if (i >= srclen) {dst[count] = 0; return count;}
  557. ucs = src[i++];
  558. if (ucs < 0x80U) {
  559. dst[count++] = ucs;
  560. if (count >= dstlen) {dst[count-1] = 0; break;}
  561. } else if (ucs < 0x800U) { /* 2 bytes */
  562. if (count+2 >= dstlen) {dst[count] = 0; count += 2; break;}
  563. dst[count++] = 0xc0 | (ucs >> 6);
  564. dst[count++] = 0x80 | (ucs & 0x3F);
  565. #if defined(WIN32) || defined(__CYGWIN__)
  566. } else if (ucs >= 0xd800 && ucs <= 0xdbff && i < srclen &&
  567. src[i] >= 0xdc00 && src[i] <= 0xdfff) {
  568. /* surrogate pair */
  569. unsigned ucs2 = src[i++];
  570. ucs = 0x10000U + ((ucs&0x3ff)<<10) + (ucs2&0x3ff);
  571. /* all surrogate pairs turn into 4-byte utf8 */
  572. #else
  573. } else if (ucs >= 0x10000) {
  574. if (ucs > 0x10ffff) {
  575. ucs = 0xfffd;
  576. goto J1;
  577. }
  578. #endif
  579. if (count+4 >= dstlen) {dst[count] = 0; count += 4; break;}
  580. dst[count++] = 0xf0 | (ucs >> 18);
  581. dst[count++] = 0x80 | ((ucs >> 12) & 0x3F);
  582. dst[count++] = 0x80 | ((ucs >> 6) & 0x3F);
  583. dst[count++] = 0x80 | (ucs & 0x3F);
  584. } else {
  585. #if !(defined(WIN32) || defined(__CYGWIN__))
  586. J1:
  587. #endif
  588. /* all others are 3 bytes: */
  589. if (count+3 >= dstlen) {dst[count] = 0; count += 3; break;}
  590. dst[count++] = 0xe0 | (ucs >> 12);
  591. dst[count++] = 0x80 | ((ucs >> 6) & 0x3F);
  592. dst[count++] = 0x80 | (ucs & 0x3F);
  593. }
  594. }
  595. /* we filled dst, measure the rest: */
  596. while (i < srclen) {
  597. unsigned ucs = src[i++];
  598. if (ucs < 0x80U) {
  599. count++;
  600. } else if (ucs < 0x800U) { /* 2 bytes */
  601. count += 2;
  602. #if defined(WIN32) || defined(__CYGWIN__)
  603. } else if (ucs >= 0xd800 && ucs <= 0xdbff && i < srclen-1 &&
  604. src[i+1] >= 0xdc00 && src[i+1] <= 0xdfff) {
  605. /* surrogate pair */
  606. ++i;
  607. #else
  608. } else if (ucs >= 0x10000 && ucs <= 0x10ffff) {
  609. #endif
  610. count += 4;
  611. } else {
  612. count += 3;
  613. }
  614. }
  615. return count;
  616. }
  617. /*! Convert an ISO-8859-1 (ie normal c-string) byte stream to UTF-8.
  618. It is possible this should convert Microsoft's CP1252 to UTF-8
  619. instead. This would translate the codes in the range 0x80-0x9f
  620. to different characters. Currently it does not do this.
  621. Up to \p dstlen bytes are written to \p dst, including a null
  622. terminator. The return value is the number of bytes that would be
  623. written, not counting the null terminator. If greater or equal to
  624. \p dstlen then if you malloc a new array of size n+1 you will have
  625. the space needed for the entire string. If \p dstlen is zero then
  626. nothing is written and this call just measures the storage space
  627. needed.
  628. \p srclen is the number of bytes in \p src to convert.
  629. If the return value equals \p srclen then this indicates that
  630. no conversion is necessary, as only ASCII characters are in the
  631. string.
  632. */
  633. unsigned fl_utf8froma(char* dst, unsigned dstlen,
  634. const char* src, unsigned srclen) {
  635. const char* p = src;
  636. const char* e = src+srclen;
  637. unsigned count = 0;
  638. if (dstlen) for (;;) {
  639. unsigned char ucs;
  640. if (p >= e) {dst[count] = 0; return count;}
  641. ucs = *(unsigned char*)p++;
  642. if (ucs < 0x80U) {
  643. dst[count++] = ucs;
  644. if (count >= dstlen) {dst[count-1] = 0; break;}
  645. } else { /* 2 bytes (note that CP1252 translate could make 3 bytes!) */
  646. if (count+2 >= dstlen) {dst[count] = 0; count += 2; break;}
  647. dst[count++] = 0xc0 | (ucs >> 6);
  648. dst[count++] = 0x80 | (ucs & 0x3F);
  649. }
  650. }
  651. /* we filled dst, measure the rest: */
  652. while (p < e) {
  653. unsigned char ucs = *(unsigned char*)p++;
  654. if (ucs < 0x80U) {
  655. count++;
  656. } else {
  657. count += 2;
  658. }
  659. }
  660. return count;
  661. }
  662. #ifdef WIN32
  663. # include <windows.h>
  664. #endif
  665. /*! Return true if the "locale" seems to indicate that UTF-8 encoding
  666. is used. If true the fl_utf8to_mb and fl_utf8from_mb don't do anything
  667. useful.
  668. <i>It is highly recommended that you change your system so this
  669. does return true.</i> On Windows this is done by setting the
  670. "codepage" to CP_UTF8. On Unix this is done by setting $LC_CTYPE
  671. to a string containing the letters "utf" or "UTF" in it, or by
  672. deleting all $LC* and $LANG environment variables. In the future
  673. it is likely that all non-Asian Unix systems will return true,
  674. due to the compatibility of UTF-8 with ISO-8859-1.
  675. */
  676. int fl_utf8locale(void) {
  677. static int ret = 2;
  678. if (ret == 2) {
  679. #ifdef WIN32
  680. ret = GetACP() == CP_UTF8;
  681. #else
  682. char* s;
  683. ret = 1; /* assume UTF-8 if no locale */
  684. if (((s = getenv("LC_CTYPE")) && *s) ||
  685. ((s = getenv("LC_ALL")) && *s) ||
  686. ((s = getenv("LANG")) && *s)) {
  687. ret = (strstr(s,"utf") || strstr(s,"UTF"));
  688. }
  689. #endif
  690. }
  691. return ret;
  692. }
  693. /*! Convert the UTF-8 used by FLTK to the locale-specific encoding
  694. used for filenames (and sometimes used for data in files).
  695. Unfortunately due to stupid design you will have to do this as
  696. needed for filenames. This is a bug on both Unix and Windows.
  697. Up to \p dstlen bytes are written to \p dst, including a null
  698. terminator. The return value is the number of bytes that would be
  699. written, not counting the null terminator. If greater or equal to
  700. \p dstlen then if you malloc a new array of size n+1 you will have
  701. the space needed for the entire string. If \p dstlen is zero then
  702. nothing is written and this call just measures the storage space
  703. needed.
  704. If fl_utf8locale() returns true then this does not change the data.
  705. */
  706. unsigned fl_utf8to_mb(const char* src, unsigned srclen,
  707. char* dst, unsigned dstlen)
  708. {
  709. if (!fl_utf8locale()) {
  710. #ifdef WIN32
  711. wchar_t lbuf[1024];
  712. wchar_t* buf = lbuf;
  713. unsigned length = fl_utf8towc(src, srclen, buf, 1024);
  714. unsigned ret;
  715. if (length >= 1024) {
  716. buf = (wchar_t*)(malloc((length+1)*sizeof(wchar_t)));
  717. fl_utf8towc(src, srclen, buf, length+1);
  718. }
  719. if (dstlen) {
  720. /* apparently this does not null-terminate, even though msdn
  721. * documentation claims it does:
  722. */
  723. ret =
  724. WideCharToMultiByte(GetACP(), 0, buf, length, dst, dstlen, 0, 0);
  725. dst[ret] = 0;
  726. }
  727. /* if it overflows or measuring length, get the actual length: */
  728. if (dstlen==0 || ret >= dstlen-1)
  729. ret =
  730. WideCharToMultiByte(GetACP(), 0, buf, length, 0, 0, 0, 0);
  731. if (buf != lbuf) free((void*)buf);
  732. return ret;
  733. #else
  734. wchar_t lbuf[1024];
  735. wchar_t* buf = lbuf;
  736. unsigned length = fl_utf8towc(src, srclen, buf, 1024);
  737. int ret;
  738. if (length >= 1024) {
  739. buf = (wchar_t*)(malloc((length+1)*sizeof(wchar_t)));
  740. fl_utf8towc(src, srclen, buf, length+1);
  741. }
  742. if (dstlen) {
  743. ret = wcstombs(dst, buf, dstlen);
  744. if (ret >= dstlen-1) ret = wcstombs(0,buf,0);
  745. } else {
  746. ret = wcstombs(0,buf,0);
  747. }
  748. if (buf != lbuf) free((void*)buf);
  749. if (ret >= 0) return (unsigned)ret;
  750. /* on any errors we return the UTF-8 as raw text...*/
  751. #endif
  752. }
  753. /* identity transform: */
  754. if (srclen < dstlen) {
  755. memcpy(dst, src, srclen);
  756. dst[srclen] = 0;
  757. } else {
  758. /* Buffer insufficent or buffer query */
  759. }
  760. return srclen;
  761. }
  762. /*! Convert a filename from the locale-specific multibyte encoding
  763. used by Windows to UTF-8 as used by FLTK.
  764. Up to \p dstlen bytes are written to \p dst, including a null
  765. terminator. The return value is the number of bytes that would be
  766. written, not counting the null terminator. If greater or equal to
  767. \p dstlen then if you malloc a new array of size n+1 you will have
  768. the space needed for the entire string. If \p dstlen is zero then
  769. nothing is written and this call just measures the storage space
  770. needed.
  771. On Unix or on Windows when a UTF-8 locale is in effect, this
  772. does not change the data.
  773. You may also want to check if fl_utf8test() returns non-zero, so that
  774. the filesystem can store filenames in UTF-8 encoding regardless of
  775. the locale.
  776. */
  777. unsigned fl_utf8from_mb(char* dst, unsigned dstlen,
  778. const char* src, unsigned srclen)
  779. {
  780. if (!fl_utf8locale()) {
  781. #ifdef WIN32
  782. wchar_t lbuf[1024];
  783. wchar_t* buf = lbuf;
  784. unsigned length;
  785. unsigned ret;
  786. length = MultiByteToWideChar(GetACP(), 0, src, srclen, buf, 1024);
  787. if ((length == 0)&&(GetLastError()==ERROR_INSUFFICIENT_BUFFER)) {
  788. length = MultiByteToWideChar(GetACP(), 0, src, srclen, 0, 0);
  789. buf = (wchar_t*)(malloc(length*sizeof(wchar_t)));
  790. MultiByteToWideChar(GetACP(), 0, src, srclen, buf, length);
  791. }
  792. ret = fl_utf8fromwc(dst, dstlen, buf, length);
  793. if (buf != lbuf) free((void*)buf);
  794. return ret;
  795. #else
  796. wchar_t lbuf[1024];
  797. wchar_t* buf = lbuf;
  798. int length;
  799. unsigned ret;
  800. length = mbstowcs(buf, src, 1024);
  801. if (length >= 1024) {
  802. length = mbstowcs(0, src, 0)+1;
  803. buf = (wchar_t*)(malloc(length*sizeof(wchar_t)));
  804. mbstowcs(buf, src, length);
  805. }
  806. if (length >= 0) {
  807. ret = fl_utf8fromwc(dst, dstlen, buf, length);
  808. if (buf != lbuf) free((void*)buf);
  809. return ret;
  810. }
  811. /* errors in conversion return the UTF-8 unchanged */
  812. #endif
  813. }
  814. /* identity transform: */
  815. if (srclen < dstlen) {
  816. memcpy(dst, src, srclen);
  817. dst[srclen] = 0;
  818. } else {
  819. /* Buffer insufficent or buffer query */
  820. }
  821. return srclen;
  822. }
  823. /*! Examines the first \p srclen bytes in \p src and returns a verdict
  824. on whether it is UTF-8 or not.
  825. - Returns 0 if there is any illegal UTF-8 sequences, using the
  826. same rules as fl_utf8decode(). Note that some UCS values considered
  827. illegal by RFC 3629, such as 0xffff, are considered legal by this.
  828. - Returns 1 if there are only single-byte characters (ie no bytes
  829. have the high bit set). This is legal UTF-8, but also indicates
  830. plain ASCII. It also returns 1 if \p srclen is zero.
  831. - Returns 2 if there are only characters less than 0x800.
  832. - Returns 3 if there are only characters less than 0x10000.
  833. - Returns 4 if there are characters in the 0x10000 to 0x10ffff range.
  834. Because there are many illegal sequences in UTF-8, it is almost
  835. impossible for a string in another encoding to be confused with
  836. UTF-8. This is very useful for transitioning Unix to UTF-8
  837. filenames, you can simply test each filename with this to decide
  838. if it is UTF-8 or in the locale encoding. My hope is that if
  839. this is done we will be able to cleanly transition to a locale-less
  840. encoding.
  841. */
  842. int fl_utf8test(const char* src, unsigned srclen) {
  843. int ret = 1;
  844. const char* p = src;
  845. const char* e = src+srclen;
  846. while (p < e) {
  847. if (*p & 0x80) {
  848. int len; fl_utf8decode(p,e,&len);
  849. if (len < 2) return 0;
  850. if (len > ret) ret = len;
  851. p += len;
  852. } else {
  853. p++;
  854. }
  855. }
  856. return ret;
  857. }
  858. /* forward declare mk_wcwidth() as static so the name is not visible.
  859. */
  860. static int mk_wcwidth(unsigned int ucs);
  861. /* include the c source directly so it's contents are only visible here
  862. */
  863. #include "xutf8/mk_wcwidth.c"
  864. /** wrapper to adapt Markus Kuhn's implementation of wcwidth() for FLTK
  865. \param [in] ucs Unicode character value
  866. \returns width of character in columns
  867. See http://www.cl.cam.ac.uk/~mgk25/ucs/wcwidth.c for Markus Kuhn's
  868. original implementation of wcwidth() and wcswidth()
  869. (defined in IEEE Std 1002.1-2001) for Unicode.
  870. \b WARNING: this function returns widths for "raw" Unicode characters.
  871. It does not even try to map C1 control characters (0x80 to 0x9F) to
  872. CP1252, and C0/C1 control characters and DEL will return -1.
  873. You are advised to use fl_width(const char* src) instead.
  874. */
  875. int fl_wcwidth_(unsigned int ucs) {
  876. return mk_wcwidth(ucs);
  877. }
  878. /** extended wrapper around fl_wcwidth_(unsigned int ucs) function.
  879. \param[in] src pointer to start of UTF-8 byte sequence
  880. \returns width of character in columns
  881. Depending on build options, this function may map C1 control
  882. characters (0x80 to 0x9f) to CP1252, and return the width of
  883. that character instead. This is not the same behaviour as
  884. fl_wcwidth_(unsigned int ucs) .
  885. Note that other control characters and DEL will still return -1,
  886. so if you want different behaviour, you need to test for those
  887. characters before calling fl_wcwidth(), and handle them separately.
  888. */
  889. int fl_wcwidth(const char* src) {
  890. int len = fl_utf8len(*src);
  891. int ret = 0;
  892. unsigned int ucs = fl_utf8decode(src, src+len, &ret);
  893. int width = fl_wcwidth_(ucs);
  894. return width;
  895. }
  896. /** @} */
  897. /*
  898. * End of "$Id: fl_utf.c 8864 2011-07-19 04:49:30Z greg.ercolano $".
  899. */