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