1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1998 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the
16 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 * Boston, MA 02111-1307, USA.
21 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
22 * file for a list of people on the GLib Team. See the ChangeLog
23 * files for a list of changes. These files are distributed with
24 * GLib at ftp://ftp.gtk.org/pub/gtk/.
28 * MT safe for the unix part, FIXME: make the win32 part MT safe as well.
41 #include <ctype.h> /* For tolower() */
43 #include <sys/types.h>
48 #include <sys/types.h>
49 #ifdef HAVE_SYS_PARAM_H
50 #include <sys/param.h>
52 #ifdef HAVE_CRT_EXTERNS_H
53 #include <crt_externs.h> /* for _NSGetEnviron */
56 /* implement gutils's inline functions
58 #define G_IMPLEMENT_INLINES 1
61 #include "gprintfint.h"
62 #include "gthreadprivate.h"
67 #define G_PATH_LENGTH MAXPATHLEN
68 #elif defined (PATH_MAX)
69 #define G_PATH_LENGTH PATH_MAX
70 #elif defined (_PC_PATH_MAX)
71 #define G_PATH_LENGTH sysconf(_PC_PATH_MAX)
73 #define G_PATH_LENGTH 2048
76 #ifdef G_PLATFORM_WIN32
77 # define STRICT /* Strict typing, please */
80 # ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
81 # define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2
82 # define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4
84 # include <lmcons.h> /* For UNLEN */
85 #endif /* G_PLATFORM_WIN32 */
90 /* older SDK (e.g. msvc 5.0) does not have these*/
91 # ifndef CSIDL_MYMUSIC
92 # define CSIDL_MYMUSIC 13
94 # ifndef CSIDL_MYVIDEO
95 # define CSIDL_MYVIDEO 14
97 # ifndef CSIDL_INTERNET_CACHE
98 # define CSIDL_INTERNET_CACHE 32
100 # ifndef CSIDL_COMMON_APPDATA
101 # define CSIDL_COMMON_APPDATA 35
103 # ifndef CSIDL_MYPICTURES
104 # define CSIDL_MYPICTURES 0x27
106 # ifndef CSIDL_COMMON_DOCUMENTS
107 # define CSIDL_COMMON_DOCUMENTS 46
109 # ifndef CSIDL_PROFILE
110 # define CSIDL_PROFILE 40
112 # include <process.h>
116 #include <CoreServices/CoreServices.h>
120 #include <langinfo.h>
123 #ifdef HAVE_BIND_TEXTDOMAIN_CODESET
127 const guint glib_major_version = GLIB_MAJOR_VERSION;
128 const guint glib_minor_version = GLIB_MINOR_VERSION;
129 const guint glib_micro_version = GLIB_MICRO_VERSION;
130 const guint glib_interface_age = GLIB_INTERFACE_AGE;
131 const guint glib_binary_age = GLIB_BINARY_AGE;
133 #ifdef G_PLATFORM_WIN32
135 static HMODULE glib_dll = NULL;
138 DllMain (HINSTANCE hinstDLL,
142 if (fdwReason == DLL_PROCESS_ATTACH)
149 _glib_get_installation_directory (void)
151 if (glib_dll == NULL)
154 return g_win32_get_package_installation_directory_of_module (glib_dll);
160 * glib_check_version:
161 * @required_major: the required major version.
162 * @required_minor: the required minor version.
163 * @required_micro: the required micro version.
165 * Checks that the GLib library in use is compatible with the
166 * given version. Generally you would pass in the constants
167 * #GLIB_MAJOR_VERSION, #GLIB_MINOR_VERSION, #GLIB_MICRO_VERSION
168 * as the three arguments to this function; that produces
169 * a check that the library in use is compatible with
170 * the version of GLib the application or module was compiled
173 * Compatibility is defined by two things: first the version
174 * of the running library is newer than the version
175 * @required_major.required_minor.@required_micro. Second
176 * the running library must be binary compatible with the
177 * version @required_major.required_minor.@required_micro
178 * (same major version.)
180 * Return value: %NULL if the GLib library is compatible with the
181 * given version, or a string describing the version mismatch.
182 * The returned string is owned by GLib and must not be modified
188 glib_check_version (guint required_major,
189 guint required_minor,
190 guint required_micro)
192 gint glib_effective_micro = 100 * GLIB_MINOR_VERSION + GLIB_MICRO_VERSION;
193 gint required_effective_micro = 100 * required_minor + required_micro;
195 if (required_major > GLIB_MAJOR_VERSION)
196 return "GLib version too old (major mismatch)";
197 if (required_major < GLIB_MAJOR_VERSION)
198 return "GLib version too new (major mismatch)";
199 if (required_effective_micro < glib_effective_micro - GLIB_BINARY_AGE)
200 return "GLib version too new (micro mismatch)";
201 if (required_effective_micro > glib_effective_micro)
202 return "GLib version too old (micro mismatch)";
206 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
209 * @dest: the destination address to copy the bytes to.
210 * @src: the source address to copy the bytes from.
211 * @len: the number of bytes to copy.
213 * Copies a block of memory @len bytes long, from @src to @dest.
214 * The source and destination areas may overlap.
216 * In order to use this function, you must include
217 * <filename>string.h</filename> yourself, because this macro will
218 * typically simply resolve to memmove() and GLib does not include
219 * <filename>string.h</filename> for you.
222 g_memmove (gpointer dest,
226 gchar* destptr = dest;
227 const gchar* srcptr = src;
228 if (src + len < dest || dest + len < src)
230 bcopy (src, dest, len);
233 else if (dest <= src)
236 *(destptr++) = *(srcptr++);
243 *(--destptr) = *(--srcptr);
246 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
254 * @func: the function to call on normal program termination.
256 * Specifies a function to be called at normal program termination.
258 * Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
259 * macro that maps to a call to the atexit() function in the C
260 * library. This means that in case the code that calls g_atexit(),
261 * i.e. atexit(), is in a DLL, the function will be called when the
262 * DLL is detached from the program. This typically makes more sense
263 * than that the function is called when the GLib DLL is detached,
264 * which happened earlier when g_atexit() was a function in the GLib
267 * The behaviour of atexit() in the context of dynamically loaded
268 * modules is not formally specified and varies wildly.
270 * On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
271 * loaded module which is unloaded before the program terminates might
272 * well cause a crash at program exit.
274 * Some POSIX systems implement atexit() like Windows, and have each
275 * dynamically loaded module maintain an own atexit chain that is
276 * called when the module is unloaded.
278 * On other POSIX systems, before a dynamically loaded module is
279 * unloaded, the registered atexit functions (if any) residing in that
280 * module are called, regardless where the code that registered them
281 * resided. This is presumably the most robust approach.
283 * As can be seen from the above, for portability it's best to avoid
284 * calling g_atexit() (or atexit()) except in the main executable of a
288 g_atexit (GVoidFunc func)
291 const gchar *error = NULL;
293 /* keep this in sync with glib.h */
295 #ifdef G_NATIVE_ATEXIT
296 result = ATEXIT (func);
298 error = g_strerror (errno);
299 #elif defined (HAVE_ATEXIT)
300 # ifdef NeXT /* @#%@! NeXTStep */
301 result = !atexit ((void (*)(void)) func);
303 error = g_strerror (errno);
305 result = atexit ((void (*)(void)) func);
307 error = g_strerror (errno);
309 #elif defined (HAVE_ON_EXIT)
310 result = on_exit ((void (*)(int, void *)) func, NULL);
312 error = g_strerror (errno);
315 error = "no implementation";
316 #endif /* G_NATIVE_ATEXIT */
319 g_error ("Could not register atexit() function: %s", error);
322 /* Based on execvp() from GNU Libc.
323 * Some of this code is cut-and-pasted into gspawn.c
327 my_strchrnul (const gchar *str,
330 gchar *p = (gchar*)str;
331 while (*p && (*p != c))
339 static gchar *inner_find_program_in_path (const gchar *program);
342 g_find_program_in_path (const gchar *program)
344 const gchar *last_dot = strrchr (program, '.');
346 if (last_dot == NULL ||
347 strchr (last_dot, '\\') != NULL ||
348 strchr (last_dot, '/') != NULL)
350 const gint program_length = strlen (program);
351 gchar *pathext = g_build_path (";",
352 ".exe;.cmd;.bat;.com",
353 g_getenv ("PATHEXT"),
356 gchar *decorated_program;
362 gchar *q = my_strchrnul (p, ';');
364 decorated_program = g_malloc (program_length + (q-p) + 1);
365 memcpy (decorated_program, program, program_length);
366 memcpy (decorated_program+program_length, p, q-p);
367 decorated_program [program_length + (q-p)] = '\0';
369 retval = inner_find_program_in_path (decorated_program);
370 g_free (decorated_program);
378 } while (*p++ != '\0');
383 return inner_find_program_in_path (program);
389 * g_find_program_in_path:
390 * @program: a program name in the GLib file name encoding
392 * Locates the first executable named @program in the user's path, in the
393 * same way that execvp() would locate it. Returns an allocated string
394 * with the absolute path name, or %NULL if the program is not found in
395 * the path. If @program is already an absolute path, returns a copy of
396 * @program if @program exists and is executable, and %NULL otherwise.
398 * On Windows, if @program does not have a file type suffix, tries
399 * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
400 * the <envar>PATHEXT</envar> environment variable.
402 * On Windows, it looks for the file in the same way as CreateProcess()
403 * would. This means first in the directory where the executing
404 * program was loaded from, then in the current directory, then in the
405 * Windows 32-bit system directory, then in the Windows directory, and
406 * finally in the directories in the <envar>PATH</envar> environment
407 * variable. If the program is found, the return value contains the
408 * full name including the type suffix.
410 * Return value: absolute path, or %NULL
414 inner_find_program_in_path (const gchar *program)
417 g_find_program_in_path (const gchar *program)
420 const gchar *path, *p;
421 gchar *name, *freeme;
423 const gchar *path_copy;
424 gchar *filename = NULL, *appdir = NULL;
425 gchar *sysdir = NULL, *windir = NULL;
427 wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
433 g_return_val_if_fail (program != NULL, NULL);
435 /* If it is an absolute path, or a relative path including subdirectories,
436 * don't look in PATH.
438 if (g_path_is_absolute (program)
439 || strchr (program, G_DIR_SEPARATOR) != NULL
441 || strchr (program, '/') != NULL
445 if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
446 !g_file_test (program, G_FILE_TEST_IS_DIR))
447 return g_strdup (program);
452 path = g_getenv ("PATH");
453 #if defined(G_OS_UNIX) || defined(G_OS_BEOS)
456 /* There is no `PATH' in the environment. The default
457 * search path in GNU libc is the current directory followed by
458 * the path `confstr' returns for `_CS_PATH'.
461 /* In GLib we put . last, for security, and don't use the
462 * unportable confstr(); UNIX98 does not actually specify
463 * what to search if PATH is unset. POSIX may, dunno.
466 path = "/bin:/usr/bin:.";
469 n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
470 if (n > 0 && n < MAXPATHLEN)
471 filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
473 n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
474 if (n > 0 && n < MAXPATHLEN)
475 sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
477 n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
478 if (n > 0 && n < MAXPATHLEN)
479 windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
483 appdir = g_path_get_dirname (filename);
487 path = g_strdup (path);
491 const gchar *tem = path;
492 path = g_strconcat (windir, ";", path, NULL);
493 g_free ((gchar *) tem);
499 const gchar *tem = path;
500 path = g_strconcat (sysdir, ";", path, NULL);
501 g_free ((gchar *) tem);
506 const gchar *tem = path;
507 path = g_strconcat (".;", path, NULL);
508 g_free ((gchar *) tem);
513 const gchar *tem = path;
514 path = g_strconcat (appdir, ";", path, NULL);
515 g_free ((gchar *) tem);
522 len = strlen (program) + 1;
523 pathlen = strlen (path);
524 freeme = name = g_malloc (pathlen + len + 1);
526 /* Copy the file name at the top, including '\0' */
527 memcpy (name + pathlen + 1, program, len);
528 name = name + pathlen;
529 /* And add the slash before the filename */
530 *name = G_DIR_SEPARATOR;
538 p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
541 /* Two adjacent colons, or a colon at the beginning or the end
542 * of `PATH' means to search the current directory.
546 startp = memcpy (name - (p - path), path, p - path);
548 if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
549 !g_file_test (startp, G_FILE_TEST_IS_DIR))
552 ret = g_strdup (startp);
555 g_free ((gchar *) path_copy);
560 while (*p++ != '\0');
564 g_free ((gchar *) path_copy);
571 debug_key_matches (const gchar *key,
575 for (; length; length--, key++, token++)
577 char k = (*key == '_') ? '-' : tolower (*key );
578 char t = (*token == '_') ? '-' : tolower (*token);
588 * g_parse_debug_string:
589 * @string: a list of debug options separated by colons, spaces, or
590 * commas; or the string "all" to set all flags, or %NULL.
591 * @keys: pointer to an array of #GDebugKey which associate
592 * strings with bit flags.
593 * @nkeys: the number of #GDebugKey<!-- -->s in the array.
595 * Parses a string containing debugging options
596 * into a %guint containing bit flags. This is used
597 * within GDK and GTK+ to parse the debug options passed on the
598 * command line or through environment variables.
600 * Returns: the combined set of bit flags.
603 g_parse_debug_string (const gchar *string,
604 const GDebugKey *keys,
613 /* this function is used by gmem.c/gslice.c initialization code,
614 * so introducing malloc dependencies here would require adaptions
615 * of those code portions.
618 if (!g_ascii_strcasecmp (string, "all"))
620 for (i=0; i<nkeys; i++)
621 result |= keys[i].value;
625 const gchar *p = string;
630 q = strpbrk (p, ":;, \t");
634 for (i = 0; i < nkeys; i++)
635 if (debug_key_matches (keys[i].key, p, q - p))
636 result |= keys[i].value;
649 * @file_name: the name of the file.
651 * Gets the name of the file without any leading directory components.
652 * It returns a pointer into the given file name string.
654 * Return value: the name of the file without any leading directory components.
656 * Deprecated:2.2: Use g_path_get_basename() instead, but notice that
657 * g_path_get_basename() allocates new memory for the returned string, unlike
658 * this function which returns a pointer into the argument.
660 G_CONST_RETURN gchar*
661 g_basename (const gchar *file_name)
663 register gchar *base;
665 g_return_val_if_fail (file_name != NULL, NULL);
667 base = strrchr (file_name, G_DIR_SEPARATOR);
671 gchar *q = strrchr (file_name, '/');
672 if (base == NULL || (q != NULL && q > base))
681 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
682 return (gchar*) file_name + 2;
683 #endif /* G_OS_WIN32 */
685 return (gchar*) file_name;
689 * g_path_get_basename:
690 * @file_name: the name of the file.
692 * Gets the last component of the filename. If @file_name ends with a
693 * directory separator it gets the component before the last slash. If
694 * @file_name consists only of directory separators (and on Windows,
695 * possibly a drive letter), a single separator is returned. If
696 * @file_name is empty, it gets ".".
698 * Return value: a newly allocated string containing the last component of
702 g_path_get_basename (const gchar *file_name)
704 register gssize base;
705 register gssize last_nonslash;
709 g_return_val_if_fail (file_name != NULL, NULL);
711 if (file_name[0] == '\0')
713 return g_strdup (".");
715 last_nonslash = strlen (file_name) - 1;
717 while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
720 if (last_nonslash == -1)
721 /* string only containing slashes */
722 return g_strdup (G_DIR_SEPARATOR_S);
725 if (last_nonslash == 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
726 /* string only containing slashes and a drive */
727 return g_strdup (G_DIR_SEPARATOR_S);
728 #endif /* G_OS_WIN32 */
730 base = last_nonslash;
732 while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
736 if (base == -1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
738 #endif /* G_OS_WIN32 */
740 len = last_nonslash - base;
741 retval = g_malloc (len + 1);
742 memcpy (retval, file_name + base + 1, len);
748 * g_path_is_absolute:
749 * @file_name: a file name.
751 * Returns %TRUE if the given @file_name is an absolute file name,
752 * i.e. it contains a full path from the root directory such as "/usr/local"
753 * on UNIX or "C:\windows" on Windows systems.
755 * Returns: %TRUE if @file_name is an absolute path.
758 g_path_is_absolute (const gchar *file_name)
760 g_return_val_if_fail (file_name != NULL, FALSE);
762 if (G_IS_DIR_SEPARATOR (file_name[0]))
766 /* Recognize drive letter on native Windows */
767 if (g_ascii_isalpha (file_name[0]) &&
768 file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
770 #endif /* G_OS_WIN32 */
777 * @file_name: a file name.
779 * Returns a pointer into @file_name after the root component, i.e. after
780 * the "/" in UNIX or "C:\" under Windows. If @file_name is not an absolute
781 * path it returns %NULL.
783 * Returns: a pointer into @file_name after the root component.
785 G_CONST_RETURN gchar*
786 g_path_skip_root (const gchar *file_name)
788 g_return_val_if_fail (file_name != NULL, NULL);
790 #ifdef G_PLATFORM_WIN32
791 /* Skip \\server\share or //server/share */
792 if (G_IS_DIR_SEPARATOR (file_name[0]) &&
793 G_IS_DIR_SEPARATOR (file_name[1]) &&
795 !G_IS_DIR_SEPARATOR (file_name[2]))
799 p = strchr (file_name + 2, G_DIR_SEPARATOR);
802 gchar *q = strchr (file_name + 2, '/');
803 if (p == NULL || (q != NULL && q < p))
813 while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
816 /* Possibly skip a backslash after the share name */
817 if (G_IS_DIR_SEPARATOR (file_name[0]))
820 return (gchar *)file_name;
825 /* Skip initial slashes */
826 if (G_IS_DIR_SEPARATOR (file_name[0]))
828 while (G_IS_DIR_SEPARATOR (file_name[0]))
830 return (gchar *)file_name;
835 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
836 return (gchar *)file_name + 3;
843 * g_path_get_dirname:
844 * @file_name: the name of the file.
846 * Gets the directory components of a file name. If the file name has no
847 * directory components "." is returned. The returned string should be
848 * freed when no longer needed.
850 * Returns: the directory components of the file.
853 g_path_get_dirname (const gchar *file_name)
855 register gchar *base;
858 g_return_val_if_fail (file_name != NULL, NULL);
860 base = strrchr (file_name, G_DIR_SEPARATOR);
863 gchar *q = strrchr (file_name, '/');
864 if (base == NULL || (q != NULL && q > base))
871 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
873 gchar drive_colon_dot[4];
875 drive_colon_dot[0] = file_name[0];
876 drive_colon_dot[1] = ':';
877 drive_colon_dot[2] = '.';
878 drive_colon_dot[3] = '\0';
880 return g_strdup (drive_colon_dot);
883 return g_strdup (".");
886 while (base > file_name && G_IS_DIR_SEPARATOR (*base))
890 /* base points to the char before the last slash.
892 * In case file_name is the root of a drive (X:\) or a child of the
893 * root of a drive (X:\foo), include the slash.
895 * In case file_name is the root share of an UNC path
896 * (\\server\share), add a slash, returning \\server\share\ .
898 * In case file_name is a direct child of a share in an UNC path
899 * (\\server\share\foo), include the slash after the share name,
900 * returning \\server\share\ .
902 if (base == file_name + 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
904 else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
905 G_IS_DIR_SEPARATOR (file_name[1]) &&
907 !G_IS_DIR_SEPARATOR (file_name[2]) &&
908 base >= file_name + 2)
910 const gchar *p = file_name + 2;
911 while (*p && !G_IS_DIR_SEPARATOR (*p))
915 len = (guint) strlen (file_name) + 1;
916 base = g_new (gchar, len + 1);
917 strcpy (base, file_name);
918 base[len-1] = G_DIR_SEPARATOR;
922 if (G_IS_DIR_SEPARATOR (*p))
925 while (*p && !G_IS_DIR_SEPARATOR (*p))
933 len = (guint) 1 + base - file_name;
935 base = g_new (gchar, len + 1);
936 g_memmove (base, file_name, len);
945 * Gets the current directory.
946 * The returned string should be freed when no longer needed. The encoding
947 * of the returned string is system defined. On Windows, it is always UTF-8.
949 * Returns: the current directory.
952 g_get_current_dir (void)
957 wchar_t dummy[2], *wdir;
960 len = GetCurrentDirectoryW (2, dummy);
961 wdir = g_new (wchar_t, len);
963 if (GetCurrentDirectoryW (len, wdir) == len - 1)
964 dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
969 dir = g_strdup ("\\");
975 gchar *buffer = NULL;
977 static gulong max_len = 0;
980 max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
982 /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
983 * and, if that wasn't bad enough, hangs in doing so.
985 #if (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
986 buffer = g_new (gchar, max_len + 1);
988 dir = getwd (buffer);
989 #else /* !sun || !HAVE_GETCWD */
990 while (max_len < G_MAXULONG / 2)
993 buffer = g_new (gchar, max_len + 1);
995 dir = getcwd (buffer, max_len);
997 if (dir || errno != ERANGE)
1002 #endif /* !sun || !HAVE_GETCWD */
1004 if (!dir || !*buffer)
1006 /* hm, should we g_error() out here?
1007 * this can happen if e.g. "./" has mode \0000
1009 buffer[0] = G_DIR_SEPARATOR;
1013 dir = g_strdup (buffer);
1022 * @variable: the environment variable to get, in the GLib file name encoding.
1024 * Returns the value of an environment variable. The name and value
1025 * are in the GLib file name encoding. On UNIX, this means the actual
1026 * bytes which might or might not be in some consistent character set
1027 * and encoding. On Windows, it is in UTF-8. On Windows, in case the
1028 * environment variable's value contains references to other
1029 * environment variables, they are expanded.
1031 * Return value: the value of the environment variable, or %NULL if
1032 * the environment variable is not found. The returned string may be
1033 * overwritten by the next call to g_getenv(), g_setenv() or
1036 G_CONST_RETURN gchar*
1037 g_getenv (const gchar *variable)
1041 g_return_val_if_fail (variable != NULL, NULL);
1043 return getenv (variable);
1045 #else /* G_OS_WIN32 */
1049 wchar_t dummy[2], *wname, *wvalue;
1052 g_return_val_if_fail (variable != NULL, NULL);
1053 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), NULL);
1055 /* On Windows NT, it is relatively typical that environment
1056 * variables contain references to other environment variables. If
1057 * so, use ExpandEnvironmentStrings(). (In an ideal world, such
1058 * environment variables would be stored in the Registry as
1059 * REG_EXPAND_SZ type values, and would then get automatically
1060 * expanded before a program sees them. But there is broken software
1061 * that stores environment variables as REG_SZ values even if they
1062 * contain references to other environment variables.)
1065 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1067 len = GetEnvironmentVariableW (wname, dummy, 2);
1077 wvalue = g_new (wchar_t, len);
1079 if (GetEnvironmentVariableW (wname, wvalue, len) != len - 1)
1086 if (wcschr (wvalue, L'%') != NULL)
1088 wchar_t *tem = wvalue;
1090 len = ExpandEnvironmentStringsW (wvalue, dummy, 2);
1094 wvalue = g_new (wchar_t, len);
1096 if (ExpandEnvironmentStringsW (tem, wvalue, len) != len)
1106 value = g_utf16_to_utf8 (wvalue, -1, NULL, NULL, NULL);
1111 quark = g_quark_from_string (value);
1114 return g_quark_to_string (quark);
1116 #endif /* G_OS_WIN32 */
1119 /* _g_getenv_nomalloc
1120 * this function does a getenv() without doing any kind of allocation
1121 * through glib. it's suitable for chars <= 127 only (both, for the
1122 * variable name and the contents) and for contents < 1024 chars in
1123 * length. also, it aliases "" to a NULL return value.
1126 _g_getenv_nomalloc (const gchar *variable,
1129 const gchar *retval = getenv (variable);
1130 if (retval && retval[0])
1132 gint l = strlen (retval);
1135 strncpy (buffer, retval, l);
1145 * @variable: the environment variable to set, must not contain '='.
1146 * @value: the value for to set the variable to.
1147 * @overwrite: whether to change the variable if it already exists.
1149 * Sets an environment variable. Both the variable's name and value
1150 * should be in the GLib file name encoding. On UNIX, this means that
1151 * they can be any sequence of bytes. On Windows, they should be in
1154 * Note that on some systems, when variables are overwritten, the memory
1155 * used for the previous variables and its value isn't reclaimed.
1157 * Returns: %FALSE if the environment variable couldn't be set.
1162 g_setenv (const gchar *variable,
1173 g_return_val_if_fail (variable != NULL, FALSE);
1174 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1177 result = setenv (variable, value, overwrite);
1179 if (!overwrite && getenv (variable) != NULL)
1182 /* This results in a leak when you overwrite existing
1183 * settings. It would be fairly easy to fix this by keeping
1184 * our own parallel array or hash table.
1186 string = g_strconcat (variable, "=", value, NULL);
1187 result = putenv (string);
1191 #else /* G_OS_WIN32 */
1194 wchar_t *wname, *wvalue, *wassignment;
1197 g_return_val_if_fail (variable != NULL, FALSE);
1198 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1199 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), FALSE);
1200 g_return_val_if_fail (g_utf8_validate (value, -1, NULL), FALSE);
1202 if (!overwrite && g_getenv (variable) != NULL)
1205 /* We want to (if possible) set both the environment variable copy
1206 * kept by the C runtime and the one kept by the system.
1208 * We can't use only the C runtime's putenv or _wputenv() as that
1209 * won't work for arbitrary Unicode strings in a "non-Unicode" app
1210 * (with main() and not wmain()). In a "main()" app the C runtime
1211 * initializes the C runtime's environment table by converting the
1212 * real (wide char) environment variables to system codepage, thus
1213 * breaking those that aren't representable in the system codepage.
1215 * As the C runtime's putenv() will also set the system copy, we do
1216 * the putenv() first, then call SetEnvironmentValueW ourselves.
1219 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1220 wvalue = g_utf8_to_utf16 (value, -1, NULL, NULL, NULL);
1221 tem = g_strconcat (variable, "=", value, NULL);
1222 wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1225 _wputenv (wassignment);
1226 g_free (wassignment);
1228 retval = (SetEnvironmentVariableW (wname, wvalue) != 0);
1235 #endif /* G_OS_WIN32 */
1238 #ifdef HAVE__NSGETENVIRON
1239 #define environ (*_NSGetEnviron())
1240 #elif !defined(G_OS_WIN32)
1242 /* According to the Single Unix Specification, environ is not in
1243 * any system header, although unistd.h often declares it.
1245 extern char **environ;
1250 * @variable: the environment variable to remove, must not contain '='.
1252 * Removes an environment variable from the environment.
1254 * Note that on some systems, when variables are overwritten, the memory
1255 * used for the previous variables and its value isn't reclaimed.
1256 * Furthermore, this function can't be guaranteed to operate in a
1262 g_unsetenv (const gchar *variable)
1266 #ifdef HAVE_UNSETENV
1267 g_return_if_fail (variable != NULL);
1268 g_return_if_fail (strchr (variable, '=') == NULL);
1270 unsetenv (variable);
1271 #else /* !HAVE_UNSETENV */
1275 g_return_if_fail (variable != NULL);
1276 g_return_if_fail (strchr (variable, '=') == NULL);
1278 len = strlen (variable);
1280 /* Mess directly with the environ array.
1281 * This seems to be the only portable way to do this.
1283 * Note that we remove *all* environment entries for
1284 * the variable name, not just the first.
1289 if (strncmp (*e, variable, len) != 0 || (*e)[len] != '=')
1297 #endif /* !HAVE_UNSETENV */
1299 #else /* G_OS_WIN32 */
1301 wchar_t *wname, *wassignment;
1304 g_return_if_fail (variable != NULL);
1305 g_return_if_fail (strchr (variable, '=') == NULL);
1306 g_return_if_fail (g_utf8_validate (variable, -1, NULL));
1308 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1309 tem = g_strconcat (variable, "=", NULL);
1310 wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1313 _wputenv (wassignment);
1314 g_free (wassignment);
1316 SetEnvironmentVariableW (wname, NULL);
1320 #endif /* G_OS_WIN32 */
1326 * Gets the names of all variables set in the environment.
1328 * Returns: a %NULL-terminated list of strings which must be freed
1329 * with g_strfreev().
1331 * Programs that want to be portable to Windows should typically use
1332 * this function and g_getenv() instead of using the environ array
1333 * from the C library directly. On Windows, the strings in the environ
1334 * array are in system codepage encoding, while in most of the typical
1335 * use cases for environment variables in GLib-using programs you want
1336 * the UTF-8 encoding that this function and g_getenv() provide.
1344 gchar **result, *eq;
1347 len = g_strv_length (environ);
1348 result = g_new0 (gchar *, len + 1);
1351 for (i = 0; i < len; i++)
1353 eq = strchr (environ[i], '=');
1355 result[j++] = g_strndup (environ[i], eq - environ[i]);
1362 gchar **result, *eq;
1366 p = (wchar_t *) GetEnvironmentStringsW ();
1372 q += wcslen (q) + 1;
1376 result = g_new0 (gchar *, len + 1);
1382 result[j] = g_utf16_to_utf8 (q, -1, NULL, NULL, NULL);
1383 if (result[j] != NULL)
1385 eq = strchr (result[j], '=');
1386 if (eq && eq > result[j])
1394 q += wcslen (q) + 1;
1397 FreeEnvironmentStringsW (p);
1403 G_LOCK_DEFINE_STATIC (g_utils_global);
1405 static gchar *g_tmp_dir = NULL;
1406 static gchar *g_user_name = NULL;
1407 static gchar *g_real_name = NULL;
1408 static gchar *g_home_dir = NULL;
1409 static gchar *g_host_name = NULL;
1412 /* System codepage versions of the above, kept at file level so that they,
1413 * too, are produced only once.
1415 static gchar *g_tmp_dir_cp = NULL;
1416 static gchar *g_user_name_cp = NULL;
1417 static gchar *g_real_name_cp = NULL;
1418 static gchar *g_home_dir_cp = NULL;
1421 static gchar *g_user_data_dir = NULL;
1422 static gchar **g_system_data_dirs = NULL;
1423 static gchar *g_user_cache_dir = NULL;
1424 static gchar *g_user_config_dir = NULL;
1425 static gchar **g_system_config_dirs = NULL;
1427 static gchar **g_user_special_dirs = NULL;
1429 /* fifteen minutes of fame for everybody */
1430 #define G_USER_DIRS_EXPIRE 15 * 60
1435 get_special_folder (int csidl)
1437 wchar_t path[MAX_PATH+1];
1439 LPITEMIDLIST pidl = NULL;
1441 gchar *retval = NULL;
1443 hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
1446 b = SHGetPathFromIDListW (pidl, path);
1448 retval = g_utf16_to_utf8 (path, -1, NULL, NULL, NULL);
1449 CoTaskMemFree (pidl);
1455 get_windows_directory_root (void)
1457 wchar_t wwindowsdir[MAX_PATH];
1459 if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
1461 /* Usually X:\Windows, but in terminal server environments
1462 * might be an UNC path, AFAIK.
1464 char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
1467 if (windowsdir == NULL)
1468 return g_strdup ("C:\\");
1470 p = (char *) g_path_skip_root (windowsdir);
1471 if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
1477 return g_strdup ("C:\\");
1482 /* HOLDS: g_utils_global_lock */
1484 g_get_any_init_do (void)
1486 gchar hostname[100];
1488 g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
1490 g_tmp_dir = g_strdup (g_getenv ("TMP"));
1492 g_tmp_dir = g_strdup (g_getenv ("TEMP"));
1496 g_tmp_dir = get_windows_directory_root ();
1502 g_tmp_dir = g_strdup (P_tmpdir);
1503 k = strlen (g_tmp_dir);
1504 if (k > 1 && G_IS_DIR_SEPARATOR (g_tmp_dir[k - 1]))
1505 g_tmp_dir[k - 1] = '\0';
1511 g_tmp_dir = g_strdup ("/tmp");
1513 #endif /* !G_OS_WIN32 */
1516 /* We check $HOME first for Win32, though it is a last resort for Unix
1517 * where we prefer the results of getpwuid().
1519 g_home_dir = g_strdup (g_getenv ("HOME"));
1521 /* Only believe HOME if it is an absolute path and exists */
1524 if (!(g_path_is_absolute (g_home_dir) &&
1525 g_file_test (g_home_dir, G_FILE_TEST_IS_DIR)))
1527 g_free (g_home_dir);
1532 /* In case HOME is Unix-style (it happens), convert it to
1538 while ((p = strchr (g_home_dir, '/')) != NULL)
1544 /* USERPROFILE is probably the closest equivalent to $HOME? */
1545 if (g_getenv ("USERPROFILE") != NULL)
1546 g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
1550 g_home_dir = get_special_folder (CSIDL_PROFILE);
1553 g_home_dir = get_windows_directory_root ();
1554 #endif /* G_OS_WIN32 */
1558 struct passwd *pw = NULL;
1559 gpointer buffer = NULL;
1563 # if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
1565 # ifdef _SC_GETPW_R_SIZE_MAX
1566 /* This reurns the maximum length */
1567 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
1571 # else /* _SC_GETPW_R_SIZE_MAX */
1573 # endif /* _SC_GETPW_R_SIZE_MAX */
1575 logname = (gchar *) g_getenv ("LOGNAME");
1580 /* we allocate 6 extra bytes to work around a bug in
1581 * Mac OS < 10.3. See #156446
1583 buffer = g_malloc (bufsize + 6);
1586 # ifdef HAVE_POSIX_GETPWUID_R
1588 error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
1589 if (!pw || (pw->pw_uid != getuid ())) {
1590 /* LOGNAME is lying, fall back to looking up the uid */
1591 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1594 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1596 error = error < 0 ? errno : error;
1597 # else /* HAVE_NONPOSIX_GETPWUID_R */
1598 /* HPUX 11 falls into the HAVE_POSIX_GETPWUID_R case */
1599 # if defined(_AIX) || defined(__hpux)
1600 error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1601 pw = error == 0 ? &pwd : NULL;
1604 pw = getpwnam_r (logname, &pwd, buffer, bufsize);
1605 if (!pw || (pw->pw_uid != getuid ())) {
1606 /* LOGNAME is lying, fall back to looking up the uid */
1607 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1610 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1612 error = pw ? 0 : errno;
1614 # endif /* HAVE_NONPOSIX_GETPWUID_R */
1618 /* we bail out prematurely if the user id can't be found
1619 * (should be pretty rare case actually), or if the buffer
1620 * should be sufficiently big and lookups are still not
1623 if (error == 0 || error == ENOENT)
1625 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
1626 (gulong) getuid ());
1629 if (bufsize > 32 * 1024)
1631 g_warning ("getpwuid_r(): failed due to: %s.",
1632 g_strerror (error));
1640 # endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
1645 pw = getpwuid (getuid ());
1650 g_user_name = g_strdup (pw->pw_name);
1652 if (pw->pw_gecos && *pw->pw_gecos != '\0')
1654 gchar **gecos_fields;
1657 /* split the gecos field and substitute '&' */
1658 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
1659 name_parts = g_strsplit (gecos_fields[0], "&", 0);
1660 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
1661 g_real_name = g_strjoinv (pw->pw_name, name_parts);
1662 g_strfreev (gecos_fields);
1663 g_strfreev (name_parts);
1667 g_home_dir = g_strdup (pw->pw_dir);
1672 #else /* !HAVE_PWD_H */
1676 guint len = UNLEN+1;
1677 wchar_t buffer[UNLEN+1];
1679 if (GetUserNameW (buffer, (LPDWORD) &len))
1681 g_user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
1682 g_real_name = g_strdup (g_user_name);
1685 #endif /* G_OS_WIN32 */
1687 #endif /* !HAVE_PWD_H */
1691 g_home_dir = g_strdup (g_getenv ("HOME"));
1695 /* change '\\' in %HOME% to '/' */
1696 g_strdelimit (g_home_dir, "\\",'/');
1699 g_user_name = g_strdup ("somebody");
1701 g_real_name = g_strdup ("Unknown");
1705 gboolean hostname_fail = (gethostname (hostname, sizeof (hostname)) == -1);
1707 DWORD size = sizeof (hostname);
1708 gboolean hostname_fail = (!GetComputerName (hostname, &size));
1710 g_host_name = g_strdup (hostname_fail ? "localhost" : hostname);
1714 g_tmp_dir_cp = g_locale_from_utf8 (g_tmp_dir, -1, NULL, NULL, NULL);
1715 g_user_name_cp = g_locale_from_utf8 (g_user_name, -1, NULL, NULL, NULL);
1716 g_real_name_cp = g_locale_from_utf8 (g_real_name, -1, NULL, NULL, NULL);
1719 g_tmp_dir_cp = g_strdup ("\\");
1720 if (!g_user_name_cp)
1721 g_user_name_cp = g_strdup ("somebody");
1722 if (!g_real_name_cp)
1723 g_real_name_cp = g_strdup ("Unknown");
1725 /* home_dir might be NULL, unlike tmp_dir, user_name and
1729 g_home_dir_cp = g_locale_from_utf8 (g_home_dir, -1, NULL, NULL, NULL);
1731 g_home_dir_cp = NULL;
1732 #endif /* G_OS_WIN32 */
1736 g_get_any_init (void)
1739 g_get_any_init_do ();
1743 g_get_any_init_locked (void)
1745 G_LOCK (g_utils_global);
1747 G_UNLOCK (g_utils_global);
1754 * Gets the user name of the current user. The encoding of the returned
1755 * string is system-defined. On UNIX, it might be the preferred file name
1756 * encoding, or something else, and there is no guarantee that it is even
1757 * consistent on a machine. On Windows, it is always UTF-8.
1759 * Returns: the user name of the current user.
1761 G_CONST_RETURN gchar*
1762 g_get_user_name (void)
1764 g_get_any_init_locked ();
1771 * Gets the real name of the user. This usually comes from the user's entry
1772 * in the <filename>passwd</filename> file. The encoding of the returned
1773 * string is system-defined. (On Windows, it is, however, always UTF-8.)
1774 * If the real user name cannot be determined, the string "Unknown" is
1777 * Returns: the user's real name.
1779 G_CONST_RETURN gchar*
1780 g_get_real_name (void)
1782 g_get_any_init_locked ();
1789 * Gets the current user's home directory as defined in the
1790 * password database.
1792 * Note that in contrast to traditional UNIX tools, this function
1793 * prefers <filename>passwd</filename> entries over the <envar>HOME</envar>
1794 * environment variable.
1796 * One of the reasons for this decision is that applications in many
1797 * cases need special handling to deal with the case where
1798 * <envar>HOME</envar> is
1800 * <member>Not owned by the user</member>
1801 * <member>Not writeable</member>
1802 * <member>Not even readable</member>
1804 * Since applications are in general <emphasis>not</emphasis> written
1805 * to deal with these situations it was considered better to make
1806 * g_get_homedir() not pay attention to <envar>HOME</envar> and to
1807 * return the real home directory for the user. If applications
1808 * want to pay attention to <envar>HOME</envar>, they can do:
1810 * const char *homedir = g_getenv ("HOME");
1812 * homedir = g_get_homedir (<!-- -->);
1815 * Returns: the current user's home directory
1817 G_CONST_RETURN gchar*
1818 g_get_home_dir (void)
1820 g_get_any_init_locked ();
1827 * Gets the directory to use for temporary files. This is found from
1828 * inspecting the environment variables <envar>TMPDIR</envar>,
1829 * <envar>TMP</envar>, and <envar>TEMP</envar> in that order. If none
1830 * of those are defined "/tmp" is returned on UNIX and "C:\" on Windows.
1831 * The encoding of the returned string is system-defined. On Windows,
1832 * it is always UTF-8. The return value is never %NULL.
1834 * Returns: the directory to use for temporary files.
1836 G_CONST_RETURN gchar*
1837 g_get_tmp_dir (void)
1839 g_get_any_init_locked ();
1846 * Return a name for the machine.
1848 * The returned name is not necessarily a fully-qualified domain name,
1849 * or even present in DNS or some other name service at all. It need
1850 * not even be unique on your local network or site, but usually it
1851 * is. Callers should not rely on the return value having any specific
1852 * properties like uniqueness for security purposes. Even if the name
1853 * of the machine is changed while an application is running, the
1854 * return value from this function does not change. The returned
1855 * string is owned by GLib and should not be modified or freed. If no
1856 * name can be determined, a default fixed string "localhost" is
1859 * Returns: the host name of the machine.
1864 g_get_host_name (void)
1866 g_get_any_init_locked ();
1870 G_LOCK_DEFINE_STATIC (g_prgname);
1871 static gchar *g_prgname = NULL;
1876 * Gets the name of the program. This name should <emphasis>not</emphasis>
1877 * be localized, contrast with g_get_application_name().
1878 * (If you are using GDK or GTK+ the program name is set in gdk_init(),
1879 * which is called by gtk_init(). The program name is found by taking
1880 * the last component of <literal>argv[0]</literal>.)
1882 * Returns: the name of the program. The returned string belongs
1883 * to GLib and must not be modified or freed.
1886 g_get_prgname (void)
1892 if (g_prgname == NULL)
1894 static gboolean beenhere = FALSE;
1898 gchar *utf8_buf = NULL;
1899 wchar_t buf[MAX_PATH+1];
1902 if (GetModuleFileNameW (GetModuleHandle (NULL),
1903 buf, G_N_ELEMENTS (buf)) > 0)
1904 utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
1908 g_prgname = g_path_get_basename (utf8_buf);
1915 G_UNLOCK (g_prgname);
1922 * @prgname: the name of the program.
1924 * Sets the name of the program. This name should <emphasis>not</emphasis>
1925 * be localized, contrast with g_set_application_name(). Note that for
1926 * thread-safety reasons this function can only be called once.
1929 g_set_prgname (const gchar *prgname)
1933 g_prgname = g_strdup (prgname);
1934 G_UNLOCK (g_prgname);
1937 G_LOCK_DEFINE_STATIC (g_application_name);
1938 static gchar *g_application_name = NULL;
1941 * g_get_application_name:
1943 * Gets a human-readable name for the application, as set by
1944 * g_set_application_name(). This name should be localized if
1945 * possible, and is intended for display to the user. Contrast with
1946 * g_get_prgname(), which gets a non-localized name. If
1947 * g_set_application_name() has not been called, returns the result of
1948 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1951 * Return value: human-readable application name. may return %NULL
1955 G_CONST_RETURN gchar*
1956 g_get_application_name (void)
1960 G_LOCK (g_application_name);
1961 retval = g_application_name;
1962 G_UNLOCK (g_application_name);
1965 return g_get_prgname ();
1971 * g_set_application_name:
1972 * @application_name: localized name of the application
1974 * Sets a human-readable name for the application. This name should be
1975 * localized if possible, and is intended for display to the user.
1976 * Contrast with g_set_prgname(), which sets a non-localized name.
1977 * g_set_prgname() will be called automatically by gtk_init(),
1978 * but g_set_application_name() will not.
1980 * Note that for thread safety reasons, this function can only
1983 * The application name will be used in contexts such as error messages,
1984 * or when displaying an application's name in the task list.
1989 g_set_application_name (const gchar *application_name)
1991 gboolean already_set = FALSE;
1993 G_LOCK (g_application_name);
1994 if (g_application_name)
1997 g_application_name = g_strdup (application_name);
1998 G_UNLOCK (g_application_name);
2001 g_warning ("g_set_application() name called multiple times");
2005 * g_get_user_data_dir:
2007 * Returns a base directory in which to access application data such
2008 * as icons that is customized for a particular user.
2010 * On UNIX platforms this is determined using the mechanisms described in
2011 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2012 * XDG Base Directory Specification</ulink>
2014 * Return value: a string owned by GLib that must not be modified
2018 G_CONST_RETURN gchar*
2019 g_get_user_data_dir (void)
2023 G_LOCK (g_utils_global);
2025 if (!g_user_data_dir)
2028 data_dir = get_special_folder (CSIDL_PERSONAL);
2030 data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
2032 if (data_dir && data_dir[0])
2033 data_dir = g_strdup (data_dir);
2035 if (!data_dir || !data_dir[0])
2040 data_dir = g_build_filename (g_home_dir, ".local",
2043 data_dir = g_build_filename (g_tmp_dir, g_user_name, ".local",
2047 g_user_data_dir = data_dir;
2050 data_dir = g_user_data_dir;
2052 G_UNLOCK (g_utils_global);
2058 g_init_user_config_dir (void)
2062 if (!g_user_config_dir)
2065 config_dir = get_special_folder (CSIDL_APPDATA);
2067 config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
2069 if (config_dir && config_dir[0])
2070 config_dir = g_strdup (config_dir);
2072 if (!config_dir || !config_dir[0])
2077 config_dir = g_build_filename (g_home_dir, ".config", NULL);
2079 config_dir = g_build_filename (g_tmp_dir, g_user_name, ".config", NULL);
2082 g_user_config_dir = config_dir;
2087 * g_get_user_config_dir:
2089 * Returns a base directory in which to store user-specific application
2090 * configuration information such as user preferences and settings.
2092 * On UNIX platforms this is determined using the mechanisms described in
2093 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2094 * XDG Base Directory Specification</ulink>
2096 * Return value: a string owned by GLib that must not be modified
2100 G_CONST_RETURN gchar*
2101 g_get_user_config_dir (void)
2103 G_LOCK (g_utils_global);
2105 g_init_user_config_dir ();
2107 G_UNLOCK (g_utils_global);
2109 return g_user_config_dir;
2113 * g_get_user_cache_dir:
2115 * Returns a base directory in which to store non-essential, cached
2116 * data specific to particular user.
2118 * On UNIX platforms this is determined using the mechanisms described in
2119 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2120 * XDG Base Directory Specification</ulink>
2122 * Return value: a string owned by GLib that must not be modified
2126 G_CONST_RETURN gchar*
2127 g_get_user_cache_dir (void)
2131 G_LOCK (g_utils_global);
2133 if (!g_user_cache_dir)
2136 cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
2138 cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
2140 if (cache_dir && cache_dir[0])
2141 cache_dir = g_strdup (cache_dir);
2143 if (!cache_dir || !cache_dir[0])
2148 cache_dir = g_build_filename (g_home_dir, ".cache", NULL);
2150 cache_dir = g_build_filename (g_tmp_dir, g_user_name, ".cache", NULL);
2152 g_user_cache_dir = cache_dir;
2155 cache_dir = g_user_cache_dir;
2157 G_UNLOCK (g_utils_global);
2165 find_folder (OSType type)
2167 gchar *filename = NULL;
2170 if (FSFindFolder (kUserDomain, type, kDontCreateFolder, &found) == noErr)
2172 CFURLRef url = CFURLCreateFromFSRef (kCFAllocatorSystemDefault, &found);
2176 CFStringRef path = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle);
2180 filename = g_strdup (CFStringGetCStringPtr (path, kCFStringEncodingUTF8));
2184 filename = g_new0 (gchar, CFStringGetLength (path) * 3 + 1);
2186 CFStringGetCString (path, filename,
2187 CFStringGetLength (path) * 3 + 1,
2188 kCFStringEncodingUTF8);
2202 load_user_special_dirs (void)
2204 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = find_folder (kDesktopFolderType);
2205 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = find_folder (kDocumentsFolderType);
2206 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = find_folder (kDesktopFolderType); /* XXX correct ? */
2207 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = find_folder (kMusicDocumentsFolderType);
2208 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = find_folder (kPictureDocumentsFolderType);
2209 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = NULL;
2210 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = NULL;
2211 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = find_folder (kMovieDocumentsFolderType);
2214 #endif /* HAVE_CARBON */
2216 #if defined(G_OS_WIN32)
2218 load_user_special_dirs (void)
2220 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2221 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
2222 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY); /* XXX correct ? */
2223 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
2224 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
2225 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS); /* XXX correct ? */
2226 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
2227 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
2229 #endif /* G_OS_WIN32 */
2231 static void g_init_user_config_dir (void);
2233 #if defined(G_OS_UNIX) && !defined(HAVE_CARBON)
2235 /* adapted from xdg-user-dir-lookup.c
2237 * Copyright (C) 2007 Red Hat Inc.
2239 * Permission is hereby granted, free of charge, to any person
2240 * obtaining a copy of this software and associated documentation files
2241 * (the "Software"), to deal in the Software without restriction,
2242 * including without limitation the rights to use, copy, modify, merge,
2243 * publish, distribute, sublicense, and/or sell copies of the Software,
2244 * and to permit persons to whom the Software is furnished to do so,
2245 * subject to the following conditions:
2247 * The above copyright notice and this permission notice shall be
2248 * included in all copies or substantial portions of the Software.
2250 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
2251 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
2252 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
2253 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
2254 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
2255 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
2256 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2260 load_user_special_dirs (void)
2267 g_init_user_config_dir ();
2268 config_file = g_build_filename (g_user_config_dir,
2272 if (!g_file_get_contents (config_file, &data, NULL, NULL))
2274 g_free (config_file);
2278 lines = g_strsplit (data, "\n", -1);
2279 n_lines = g_strv_length (lines);
2282 for (i = 0; i < n_lines; i++)
2284 gchar *buffer = lines[i];
2287 gboolean is_relative = FALSE;
2288 GUserDirectory directory;
2290 /* Remove newline at end */
2291 len = strlen (buffer);
2292 if (len > 0 && buffer[len - 1] == '\n')
2293 buffer[len - 1] = 0;
2296 while (*p == ' ' || *p == '\t')
2299 if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
2301 directory = G_USER_DIRECTORY_DESKTOP;
2302 p += strlen ("XDG_DESKTOP_DIR");
2304 else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
2306 directory = G_USER_DIRECTORY_DOCUMENTS;
2307 p += strlen ("XDG_DOCUMENTS_DIR");
2309 else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
2311 directory = G_USER_DIRECTORY_DOWNLOAD;
2312 p += strlen ("XDG_DOWNLOAD_DIR");
2314 else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
2316 directory = G_USER_DIRECTORY_MUSIC;
2317 p += strlen ("XDG_MUSIC_DIR");
2319 else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
2321 directory = G_USER_DIRECTORY_PICTURES;
2322 p += strlen ("XDG_PICTURES_DIR");
2324 else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
2326 directory = G_USER_DIRECTORY_PUBLIC_SHARE;
2327 p += strlen ("XDG_PUBLICSHARE_DIR");
2329 else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
2331 directory = G_USER_DIRECTORY_TEMPLATES;
2332 p += strlen ("XDG_TEMPLATES_DIR");
2334 else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
2336 directory = G_USER_DIRECTORY_VIDEOS;
2337 p += strlen ("XDG_VIDEOS_DIR");
2342 while (*p == ' ' || *p == '\t')
2349 while (*p == ' ' || *p == '\t')
2356 if (strncmp (p, "$HOME", 5) == 0)
2364 d = strrchr (p, '"');
2371 /* remove trailing slashes */
2373 if (d[len - 1] == '/')
2379 g_user_special_dirs[directory] = g_build_filename (g_home_dir, d, NULL);
2382 g_user_special_dirs[directory] = g_strdup (d);
2386 g_free (config_file);
2389 #endif /* G_OS_UNIX && !HAVE_CARBON */
2392 * g_get_user_special_dir:
2393 * @directory: the logical id of special directory
2395 * Returns the full path of a special directory using its logical id.
2397 * On Unix this is done using the XDG special user directories.
2399 * Depending on the platform, the user might be able to change the path
2400 * of the special directory without requiring the session to restart; GLib
2401 * will not reflect any change once the special directories are loaded.
2403 * Return value: the path to the specified special directory, or %NULL
2404 * if the logical id was not found. The returned string is owned by
2405 * GLib and should not be modified or freed.
2409 G_CONST_RETURN gchar *
2410 g_get_user_special_dir (GUserDirectory directory)
2412 g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
2413 directory < G_USER_N_DIRECTORIES, NULL);
2415 G_LOCK (g_utils_global);
2417 if (G_UNLIKELY (g_user_special_dirs == NULL))
2419 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
2421 load_user_special_dirs ();
2423 /* Special-case desktop for historical compatibility */
2424 if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
2428 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] =
2429 g_build_filename (g_home_dir, "Desktop", NULL);
2433 G_UNLOCK (g_utils_global);
2435 return g_user_special_dirs[directory];
2440 #undef g_get_system_data_dirs
2443 get_module_for_address (gconstpointer address)
2445 /* Holds the g_utils_global lock */
2447 static gboolean beenhere = FALSE;
2448 typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
2449 static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
2450 HMODULE hmodule = NULL;
2457 p_GetModuleHandleExA =
2458 (t_GetModuleHandleExA) GetProcAddress (LoadLibrary ("kernel32.dll"),
2459 "GetModuleHandleExA");
2463 if (p_GetModuleHandleExA == NULL ||
2464 !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
2465 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
2468 MEMORY_BASIC_INFORMATION mbi;
2469 VirtualQuery (address, &mbi, sizeof (mbi));
2470 hmodule = (HMODULE) mbi.AllocationBase;
2477 get_module_share_dir (gconstpointer address)
2483 hmodule = get_module_for_address (address);
2484 if (hmodule == NULL)
2487 filename = g_win32_get_package_installation_directory_of_module (hmodule);
2488 retval = g_build_filename (filename, "share", NULL);
2494 G_CONST_RETURN gchar * G_CONST_RETURN *
2495 g_win32_get_system_data_dirs_for_module (gconstpointer address)
2499 static GHashTable *per_module_data_dirs = NULL;
2506 G_LOCK (g_utils_global);
2507 hmodule = get_module_for_address (address);
2508 if (hmodule != NULL)
2510 if (per_module_data_dirs == NULL)
2511 per_module_data_dirs = g_hash_table_new (NULL, NULL);
2514 retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
2518 G_UNLOCK (g_utils_global);
2519 return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2525 data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
2527 /* Documents and Settings\All Users\Application Data */
2528 p = get_special_folder (CSIDL_COMMON_APPDATA);
2530 g_array_append_val (data_dirs, p);
2532 /* Documents and Settings\All Users\Documents */
2533 p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2535 g_array_append_val (data_dirs, p);
2537 /* Using the above subfolders of Documents and Settings perhaps
2538 * makes sense from a Windows perspective.
2540 * But looking at the actual use cases of this function in GTK+
2541 * and GNOME software, what we really want is the "share"
2542 * subdirectory of the installation directory for the package
2543 * our caller is a part of.
2545 * The address parameter, if non-NULL, points to a function in the
2546 * calling module. Use that to determine that module's installation
2547 * folder, and use its "share" subfolder.
2549 * Additionally, also use the "share" subfolder of the installation
2550 * locations of GLib and the .exe file being run.
2552 * To guard against none of the above being what is really wanted,
2553 * callers of this function should have Win32-specific code to look
2554 * up their installation folder themselves, and handle a subfolder
2555 * "share" of it in the same way as the folders returned from this
2559 p = get_module_share_dir (address);
2561 g_array_append_val (data_dirs, p);
2563 if (glib_dll != NULL)
2565 gchar *glib_root = g_win32_get_package_installation_directory_of_module (glib_dll);
2566 p = g_build_filename (glib_root, "share", NULL);
2568 g_array_append_val (data_dirs, p);
2572 exe_root = g_win32_get_package_installation_directory_of_module (NULL);
2573 p = g_build_filename (exe_root, "share", NULL);
2575 g_array_append_val (data_dirs, p);
2578 retval = (gchar **) g_array_free (data_dirs, FALSE);
2582 if (hmodule != NULL)
2583 g_hash_table_insert (per_module_data_dirs, hmodule, retval);
2584 G_UNLOCK (g_utils_global);
2587 return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2593 * g_get_system_data_dirs:
2595 * Returns an ordered list of base directories in which to access
2596 * system-wide application data.
2598 * On UNIX platforms this is determined using the mechanisms described in
2599 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2600 * XDG Base Directory Specification</ulink>
2602 * On Windows the first elements in the list are the Application Data
2603 * and Documents folders for All Users. (These can be determined only
2604 * on Windows 2000 or later and are not present in the list on other
2605 * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
2606 * CSIDL_COMMON_DOCUMENTS.
2608 * Then follows the "share" subfolder in the installation folder for
2609 * the package containing the DLL that calls this function, if it can
2612 * Finally the list contains the "share" subfolder in the installation
2613 * folder for GLib, and in the installation folder for the package the
2614 * application's .exe file belongs to.
2616 * The installation folders above are determined by looking up the
2617 * folder where the module (DLL or EXE) in question is located. If the
2618 * folder's name is "bin", its parent is used, otherwise the folder
2621 * Note that on Windows the returned list can vary depending on where
2622 * this function is called.
2624 * Return value: a %NULL-terminated array of strings owned by GLib that must
2625 * not be modified or freed.
2628 G_CONST_RETURN gchar * G_CONST_RETURN *
2629 g_get_system_data_dirs (void)
2631 gchar **data_dir_vector;
2633 G_LOCK (g_utils_global);
2635 if (!g_system_data_dirs)
2638 data_dir_vector = (gchar **) g_win32_get_system_data_dirs_for_module (NULL);
2640 gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
2642 if (!data_dirs || !data_dirs[0])
2643 data_dirs = "/usr/local/share/:/usr/share/";
2645 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2648 g_system_data_dirs = data_dir_vector;
2651 data_dir_vector = g_system_data_dirs;
2653 G_UNLOCK (g_utils_global);
2655 return (G_CONST_RETURN gchar * G_CONST_RETURN *) data_dir_vector;
2659 * g_get_system_config_dirs:
2661 * Returns an ordered list of base directories in which to access
2662 * system-wide configuration information.
2664 * On UNIX platforms this is determined using the mechanisms described in
2665 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2666 * XDG Base Directory Specification</ulink>
2668 * Return value: a %NULL-terminated array of strings owned by GLib that must
2669 * not be modified or freed.
2672 G_CONST_RETURN gchar * G_CONST_RETURN *
2673 g_get_system_config_dirs (void)
2675 gchar *conf_dirs, **conf_dir_vector;
2677 G_LOCK (g_utils_global);
2679 if (!g_system_config_dirs)
2682 conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
2685 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2690 /* Return empty list */
2691 conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2694 conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
2696 if (!conf_dirs || !conf_dirs[0])
2697 conf_dirs = "/etc/xdg";
2699 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2702 g_system_config_dirs = conf_dir_vector;
2705 conf_dir_vector = g_system_config_dirs;
2706 G_UNLOCK (g_utils_global);
2708 return (G_CONST_RETURN gchar * G_CONST_RETURN *) conf_dir_vector;
2713 static GHashTable *alias_table = NULL;
2715 /* read an alias file for the locales */
2717 read_aliases (gchar *file)
2723 alias_table = g_hash_table_new (g_str_hash, g_str_equal);
2724 fp = fopen (file,"r");
2727 while (fgets (buf, 256, fp))
2733 /* Line is a comment */
2734 if ((buf[0] == '#') || (buf[0] == '\0'))
2737 /* Reads first column */
2738 for (p = buf, q = NULL; *p; p++) {
2739 if ((*p == '\t') || (*p == ' ') || (*p == ':')) {
2742 while ((*q == '\t') || (*q == ' ')) {
2748 /* The line only had one column */
2749 if (!q || *q == '\0')
2752 /* Read second column */
2753 for (p = q; *p; p++) {
2754 if ((*p == '\t') || (*p == ' ')) {
2760 /* Add to alias table if necessary */
2761 if (!g_hash_table_lookup (alias_table, buf)) {
2762 g_hash_table_insert (alias_table, g_strdup (buf), g_strdup (q));
2771 unalias_lang (char *lang)
2778 read_aliases ("/usr/share/locale/locale.alias");
2781 while ((p = g_hash_table_lookup (alias_table, lang)) && (strcmp (p, lang) != 0))
2786 static gboolean said_before = FALSE;
2788 g_warning ("Too many alias levels for a locale, "
2789 "may indicate a loop");
2798 /* Mask for components of locale spec. The ordering here is from
2799 * least significant to most significant
2803 COMPONENT_CODESET = 1 << 0,
2804 COMPONENT_TERRITORY = 1 << 1,
2805 COMPONENT_MODIFIER = 1 << 2
2808 /* Break an X/Open style locale specification into components
2811 explode_locale (const gchar *locale,
2817 const gchar *uscore_pos;
2818 const gchar *at_pos;
2819 const gchar *dot_pos;
2823 uscore_pos = strchr (locale, '_');
2824 dot_pos = strchr (uscore_pos ? uscore_pos : locale, '.');
2825 at_pos = strchr (dot_pos ? dot_pos : (uscore_pos ? uscore_pos : locale), '@');
2829 mask |= COMPONENT_MODIFIER;
2830 *modifier = g_strdup (at_pos);
2833 at_pos = locale + strlen (locale);
2837 mask |= COMPONENT_CODESET;
2838 *codeset = g_strndup (dot_pos, at_pos - dot_pos);
2845 mask |= COMPONENT_TERRITORY;
2846 *territory = g_strndup (uscore_pos, dot_pos - uscore_pos);
2849 uscore_pos = dot_pos;
2851 *language = g_strndup (locale, uscore_pos - locale);
2857 * Compute all interesting variants for a given locale name -
2858 * by stripping off different components of the value.
2860 * For simplicity, we assume that the locale is in
2861 * X/Open format: language[_territory][.codeset][@modifier]
2863 * TODO: Extend this to handle the CEN format (see the GNUlibc docs)
2864 * as well. We could just copy the code from glibc wholesale
2865 * but it is big, ugly, and complicated, so I'm reluctant
2866 * to do so when this should handle 99% of the time...
2869 _g_compute_locale_variants (const gchar *locale)
2871 GSList *retval = NULL;
2873 gchar *language = NULL;
2874 gchar *territory = NULL;
2875 gchar *codeset = NULL;
2876 gchar *modifier = NULL;
2881 g_return_val_if_fail (locale != NULL, NULL);
2883 mask = explode_locale (locale, &language, &territory, &codeset, &modifier);
2885 /* Iterate through all possible combinations, from least attractive
2886 * to most attractive.
2888 for (i = 0; i <= mask; i++)
2889 if ((i & ~mask) == 0)
2891 gchar *val = g_strconcat (language,
2892 (i & COMPONENT_TERRITORY) ? territory : "",
2893 (i & COMPONENT_CODESET) ? codeset : "",
2894 (i & COMPONENT_MODIFIER) ? modifier : "",
2896 retval = g_slist_prepend (retval, val);
2900 if (mask & COMPONENT_CODESET)
2902 if (mask & COMPONENT_TERRITORY)
2904 if (mask & COMPONENT_MODIFIER)
2910 /* The following is (partly) taken from the gettext package.
2911 Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc. */
2913 static const gchar *
2914 guess_category_value (const gchar *category_name)
2916 const gchar *retval;
2918 /* The highest priority value is the `LANGUAGE' environment
2919 variable. This is a GNU extension. */
2920 retval = g_getenv ("LANGUAGE");
2921 if ((retval != NULL) && (retval[0] != '\0'))
2924 /* `LANGUAGE' is not set. So we have to proceed with the POSIX
2925 methods of looking to `LC_ALL', `LC_xxx', and `LANG'. On some
2926 systems this can be done by the `setlocale' function itself. */
2928 /* Setting of LC_ALL overwrites all other. */
2929 retval = g_getenv ("LC_ALL");
2930 if ((retval != NULL) && (retval[0] != '\0'))
2933 /* Next comes the name of the desired category. */
2934 retval = g_getenv (category_name);
2935 if ((retval != NULL) && (retval[0] != '\0'))
2938 /* Last possibility is the LANG environment variable. */
2939 retval = g_getenv ("LANG");
2940 if ((retval != NULL) && (retval[0] != '\0'))
2943 #ifdef G_PLATFORM_WIN32
2944 /* g_win32_getlocale() first checks for LC_ALL, LC_MESSAGES and
2945 * LANG, which we already did above. Oh well. The main point of
2946 * calling g_win32_getlocale() is to get the thread's locale as used
2947 * by Windows and the Microsoft C runtime (in the "English_United
2948 * States" format) translated into the Unixish format.
2950 retval = g_win32_getlocale ();
2951 if ((retval != NULL) && (retval[0] != '\0'))
2958 typedef struct _GLanguageNamesCache GLanguageNamesCache;
2960 struct _GLanguageNamesCache {
2962 gchar **language_names;
2966 language_names_cache_free (gpointer data)
2968 GLanguageNamesCache *cache = data;
2969 g_free (cache->languages);
2970 g_strfreev (cache->language_names);
2975 * g_get_language_names:
2977 * Computes a list of applicable locale names, which can be used to
2978 * e.g. construct locale-dependent filenames or search paths. The returned
2979 * list is sorted from most desirable to least desirable and always contains
2980 * the default locale "C".
2982 * For example, if LANGUAGE=de:en_US, then the returned list is
2983 * "de", "en_US", "en", "C".
2985 * This function consults the environment variables <envar>LANGUAGE</envar>,
2986 * <envar>LC_ALL</envar>, <envar>LC_MESSAGES</envar> and <envar>LANG</envar>
2987 * to find the list of locales specified by the user.
2989 * Return value: a %NULL-terminated array of strings owned by GLib
2990 * that must not be modified or freed.
2994 G_CONST_RETURN gchar * G_CONST_RETURN *
2995 g_get_language_names (void)
2997 static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
2998 GLanguageNamesCache *cache = g_static_private_get (&cache_private);
3003 cache = g_new0 (GLanguageNamesCache, 1);
3004 g_static_private_set (&cache_private, cache, language_names_cache_free);
3007 value = guess_category_value ("LC_MESSAGES");
3011 if (!(cache->languages && strcmp (cache->languages, value) == 0))
3018 g_free (cache->languages);
3019 g_strfreev (cache->language_names);
3020 cache->languages = g_strdup (value);
3022 alist = g_strsplit (value, ":", 0);
3024 for (a = alist; *a; a++)
3026 gchar *b = unalias_lang (*a);
3027 list = g_slist_concat (list, _g_compute_locale_variants (b));
3030 list = g_slist_append (list, g_strdup ("C"));
3032 cache->language_names = languages = g_new (gchar *, g_slist_length (list) + 1);
3033 for (l = list, i = 0; l; l = l->next, i++)
3034 languages[i] = l->data;
3035 languages[i] = NULL;
3037 g_slist_free (list);
3040 return (G_CONST_RETURN gchar * G_CONST_RETURN *) cache->language_names;
3045 * @v: a #gpointer key
3047 * Converts a gpointer to a hash value.
3048 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3049 * when using pointers as keys in a #GHashTable.
3051 * Returns: a hash value corresponding to the key.
3054 g_direct_hash (gconstpointer v)
3056 return GPOINTER_TO_UINT (v);
3062 * @v2: a key to compare with @v1.
3064 * Compares two #gpointer arguments and returns %TRUE if they are equal.
3065 * It can be passed to g_hash_table_new() as the @key_equal_func
3066 * parameter, when using pointers as keys in a #GHashTable.
3068 * Returns: %TRUE if the two keys match.
3071 g_direct_equal (gconstpointer v1,
3079 * @v1: a pointer to a #gint key.
3080 * @v2: a pointer to a #gint key to compare with @v1.
3082 * Compares the two #gint values being pointed to and returns
3083 * %TRUE if they are equal.
3084 * It can be passed to g_hash_table_new() as the @key_equal_func
3085 * parameter, when using pointers to integers as keys in a #GHashTable.
3087 * Returns: %TRUE if the two keys match.
3090 g_int_equal (gconstpointer v1,
3093 return *((const gint*) v1) == *((const gint*) v2);
3098 * @v: a pointer to a #gint key
3100 * Converts a pointer to a #gint to a hash value.
3101 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3102 * when using pointers to integers values as keys in a #GHashTable.
3104 * Returns: a hash value corresponding to the key.
3107 g_int_hash (gconstpointer v)
3109 return *(const gint*) v;
3113 * g_nullify_pointer:
3114 * @nullify_location: the memory address of the pointer.
3116 * Set the pointer at the specified location to %NULL.
3119 g_nullify_pointer (gpointer *nullify_location)
3121 g_return_if_fail (nullify_location != NULL);
3123 *nullify_location = NULL;
3129 * Get the codeset for the current locale.
3131 * Return value: a newly allocated string containing the name
3132 * of the codeset. This string must be freed with g_free().
3135 g_get_codeset (void)
3137 const gchar *charset;
3139 g_get_charset (&charset);
3141 return g_strdup (charset);
3144 /* This is called from g_thread_init(). It's used to
3145 * initialize some static data in a threadsafe way.
3148 _g_utils_thread_init (void)
3150 g_get_language_names ();
3156 * _glib_get_locale_dir:
3158 * Return the path to the share\locale or lib\locale subfolder of the
3159 * GLib installation folder. The path is in the system codepage. We
3160 * have to use system codepage as bindtextdomain() doesn't have a
3164 _glib_get_locale_dir (void)
3166 gchar *install_dir = NULL, *locale_dir;
3167 gchar *retval = NULL;
3169 if (glib_dll != NULL)
3170 install_dir = g_win32_get_package_installation_directory_of_module (glib_dll);
3175 * Append "/share/locale" or "/lib/locale" depending on whether
3176 * autoconfigury detected GNU gettext or not.
3178 const char *p = GLIB_LOCALE_DIR + strlen (GLIB_LOCALE_DIR);
3184 locale_dir = g_build_filename (install_dir, p, NULL);
3186 retval = g_win32_locale_filename_from_utf8 (locale_dir);
3188 g_free (install_dir);
3189 g_free (locale_dir);
3195 return g_strdup ("");
3198 #undef GLIB_LOCALE_DIR
3200 #endif /* G_OS_WIN32 */
3204 * @str: The string to be translated
3206 * Returns the translated string from the glib translations.
3207 * This is an internal function and should only be used by
3208 * the internals of glib (such as libgio).
3210 * Returns: the transation of @str to the current locale
3212 G_CONST_RETURN gchar *
3213 glib_gettext (const gchar *str)
3215 static gboolean _glib_gettext_initialized = FALSE;
3217 if (!_glib_gettext_initialized)
3220 gchar *tmp = _glib_get_locale_dir ();
3221 bindtextdomain (GETTEXT_PACKAGE, tmp);
3224 bindtextdomain (GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
3226 # ifdef HAVE_BIND_TEXTDOMAIN_CODESET
3227 bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
3229 _glib_gettext_initialized = TRUE;
3232 return dgettext (GETTEXT_PACKAGE, str);
3237 /* Binary compatibility versions. Not for newly compiled code. */
3239 #undef g_find_program_in_path
3242 g_find_program_in_path (const gchar *program)
3244 gchar *utf8_program = g_locale_to_utf8 (program, -1, NULL, NULL, NULL);
3245 gchar *utf8_retval = g_find_program_in_path_utf8 (utf8_program);
3248 g_free (utf8_program);
3249 if (utf8_retval == NULL)
3251 retval = g_locale_from_utf8 (utf8_retval, -1, NULL, NULL, NULL);
3252 g_free (utf8_retval);
3257 #undef g_get_current_dir
3260 g_get_current_dir (void)
3262 gchar *utf8_dir = g_get_current_dir_utf8 ();
3263 gchar *dir = g_locale_from_utf8 (utf8_dir, -1, NULL, NULL, NULL);
3270 G_CONST_RETURN gchar*
3271 g_getenv (const gchar *variable)
3273 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3274 const gchar *utf8_value = g_getenv_utf8 (utf8_variable);
3278 g_free (utf8_variable);
3281 value = g_locale_from_utf8 (utf8_value, -1, NULL, NULL, NULL);
3282 quark = g_quark_from_string (value);
3285 return g_quark_to_string (quark);
3291 g_setenv (const gchar *variable,
3295 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3296 gchar *utf8_value = g_locale_to_utf8 (value, -1, NULL, NULL, NULL);
3297 gboolean retval = g_setenv_utf8 (utf8_variable, utf8_value, overwrite);
3299 g_free (utf8_variable);
3300 g_free (utf8_value);
3308 g_unsetenv (const gchar *variable)
3310 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3312 g_unsetenv_utf8 (utf8_variable);
3314 g_free (utf8_variable);
3317 #undef g_get_user_name
3319 G_CONST_RETURN gchar*
3320 g_get_user_name (void)
3322 g_get_any_init_locked ();
3323 return g_user_name_cp;
3326 #undef g_get_real_name
3328 G_CONST_RETURN gchar*
3329 g_get_real_name (void)
3331 g_get_any_init_locked ();
3332 return g_real_name_cp;
3335 #undef g_get_home_dir
3337 G_CONST_RETURN gchar*
3338 g_get_home_dir (void)
3340 g_get_any_init_locked ();
3341 return g_home_dir_cp;
3344 #undef g_get_tmp_dir
3346 G_CONST_RETURN gchar*
3347 g_get_tmp_dir (void)
3349 g_get_any_init_locked ();
3350 return g_tmp_dir_cp;
3355 #define __G_UTILS_C__
3356 #include "galiasdef.c"