You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

996 lines
33KB

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