unicode.h 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. /////////////////////////////////////////////////////////////////////////////
  2. // Name: unicode.h
  3. // Purpose: topic overview
  4. // Author: wxWidgets team
  5. // Licence: wxWindows licence
  6. /////////////////////////////////////////////////////////////////////////////
  7. /**
  8. @page overview_unicode Unicode Support in wxWidgets
  9. @tableofcontents
  10. This section describes how does wxWidgets support Unicode and how can it affect
  11. your programs.
  12. Notice that Unicode support has changed radically in wxWidgets 3.0 and a lot of
  13. existing material pertaining to the previous versions of the library is not
  14. correct any more. Please see @ref overview_changes_unicode for the details of
  15. these changes.
  16. You can skip the first two sections if you're already familiar with Unicode and
  17. wish to jump directly in the details of its support in the library.
  18. @section overview_unicode_what What is Unicode?
  19. Unicode is a standard for character encoding which addresses the shortcomings
  20. of the previous standards (e.g. the ASCII standard), by using 8, 16 or 32 bits
  21. for encoding each character.
  22. This allows enough code points (see below for the definition) sufficient to
  23. encode all of the world languages at once.
  24. More details about Unicode may be found at http://www.unicode.org/.
  25. From a practical point of view, using Unicode is almost a requirement when
  26. writing applications for international audience. Moreover, any application
  27. reading files which it didn't produce or receiving data from the network from
  28. other services should be ready to deal with Unicode.
  29. @section overview_unicode_encodings Unicode Representations and Terminology
  30. When working with Unicode, it's important to define the meaning of some terms.
  31. A <b><em>glyph</em></b> is a particular image (usually part of a font) that
  32. represents a character or part of a character.
  33. Any character may have one or more glyph associated; e.g. some of the possible
  34. glyphs for the capital letter 'A' are:
  35. @image html overview_unicode_glyphs.png
  36. Unicode assigns each character of almost any existing alphabet/script a number,
  37. which is called <b><em>code point</em></b>; it's typically indicated in documentation
  38. manuals and in the Unicode website as @c U+xxxx where @c xxxx is an hexadecimal number.
  39. Note that typically one character is assigned exactly one code point, but there
  40. are exceptions; the so-called <em>precomposed characters</em>
  41. (see http://en.wikipedia.org/wiki/Precomposed_character) or the <em>ligatures</em>.
  42. In these cases a single "character" may be mapped to more than one code point or
  43. vice versa more than one character may be mapped to a single code point.
  44. The Unicode standard divides the space of all possible code points in <b><em>planes</em></b>;
  45. a plane is a range of 65,536 (1000016) contiguous Unicode code points.
  46. Planes are numbered from 0 to 16, where the first one is the @e BMP, or Basic
  47. Multilingual Plane.
  48. The BMP contains characters for all modern languages, and a large number of
  49. special characters. The other planes in fact contain mainly historic scripts,
  50. special-purpose characters or are unused.
  51. Code points are represented in computer memory as a sequence of one or more
  52. <b><em>code units</em></b>, where a code unit is a unit of memory: 8, 16, or 32 bits.
  53. More precisely, a code unit is the minimal bit combination that can represent a
  54. unit of encoded text for processing or interchange.
  55. The <b><em>UTF</em></b> or Unicode Transformation Formats are algorithms mapping the Unicode
  56. code points to code unit sequences. The simplest of them is <b>UTF-32</b> where
  57. each code unit is composed by 32 bits (4 bytes) and each code point is always
  58. represented by a single code unit (fixed length encoding).
  59. (Note that even UTF-32 is still not completely trivial as the mapping is different
  60. for little and big-endian architectures). UTF-32 is commonly used under Unix systems for
  61. internal representation of Unicode strings.
  62. Another very widespread standard is <b>UTF-16</b> which is used by Microsoft Windows:
  63. it encodes the first (approximately) 64 thousands of Unicode code points
  64. (the BMP plane) using 16-bit code units (2 bytes) and uses a pair of 16-bit code
  65. units to encode the characters beyond this. These pairs are called @e surrogate.
  66. Thus UTF16 uses a variable number of code units to encode each code point.
  67. Finally, the most widespread encoding used for the external Unicode storage
  68. (e.g. files and network protocols) is <b>UTF-8</b> which is byte-oriented and so
  69. avoids the endianness ambiguities of UTF-16 and UTF-32.
  70. UTF-8 uses code units of 8 bits (1 byte); code points beyond the usual english
  71. alphabet are represented using a variable number of bytes, which makes it less
  72. efficient than UTF-32 for internal representation.
  73. As visual aid to understand the differences between the various concepts described
  74. so far, look at the different UTF representations of the same code point:
  75. @image html overview_unicode_codes.png
  76. In this particular case UTF8 requires more space than UTF16 (3 bytes instead of 2).
  77. Note that from the C/C++ programmer perspective the situation is further complicated
  78. by the fact that the standard type @c wchar_t which is usually used to represent the
  79. Unicode ("wide") strings in C/C++ doesn't have the same size on all platforms.
  80. It is 4 bytes under Unix systems, corresponding to the tradition of using
  81. UTF-32, but only 2 bytes under Windows which is required by compatibility with
  82. the OS which uses UTF-16.
  83. Typically when UTF8 is used, code units are stored into @c char types, since
  84. @c char are 8bit wide on almost all systems; when using UTF16 typically code
  85. units are stored into @c wchar_t types since @c wchar_t is at least 16bits on
  86. all systems. This is also the approach used by wxString.
  87. See @ref overview_string for more info.
  88. See also http://unicode.org/glossary/ for the official definitions of the
  89. terms reported above.
  90. @section overview_unicode_supportin Unicode Support in wxWidgets
  91. @subsection overview_unicode_support_default Unicode is Always Used by Default
  92. Since wxWidgets 3.0 Unicode support is always enabled and while building the
  93. library without it is still possible, it is not recommended any longer and will
  94. cease to be supported in the near future. This means that internally only
  95. Unicode strings are used and that, under Microsoft Windows, Unicode system API
  96. is used which means that wxWidgets programs require the Microsoft Layer for
  97. Unicode to run on Windows 95/98/ME.
  98. However, unlike the Unicode build mode of the previous versions of wxWidgets, this
  99. support is mostly transparent: you can still continue to work with the @b narrow
  100. (i.e. current locale-encoded @c char*) strings even if @b wide
  101. (i.e. UTF16-encoded @c wchar_t* or UTF8-encoded @c char*) strings are also
  102. supported. Any wxWidgets function accepts arguments of either type as both
  103. kinds of strings are implicitly converted to wxString, so both
  104. @code
  105. wxMessageBox("Hello, world!");
  106. @endcode
  107. and the somewhat less usual
  108. @code
  109. wxMessageBox(L"Salut \u00E0 toi!"); // U+00E0 is "Latin Small Letter a with Grave"
  110. @endcode
  111. work as expected.
  112. Notice that the narrow strings used with wxWidgets are @e always assumed to be
  113. in the current locale encoding, so writing
  114. @code
  115. wxMessageBox("Salut à toi!");
  116. @endcode
  117. wouldn't work if the encoding used on the user system is incompatible with
  118. ISO-8859-1 (or even if the sources were compiled under different locale
  119. in the case of gcc). In particular, the most common encoding used under
  120. modern Unix systems is UTF-8 and as the string above is not a valid UTF-8 byte
  121. sequence, nothing would be displayed at all in this case. Thus it is important
  122. to <b>never use 8-bit (instead of 7-bit) characters directly in the program source</b>
  123. but use wide strings or, alternatively, write:
  124. @code
  125. wxMessageBox(wxString::FromUTF8("Salut \xC3\xA0 toi!"));
  126. // in UTF8 the character U+00E0 is encoded as 0xC3A0
  127. @endcode
  128. In a similar way, wxString provides access to its contents as either @c wchar_t or
  129. @c char character buffer. Of course, the latter only works if the string contains
  130. data representable in the current locale encoding. This will always be the case
  131. if the string had been initially constructed from a narrow string or if it
  132. contains only 7-bit ASCII data but otherwise this conversion is not guaranteed
  133. to succeed. And as with wxString::FromUTF8() example above, you can always use
  134. wxString::ToUTF8() to retrieve the string contents in UTF-8 encoding -- this,
  135. unlike converting to @c char* using the current locale, never fails.
  136. For more info about how wxString works, please see the @ref overview_string.
  137. To summarize, Unicode support in wxWidgets is mostly @b transparent for the
  138. application and if you use wxString objects for storing all the character data
  139. in your program there is really nothing special to do. However you should be
  140. aware of the potential problems covered by the following section.
  141. @subsection overview_unicode_support_utf Choosing Unicode Representation
  142. wxWidgets uses the system @c wchar_t in wxString implementation by default
  143. under all systems. Thus, under Microsoft Windows, UCS-2 (simplified version of
  144. UTF-16 without support for surrogate characters) is used as @c wchar_t is 2
  145. bytes on this platform. Under Unix systems, including Mac OS X, UCS-4 (also
  146. known as UTF-32) is used by default, however it is also possible to build
  147. wxWidgets to use UTF-8 internally by passing @c --enable-utf8 option to
  148. configure.
  149. The interface provided by wxString is the same independently of the format used
  150. internally. However different formats have specific advantages and
  151. disadvantages. Notably, under Unix, the underlying graphical toolkit (e.g.
  152. GTK+) usually uses UTF-8 encoded strings and using the same representations for
  153. the strings in wxWidgets allows to avoid conversion from UTF-32 to UTF-8 and
  154. vice versa each time a string is shown in the UI or retrieved from it. The
  155. overhead of such conversions is usually negligible for small strings but may be
  156. important for some programs. If you believe that it would be advantageous to
  157. use UTF-8 for the strings in your particular application, you may rebuild
  158. wxWidgets to use UTF-8 as explained above (notice that this is currently not
  159. supported under Microsoft Windows and arguably doesn't make much sense there as
  160. Windows itself uses UTF-16 and not UTF-8) but be sure to be aware of the
  161. performance implications (see @ref overview_unicode_performance) of using UTF-8
  162. in wxString before doing this!
  163. Generally speaking you should only use non-default UTF-8 build in specific
  164. circumstances e.g. building for resource-constrained systems where the overhead
  165. of conversions (and also reduced memory usage of UTF-8 compared to UTF-32 for
  166. the European languages) can be important. If the environment in which your
  167. program is running is under your control -- as is quite often the case in such
  168. scenarios -- consider ensuring that the system always uses UTF-8 locale and
  169. use @c --enable-utf8only configure option to disable support for the other
  170. locales and consider all strings to be in UTF-8. This further reduces the code
  171. size and removes the need for conversions in more cases.
  172. @subsection overview_unicode_settings Unicode Related Preprocessor Symbols
  173. @c wxUSE_UNICODE is defined as 1 now to indicate Unicode support. It can be
  174. explicitly set to 0 in @c setup.h under MSW or you can use @c --disable-unicode
  175. under Unix but doing this is strongly discouraged. By default, @c
  176. wxUSE_UNICODE_WCHAR is also defined as 1, however in UTF-8 build (described in
  177. the previous section), it is set to 0 and @c wxUSE_UNICODE_UTF8, which is
  178. usually 0, is set to 1 instead. In the latter case, @c wxUSE_UTF8_LOCALE_ONLY
  179. can also be set to 1 to indicate that all strings are considered to be in UTF-8.
  180. @section overview_unicode_pitfalls Potential Unicode Pitfalls
  181. The problems can be separated into three broad classes:
  182. @subsection overview_unicode_compilation_errors Unicode-Related Compilation Errors
  183. Because of the need to support implicit conversions to both @c char and
  184. @c wchar_t, wxString implementation is rather involved and many of its operators
  185. don't return the types which they could be naively expected to return.
  186. For example, the @c operator[] doesn't return neither a @c char nor a @c wchar_t
  187. but an object of a helper class wxUniChar or wxUniCharRef which is implicitly
  188. convertible to either. Usually you don't need to worry about this as the
  189. conversions do their work behind the scenes however in some cases it doesn't
  190. work. Here are some examples, using a wxString object @c s and some integer @c
  191. n:
  192. - Writing @code switch ( s[n] ) @endcode doesn't work because the argument of
  193. the switch statement must be an integer expression so you need to replace
  194. @c s[n] with @code s[n].GetValue() @endcode. You may also force the
  195. conversion to @c char or @c wchar_t by using an explicit cast but beware that
  196. converting the value to char uses the conversion to current locale and may
  197. return 0 if it fails. Finally notice that writing @code (wxChar)s[n] @endcode
  198. works both with wxWidgets 3.0 and previous library versions and so should be
  199. used for writing code which should be compatible with both 2.8 and 3.0.
  200. - Similarly, @code &s[n] @endcode doesn't yield a pointer to char so you may
  201. not pass it to functions expecting @c char* or @c wchar_t*. Consider using
  202. string iterators instead if possible or replace this expression with
  203. @code s.c_str() + n @endcode otherwise.
  204. Another class of problems is related to the fact that the value returned by
  205. @c c_str() itself is also not just a pointer to a buffer but a value of helper
  206. class wxCStrData which is implicitly convertible to both narrow and wide
  207. strings. Again, this mostly will be unnoticeable but can result in some
  208. problems:
  209. - You shouldn't pass @c c_str() result to vararg functions such as standard
  210. @c printf(). Some compilers (notably g++) warn about this but even if they
  211. don't, this @code printf("Hello, %s", s.c_str()) @endcode is not going to
  212. work. It can be corrected in one of the following ways:
  213. - Preferred: @code wxPrintf("Hello, %s", s) @endcode (notice the absence
  214. of @c c_str(), it is not needed at all with wxWidgets functions)
  215. - Compatible with wxWidgets 2.8: @code wxPrintf("Hello, %s", s.c_str()) @endcode
  216. - Using an explicit conversion to narrow, multibyte, string:
  217. @code printf("Hello, %s", (const char *)s.mb_str()) @endcode
  218. - Using a cast to force the issue (listed only for completeness):
  219. @code printf("Hello, %s", (const char *)s.c_str()) @endcode
  220. - The result of @c c_str() cannot be cast to @c char* but only to @c const @c
  221. @c char*. Of course, modifying the string via the pointer returned by this
  222. method has never been possible but unfortunately it was occasionally useful
  223. to use a @c const_cast here to pass the value to const-incorrect functions.
  224. This can be done either using new wxString::char_str() (and matching
  225. wchar_str()) method or by writing a double cast:
  226. @code (char *)(const char *)s.c_str() @endcode
  227. - One of the unfortunate consequences of the possibility to pass wxString to
  228. @c wxPrintf() without using @c c_str() is that it is now impossible to pass
  229. the elements of unnamed enumerations to @c wxPrintf() and other similar
  230. vararg functions, i.e.
  231. @code
  232. enum { Red, Green, Blue };
  233. wxPrintf("Red is %d", Red);
  234. @endcode
  235. doesn't compile. The easiest workaround is to give a name to the enum.
  236. Other unexpected compilation errors may arise but they should happen even more
  237. rarely than the above-mentioned ones and the solution should usually be quite
  238. simple: just use the explicit methods of wxUniChar and wxCStrData classes
  239. instead of relying on their implicit conversions if the compiler can't choose
  240. among them.
  241. @subsection overview_unicode_data_loss Data Loss due To Unicode Conversion Errors
  242. wxString API provides implicit conversion of the internal Unicode string
  243. contents to narrow, char strings. This can be very convenient and is absolutely
  244. necessary for backwards compatibility with the existing code using wxWidgets
  245. however it is a rather dangerous operation as it can easily give unexpected
  246. results if the string contents isn't convertible to the current locale.
  247. To be precise, the conversion will always succeed if the string was created
  248. from a narrow string initially. It will also succeed if the current encoding is
  249. UTF-8 as all Unicode strings are representable in this encoding. However
  250. initializing the string using wxString::FromUTF8() method and then accessing it
  251. as a char string via its wxString::c_str() method is a recipe for disaster as the
  252. program may work perfectly well during testing on Unix systems using UTF-8 locale
  253. but completely fail under Windows where UTF-8 locales are never used because
  254. wxString::c_str() would return an empty string.
  255. The simplest way to ensure that this doesn't happen is to avoid conversions to
  256. @c char* completely by using wxString throughout your program. However if the
  257. program never manipulates 8 bit strings internally, using @c char* pointers is
  258. safe as well. So the existing code needs to be reviewed when upgrading to
  259. wxWidgets 3.0 and the new code should be used with this in mind and ideally
  260. avoiding implicit conversions to @c char*.
  261. @subsection overview_unicode_performance Performance Implications of Using UTF-8
  262. As mentioned above, under Unix systems wxString class can use variable-width
  263. UTF-8 encoding for internal representation. In this case it can't guarantee
  264. constant-time access to N-th element of the string any longer as to find the
  265. position of this character in the string we have to examine all the preceding
  266. ones. Usually this doesn't matter much because most algorithms used on the
  267. strings examine them sequentially anyhow and because wxString implements a
  268. cache for iterating over the string by index but it can have serious
  269. consequences for algorithms using random access to string elements as they
  270. typically acquire O(N^2) time complexity instead of O(N) where N is the length
  271. of the string.
  272. Even despite caching the index, indexed access should be replaced with
  273. sequential access using string iterators. For example a typical loop:
  274. @code
  275. wxString s("hello");
  276. for ( size_t i = 0; i < s.length(); i++ )
  277. {
  278. wchar_t ch = s[i];
  279. // do something with it
  280. }
  281. @endcode
  282. should be rewritten as
  283. @code
  284. wxString s("hello");
  285. for ( wxString::const_iterator i = s.begin(); i != s.end(); ++i )
  286. {
  287. wchar_t ch = *i
  288. // do something with it
  289. }
  290. @endcode
  291. Another, similar, alternative is to use pointer arithmetic:
  292. @code
  293. wxString s("hello");
  294. for ( const wchar_t *p = s.wc_str(); *p; p++ )
  295. {
  296. wchar_t ch = *i
  297. // do something with it
  298. }
  299. @endcode
  300. however this doesn't work correctly for strings with embedded @c NUL characters
  301. and the use of iterators is generally preferred as they provide some run-time
  302. checks (at least in debug build) unlike the raw pointers. But if you do use
  303. them, it is better to use @c wchar_t pointers rather than @c char ones to avoid the
  304. data loss problems due to conversion as discussed in the previous section.
  305. @section overview_unicode_supportout Unicode and the Outside World
  306. Even though wxWidgets always uses Unicode internally, not all the other
  307. libraries and programs do and even those that do use Unicode may use a
  308. different encoding of it. So you need to be able to convert the data to various
  309. representations and the wxString methods wxString::ToAscii(), wxString::ToUTF8()
  310. (or its synonym wxString::utf8_str()), wxString::mb_str(), wxString::c_str() and
  311. wxString::wc_str() can be used for this.
  312. The first of them should be only used for the string containing 7-bit ASCII characters
  313. only, anything else will be replaced by some substitution character.
  314. wxString::mb_str() converts the string to the encoding used by the current locale
  315. and so can return an empty string if the string contains characters not representable in
  316. it as explained in @ref overview_unicode_data_loss. The same applies to wxString::c_str()
  317. if its result is used as a narrow string. Finally, wxString::ToUTF8() and wxString::wc_str()
  318. functions never fail and always return a pointer to char string containing the
  319. UTF-8 representation of the string or @c wchar_t string.
  320. wxString also provides two convenience functions: wxString::From8BitData() and
  321. wxString::To8BitData(). They can be used to create a wxString from arbitrary binary
  322. data without supposing that it is in current locale encoding, and then get it back,
  323. again, without any conversion or, rather, undoing the conversion used by
  324. wxString::From8BitData(). Because of this you should only use wxString::From8BitData()
  325. for the strings created using wxString::To8BitData(). Also notice that in spite
  326. of the availability of these functions, wxString is not the ideal class for storing
  327. arbitrary binary data as they can take up to 4 times more space than needed
  328. (when using @c wchar_t internal representation on the systems where size of
  329. wide characters is 4 bytes) and you should consider using wxMemoryBuffer
  330. instead.
  331. Final word of caution: most of these functions may return either directly the
  332. pointer to internal string buffer or a temporary wxCharBuffer or wxWCharBuffer
  333. object. Such objects are implicitly convertible to @c char and @c wchar_t pointers,
  334. respectively, and so the result of, for example, wxString::ToUTF8() can always be
  335. passed directly to a function taking <tt>const char*</tt>. However code such as
  336. @code
  337. const char *p = s.ToUTF8();
  338. ...
  339. puts(p); // or call any other function taking const char *
  340. @endcode
  341. does @b not work because the temporary buffer returned by wxString::ToUTF8() is
  342. destroyed and @c p is left pointing nowhere. To correct this you should use
  343. @code
  344. const wxScopedCharBuffer p(s.ToUTF8());
  345. puts(p);
  346. @endcode
  347. which does work.
  348. Similarly, wxWX2WCbuf can be used for the return type of wxString::wc_str().
  349. But, once again, none of these cryptic types is really needed if you just pass
  350. the return value of any of the functions mentioned in this section to another
  351. function directly.
  352. */