glib/giowin32.c glib/gmain.c glib/gstrfuncs.c Decorating variable
[platform/upstream/glib.git] / glib / libcharset / localcharset.c
1 /* Determine a canonical name for the current locale's character encoding.
2
3    Copyright (C) 2000-2002 Free Software Foundation, Inc.
4
5    This program is free software; you can redistribute it and/or modify it
6    under the terms of the GNU Library General Public License as published
7    by the Free Software Foundation; either version 2, or (at your option)
8    any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13    Library General Public License for more details.
14
15    You should have received a copy of the GNU Library General Public
16    License along with this program; if not, write to the Free Software
17    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
18    USA.  */
19
20 /* Written by Bruno Haible <bruno@clisp.org>.  */
21
22 #ifdef HAVE_CONFIG_H
23 # include <config.h>
24 #endif
25
26 #include <glibconfig.h>
27
28 #if defined G_PLATFORM_WIN32
29 /* Want to use Win32-specific code in this file also on Cygwin */
30 # define _WIN32 1               
31 #endif
32
33 #if HAVE_STDDEF_H
34 # include <stddef.h>
35 #endif
36
37 #include <stdio.h>
38 #if HAVE_STRING_H
39 # include <string.h>
40 #else
41 # include <strings.h>
42 #endif
43 #if HAVE_STDLIB_H
44 # include <stdlib.h>
45 #endif
46
47 #if defined _WIN32 || defined __WIN32__
48 # undef WIN32   /* avoid warning on mingw32 */
49 # define WIN32
50 #endif
51
52 #if defined __EMX__
53 /* Assume EMX program runs on OS/2, even if compiled under DOS.  */
54 # define OS2
55 #endif
56
57 #if !defined WIN32
58 # if HAVE_LANGINFO_CODESET
59 #  include <langinfo.h>
60 # else
61 #  if HAVE_SETLOCALE
62 #   include <locale.h>
63 #  endif
64 # endif
65 #elif defined WIN32
66 # define WIN32_LEAN_AND_MEAN
67 # include <windows.h>
68 #endif
69 #if defined OS2
70 # define INCL_DOS
71 # include <os2.h>
72 #endif
73
74 #if defined _WIN32 || defined __WIN32__ || defined __EMX__ || defined __DJGPP__
75   /* Win32, OS/2, DOS */
76 # define ISSLASH(C) ((C) == '/' || (C) == '\\')
77 #endif
78
79 #ifndef DIRECTORY_SEPARATOR
80 # define DIRECTORY_SEPARATOR '/'
81 #endif
82
83 #ifndef ISSLASH
84 # define ISSLASH(C) ((C) == DIRECTORY_SEPARATOR)
85 #endif
86
87 #ifdef HAVE_GETC_UNLOCKED
88 # undef getc
89 # define getc getc_unlocked
90 #endif
91
92 #ifdef __cplusplus
93 /* When compiling with "gcc -x c++", produce a function with C linkage.  */
94 extern "C" const char * locale_charset (void);
95 #endif
96
97 /* The following static variable is declared 'volatile' to avoid a
98    possible multithread problem in the function get_charset_aliases. If we
99    are running in a threaded environment, and if two threads initialize
100    'charset_aliases' simultaneously, both will produce the same value,
101    and everything will be ok if the two assignments to 'charset_aliases'
102    are atomic. But I don't know what will happen if the two assignments mix.  */
103 #if __STDC__ != 1
104 # define volatile /* empty */
105 #endif
106 /* Pointer to the contents of the charset.alias file, if it has already been
107    read, else NULL.  Its format is:
108    ALIAS_1 '\0' CANONICAL_1 '\0' ... ALIAS_n '\0' CANONICAL_n '\0' '\0'  */
109 static const char * volatile charset_aliases;
110
111 /* Return a pointer to the contents of the charset.alias file.  */
112 const char *
113 _g_locale_get_charset_aliases ()
114 {
115   const char *cp;
116
117   cp = charset_aliases;
118   if (cp == NULL)
119     {
120 #if !defined WIN32
121       FILE *fp;
122       const char *dir = LIBDIR;
123       const char *base = "charset.alias";
124       char *file_name;
125
126       /* Concatenate dir and base into freshly allocated file_name.  */
127       {
128         size_t dir_len = strlen (dir);
129         size_t base_len = strlen (base);
130         int add_slash = (dir_len > 0 && !ISSLASH (dir[dir_len - 1]));
131         file_name = (char *) malloc (dir_len + add_slash + base_len + 1);
132         if (file_name != NULL)
133           {
134             memcpy (file_name, dir, dir_len);
135             if (add_slash)
136               file_name[dir_len] = DIRECTORY_SEPARATOR;
137             memcpy (file_name + dir_len + add_slash, base, base_len + 1);
138           }
139       }
140
141       if (file_name == NULL || (fp = fopen (file_name, "r")) == NULL)
142         /* Out of memory or file not found, treat it as empty.  */
143         cp = "";
144       else
145         {
146           /* Parse the file's contents.  */
147           int c;
148           char buf1[50+1];
149           char buf2[50+1];
150           char *res_ptr = NULL;
151           size_t res_size = 0;
152           size_t l1, l2;
153
154           for (;;)
155             {
156               c = getc (fp);
157               if (c == EOF)
158                 break;
159               if (c == '\n' || c == ' ' || c == '\t')
160                 continue;
161               if (c == '#')
162                 {
163                   /* Skip comment, to end of line.  */
164                   do
165                     c = getc (fp);
166                   while (!(c == EOF || c == '\n'));
167                   if (c == EOF)
168                     break;
169                   continue;
170                 }
171               ungetc (c, fp);
172               if (fscanf (fp, "%50s %50s", buf1, buf2) < 2)
173                 break;
174               l1 = strlen (buf1);
175               l2 = strlen (buf2);
176               if (res_size == 0)
177                 {
178                   res_size = l1 + 1 + l2 + 1;
179                   res_ptr = (char *) malloc (res_size + 1);
180                 }
181               else
182                 {
183                   res_size += l1 + 1 + l2 + 1;
184                   res_ptr = (char *) realloc (res_ptr, res_size + 1);
185                 }
186               if (res_ptr == NULL)
187                 {
188                   /* Out of memory. */
189                   res_size = 0;
190                   break;
191                 }
192               strcpy (res_ptr + res_size - (l2 + 1) - (l1 + 1), buf1);
193               strcpy (res_ptr + res_size - (l2 + 1), buf2);
194             }
195           fclose (fp);
196           if (res_size == 0)
197             cp = "";
198           else
199             {
200               *(res_ptr + res_size) = '\0';
201               cp = res_ptr;
202             }
203         }
204
205       if (file_name != NULL)
206         free (file_name);
207
208 #else
209
210       /* To avoid the troubles of installing a separate file in the same
211          directory as the DLL and of retrieving the DLL's directory at
212          runtime, simply inline the aliases here.  */
213
214 # if defined WIN32
215       cp = "CP936" "\0" "GBK" "\0"
216            "CP1361" "\0" "JOHAB" "\0"
217            "CP20127" "\0" "ASCII" "\0"
218            "CP20866" "\0" "KOI8-R" "\0"
219            "CP21866" "\0" "KOI8-RU" "\0"
220            "CP28591" "\0" "ISO-8859-1" "\0"
221            "CP28592" "\0" "ISO-8859-2" "\0"
222            "CP28593" "\0" "ISO-8859-3" "\0"
223            "CP28594" "\0" "ISO-8859-4" "\0"
224            "CP28595" "\0" "ISO-8859-5" "\0"
225            "CP28596" "\0" "ISO-8859-6" "\0"
226            "CP28597" "\0" "ISO-8859-7" "\0"
227            "CP28598" "\0" "ISO-8859-8" "\0"
228            "CP28599" "\0" "ISO-8859-9" "\0"
229            "CP28605" "\0" "ISO-8859-15" "\0";
230 # endif
231 #endif
232
233       charset_aliases = cp;
234     }
235
236   return cp;
237 }
238
239 /* Determine the current locale's character encoding, and canonicalize it
240    into one of the canonical names listed in config.charset.
241    The result must not be freed; it is statically allocated.
242    If the canonical name cannot be determined, the result is a non-canonical
243    name.  */
244
245 const char *
246 _g_locale_charset_raw ()
247 {
248   const char *codeset;
249
250 #if !(defined WIN32 || defined OS2)
251
252 # if HAVE_LANGINFO_CODESET
253
254   /* Most systems support nl_langinfo (CODESET) nowadays.  */
255   codeset = nl_langinfo (CODESET);
256
257 # else
258
259   /* On old systems which lack it, use setlocale or getenv.  */
260   const char *locale = NULL;
261
262   /* But most old systems don't have a complete set of locales.  Some
263      (like SunOS 4 or DJGPP) have only the C locale.  Therefore we don't
264      use setlocale here; it would return "C" when it doesn't support the
265      locale name the user has set.  */
266 #  if HAVE_SETLOCALE && 0
267   locale = setlocale (LC_CTYPE, NULL);
268 #  endif
269   if (locale == NULL || locale[0] == '\0')
270     {
271       locale = getenv ("LC_ALL");
272       if (locale == NULL || locale[0] == '\0')
273         {
274           locale = getenv ("LC_CTYPE");
275           if (locale == NULL || locale[0] == '\0')
276             locale = getenv ("LANG");
277         }
278     }
279
280   /* On some old systems, one used to set locale = "iso8859_1". On others,
281      you set it to "language_COUNTRY.charset". In any case, we resolve it
282      through the charset.alias file.  */
283   codeset = locale;
284
285 # endif
286
287 #elif defined WIN32
288
289   static char buf[2 + 10 + 1];
290
291   /* Woe32 has a function returning the locale's codepage as a number.  */
292   sprintf (buf, "CP%u", GetACP ());
293   codeset = buf;
294
295 #elif defined OS2
296
297   const char *locale;
298   static char buf[2 + 10 + 1];
299   ULONG cp[3];
300   ULONG cplen;
301
302   /* Allow user to override the codeset, as set in the operating system,
303      with standard language environment variables.  */
304   locale = getenv ("LC_ALL");
305   if (locale == NULL || locale[0] == '\0')
306     {
307       locale = getenv ("LC_CTYPE");
308       if (locale == NULL || locale[0] == '\0')
309         locale = getenv ("LANG");
310     }
311   if (locale != NULL && locale[0] != '\0')
312     {
313       /* If the locale name contains an encoding after the dot, return it.  */
314       const char *dot = strchr (locale, '.');
315
316       if (dot != NULL)
317         {
318           const char *modifier;
319
320           dot++;
321           /* Look for the possible @... trailer and remove it, if any.  */
322           modifier = strchr (dot, '@');
323           if (modifier == NULL)
324             return dot;
325           if (modifier - dot < sizeof (buf))
326             {
327               memcpy (buf, dot, modifier - dot);
328               buf [modifier - dot] = '\0';
329               return buf;
330             }
331         }
332
333       /* Resolve through the charset.alias file.  */
334       codeset = locale;
335     }
336   else
337     {
338       /* OS/2 has a function returning the locale's codepage as a number.  */
339       if (DosQueryCp (sizeof (cp), cp, &cplen))
340         codeset = "";
341       else
342         {
343           sprintf (buf, "CP%u", cp[0]);
344           codeset = buf;
345         }
346     }
347
348 #endif
349
350   return codeset;
351 }
352
353 #ifdef STATIC
354 STATIC
355 #endif
356 const char *
357 _g_locale_charset_unalias (const char *codeset)
358 {
359   const char *aliases;
360
361   if (codeset == NULL)
362     /* The canonical name cannot be determined.  */
363     codeset = "";
364
365   /* Resolve alias. */
366   for (aliases = _g_locale_get_charset_aliases ();
367        *aliases != '\0';
368        aliases += strlen (aliases) + 1, aliases += strlen (aliases) + 1)
369     if (strcmp (codeset, aliases) == 0
370         || (aliases[0] == '*' && aliases[1] == '\0'))
371       {
372         codeset = aliases + strlen (aliases) + 1;
373         break;
374       }
375
376   /* Don't return an empty string.  GNU libc and GNU libiconv interpret
377      the empty string as denoting "the locale's character encoding",
378      thus GNU libiconv would call this function a second time.  */
379   if (codeset[0] == '\0')
380     codeset = "ASCII";
381
382   return codeset;
383 }