Update doc comments. Mention that it is not recommeded to use the Registry
[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, write to the
17  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18  * Boston, MA 02111-1307, USA.
19  */
20
21 /*
22  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
23  * file for a list of people on the GLib Team.  See the ChangeLog
24  * files for a list of changes.  These files are distributed with
25  * GLib at ftp://ftp.gtk.org/pub/gtk/. 
26  */
27
28 /* 
29  * MT safe for the unix part, FIXME: make the win32 part MT safe as well.
30  */
31
32 #include "config.h"
33
34 #include "glibconfig.h"
35
36 #include <stdlib.h>
37 #include <stdio.h>
38 #include <string.h>
39 #include <wchar.h>
40 #include <errno.h>
41
42 #define STRICT                  /* Strict typing, please */
43 #include <windows.h>
44 #undef STRICT
45 #ifndef G_WITH_CYGWIN
46 #include <direct.h>
47 #endif
48 #include <errno.h>
49 #include <ctype.h>
50 #if defined(_MSC_VER) || defined(__DMC__)
51 #  include <io.h>
52 #endif /* _MSC_VER || __DMC__ */
53
54 #include "glib.h"
55 #include "galias.h"
56
57 #ifdef G_WITH_CYGWIN
58 #include <sys/cygwin.h>
59 #endif
60
61 #ifndef G_WITH_CYGWIN
62
63 gint
64 g_win32_ftruncate (gint  fd,
65                    guint size)
66 {
67   return _chsize (fd, size);
68 }
69
70 #endif
71
72 /**
73  * g_win32_getlocale:
74  *
75  * The setlocale() function in the Microsoft C library uses locale
76  * names of the form "English_United States.1252" etc. We want the
77  * UNIXish standard form "en_US", "zh_TW" etc. This function gets the
78  * current thread locale from Windows - without any encoding info -
79  * and returns it as a string of the above form for use in forming
80  * file names etc. The returned string should be deallocated with
81  * g_free().
82  *
83  * Returns: newly-allocated locale name.
84  **/
85
86 #ifndef SUBLANG_SERBIAN_LATIN_BA
87 #define SUBLANG_SERBIAN_LATIN_BA 0x06
88 #endif
89
90 gchar *
91 g_win32_getlocale (void)
92 {
93   LCID lcid;
94   LANGID langid;
95   gchar *ev;
96   gint primary, sub;
97   char iso639[10];
98   char iso3166[10];
99   const gchar *script = NULL;
100
101   /* Let the user override the system settings through environment
102    * variables, as on POSIX systems. Note that in GTK+ applications
103    * since GTK+ 2.10.7 setting either LC_ALL or LANG also sets the
104    * Win32 locale and C library locale through code in gtkmain.c.
105    */
106   if (((ev = getenv ("LC_ALL")) != NULL && ev[0] != '\0')
107       || ((ev = getenv ("LC_MESSAGES")) != NULL && ev[0] != '\0')
108       || ((ev = getenv ("LANG")) != NULL && ev[0] != '\0'))
109     return g_strdup (ev);
110
111   lcid = GetThreadLocale ();
112
113   if (!GetLocaleInfo (lcid, LOCALE_SISO639LANGNAME, iso639, sizeof (iso639)) ||
114       !GetLocaleInfo (lcid, LOCALE_SISO3166CTRYNAME, iso3166, sizeof (iso3166)))
115     return g_strdup ("C");
116   
117   /* Strip off the sorting rules, keep only the language part.  */
118   langid = LANGIDFROMLCID (lcid);
119
120   /* Split into language and territory part.  */
121   primary = PRIMARYLANGID (langid);
122   sub = SUBLANGID (langid);
123
124   /* Handle special cases */
125   switch (primary)
126     {
127     case LANG_AZERI:
128       switch (sub)
129         {
130         case SUBLANG_AZERI_LATIN:
131           script = "@Latn";
132           break;
133         case SUBLANG_AZERI_CYRILLIC:
134           script = "@Cyrl";
135           break;
136         }
137       break;
138     case LANG_SERBIAN:          /* LANG_CROATIAN == LANG_SERBIAN */
139       switch (sub)
140         {
141         case SUBLANG_SERBIAN_LATIN:
142         case 0x06: /* Serbian (Latin) - Bosnia and Herzegovina */
143           script = "@Latn";
144           break;
145         }
146       break;
147     case LANG_UZBEK:
148       switch (sub)
149         {
150         case SUBLANG_UZBEK_LATIN:
151           script = "@Latn";
152           break;
153         case SUBLANG_UZBEK_CYRILLIC:
154           script = "@Cyrl";
155           break;
156         }
157       break;
158     }
159   return g_strconcat (iso639, "_", iso3166, script, NULL);
160 }
161
162 /**
163  * g_win32_error_message:
164  * @error: error code.
165  *
166  * Translate a Win32 error code (as returned by GetLastError()) into
167  * the corresponding message. The message is either language neutral,
168  * or in the thread's language, or the user's language, the system's
169  * language, or US English (see docs for FormatMessage()). The
170  * returned string is in UTF-8. It should be deallocated with
171  * g_free().
172  *
173  * Returns: newly-allocated error message
174  **/
175 gchar *
176 g_win32_error_message (gint error)
177 {
178   gchar *retval;
179   wchar_t *msg = NULL;
180   int nchars;
181
182   FormatMessageW (FORMAT_MESSAGE_ALLOCATE_BUFFER
183                   |FORMAT_MESSAGE_IGNORE_INSERTS
184                   |FORMAT_MESSAGE_FROM_SYSTEM,
185                   NULL, error, 0,
186                   (LPWSTR) &msg, 0, NULL);
187   if (msg != NULL)
188     {
189       nchars = wcslen (msg);
190       
191       if (nchars > 2 && msg[nchars-1] == '\n' && msg[nchars-2] == '\r')
192         msg[nchars-2] = '\0';
193       
194       retval = g_utf16_to_utf8 (msg, -1, NULL, NULL, NULL);
195       
196       LocalFree (msg);
197     }
198   else
199     retval = g_strdup ("");
200
201   return retval;
202 }
203
204 static gchar *
205 get_package_directory_from_module (const gchar *module_name)
206 {
207   static GHashTable *module_dirs = NULL;
208   G_LOCK_DEFINE_STATIC (module_dirs);
209   HMODULE hmodule = NULL;
210   gchar *fn;
211   gchar *p;
212   gchar *result;
213   wchar_t wc_fn[MAX_PATH];
214
215   G_LOCK (module_dirs);
216
217   if (module_dirs == NULL)
218     module_dirs = g_hash_table_new (g_str_hash, g_str_equal);
219   
220   result = g_hash_table_lookup (module_dirs, module_name ? module_name : "");
221       
222   if (result)
223     {
224       G_UNLOCK (module_dirs);
225       return g_strdup (result);
226     }
227
228   if (module_name)
229     {
230       wchar_t *wc_module_name = g_utf8_to_utf16 (module_name, -1, NULL, NULL, NULL);
231       hmodule = GetModuleHandleW (wc_module_name);
232       g_free (wc_module_name);
233
234       if (!hmodule)
235         return NULL;
236     }
237
238   if (!GetModuleFileNameW (hmodule, wc_fn, MAX_PATH))
239     {
240       G_UNLOCK (module_dirs);
241       return NULL;
242     }
243   fn = g_utf16_to_utf8 (wc_fn, -1, NULL, NULL, NULL);
244
245   if ((p = strrchr (fn, G_DIR_SEPARATOR)) != NULL)
246     *p = '\0';
247
248   p = strrchr (fn, G_DIR_SEPARATOR);
249   if (p && (g_ascii_strcasecmp (p + 1, "bin") == 0 ||
250             g_ascii_strcasecmp (p + 1, "lib") == 0))
251     *p = '\0';
252
253 #ifdef G_WITH_CYGWIN
254   /* In Cygwin we need to have POSIX paths */
255   {
256     gchar tmp[MAX_PATH];
257
258     cygwin_conv_to_posix_path(fn, tmp);
259     g_free(fn);
260     fn = g_strdup(tmp);
261   }
262 #endif
263
264   g_hash_table_insert (module_dirs, module_name ? g_strdup (module_name) : "", fn);
265
266   G_UNLOCK (module_dirs);
267
268   return g_strdup (fn);
269 }
270
271 /**
272  * g_win32_get_package_installation_directory:
273  * @package: An identifier for a software package, or %NULL, in UTF-8
274  * @dll_name: The name of a DLL that a package provides, or %NULL, in UTF-8
275  *
276  * Try to determine the installation directory for a software package.
277  *
278  * @package should be a short identifier for the package. Typically it
279  * is the same identifier as used for
280  * <literal>GETTEXT_PACKAGE</literal> in software configured using GNU
281  * autotools. The function first looks in the Windows Registry for the
282  * value <literal>&num;InstallationDirectory</literal> in the key
283  * <literal>&num;HKLM\Software\@package</literal>, and if that value
284  * exists and is a string, returns that.
285  *
286  * It is strongly recommended that packagers of GLib-using libraries
287  * for Windows do not store installation paths in the Registry to be
288  * used by this function as that interfers with having several
289  * parallel installations of the library. Parallel installations of
290  * different versions of some GLib-using library, or GLib itself,
291  * might well be desirable for various reasons.
292  *
293  * For the same reason it is recommeded to always pass %NULL as
294  * @package to this function, to avoid the temptation to use the
295  * Registry.
296  *
297  * If @package is %NULL, or the above value isn't found in the
298  * Registry, but @dll_name is non-%NULL, it should name a DLL loaded
299  * into the current process. Typically that would be the name of the
300  * DLL calling this function, looking for its installation
301  * directory. The function then asks Windows what directory that DLL
302  * was loaded from. If that directory's last component is "bin" or
303  * "lib", the parent directory is returned, otherwise the directory
304  * itself. If that DLL isn't loaded, the function proceeds as if
305  * @dll_name was %NULL.
306  *
307  * If both @package and @dll_name are %NULL, the directory from where
308  * the main executable of the process was loaded is used instead in
309  * the same way as above.
310  *
311  * Returns: a string containing the installation directory for
312  * @package. The string is in the GLib file name encoding, i.e. UTF-8
313  * on Windows. The return value should be freed with g_free() when not
314  * needed any longer.
315  **/
316
317 gchar *
318 g_win32_get_package_installation_directory (const gchar *package,
319                                             const gchar *dll_name)
320 {
321   static GHashTable *package_dirs = NULL;
322   G_LOCK_DEFINE_STATIC (package_dirs);
323   gchar *result = NULL;
324   gchar *key;
325   wchar_t *wc_key;
326   HKEY reg_key = NULL;
327   DWORD type;
328   DWORD nbytes;
329
330   if (package != NULL)
331     {
332       G_LOCK (package_dirs);
333       
334       if (package_dirs == NULL)
335         package_dirs = g_hash_table_new (g_str_hash, g_str_equal);
336       
337       result = g_hash_table_lookup (package_dirs, package);
338       
339       if (result && result[0])
340         {
341           G_UNLOCK (package_dirs);
342           return g_strdup (result);
343         }
344       
345       key = g_strconcat ("Software\\", package, NULL);
346       
347       nbytes = 0;
348
349       wc_key = g_utf8_to_utf16 (key, -1, NULL, NULL, NULL);
350       if (((RegOpenKeyExW (HKEY_CURRENT_USER, wc_key, 0,
351                            KEY_QUERY_VALUE, &reg_key) == ERROR_SUCCESS
352             && RegQueryValueExW (reg_key, L"InstallationDirectory", 0,
353                                  &type, NULL, &nbytes) == ERROR_SUCCESS)
354            ||
355            (RegOpenKeyExW (HKEY_LOCAL_MACHINE, wc_key, 0,
356                            KEY_QUERY_VALUE, &reg_key) == ERROR_SUCCESS
357             && RegQueryValueExW (reg_key, L"InstallationDirectory", 0,
358                                  &type, NULL, &nbytes) == ERROR_SUCCESS))
359           && type == REG_SZ)
360         {
361           wchar_t *wc_temp = g_new (wchar_t, (nbytes+1)/2 + 1);
362           RegQueryValueExW (reg_key, L"InstallationDirectory", 0,
363                             &type, (LPBYTE) wc_temp, &nbytes);
364           wc_temp[nbytes/2] = '\0';
365           result = g_utf16_to_utf8 (wc_temp, -1, NULL, NULL, NULL);
366           g_free (wc_temp);
367         }
368       g_free (wc_key);
369
370       if (reg_key != NULL)
371         RegCloseKey (reg_key);
372       
373       g_free (key);
374
375       if (result)
376         {
377           g_hash_table_insert (package_dirs, g_strdup (package), result);
378           G_UNLOCK (package_dirs);
379           return g_strdup (result);
380         }
381       G_UNLOCK (package_dirs);
382     }
383
384   if (dll_name != NULL)
385     result = get_package_directory_from_module (dll_name);
386
387   if (result == NULL)
388     result = get_package_directory_from_module (NULL);
389
390   return result;
391 }
392
393 #undef g_win32_get_package_installation_directory
394
395 /* DLL ABI binary compatibility version that uses system codepage file names */
396
397 gchar *
398 g_win32_get_package_installation_directory (const gchar *package,
399                                             const gchar *dll_name)
400 {
401   gchar *utf8_package = NULL, *utf8_dll_name = NULL;
402   gchar *utf8_retval, *retval;
403
404   if (package != NULL)
405     utf8_package = g_locale_to_utf8 (package, -1, NULL, NULL, NULL);
406
407   if (dll_name != NULL)
408     utf8_dll_name = g_locale_to_utf8 (dll_name, -1, NULL, NULL, NULL);
409
410   utf8_retval =
411     g_win32_get_package_installation_directory_utf8 (utf8_package,
412                                                      utf8_dll_name);
413
414   retval = g_locale_from_utf8 (utf8_retval, -1, NULL, NULL, NULL);
415
416   g_free (utf8_package);
417   g_free (utf8_dll_name);
418   g_free (utf8_retval);
419
420   return retval;
421 }
422
423 /**
424  * g_win32_get_package_installation_subdirectory:
425  * @package: An identifier for a software package, in UTF-8, or %NULL
426  * @dll_name: The name of a DLL that a package provides, in UTF-8, or %NULL
427  * @subdir: A subdirectory of the package installation directory, also in UTF-8
428  *
429  * Returns a newly-allocated string containing the path of the
430  * subdirectory @subdir in the return value from calling
431  * g_win32_get_package_installation_directory() with the @package and
432  * @dll_name parameters. See the documentation for
433  * g_win32_get_package_installation_directory() for more details. In
434  * particular, note that it is recomended to always pass NULL as
435  * @package.
436  *
437  * Returns: a string containing the complete path to @subdir inside
438  * the installation directory of @package. The returned string is in
439  * the GLib file name encoding, i.e. UTF-8 on Windows. The return
440  * value should be freed with g_free() when no longer needed.
441  **/
442
443 gchar *
444 g_win32_get_package_installation_subdirectory (const gchar *package,
445                                                const gchar *dll_name,
446                                                const gchar *subdir)
447 {
448   gchar *prefix;
449   gchar *dirname;
450
451   prefix = g_win32_get_package_installation_directory_utf8 (package, dll_name);
452
453   dirname = g_build_filename (prefix, subdir, NULL);
454   g_free (prefix);
455
456   return dirname;
457 }
458
459 #undef g_win32_get_package_installation_subdirectory
460
461 /* DLL ABI binary compatibility version that uses system codepage file names */
462
463 gchar *
464 g_win32_get_package_installation_subdirectory (const gchar *package,
465                                                const gchar *dll_name,
466                                                const gchar *subdir)
467 {
468   gchar *prefix;
469   gchar *dirname;
470
471   prefix = g_win32_get_package_installation_directory (package, dll_name);
472
473   dirname = g_build_filename (prefix, subdir, NULL);
474   g_free (prefix);
475
476   return dirname;
477 }
478
479 static guint windows_version;
480
481 static void 
482 g_win32_windows_version_init (void)
483 {
484   static gboolean beenhere = FALSE;
485
486   if (!beenhere)
487     {
488       beenhere = TRUE;
489       windows_version = GetVersion ();
490
491       if (windows_version & 0x80000000)
492         g_error ("This version of GLib requires NT-based Windows.");
493     }
494 }
495
496 void 
497 _g_win32_thread_init (void)
498 {
499   g_win32_windows_version_init ();
500 }
501
502 /**
503  * g_win32_get_windows_version:
504  *
505  * Returns version information for the Windows operating system the
506  * code is running on. See MSDN documentation for the GetVersion()
507  * function. To summarize, the most significant bit is one on Win9x,
508  * and zero on NT-based systems. Since version 2.14, GLib works only
509  * on NT-based systems, so checking whether your are running on Win9x
510  * in your own software is moot. The least significant byte is 4 on
511  * Windows NT 4, and 5 on Windows XP. Software that needs really
512  * detailled version and feature information should use Win32 API like
513  * GetVersionEx() and VerifyVersionInfo().
514  *
515  * Returns: The version information.
516  * 
517  * Since: 2.6
518  **/
519 guint
520 g_win32_get_windows_version (void)
521 {
522   g_win32_windows_version_init ();
523   
524   return windows_version;
525 }
526
527 /**
528  * g_win32_locale_filename_from_utf8:
529  * @utf8filename: a UTF-8 encoded filename.
530  *
531  * Converts a filename from UTF-8 to the system codepage.
532  *
533  * On NT-based Windows, on NTFS file systems, file names are in
534  * Unicode. It is quite possible that Unicode file names contain
535  * characters not representable in the system codepage. (For instance,
536  * Greek or Cyrillic characters on Western European or US Windows
537  * installations, or various less common CJK characters on CJK Windows
538  * installations.)
539  *
540  * In such a case, and if the filename refers to an existing file, and
541  * the file system stores alternate short (8.3) names for directory
542  * entries, the short form of the filename is returned. Note that the
543  * "short" name might in fact be longer than the Unicode name if the
544  * Unicode name has very short pathname components containing
545  * non-ASCII characters. If no system codepage name for the file is
546  * possible, %NULL is returned.
547  *
548  * The return value is dynamically allocated and should be freed with
549  * g_free() when no longer needed.
550  *
551  * Return value: The converted filename, or %NULL on conversion
552  * failure and lack of short names.
553  *
554  * Since: 2.8
555  */
556 gchar *
557 g_win32_locale_filename_from_utf8 (const gchar *utf8filename)
558 {
559   gchar *retval = g_locale_from_utf8 (utf8filename, -1, NULL, NULL, NULL);
560
561   if (retval == NULL)
562     {
563       /* Conversion failed, so convert to wide chars, check if there
564        * is a 8.3 version, and use that.
565        */
566       wchar_t *wname = g_utf8_to_utf16 (utf8filename, -1, NULL, NULL, NULL);
567       if (wname != NULL)
568         {
569           wchar_t wshortname[MAX_PATH + 1];
570           if (GetShortPathNameW (wname, wshortname, G_N_ELEMENTS (wshortname)))
571             {
572               gchar *tem = g_utf16_to_utf8 (wshortname, -1, NULL, NULL, NULL);
573               retval = g_locale_from_utf8 (tem, -1, NULL, NULL, NULL);
574               g_free (tem);
575             }
576           g_free (wname);
577         }
578     }
579   return retval;
580 }
581
582 #define __G_WIN32_C__
583 #include "galiasdef.c"