unicode: Move gscripttable.h generation into main script
[platform/upstream/glib.git] / glib / gwin32.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1998  Peter Mattis, Spencer Kimball and Josh MacDonald
3  * Copyright (C) 1998-1999  Tor Lillqvist
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library 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  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
17  */
18
19 /*
20  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
21  * file for a list of people on the GLib Team.  See the ChangeLog
22  * files for a list of changes.  These files are distributed with
23  * GLib at ftp://ftp.gtk.org/pub/gtk/. 
24  */
25
26 /* 
27  * MT safe for the unix part, FIXME: make the win32 part MT safe as well.
28  */
29
30 #include "config.h"
31
32 #include "glibconfig.h"
33
34 #include <stdlib.h>
35 #include <stdio.h>
36 #include <string.h>
37 #include <wchar.h>
38 #include <errno.h>
39
40 #define STRICT                  /* Strict typing, please */
41 #include <windows.h>
42 #undef STRICT
43 #ifndef G_WITH_CYGWIN
44 #include <direct.h>
45 #endif
46 #include <errno.h>
47 #include <ctype.h>
48 #if defined(_MSC_VER) || defined(__DMC__)
49 #  include <io.h>
50 #endif /* _MSC_VER || __DMC__ */
51
52 #include "glib.h"
53 #include "gthreadprivate.h"
54
55 #ifdef G_WITH_CYGWIN
56 #include <sys/cygwin.h>
57 #endif
58
59 #ifndef G_WITH_CYGWIN
60
61 gint
62 g_win32_ftruncate (gint  fd,
63                    guint size)
64 {
65   return _chsize (fd, size);
66 }
67
68 #endif
69
70 /**
71  * g_win32_getlocale:
72  *
73  * The setlocale() function in the Microsoft C library uses locale
74  * names of the form "English_United States.1252" etc. We want the
75  * UNIXish standard form "en_US", "zh_TW" etc. This function gets the
76  * current thread locale from Windows - without any encoding info -
77  * and returns it as a string of the above form for use in forming
78  * file names etc. The returned string should be deallocated with
79  * g_free().
80  *
81  * Returns: newly-allocated locale name.
82  **/
83
84 #ifndef SUBLANG_SERBIAN_LATIN_BA
85 #define SUBLANG_SERBIAN_LATIN_BA 0x06
86 #endif
87
88 gchar *
89 g_win32_getlocale (void)
90 {
91   LCID lcid;
92   LANGID langid;
93   gchar *ev;
94   gint primary, sub;
95   char iso639[10];
96   char iso3166[10];
97   const gchar *script = NULL;
98
99   /* Let the user override the system settings through environment
100    * variables, as on POSIX systems. Note that in GTK+ applications
101    * since GTK+ 2.10.7 setting either LC_ALL or LANG also sets the
102    * Win32 locale and C library locale through code in gtkmain.c.
103    */
104   if (((ev = getenv ("LC_ALL")) != NULL && ev[0] != '\0')
105       || ((ev = getenv ("LC_MESSAGES")) != NULL && ev[0] != '\0')
106       || ((ev = getenv ("LANG")) != NULL && ev[0] != '\0'))
107     return g_strdup (ev);
108
109   lcid = GetThreadLocale ();
110
111   if (!GetLocaleInfo (lcid, LOCALE_SISO639LANGNAME, iso639, sizeof (iso639)) ||
112       !GetLocaleInfo (lcid, LOCALE_SISO3166CTRYNAME, iso3166, sizeof (iso3166)))
113     return g_strdup ("C");
114   
115   /* Strip off the sorting rules, keep only the language part.  */
116   langid = LANGIDFROMLCID (lcid);
117
118   /* Split into language and territory part.  */
119   primary = PRIMARYLANGID (langid);
120   sub = SUBLANGID (langid);
121
122   /* Handle special cases */
123   switch (primary)
124     {
125     case LANG_AZERI:
126       switch (sub)
127         {
128         case SUBLANG_AZERI_LATIN:
129           script = "@Latn";
130           break;
131         case SUBLANG_AZERI_CYRILLIC:
132           script = "@Cyrl";
133           break;
134         }
135       break;
136     case LANG_SERBIAN:          /* LANG_CROATIAN == LANG_SERBIAN */
137       switch (sub)
138         {
139         case SUBLANG_SERBIAN_LATIN:
140         case 0x06: /* Serbian (Latin) - Bosnia and Herzegovina */
141           script = "@Latn";
142           break;
143         }
144       break;
145     case LANG_UZBEK:
146       switch (sub)
147         {
148         case SUBLANG_UZBEK_LATIN:
149           script = "@Latn";
150           break;
151         case SUBLANG_UZBEK_CYRILLIC:
152           script = "@Cyrl";
153           break;
154         }
155       break;
156     }
157   return g_strconcat (iso639, "_", iso3166, script, NULL);
158 }
159
160 /**
161  * g_win32_error_message:
162  * @error: error code.
163  *
164  * Translate a Win32 error code (as returned by GetLastError() or
165  * WSAGetLastError()) into the corresponding message. The message is
166  * either language neutral, or in the thread's language, or the user's
167  * language, the system's language, or US English (see docs for
168  * FormatMessage()). The returned string is in UTF-8. It should be
169  * deallocated with g_free().
170  *
171  * Returns: newly-allocated error message
172  **/
173 gchar *
174 g_win32_error_message (gint error)
175 {
176   gchar *retval;
177   wchar_t *msg = NULL;
178   int nchars;
179
180   FormatMessageW (FORMAT_MESSAGE_ALLOCATE_BUFFER
181                   |FORMAT_MESSAGE_IGNORE_INSERTS
182                   |FORMAT_MESSAGE_FROM_SYSTEM,
183                   NULL, error, 0,
184                   (LPWSTR) &msg, 0, NULL);
185   if (msg != NULL)
186     {
187       nchars = wcslen (msg);
188       
189       if (nchars > 2 && msg[nchars-1] == '\n' && msg[nchars-2] == '\r')
190         msg[nchars-2] = '\0';
191       
192       retval = g_utf16_to_utf8 (msg, -1, NULL, NULL, NULL);
193       
194       LocalFree (msg);
195     }
196   else
197     retval = g_strdup ("");
198
199   return retval;
200 }
201
202 /**
203  * g_win32_get_package_installation_directory_of_module:
204  * @hmodule: (allow-none): The Win32 handle for a DLL loaded into the current process, or %NULL
205  *
206  * This function tries to determine the installation directory of a
207  * software package based on the location of a DLL of the software
208  * package.
209  *
210  * @hmodule should be the handle of a loaded DLL or %NULL. The
211  * function looks up the directory that DLL was loaded from. If
212  * @hmodule is NULL, the directory the main executable of the current
213  * process is looked up. If that directory's last component is "bin"
214  * or "lib", its parent directory is returned, otherwise the directory
215  * itself.
216  *
217  * It thus makes sense to pass only the handle to a "public" DLL of a
218  * software package to this function, as such DLLs typically are known
219  * to be installed in a "bin" or occasionally "lib" subfolder of the
220  * installation folder. DLLs that are of the dynamically loaded module
221  * or plugin variety are often located in more private locations
222  * deeper down in the tree, from which it is impossible for GLib to
223  * deduce the root of the package installation.
224  *
225  * The typical use case for this function is to have a DllMain() that
226  * saves the handle for the DLL. Then when code in the DLL needs to
227  * construct names of files in the installation tree it calls this
228  * function passing the DLL handle.
229  *
230  * Returns: a string containing the guessed installation directory for
231  * the software package @hmodule is from. The string is in the GLib
232  * file name encoding, i.e. UTF-8. The return value should be freed
233  * with g_free() when not needed any longer. If the function fails
234  * %NULL is returned.
235  *
236  * Since: 2.16
237  */
238 gchar *
239 g_win32_get_package_installation_directory_of_module (gpointer hmodule)
240 {
241   gchar *retval;
242   gchar *p;
243   wchar_t wc_fn[MAX_PATH];
244
245   if (!GetModuleFileNameW (hmodule, wc_fn, MAX_PATH))
246     return NULL;
247
248   retval = g_utf16_to_utf8 (wc_fn, -1, NULL, NULL, NULL);
249
250   if ((p = strrchr (retval, G_DIR_SEPARATOR)) != NULL)
251     *p = '\0';
252
253   p = strrchr (retval, G_DIR_SEPARATOR);
254   if (p && (g_ascii_strcasecmp (p + 1, "bin") == 0 ||
255             g_ascii_strcasecmp (p + 1, "lib") == 0))
256     *p = '\0';
257
258 #ifdef G_WITH_CYGWIN
259   /* In Cygwin we need to have POSIX paths */
260   {
261     gchar tmp[MAX_PATH];
262
263     cygwin_conv_to_posix_path (retval, tmp);
264     g_free (retval);
265     retval = g_strdup (tmp);
266   }
267 #endif
268
269   return retval;
270 }
271
272 static gchar *
273 get_package_directory_from_module (const gchar *module_name)
274 {
275   static GHashTable *module_dirs = NULL;
276   G_LOCK_DEFINE_STATIC (module_dirs);
277   HMODULE hmodule = NULL;
278   gchar *fn;
279
280   G_LOCK (module_dirs);
281
282   if (module_dirs == NULL)
283     module_dirs = g_hash_table_new (g_str_hash, g_str_equal);
284   
285   fn = g_hash_table_lookup (module_dirs, module_name ? module_name : "");
286       
287   if (fn)
288     {
289       G_UNLOCK (module_dirs);
290       return g_strdup (fn);
291     }
292
293   if (module_name)
294     {
295       wchar_t *wc_module_name = g_utf8_to_utf16 (module_name, -1, NULL, NULL, NULL);
296       hmodule = GetModuleHandleW (wc_module_name);
297       g_free (wc_module_name);
298
299       if (!hmodule)
300         {
301           G_UNLOCK (module_dirs);
302           return NULL;
303         }
304     }
305
306   fn = g_win32_get_package_installation_directory_of_module (hmodule);
307
308   if (fn == NULL)
309     {
310       G_UNLOCK (module_dirs);
311       return NULL;
312     }
313   
314   g_hash_table_insert (module_dirs, module_name ? g_strdup (module_name) : "", fn);
315
316   G_UNLOCK (module_dirs);
317
318   return g_strdup (fn);
319 }
320
321 /**
322  * g_win32_get_package_installation_directory:
323  * @package: (allow-none): You should pass %NULL for this.
324  * @dll_name: (allow-none): The name of a DLL that a package provides in UTF-8, or %NULL.
325  *
326  * Try to determine the installation directory for a software package.
327  *
328  * This function is deprecated. Use
329  * g_win32_get_package_installation_directory_of_module() instead.
330  *
331  * The use of @package is deprecated. You should always pass %NULL. A
332  * warning is printed if non-NULL is passed as @package.
333  *
334  * The original intended use of @package was for a short identifier of
335  * the package, typically the same identifier as used for
336  * `GETTEXT_PACKAGE` in software configured using GNU
337  * autotools. The function first looks in the Windows Registry for the
338  * value `#InstallationDirectory` in the key
339  * `#HKLM\Software\@package`, and if that value
340  * exists and is a string, returns that.
341  *
342  * It is strongly recommended that packagers of GLib-using libraries
343  * for Windows do not store installation paths in the Registry to be
344  * used by this function as that interfers with having several
345  * parallel installations of the library. Enabling multiple
346  * installations of different versions of some GLib-using library, or
347  * GLib itself, is desirable for various reasons.
348  *
349  * For this reason it is recommeded to always pass %NULL as
350  * @package to this function, to avoid the temptation to use the
351  * Registry. In version 2.20 of GLib the @package parameter
352  * will be ignored and this function won't look in the Registry at all.
353  *
354  * If @package is %NULL, or the above value isn't found in the
355  * Registry, but @dll_name is non-%NULL, it should name a DLL loaded
356  * into the current process. Typically that would be the name of the
357  * DLL calling this function, looking for its installation
358  * directory. The function then asks Windows what directory that DLL
359  * was loaded from. If that directory's last component is "bin" or
360  * "lib", the parent directory is returned, otherwise the directory
361  * itself. If that DLL isn't loaded, the function proceeds as if
362  * @dll_name was %NULL.
363  *
364  * If both @package and @dll_name are %NULL, the directory from where
365  * the main executable of the process was loaded is used instead in
366  * the same way as above.
367  *
368  * Returns: a string containing the installation directory for
369  * @package. The string is in the GLib file name encoding,
370  * i.e. UTF-8. The return value should be freed with g_free() when not
371  * needed any longer. If the function fails %NULL is returned.
372  *
373  * Deprecated: 2.18: Pass the HMODULE of a DLL or EXE to
374  * g_win32_get_package_installation_directory_of_module() instead.
375  **/
376
377  gchar *
378 g_win32_get_package_installation_directory_utf8 (const gchar *package,
379                                                  const gchar *dll_name)
380 {
381   gchar *result = NULL;
382
383   if (package != NULL)
384       g_warning ("Passing a non-NULL package to g_win32_get_package_installation_directory() is deprecated and it is ignored.");
385
386   if (dll_name != NULL)
387     result = get_package_directory_from_module (dll_name);
388
389   if (result == NULL)
390     result = get_package_directory_from_module (NULL);
391
392   return result;
393 }
394
395 #if !defined (_WIN64)
396
397 /* DLL ABI binary compatibility version that uses system codepage file names */
398
399 gchar *
400 g_win32_get_package_installation_directory (const gchar *package,
401                                             const gchar *dll_name)
402 {
403   gchar *utf8_package = NULL, *utf8_dll_name = NULL;
404   gchar *utf8_retval, *retval;
405
406   if (package != NULL)
407     utf8_package = g_locale_to_utf8 (package, -1, NULL, NULL, NULL);
408
409   if (dll_name != NULL)
410     utf8_dll_name = g_locale_to_utf8 (dll_name, -1, NULL, NULL, NULL);
411
412   utf8_retval =
413     g_win32_get_package_installation_directory_utf8 (utf8_package,
414                                                      utf8_dll_name);
415
416   retval = g_locale_from_utf8 (utf8_retval, -1, NULL, NULL, NULL);
417
418   g_free (utf8_package);
419   g_free (utf8_dll_name);
420   g_free (utf8_retval);
421
422   return retval;
423 }
424
425 #endif
426
427 /**
428  * g_win32_get_package_installation_subdirectory:
429  * @package: (allow-none): You should pass %NULL for this.
430  * @dll_name: (allow-none): The name of a DLL that a package provides, in UTF-8, or %NULL.
431  * @subdir: A subdirectory of the package installation directory, also in UTF-8
432  *
433  * This function is deprecated. Use
434  * g_win32_get_package_installation_directory_of_module() and
435  * g_build_filename() instead.
436  *
437  * Returns a newly-allocated string containing the path of the
438  * subdirectory @subdir in the return value from calling
439  * g_win32_get_package_installation_directory() with the @package and
440  * @dll_name parameters. See the documentation for
441  * g_win32_get_package_installation_directory() for more details. In
442  * particular, note that it is deprecated to pass anything except NULL
443  * as @package.
444  *
445  * Returns: a string containing the complete path to @subdir inside
446  * the installation directory of @package. The returned string is in
447  * the GLib file name encoding, i.e. UTF-8. The return value should be
448  * freed with g_free() when no longer needed. If something goes wrong,
449  * %NULL is returned.
450  *
451  * Deprecated: 2.18: Pass the HMODULE of a DLL or EXE to
452  * g_win32_get_package_installation_directory_of_module() instead, and
453  * then construct a subdirectory pathname with g_build_filename().
454  **/
455
456 gchar *
457 g_win32_get_package_installation_subdirectory_utf8 (const gchar *package,
458                                                     const gchar *dll_name,
459                                                     const gchar *subdir)
460 {
461   gchar *prefix;
462   gchar *dirname;
463
464 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
465   prefix = g_win32_get_package_installation_directory_utf8 (package, dll_name);
466 G_GNUC_END_IGNORE_DEPRECATIONS
467
468   dirname = g_build_filename (prefix, subdir, NULL);
469   g_free (prefix);
470
471   return dirname;
472 }
473
474 #if !defined (_WIN64)
475
476 /* DLL ABI binary compatibility version that uses system codepage file names */
477
478 gchar *
479 g_win32_get_package_installation_subdirectory (const gchar *package,
480                                                const gchar *dll_name,
481                                                const gchar *subdir)
482 {
483   gchar *prefix;
484   gchar *dirname;
485
486   G_GNUC_BEGIN_IGNORE_DEPRECATIONS
487   prefix = g_win32_get_package_installation_directory (package, dll_name);
488   G_GNUC_END_IGNORE_DEPRECATIONS
489
490   dirname = g_build_filename (prefix, subdir, NULL);
491   g_free (prefix);
492
493   return dirname;
494 }
495
496 #endif
497
498 /**
499  * g_win32_get_windows_version:
500  *
501  * Returns version information for the Windows operating system the
502  * code is running on. See MSDN documentation for the GetVersion()
503  * function. To summarize, the most significant bit is one on Win9x,
504  * and zero on NT-based systems. Since version 2.14, GLib works only
505  * on NT-based systems, so checking whether your are running on Win9x
506  * in your own software is moot. The least significant byte is 4 on
507  * Windows NT 4, and 5 on Windows XP. Software that needs really
508  * detailed version and feature information should use Win32 API like
509  * GetVersionEx() and VerifyVersionInfo().
510  *
511  * Returns: The version information.
512  * 
513  * Since: 2.6
514  **/
515 guint
516 g_win32_get_windows_version (void)
517 {
518   static gsize windows_version;
519
520   if (g_once_init_enter (&windows_version))
521     g_once_init_leave (&windows_version, GetVersion ());
522
523   return windows_version;
524 }
525
526 /**
527  * g_win32_locale_filename_from_utf8:
528  * @utf8filename: a UTF-8 encoded filename.
529  *
530  * Converts a filename from UTF-8 to the system codepage.
531  *
532  * On NT-based Windows, on NTFS file systems, file names are in
533  * Unicode. It is quite possible that Unicode file names contain
534  * characters not representable in the system codepage. (For instance,
535  * Greek or Cyrillic characters on Western European or US Windows
536  * installations, or various less common CJK characters on CJK Windows
537  * installations.)
538  *
539  * In such a case, and if the filename refers to an existing file, and
540  * the file system stores alternate short (8.3) names for directory
541  * entries, the short form of the filename is returned. Note that the
542  * "short" name might in fact be longer than the Unicode name if the
543  * Unicode name has very short pathname components containing
544  * non-ASCII characters. If no system codepage name for the file is
545  * possible, %NULL is returned.
546  *
547  * The return value is dynamically allocated and should be freed with
548  * g_free() when no longer needed.
549  *
550  * Returns: The converted filename, or %NULL on conversion
551  * failure and lack of short names.
552  *
553  * Since: 2.8
554  */
555 gchar *
556 g_win32_locale_filename_from_utf8 (const gchar *utf8filename)
557 {
558   gchar *retval = g_locale_from_utf8 (utf8filename, -1, NULL, NULL, NULL);
559
560   if (retval == NULL)
561     {
562       /* Conversion failed, so convert to wide chars, check if there
563        * is a 8.3 version, and use that.
564        */
565       wchar_t *wname = g_utf8_to_utf16 (utf8filename, -1, NULL, NULL, NULL);
566       if (wname != NULL)
567         {
568           wchar_t wshortname[MAX_PATH + 1];
569           if (GetShortPathNameW (wname, wshortname, G_N_ELEMENTS (wshortname)))
570             {
571               gchar *tem = g_utf16_to_utf8 (wshortname, -1, NULL, NULL, NULL);
572               retval = g_locale_from_utf8 (tem, -1, NULL, NULL, NULL);
573               g_free (tem);
574             }
575           g_free (wname);
576         }
577     }
578   return retval;
579 }
580
581 /**
582  * g_win32_get_command_line:
583  *
584  * Gets the command line arguments, on Windows, in the GLib filename
585  * encoding (ie: UTF-8).
586  *
587  * Normally, on Windows, the command line arguments are passed to main()
588  * in the system codepage encoding.  This prevents passing filenames as
589  * arguments if the filenames contain characters that fall outside of
590  * this codepage.  If such filenames are passed, then substitutions
591  * will occur (such as replacing some characters with '?').
592  *
593  * GLib's policy of using UTF-8 as a filename encoding on Windows was
594  * designed to localise the pain of dealing with filenames outside of
595  * the system codepage to one area: dealing with commandline arguments
596  * in main().
597  *
598  * As such, most GLib programs should ignore the value of argv passed to
599  * their main() function and call g_win32_get_command_line() instead.
600  * This will get the "full Unicode" commandline arguments using
601  * GetCommandLineW() and convert it to the GLib filename encoding (which
602  * is UTF-8 on Windows).
603  *
604  * The strings returned by this function are suitable for use with
605  * functions such as g_open() and g_file_new_for_commandline_arg() but
606  * are not suitable for use with g_option_context_parse(), which assumes
607  * that its input will be in the system codepage.  The return value is
608  * suitable for use with g_option_context_parse_strv(), however, which
609  * is a better match anyway because it won't leak memory.
610  *
611  * Unlike argv, the returned value is a normal strv and can (and should)
612  * be freed with g_strfreev() when no longer needed.
613  *
614  * Returns: (transfer full): the commandline arguments in the GLib
615  *   filename encoding (ie: UTF-8)
616  *
617  * Since: 2.40
618  **/
619 gchar **
620 g_win32_get_command_line (void)
621 {
622   gchar **result;
623   LPWSTR *args;
624   gint i, n;
625
626   args = CommandLineToArgvW (GetCommandLineW(), &n);
627
628   result = g_new (gchar *, n + 1);
629   for (i = 0; i < n; i++)
630     result[i] = g_utf16_to_utf8 (args[i], -1, NULL, NULL, NULL);
631   result[i] = NULL;
632
633   return result;
634 }