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