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;
140 DllMain (HINSTANCE hinstDLL,
144 if (fdwReason == DLL_PROCESS_ATTACH)
153 _glib_get_installation_directory (void)
156 if (glib_dll == NULL)
159 /* In a static build of GLib just use the application's .exe file's
160 * installation directory...
162 return g_win32_get_package_installation_directory_of_module (glib_dll);
168 * glib_check_version:
169 * @required_major: the required major version.
170 * @required_minor: the required minor version.
171 * @required_micro: the required micro version.
173 * Checks that the GLib library in use is compatible with the
174 * given version. Generally you would pass in the constants
175 * #GLIB_MAJOR_VERSION, #GLIB_MINOR_VERSION, #GLIB_MICRO_VERSION
176 * as the three arguments to this function; that produces
177 * a check that the library in use is compatible with
178 * the version of GLib the application or module was compiled
181 * Compatibility is defined by two things: first the version
182 * of the running library is newer than the version
183 * @required_major.required_minor.@required_micro. Second
184 * the running library must be binary compatible with the
185 * version @required_major.required_minor.@required_micro
186 * (same major version.)
188 * Return value: %NULL if the GLib library is compatible with the
189 * given version, or a string describing the version mismatch.
190 * The returned string is owned by GLib and must not be modified
196 glib_check_version (guint required_major,
197 guint required_minor,
198 guint required_micro)
200 gint glib_effective_micro = 100 * GLIB_MINOR_VERSION + GLIB_MICRO_VERSION;
201 gint required_effective_micro = 100 * required_minor + required_micro;
203 if (required_major > GLIB_MAJOR_VERSION)
204 return "GLib version too old (major mismatch)";
205 if (required_major < GLIB_MAJOR_VERSION)
206 return "GLib version too new (major mismatch)";
207 if (required_effective_micro < glib_effective_micro - GLIB_BINARY_AGE)
208 return "GLib version too new (micro mismatch)";
209 if (required_effective_micro > glib_effective_micro)
210 return "GLib version too old (micro mismatch)";
214 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
217 * @dest: the destination address to copy the bytes to.
218 * @src: the source address to copy the bytes from.
219 * @len: the number of bytes to copy.
221 * Copies a block of memory @len bytes long, from @src to @dest.
222 * The source and destination areas may overlap.
224 * In order to use this function, you must include
225 * <filename>string.h</filename> yourself, because this macro will
226 * typically simply resolve to memmove() and GLib does not include
227 * <filename>string.h</filename> for you.
230 g_memmove (gpointer dest,
234 gchar* destptr = dest;
235 const gchar* srcptr = src;
236 if (src + len < dest || dest + len < src)
238 bcopy (src, dest, len);
241 else if (dest <= src)
244 *(destptr++) = *(srcptr++);
251 *(--destptr) = *(--srcptr);
254 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
262 * @func: the function to call on normal program termination.
264 * Specifies a function to be called at normal program termination.
266 * Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
267 * macro that maps to a call to the atexit() function in the C
268 * library. This means that in case the code that calls g_atexit(),
269 * i.e. atexit(), is in a DLL, the function will be called when the
270 * DLL is detached from the program. This typically makes more sense
271 * than that the function is called when the GLib DLL is detached,
272 * which happened earlier when g_atexit() was a function in the GLib
275 * The behaviour of atexit() in the context of dynamically loaded
276 * modules is not formally specified and varies wildly.
278 * On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
279 * loaded module which is unloaded before the program terminates might
280 * well cause a crash at program exit.
282 * Some POSIX systems implement atexit() like Windows, and have each
283 * dynamically loaded module maintain an own atexit chain that is
284 * called when the module is unloaded.
286 * On other POSIX systems, before a dynamically loaded module is
287 * unloaded, the registered atexit functions (if any) residing in that
288 * module are called, regardless where the code that registered them
289 * resided. This is presumably the most robust approach.
291 * As can be seen from the above, for portability it's best to avoid
292 * calling g_atexit() (or atexit()) except in the main executable of a
296 g_atexit (GVoidFunc func)
299 const gchar *error = NULL;
301 /* keep this in sync with glib.h */
303 #ifdef G_NATIVE_ATEXIT
304 result = ATEXIT (func);
306 error = g_strerror (errno);
307 #elif defined (HAVE_ATEXIT)
308 # ifdef NeXT /* @#%@! NeXTStep */
309 result = !atexit ((void (*)(void)) func);
311 error = g_strerror (errno);
313 result = atexit ((void (*)(void)) func);
315 error = g_strerror (errno);
317 #elif defined (HAVE_ON_EXIT)
318 result = on_exit ((void (*)(int, void *)) func, NULL);
320 error = g_strerror (errno);
323 error = "no implementation";
324 #endif /* G_NATIVE_ATEXIT */
327 g_error ("Could not register atexit() function: %s", error);
330 /* Based on execvp() from GNU Libc.
331 * Some of this code is cut-and-pasted into gspawn.c
335 my_strchrnul (const gchar *str,
338 gchar *p = (gchar*)str;
339 while (*p && (*p != c))
347 static gchar *inner_find_program_in_path (const gchar *program);
350 g_find_program_in_path (const gchar *program)
352 const gchar *last_dot = strrchr (program, '.');
354 if (last_dot == NULL ||
355 strchr (last_dot, '\\') != NULL ||
356 strchr (last_dot, '/') != NULL)
358 const gint program_length = strlen (program);
359 gchar *pathext = g_build_path (";",
360 ".exe;.cmd;.bat;.com",
361 g_getenv ("PATHEXT"),
364 gchar *decorated_program;
370 gchar *q = my_strchrnul (p, ';');
372 decorated_program = g_malloc (program_length + (q-p) + 1);
373 memcpy (decorated_program, program, program_length);
374 memcpy (decorated_program+program_length, p, q-p);
375 decorated_program [program_length + (q-p)] = '\0';
377 retval = inner_find_program_in_path (decorated_program);
378 g_free (decorated_program);
386 } while (*p++ != '\0');
391 return inner_find_program_in_path (program);
397 * g_find_program_in_path:
398 * @program: a program name in the GLib file name encoding
400 * Locates the first executable named @program in the user's path, in the
401 * same way that execvp() would locate it. Returns an allocated string
402 * with the absolute path name, or %NULL if the program is not found in
403 * the path. If @program is already an absolute path, returns a copy of
404 * @program if @program exists and is executable, and %NULL otherwise.
406 * On Windows, if @program does not have a file type suffix, tries
407 * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
408 * the <envar>PATHEXT</envar> environment variable.
410 * On Windows, it looks for the file in the same way as CreateProcess()
411 * would. This means first in the directory where the executing
412 * program was loaded from, then in the current directory, then in the
413 * Windows 32-bit system directory, then in the Windows directory, and
414 * finally in the directories in the <envar>PATH</envar> environment
415 * variable. If the program is found, the return value contains the
416 * full name including the type suffix.
418 * Return value: absolute path, or %NULL
422 inner_find_program_in_path (const gchar *program)
425 g_find_program_in_path (const gchar *program)
428 const gchar *path, *p;
429 gchar *name, *freeme;
431 const gchar *path_copy;
432 gchar *filename = NULL, *appdir = NULL;
433 gchar *sysdir = NULL, *windir = NULL;
435 wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
441 g_return_val_if_fail (program != NULL, NULL);
443 /* If it is an absolute path, or a relative path including subdirectories,
444 * don't look in PATH.
446 if (g_path_is_absolute (program)
447 || strchr (program, G_DIR_SEPARATOR) != NULL
449 || strchr (program, '/') != NULL
453 if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
454 !g_file_test (program, G_FILE_TEST_IS_DIR))
455 return g_strdup (program);
460 path = g_getenv ("PATH");
461 #if defined(G_OS_UNIX) || defined(G_OS_BEOS)
464 /* There is no `PATH' in the environment. The default
465 * search path in GNU libc is the current directory followed by
466 * the path `confstr' returns for `_CS_PATH'.
469 /* In GLib we put . last, for security, and don't use the
470 * unportable confstr(); UNIX98 does not actually specify
471 * what to search if PATH is unset. POSIX may, dunno.
474 path = "/bin:/usr/bin:.";
477 n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
478 if (n > 0 && n < MAXPATHLEN)
479 filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
481 n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
482 if (n > 0 && n < MAXPATHLEN)
483 sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
485 n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
486 if (n > 0 && n < MAXPATHLEN)
487 windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
491 appdir = g_path_get_dirname (filename);
495 path = g_strdup (path);
499 const gchar *tem = path;
500 path = g_strconcat (windir, ";", path, NULL);
501 g_free ((gchar *) tem);
507 const gchar *tem = path;
508 path = g_strconcat (sysdir, ";", path, NULL);
509 g_free ((gchar *) tem);
514 const gchar *tem = path;
515 path = g_strconcat (".;", path, NULL);
516 g_free ((gchar *) tem);
521 const gchar *tem = path;
522 path = g_strconcat (appdir, ";", path, NULL);
523 g_free ((gchar *) tem);
530 len = strlen (program) + 1;
531 pathlen = strlen (path);
532 freeme = name = g_malloc (pathlen + len + 1);
534 /* Copy the file name at the top, including '\0' */
535 memcpy (name + pathlen + 1, program, len);
536 name = name + pathlen;
537 /* And add the slash before the filename */
538 *name = G_DIR_SEPARATOR;
546 p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
549 /* Two adjacent colons, or a colon at the beginning or the end
550 * of `PATH' means to search the current directory.
554 startp = memcpy (name - (p - path), path, p - path);
556 if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
557 !g_file_test (startp, G_FILE_TEST_IS_DIR))
560 ret = g_strdup (startp);
563 g_free ((gchar *) path_copy);
568 while (*p++ != '\0');
572 g_free ((gchar *) path_copy);
579 debug_key_matches (const gchar *key,
583 for (; length; length--, key++, token++)
585 char k = (*key == '_') ? '-' : tolower (*key );
586 char t = (*token == '_') ? '-' : tolower (*token);
596 * g_parse_debug_string:
597 * @string: a list of debug options separated by colons, spaces, or
598 * commas; or the string "all" to set all flags, or %NULL.
599 * @keys: pointer to an array of #GDebugKey which associate
600 * strings with bit flags.
601 * @nkeys: the number of #GDebugKey<!-- -->s in the array.
603 * Parses a string containing debugging options
604 * into a %guint containing bit flags. This is used
605 * within GDK and GTK+ to parse the debug options passed on the
606 * command line or through environment variables.
608 * Returns: the combined set of bit flags.
611 g_parse_debug_string (const gchar *string,
612 const GDebugKey *keys,
621 /* this function is used by gmem.c/gslice.c initialization code,
622 * so introducing malloc dependencies here would require adaptions
623 * of those code portions.
626 if (!g_ascii_strcasecmp (string, "all"))
628 for (i=0; i<nkeys; i++)
629 result |= keys[i].value;
633 const gchar *p = string;
638 q = strpbrk (p, ":;, \t");
642 for (i = 0; i < nkeys; i++)
643 if (debug_key_matches (keys[i].key, p, q - p))
644 result |= keys[i].value;
657 * @file_name: the name of the file.
659 * Gets the name of the file without any leading directory components.
660 * It returns a pointer into the given file name string.
662 * Return value: the name of the file without any leading directory components.
664 * Deprecated:2.2: Use g_path_get_basename() instead, but notice that
665 * g_path_get_basename() allocates new memory for the returned string, unlike
666 * this function which returns a pointer into the argument.
668 G_CONST_RETURN gchar*
669 g_basename (const gchar *file_name)
671 register gchar *base;
673 g_return_val_if_fail (file_name != NULL, NULL);
675 base = strrchr (file_name, G_DIR_SEPARATOR);
679 gchar *q = strrchr (file_name, '/');
680 if (base == NULL || (q != NULL && q > base))
689 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
690 return (gchar*) file_name + 2;
691 #endif /* G_OS_WIN32 */
693 return (gchar*) file_name;
697 * g_path_get_basename:
698 * @file_name: the name of the file.
700 * Gets the last component of the filename. If @file_name ends with a
701 * directory separator it gets the component before the last slash. If
702 * @file_name consists only of directory separators (and on Windows,
703 * possibly a drive letter), a single separator is returned. If
704 * @file_name is empty, it gets ".".
706 * Return value: a newly allocated string containing the last component of
710 g_path_get_basename (const gchar *file_name)
712 register gssize base;
713 register gssize last_nonslash;
717 g_return_val_if_fail (file_name != NULL, NULL);
719 if (file_name[0] == '\0')
721 return g_strdup (".");
723 last_nonslash = strlen (file_name) - 1;
725 while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
728 if (last_nonslash == -1)
729 /* string only containing slashes */
730 return g_strdup (G_DIR_SEPARATOR_S);
733 if (last_nonslash == 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
734 /* string only containing slashes and a drive */
735 return g_strdup (G_DIR_SEPARATOR_S);
736 #endif /* G_OS_WIN32 */
738 base = last_nonslash;
740 while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
744 if (base == -1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
746 #endif /* G_OS_WIN32 */
748 len = last_nonslash - base;
749 retval = g_malloc (len + 1);
750 memcpy (retval, file_name + base + 1, len);
756 * g_path_is_absolute:
757 * @file_name: a file name.
759 * Returns %TRUE if the given @file_name is an absolute file name,
760 * i.e. it contains a full path from the root directory such as "/usr/local"
761 * on UNIX or "C:\windows" on Windows systems.
763 * Returns: %TRUE if @file_name is an absolute path.
766 g_path_is_absolute (const gchar *file_name)
768 g_return_val_if_fail (file_name != NULL, FALSE);
770 if (G_IS_DIR_SEPARATOR (file_name[0]))
774 /* Recognize drive letter on native Windows */
775 if (g_ascii_isalpha (file_name[0]) &&
776 file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
778 #endif /* G_OS_WIN32 */
785 * @file_name: a file name.
787 * Returns a pointer into @file_name after the root component, i.e. after
788 * the "/" in UNIX or "C:\" under Windows. If @file_name is not an absolute
789 * path it returns %NULL.
791 * Returns: a pointer into @file_name after the root component.
793 G_CONST_RETURN gchar*
794 g_path_skip_root (const gchar *file_name)
796 g_return_val_if_fail (file_name != NULL, NULL);
798 #ifdef G_PLATFORM_WIN32
799 /* Skip \\server\share or //server/share */
800 if (G_IS_DIR_SEPARATOR (file_name[0]) &&
801 G_IS_DIR_SEPARATOR (file_name[1]) &&
803 !G_IS_DIR_SEPARATOR (file_name[2]))
807 p = strchr (file_name + 2, G_DIR_SEPARATOR);
810 gchar *q = strchr (file_name + 2, '/');
811 if (p == NULL || (q != NULL && q < p))
821 while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
824 /* Possibly skip a backslash after the share name */
825 if (G_IS_DIR_SEPARATOR (file_name[0]))
828 return (gchar *)file_name;
833 /* Skip initial slashes */
834 if (G_IS_DIR_SEPARATOR (file_name[0]))
836 while (G_IS_DIR_SEPARATOR (file_name[0]))
838 return (gchar *)file_name;
843 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
844 return (gchar *)file_name + 3;
851 * g_path_get_dirname:
852 * @file_name: the name of the file.
854 * Gets the directory components of a file name. If the file name has no
855 * directory components "." is returned. The returned string should be
856 * freed when no longer needed.
858 * Returns: the directory components of the file.
861 g_path_get_dirname (const gchar *file_name)
863 register gchar *base;
866 g_return_val_if_fail (file_name != NULL, NULL);
868 base = strrchr (file_name, G_DIR_SEPARATOR);
871 gchar *q = strrchr (file_name, '/');
872 if (base == NULL || (q != NULL && q > base))
879 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
881 gchar drive_colon_dot[4];
883 drive_colon_dot[0] = file_name[0];
884 drive_colon_dot[1] = ':';
885 drive_colon_dot[2] = '.';
886 drive_colon_dot[3] = '\0';
888 return g_strdup (drive_colon_dot);
891 return g_strdup (".");
894 while (base > file_name && G_IS_DIR_SEPARATOR (*base))
898 /* base points to the char before the last slash.
900 * In case file_name is the root of a drive (X:\) or a child of the
901 * root of a drive (X:\foo), include the slash.
903 * In case file_name is the root share of an UNC path
904 * (\\server\share), add a slash, returning \\server\share\ .
906 * In case file_name is a direct child of a share in an UNC path
907 * (\\server\share\foo), include the slash after the share name,
908 * returning \\server\share\ .
910 if (base == file_name + 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
912 else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
913 G_IS_DIR_SEPARATOR (file_name[1]) &&
915 !G_IS_DIR_SEPARATOR (file_name[2]) &&
916 base >= file_name + 2)
918 const gchar *p = file_name + 2;
919 while (*p && !G_IS_DIR_SEPARATOR (*p))
923 len = (guint) strlen (file_name) + 1;
924 base = g_new (gchar, len + 1);
925 strcpy (base, file_name);
926 base[len-1] = G_DIR_SEPARATOR;
930 if (G_IS_DIR_SEPARATOR (*p))
933 while (*p && !G_IS_DIR_SEPARATOR (*p))
941 len = (guint) 1 + base - file_name;
943 base = g_new (gchar, len + 1);
944 g_memmove (base, file_name, len);
953 * Gets the current directory.
954 * The returned string should be freed when no longer needed. The encoding
955 * of the returned string is system defined. On Windows, it is always UTF-8.
957 * Returns: the current directory.
960 g_get_current_dir (void)
965 wchar_t dummy[2], *wdir;
968 len = GetCurrentDirectoryW (2, dummy);
969 wdir = g_new (wchar_t, len);
971 if (GetCurrentDirectoryW (len, wdir) == len - 1)
972 dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
977 dir = g_strdup ("\\");
983 gchar *buffer = NULL;
985 static gulong max_len = 0;
988 max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
990 /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
991 * and, if that wasn't bad enough, hangs in doing so.
993 #if (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
994 buffer = g_new (gchar, max_len + 1);
996 dir = getwd (buffer);
997 #else /* !sun || !HAVE_GETCWD */
998 while (max_len < G_MAXULONG / 2)
1001 buffer = g_new (gchar, max_len + 1);
1003 dir = getcwd (buffer, max_len);
1005 if (dir || errno != ERANGE)
1010 #endif /* !sun || !HAVE_GETCWD */
1012 if (!dir || !*buffer)
1014 /* hm, should we g_error() out here?
1015 * this can happen if e.g. "./" has mode \0000
1017 buffer[0] = G_DIR_SEPARATOR;
1021 dir = g_strdup (buffer);
1030 * @variable: the environment variable to get, in the GLib file name encoding.
1032 * Returns the value of an environment variable. The name and value
1033 * are in the GLib file name encoding. On UNIX, this means the actual
1034 * bytes which might or might not be in some consistent character set
1035 * and encoding. On Windows, it is in UTF-8. On Windows, in case the
1036 * environment variable's value contains references to other
1037 * environment variables, they are expanded.
1039 * Return value: the value of the environment variable, or %NULL if
1040 * the environment variable is not found. The returned string may be
1041 * overwritten by the next call to g_getenv(), g_setenv() or
1044 G_CONST_RETURN gchar*
1045 g_getenv (const gchar *variable)
1049 g_return_val_if_fail (variable != NULL, NULL);
1051 return getenv (variable);
1053 #else /* G_OS_WIN32 */
1057 wchar_t dummy[2], *wname, *wvalue;
1060 g_return_val_if_fail (variable != NULL, NULL);
1061 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), NULL);
1063 /* On Windows NT, it is relatively typical that environment
1064 * variables contain references to other environment variables. If
1065 * so, use ExpandEnvironmentStrings(). (In an ideal world, such
1066 * environment variables would be stored in the Registry as
1067 * REG_EXPAND_SZ type values, and would then get automatically
1068 * expanded before a program sees them. But there is broken software
1069 * that stores environment variables as REG_SZ values even if they
1070 * contain references to other environment variables.)
1073 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1075 len = GetEnvironmentVariableW (wname, dummy, 2);
1085 wvalue = g_new (wchar_t, len);
1087 if (GetEnvironmentVariableW (wname, wvalue, len) != len - 1)
1094 if (wcschr (wvalue, L'%') != NULL)
1096 wchar_t *tem = wvalue;
1098 len = ExpandEnvironmentStringsW (wvalue, dummy, 2);
1102 wvalue = g_new (wchar_t, len);
1104 if (ExpandEnvironmentStringsW (tem, wvalue, len) != len)
1114 value = g_utf16_to_utf8 (wvalue, -1, NULL, NULL, NULL);
1119 quark = g_quark_from_string (value);
1122 return g_quark_to_string (quark);
1124 #endif /* G_OS_WIN32 */
1127 /* _g_getenv_nomalloc
1128 * this function does a getenv() without doing any kind of allocation
1129 * through glib. it's suitable for chars <= 127 only (both, for the
1130 * variable name and the contents) and for contents < 1024 chars in
1131 * length. also, it aliases "" to a NULL return value.
1134 _g_getenv_nomalloc (const gchar *variable,
1137 const gchar *retval = getenv (variable);
1138 if (retval && retval[0])
1140 gint l = strlen (retval);
1143 strncpy (buffer, retval, l);
1153 * @variable: the environment variable to set, must not contain '='.
1154 * @value: the value for to set the variable to.
1155 * @overwrite: whether to change the variable if it already exists.
1157 * Sets an environment variable. Both the variable's name and value
1158 * should be in the GLib file name encoding. On UNIX, this means that
1159 * they can be any sequence of bytes. On Windows, they should be in
1162 * Note that on some systems, when variables are overwritten, the memory
1163 * used for the previous variables and its value isn't reclaimed.
1165 * Returns: %FALSE if the environment variable couldn't be set.
1170 g_setenv (const gchar *variable,
1181 g_return_val_if_fail (variable != NULL, FALSE);
1182 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1185 result = setenv (variable, value, overwrite);
1187 if (!overwrite && getenv (variable) != NULL)
1190 /* This results in a leak when you overwrite existing
1191 * settings. It would be fairly easy to fix this by keeping
1192 * our own parallel array or hash table.
1194 string = g_strconcat (variable, "=", value, NULL);
1195 result = putenv (string);
1199 #else /* G_OS_WIN32 */
1202 wchar_t *wname, *wvalue, *wassignment;
1205 g_return_val_if_fail (variable != NULL, FALSE);
1206 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1207 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), FALSE);
1208 g_return_val_if_fail (g_utf8_validate (value, -1, NULL), FALSE);
1210 if (!overwrite && g_getenv (variable) != NULL)
1213 /* We want to (if possible) set both the environment variable copy
1214 * kept by the C runtime and the one kept by the system.
1216 * We can't use only the C runtime's putenv or _wputenv() as that
1217 * won't work for arbitrary Unicode strings in a "non-Unicode" app
1218 * (with main() and not wmain()). In a "main()" app the C runtime
1219 * initializes the C runtime's environment table by converting the
1220 * real (wide char) environment variables to system codepage, thus
1221 * breaking those that aren't representable in the system codepage.
1223 * As the C runtime's putenv() will also set the system copy, we do
1224 * the putenv() first, then call SetEnvironmentValueW ourselves.
1227 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1228 wvalue = g_utf8_to_utf16 (value, -1, NULL, NULL, NULL);
1229 tem = g_strconcat (variable, "=", value, NULL);
1230 wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1233 _wputenv (wassignment);
1234 g_free (wassignment);
1236 retval = (SetEnvironmentVariableW (wname, wvalue) != 0);
1243 #endif /* G_OS_WIN32 */
1246 #ifdef HAVE__NSGETENVIRON
1247 #define environ (*_NSGetEnviron())
1248 #elif !defined(G_OS_WIN32)
1250 /* According to the Single Unix Specification, environ is not in
1251 * any system header, although unistd.h often declares it.
1253 extern char **environ;
1258 * @variable: the environment variable to remove, must not contain '='.
1260 * Removes an environment variable from the environment.
1262 * Note that on some systems, when variables are overwritten, the memory
1263 * used for the previous variables and its value isn't reclaimed.
1264 * Furthermore, this function can't be guaranteed to operate in a
1270 g_unsetenv (const gchar *variable)
1274 #ifdef HAVE_UNSETENV
1275 g_return_if_fail (variable != NULL);
1276 g_return_if_fail (strchr (variable, '=') == NULL);
1278 unsetenv (variable);
1279 #else /* !HAVE_UNSETENV */
1283 g_return_if_fail (variable != NULL);
1284 g_return_if_fail (strchr (variable, '=') == NULL);
1286 len = strlen (variable);
1288 /* Mess directly with the environ array.
1289 * This seems to be the only portable way to do this.
1291 * Note that we remove *all* environment entries for
1292 * the variable name, not just the first.
1297 if (strncmp (*e, variable, len) != 0 || (*e)[len] != '=')
1305 #endif /* !HAVE_UNSETENV */
1307 #else /* G_OS_WIN32 */
1309 wchar_t *wname, *wassignment;
1312 g_return_if_fail (variable != NULL);
1313 g_return_if_fail (strchr (variable, '=') == NULL);
1314 g_return_if_fail (g_utf8_validate (variable, -1, NULL));
1316 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1317 tem = g_strconcat (variable, "=", NULL);
1318 wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1321 _wputenv (wassignment);
1322 g_free (wassignment);
1324 SetEnvironmentVariableW (wname, NULL);
1328 #endif /* G_OS_WIN32 */
1334 * Gets the names of all variables set in the environment.
1336 * Returns: a %NULL-terminated list of strings which must be freed
1337 * with g_strfreev().
1339 * Programs that want to be portable to Windows should typically use
1340 * this function and g_getenv() instead of using the environ array
1341 * from the C library directly. On Windows, the strings in the environ
1342 * array are in system codepage encoding, while in most of the typical
1343 * use cases for environment variables in GLib-using programs you want
1344 * the UTF-8 encoding that this function and g_getenv() provide.
1352 gchar **result, *eq;
1355 len = g_strv_length (environ);
1356 result = g_new0 (gchar *, len + 1);
1359 for (i = 0; i < len; i++)
1361 eq = strchr (environ[i], '=');
1363 result[j++] = g_strndup (environ[i], eq - environ[i]);
1370 gchar **result, *eq;
1374 p = (wchar_t *) GetEnvironmentStringsW ();
1380 q += wcslen (q) + 1;
1384 result = g_new0 (gchar *, len + 1);
1390 result[j] = g_utf16_to_utf8 (q, -1, NULL, NULL, NULL);
1391 if (result[j] != NULL)
1393 eq = strchr (result[j], '=');
1394 if (eq && eq > result[j])
1402 q += wcslen (q) + 1;
1405 FreeEnvironmentStringsW (p);
1411 G_LOCK_DEFINE_STATIC (g_utils_global);
1413 static gchar *g_tmp_dir = NULL;
1414 static gchar *g_user_name = NULL;
1415 static gchar *g_real_name = NULL;
1416 static gchar *g_home_dir = NULL;
1417 static gchar *g_host_name = NULL;
1420 /* System codepage versions of the above, kept at file level so that they,
1421 * too, are produced only once.
1423 static gchar *g_tmp_dir_cp = NULL;
1424 static gchar *g_user_name_cp = NULL;
1425 static gchar *g_real_name_cp = NULL;
1426 static gchar *g_home_dir_cp = NULL;
1429 static gchar *g_user_data_dir = NULL;
1430 static gchar **g_system_data_dirs = NULL;
1431 static gchar *g_user_cache_dir = NULL;
1432 static gchar *g_user_config_dir = NULL;
1433 static gchar **g_system_config_dirs = NULL;
1435 static gchar **g_user_special_dirs = NULL;
1437 /* fifteen minutes of fame for everybody */
1438 #define G_USER_DIRS_EXPIRE 15 * 60
1443 get_special_folder (int csidl)
1445 wchar_t path[MAX_PATH+1];
1447 LPITEMIDLIST pidl = NULL;
1449 gchar *retval = NULL;
1451 hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
1454 b = SHGetPathFromIDListW (pidl, path);
1456 retval = g_utf16_to_utf8 (path, -1, NULL, NULL, NULL);
1457 CoTaskMemFree (pidl);
1463 get_windows_directory_root (void)
1465 wchar_t wwindowsdir[MAX_PATH];
1467 if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
1469 /* Usually X:\Windows, but in terminal server environments
1470 * might be an UNC path, AFAIK.
1472 char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
1475 if (windowsdir == NULL)
1476 return g_strdup ("C:\\");
1478 p = (char *) g_path_skip_root (windowsdir);
1479 if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
1485 return g_strdup ("C:\\");
1490 /* HOLDS: g_utils_global_lock */
1492 g_get_any_init_do (void)
1494 gchar hostname[100];
1496 g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
1498 g_tmp_dir = g_strdup (g_getenv ("TMP"));
1500 g_tmp_dir = g_strdup (g_getenv ("TEMP"));
1504 g_tmp_dir = get_windows_directory_root ();
1510 g_tmp_dir = g_strdup (P_tmpdir);
1511 k = strlen (g_tmp_dir);
1512 if (k > 1 && G_IS_DIR_SEPARATOR (g_tmp_dir[k - 1]))
1513 g_tmp_dir[k - 1] = '\0';
1519 g_tmp_dir = g_strdup ("/tmp");
1521 #endif /* !G_OS_WIN32 */
1524 /* We check $HOME first for Win32, though it is a last resort for Unix
1525 * where we prefer the results of getpwuid().
1527 g_home_dir = g_strdup (g_getenv ("HOME"));
1529 /* Only believe HOME if it is an absolute path and exists */
1532 if (!(g_path_is_absolute (g_home_dir) &&
1533 g_file_test (g_home_dir, G_FILE_TEST_IS_DIR)))
1535 g_free (g_home_dir);
1540 /* In case HOME is Unix-style (it happens), convert it to
1546 while ((p = strchr (g_home_dir, '/')) != NULL)
1552 /* USERPROFILE is probably the closest equivalent to $HOME? */
1553 if (g_getenv ("USERPROFILE") != NULL)
1554 g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
1558 g_home_dir = get_special_folder (CSIDL_PROFILE);
1561 g_home_dir = get_windows_directory_root ();
1562 #endif /* G_OS_WIN32 */
1566 struct passwd *pw = NULL;
1567 gpointer buffer = NULL;
1571 # if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
1573 # ifdef _SC_GETPW_R_SIZE_MAX
1574 /* This reurns the maximum length */
1575 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
1579 # else /* _SC_GETPW_R_SIZE_MAX */
1581 # endif /* _SC_GETPW_R_SIZE_MAX */
1583 logname = (gchar *) g_getenv ("LOGNAME");
1588 /* we allocate 6 extra bytes to work around a bug in
1589 * Mac OS < 10.3. See #156446
1591 buffer = g_malloc (bufsize + 6);
1594 # ifdef HAVE_POSIX_GETPWUID_R
1596 error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
1597 if (!pw || (pw->pw_uid != getuid ())) {
1598 /* LOGNAME is lying, fall back to looking up the uid */
1599 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1602 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1604 error = error < 0 ? errno : error;
1605 # else /* HAVE_NONPOSIX_GETPWUID_R */
1606 /* HPUX 11 falls into the HAVE_POSIX_GETPWUID_R case */
1607 # if defined(_AIX) || defined(__hpux)
1608 error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1609 pw = error == 0 ? &pwd : NULL;
1612 pw = getpwnam_r (logname, &pwd, buffer, bufsize);
1613 if (!pw || (pw->pw_uid != getuid ())) {
1614 /* LOGNAME is lying, fall back to looking up the uid */
1615 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1618 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1620 error = pw ? 0 : errno;
1622 # endif /* HAVE_NONPOSIX_GETPWUID_R */
1626 /* we bail out prematurely if the user id can't be found
1627 * (should be pretty rare case actually), or if the buffer
1628 * should be sufficiently big and lookups are still not
1631 if (error == 0 || error == ENOENT)
1633 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
1634 (gulong) getuid ());
1637 if (bufsize > 32 * 1024)
1639 g_warning ("getpwuid_r(): failed due to: %s.",
1640 g_strerror (error));
1648 # endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
1653 pw = getpwuid (getuid ());
1658 g_user_name = g_strdup (pw->pw_name);
1660 if (pw->pw_gecos && *pw->pw_gecos != '\0')
1662 gchar **gecos_fields;
1665 /* split the gecos field and substitute '&' */
1666 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
1667 name_parts = g_strsplit (gecos_fields[0], "&", 0);
1668 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
1669 g_real_name = g_strjoinv (pw->pw_name, name_parts);
1670 g_strfreev (gecos_fields);
1671 g_strfreev (name_parts);
1675 g_home_dir = g_strdup (pw->pw_dir);
1680 #else /* !HAVE_PWD_H */
1684 guint len = UNLEN+1;
1685 wchar_t buffer[UNLEN+1];
1687 if (GetUserNameW (buffer, (LPDWORD) &len))
1689 g_user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
1690 g_real_name = g_strdup (g_user_name);
1693 #endif /* G_OS_WIN32 */
1695 #endif /* !HAVE_PWD_H */
1699 g_home_dir = g_strdup (g_getenv ("HOME"));
1703 /* change '\\' in %HOME% to '/' */
1704 g_strdelimit (g_home_dir, "\\",'/');
1707 g_user_name = g_strdup ("somebody");
1709 g_real_name = g_strdup ("Unknown");
1713 gboolean hostname_fail = (gethostname (hostname, sizeof (hostname)) == -1);
1715 DWORD size = sizeof (hostname);
1716 gboolean hostname_fail = (!GetComputerName (hostname, &size));
1718 g_host_name = g_strdup (hostname_fail ? "localhost" : hostname);
1722 g_tmp_dir_cp = g_locale_from_utf8 (g_tmp_dir, -1, NULL, NULL, NULL);
1723 g_user_name_cp = g_locale_from_utf8 (g_user_name, -1, NULL, NULL, NULL);
1724 g_real_name_cp = g_locale_from_utf8 (g_real_name, -1, NULL, NULL, NULL);
1727 g_tmp_dir_cp = g_strdup ("\\");
1728 if (!g_user_name_cp)
1729 g_user_name_cp = g_strdup ("somebody");
1730 if (!g_real_name_cp)
1731 g_real_name_cp = g_strdup ("Unknown");
1733 /* home_dir might be NULL, unlike tmp_dir, user_name and
1737 g_home_dir_cp = g_locale_from_utf8 (g_home_dir, -1, NULL, NULL, NULL);
1739 g_home_dir_cp = NULL;
1740 #endif /* G_OS_WIN32 */
1744 g_get_any_init (void)
1747 g_get_any_init_do ();
1751 g_get_any_init_locked (void)
1753 G_LOCK (g_utils_global);
1755 G_UNLOCK (g_utils_global);
1762 * Gets the user name of the current user. The encoding of the returned
1763 * string is system-defined. On UNIX, it might be the preferred file name
1764 * encoding, or something else, and there is no guarantee that it is even
1765 * consistent on a machine. On Windows, it is always UTF-8.
1767 * Returns: the user name of the current user.
1769 G_CONST_RETURN gchar*
1770 g_get_user_name (void)
1772 g_get_any_init_locked ();
1779 * Gets the real name of the user. This usually comes from the user's entry
1780 * in the <filename>passwd</filename> file. The encoding of the returned
1781 * string is system-defined. (On Windows, it is, however, always UTF-8.)
1782 * If the real user name cannot be determined, the string "Unknown" is
1785 * Returns: the user's real name.
1787 G_CONST_RETURN gchar*
1788 g_get_real_name (void)
1790 g_get_any_init_locked ();
1797 * Gets the current user's home directory as defined in the
1798 * password database.
1800 * Note that in contrast to traditional UNIX tools, this function
1801 * prefers <filename>passwd</filename> entries over the <envar>HOME</envar>
1802 * environment variable.
1804 * One of the reasons for this decision is that applications in many
1805 * cases need special handling to deal with the case where
1806 * <envar>HOME</envar> is
1808 * <member>Not owned by the user</member>
1809 * <member>Not writeable</member>
1810 * <member>Not even readable</member>
1812 * Since applications are in general <emphasis>not</emphasis> written
1813 * to deal with these situations it was considered better to make
1814 * g_get_homedir() not pay attention to <envar>HOME</envar> and to
1815 * return the real home directory for the user. If applications
1816 * want to pay attention to <envar>HOME</envar>, they can do:
1818 * const char *homedir = g_getenv ("HOME");
1820 * homedir = g_get_homedir (<!-- -->);
1823 * Returns: the current user's home directory
1825 G_CONST_RETURN gchar*
1826 g_get_home_dir (void)
1828 g_get_any_init_locked ();
1835 * Gets the directory to use for temporary files. This is found from
1836 * inspecting the environment variables <envar>TMPDIR</envar>,
1837 * <envar>TMP</envar>, and <envar>TEMP</envar> in that order. If none
1838 * of those are defined "/tmp" is returned on UNIX and "C:\" on Windows.
1839 * The encoding of the returned string is system-defined. On Windows,
1840 * it is always UTF-8. The return value is never %NULL.
1842 * Returns: the directory to use for temporary files.
1844 G_CONST_RETURN gchar*
1845 g_get_tmp_dir (void)
1847 g_get_any_init_locked ();
1854 * Return a name for the machine.
1856 * The returned name is not necessarily a fully-qualified domain name,
1857 * or even present in DNS or some other name service at all. It need
1858 * not even be unique on your local network or site, but usually it
1859 * is. Callers should not rely on the return value having any specific
1860 * properties like uniqueness for security purposes. Even if the name
1861 * of the machine is changed while an application is running, the
1862 * return value from this function does not change. The returned
1863 * string is owned by GLib and should not be modified or freed. If no
1864 * name can be determined, a default fixed string "localhost" is
1867 * Returns: the host name of the machine.
1872 g_get_host_name (void)
1874 g_get_any_init_locked ();
1878 G_LOCK_DEFINE_STATIC (g_prgname);
1879 static gchar *g_prgname = NULL;
1884 * Gets the name of the program. This name should <emphasis>not</emphasis>
1885 * be localized, contrast with g_get_application_name().
1886 * (If you are using GDK or GTK+ the program name is set in gdk_init(),
1887 * which is called by gtk_init(). The program name is found by taking
1888 * the last component of <literal>argv[0]</literal>.)
1890 * Returns: the name of the program. The returned string belongs
1891 * to GLib and must not be modified or freed.
1894 g_get_prgname (void)
1900 if (g_prgname == NULL)
1902 static gboolean beenhere = FALSE;
1906 gchar *utf8_buf = NULL;
1907 wchar_t buf[MAX_PATH+1];
1910 if (GetModuleFileNameW (GetModuleHandle (NULL),
1911 buf, G_N_ELEMENTS (buf)) > 0)
1912 utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
1916 g_prgname = g_path_get_basename (utf8_buf);
1923 G_UNLOCK (g_prgname);
1930 * @prgname: the name of the program.
1932 * Sets the name of the program. This name should <emphasis>not</emphasis>
1933 * be localized, contrast with g_set_application_name(). Note that for
1934 * thread-safety reasons this function can only be called once.
1937 g_set_prgname (const gchar *prgname)
1941 g_prgname = g_strdup (prgname);
1942 G_UNLOCK (g_prgname);
1945 G_LOCK_DEFINE_STATIC (g_application_name);
1946 static gchar *g_application_name = NULL;
1949 * g_get_application_name:
1951 * Gets a human-readable name for the application, as set by
1952 * g_set_application_name(). This name should be localized if
1953 * possible, and is intended for display to the user. Contrast with
1954 * g_get_prgname(), which gets a non-localized name. If
1955 * g_set_application_name() has not been called, returns the result of
1956 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1959 * Return value: human-readable application name. may return %NULL
1963 G_CONST_RETURN gchar*
1964 g_get_application_name (void)
1968 G_LOCK (g_application_name);
1969 retval = g_application_name;
1970 G_UNLOCK (g_application_name);
1973 return g_get_prgname ();
1979 * g_set_application_name:
1980 * @application_name: localized name of the application
1982 * Sets a human-readable name for the application. This name should be
1983 * localized if possible, and is intended for display to the user.
1984 * Contrast with g_set_prgname(), which sets a non-localized name.
1985 * g_set_prgname() will be called automatically by gtk_init(),
1986 * but g_set_application_name() will not.
1988 * Note that for thread safety reasons, this function can only
1991 * The application name will be used in contexts such as error messages,
1992 * or when displaying an application's name in the task list.
1997 g_set_application_name (const gchar *application_name)
1999 gboolean already_set = FALSE;
2001 G_LOCK (g_application_name);
2002 if (g_application_name)
2005 g_application_name = g_strdup (application_name);
2006 G_UNLOCK (g_application_name);
2009 g_warning ("g_set_application() name called multiple times");
2013 * g_get_user_data_dir:
2015 * Returns a base directory in which to access application data such
2016 * as icons that is customized for a particular user.
2018 * On UNIX platforms this is determined using the mechanisms described in
2019 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2020 * XDG Base Directory Specification</ulink>
2022 * Return value: a string owned by GLib that must not be modified
2026 G_CONST_RETURN gchar*
2027 g_get_user_data_dir (void)
2031 G_LOCK (g_utils_global);
2033 if (!g_user_data_dir)
2036 data_dir = get_special_folder (CSIDL_PERSONAL);
2038 data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
2040 if (data_dir && data_dir[0])
2041 data_dir = g_strdup (data_dir);
2043 if (!data_dir || !data_dir[0])
2048 data_dir = g_build_filename (g_home_dir, ".local",
2051 data_dir = g_build_filename (g_tmp_dir, g_user_name, ".local",
2055 g_user_data_dir = data_dir;
2058 data_dir = g_user_data_dir;
2060 G_UNLOCK (g_utils_global);
2066 g_init_user_config_dir (void)
2070 if (!g_user_config_dir)
2073 config_dir = get_special_folder (CSIDL_APPDATA);
2075 config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
2077 if (config_dir && config_dir[0])
2078 config_dir = g_strdup (config_dir);
2080 if (!config_dir || !config_dir[0])
2085 config_dir = g_build_filename (g_home_dir, ".config", NULL);
2087 config_dir = g_build_filename (g_tmp_dir, g_user_name, ".config", NULL);
2090 g_user_config_dir = config_dir;
2095 * g_get_user_config_dir:
2097 * Returns a base directory in which to store user-specific application
2098 * configuration information such as user preferences and settings.
2100 * On UNIX platforms this is determined using the mechanisms described in
2101 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2102 * XDG Base Directory Specification</ulink>
2104 * Return value: a string owned by GLib that must not be modified
2108 G_CONST_RETURN gchar*
2109 g_get_user_config_dir (void)
2111 G_LOCK (g_utils_global);
2113 g_init_user_config_dir ();
2115 G_UNLOCK (g_utils_global);
2117 return g_user_config_dir;
2121 * g_get_user_cache_dir:
2123 * Returns a base directory in which to store non-essential, cached
2124 * data specific to particular user.
2126 * On UNIX platforms this is determined using the mechanisms described in
2127 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2128 * XDG Base Directory Specification</ulink>
2130 * Return value: a string owned by GLib that must not be modified
2134 G_CONST_RETURN gchar*
2135 g_get_user_cache_dir (void)
2139 G_LOCK (g_utils_global);
2141 if (!g_user_cache_dir)
2144 cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
2146 cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
2148 if (cache_dir && cache_dir[0])
2149 cache_dir = g_strdup (cache_dir);
2151 if (!cache_dir || !cache_dir[0])
2156 cache_dir = g_build_filename (g_home_dir, ".cache", NULL);
2158 cache_dir = g_build_filename (g_tmp_dir, g_user_name, ".cache", NULL);
2160 g_user_cache_dir = cache_dir;
2163 cache_dir = g_user_cache_dir;
2165 G_UNLOCK (g_utils_global);
2173 find_folder (OSType type)
2175 gchar *filename = NULL;
2178 if (FSFindFolder (kUserDomain, type, kDontCreateFolder, &found) == noErr)
2180 CFURLRef url = CFURLCreateFromFSRef (kCFAllocatorSystemDefault, &found);
2184 CFStringRef path = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle);
2188 filename = g_strdup (CFStringGetCStringPtr (path, kCFStringEncodingUTF8));
2192 filename = g_new0 (gchar, CFStringGetLength (path) * 3 + 1);
2194 CFStringGetCString (path, filename,
2195 CFStringGetLength (path) * 3 + 1,
2196 kCFStringEncodingUTF8);
2210 load_user_special_dirs (void)
2212 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = find_folder (kDesktopFolderType);
2213 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = find_folder (kDocumentsFolderType);
2214 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = find_folder (kDesktopFolderType); /* XXX correct ? */
2215 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = find_folder (kMusicDocumentsFolderType);
2216 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = find_folder (kPictureDocumentsFolderType);
2217 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = NULL;
2218 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = NULL;
2219 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = find_folder (kMovieDocumentsFolderType);
2222 #endif /* HAVE_CARBON */
2224 #if defined(G_OS_WIN32)
2226 load_user_special_dirs (void)
2228 typedef HRESULT (WINAPI *t_SHGetKnownFolderPath) (const GUID *rfid,
2232 t_SHGetKnownFolderPath p_SHGetKnownFolderPath;
2233 static const GUID FOLDERID_Downloads =
2234 { 0x374de290, 0x123f, 0x4565, { 0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b } };
2235 static const GUID FOLDERID_Public =
2236 { 0xDFDF76A2, 0xC82A, 0x4D63, { 0x90, 0x6A, 0x56, 0x44, 0xAC, 0x45, 0x73, 0x85 } };
2239 p_SHGetKnownFolderPath = (t_SHGetKnownFolderPath) GetProcAddress (LoadLibrary ("shell32.dll"),
2240 "SHGetKnownFolderPath");
2242 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2243 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
2245 if (p_SHGetKnownFolderPath == NULL)
2247 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2252 (*p_SHGetKnownFolderPath) (&FOLDERID_Downloads, 0, NULL, &wcp);
2253 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
2254 if (g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] == NULL)
2255 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2256 CoTaskMemFree (wcp);
2259 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
2260 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
2262 if (p_SHGetKnownFolderPath == NULL)
2265 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2270 (*p_SHGetKnownFolderPath) (&FOLDERID_Public, 0, NULL, &wcp);
2271 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
2272 if (g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] == NULL)
2273 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2274 CoTaskMemFree (wcp);
2277 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
2278 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
2280 #endif /* G_OS_WIN32 */
2282 static void g_init_user_config_dir (void);
2284 #if defined(G_OS_UNIX) && !defined(HAVE_CARBON)
2286 /* adapted from xdg-user-dir-lookup.c
2288 * Copyright (C) 2007 Red Hat Inc.
2290 * Permission is hereby granted, free of charge, to any person
2291 * obtaining a copy of this software and associated documentation files
2292 * (the "Software"), to deal in the Software without restriction,
2293 * including without limitation the rights to use, copy, modify, merge,
2294 * publish, distribute, sublicense, and/or sell copies of the Software,
2295 * and to permit persons to whom the Software is furnished to do so,
2296 * subject to the following conditions:
2298 * The above copyright notice and this permission notice shall be
2299 * included in all copies or substantial portions of the Software.
2301 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
2302 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
2303 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
2304 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
2305 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
2306 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
2307 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2311 load_user_special_dirs (void)
2318 g_init_user_config_dir ();
2319 config_file = g_build_filename (g_user_config_dir,
2323 if (!g_file_get_contents (config_file, &data, NULL, NULL))
2325 g_free (config_file);
2329 lines = g_strsplit (data, "\n", -1);
2330 n_lines = g_strv_length (lines);
2333 for (i = 0; i < n_lines; i++)
2335 gchar *buffer = lines[i];
2338 gboolean is_relative = FALSE;
2339 GUserDirectory directory;
2341 /* Remove newline at end */
2342 len = strlen (buffer);
2343 if (len > 0 && buffer[len - 1] == '\n')
2344 buffer[len - 1] = 0;
2347 while (*p == ' ' || *p == '\t')
2350 if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
2352 directory = G_USER_DIRECTORY_DESKTOP;
2353 p += strlen ("XDG_DESKTOP_DIR");
2355 else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
2357 directory = G_USER_DIRECTORY_DOCUMENTS;
2358 p += strlen ("XDG_DOCUMENTS_DIR");
2360 else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
2362 directory = G_USER_DIRECTORY_DOWNLOAD;
2363 p += strlen ("XDG_DOWNLOAD_DIR");
2365 else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
2367 directory = G_USER_DIRECTORY_MUSIC;
2368 p += strlen ("XDG_MUSIC_DIR");
2370 else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
2372 directory = G_USER_DIRECTORY_PICTURES;
2373 p += strlen ("XDG_PICTURES_DIR");
2375 else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
2377 directory = G_USER_DIRECTORY_PUBLIC_SHARE;
2378 p += strlen ("XDG_PUBLICSHARE_DIR");
2380 else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
2382 directory = G_USER_DIRECTORY_TEMPLATES;
2383 p += strlen ("XDG_TEMPLATES_DIR");
2385 else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
2387 directory = G_USER_DIRECTORY_VIDEOS;
2388 p += strlen ("XDG_VIDEOS_DIR");
2393 while (*p == ' ' || *p == '\t')
2400 while (*p == ' ' || *p == '\t')
2407 if (strncmp (p, "$HOME", 5) == 0)
2415 d = strrchr (p, '"');
2422 /* remove trailing slashes */
2424 if (d[len - 1] == '/')
2430 g_user_special_dirs[directory] = g_build_filename (g_home_dir, d, NULL);
2433 g_user_special_dirs[directory] = g_strdup (d);
2437 g_free (config_file);
2440 #endif /* G_OS_UNIX && !HAVE_CARBON */
2443 * g_get_user_special_dir:
2444 * @directory: the logical id of special directory
2446 * Returns the full path of a special directory using its logical id.
2448 * On Unix this is done using the XDG special user directories.
2449 * For compatibility with existing practise, %G_USER_DIRECTORY_DESKTOP
2450 * falls back to <filename>$HOME/Desktop</filename> when XDG special
2451 * user directories have not been set up.
2453 * Depending on the platform, the user might be able to change the path
2454 * of the special directory without requiring the session to restart; GLib
2455 * will not reflect any change once the special directories are loaded.
2457 * Return value: the path to the specified special directory, or %NULL
2458 * if the logical id was not found. The returned string is owned by
2459 * GLib and should not be modified or freed.
2463 G_CONST_RETURN gchar *
2464 g_get_user_special_dir (GUserDirectory directory)
2466 g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
2467 directory < G_USER_N_DIRECTORIES, NULL);
2469 G_LOCK (g_utils_global);
2471 if (G_UNLIKELY (g_user_special_dirs == NULL))
2473 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
2475 load_user_special_dirs ();
2477 /* Special-case desktop for historical compatibility */
2478 if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
2482 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] =
2483 g_build_filename (g_home_dir, "Desktop", NULL);
2487 G_UNLOCK (g_utils_global);
2489 return g_user_special_dirs[directory];
2494 #undef g_get_system_data_dirs
2497 get_module_for_address (gconstpointer address)
2499 /* Holds the g_utils_global lock */
2501 static gboolean beenhere = FALSE;
2502 typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
2503 static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
2504 HMODULE hmodule = NULL;
2511 p_GetModuleHandleExA =
2512 (t_GetModuleHandleExA) GetProcAddress (LoadLibrary ("kernel32.dll"),
2513 "GetModuleHandleExA");
2517 if (p_GetModuleHandleExA == NULL ||
2518 !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
2519 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
2522 MEMORY_BASIC_INFORMATION mbi;
2523 VirtualQuery (address, &mbi, sizeof (mbi));
2524 hmodule = (HMODULE) mbi.AllocationBase;
2531 get_module_share_dir (gconstpointer address)
2537 hmodule = get_module_for_address (address);
2538 if (hmodule == NULL)
2541 filename = g_win32_get_package_installation_directory_of_module (hmodule);
2542 retval = g_build_filename (filename, "share", NULL);
2548 G_CONST_RETURN gchar * G_CONST_RETURN *
2549 g_win32_get_system_data_dirs_for_module (gconstpointer address)
2553 static GHashTable *per_module_data_dirs = NULL;
2560 G_LOCK (g_utils_global);
2561 hmodule = get_module_for_address (address);
2562 if (hmodule != NULL)
2564 if (per_module_data_dirs == NULL)
2565 per_module_data_dirs = g_hash_table_new (NULL, NULL);
2568 retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
2572 G_UNLOCK (g_utils_global);
2573 return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2579 data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
2581 /* Documents and Settings\All Users\Application Data */
2582 p = get_special_folder (CSIDL_COMMON_APPDATA);
2584 g_array_append_val (data_dirs, p);
2586 /* Documents and Settings\All Users\Documents */
2587 p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2589 g_array_append_val (data_dirs, p);
2591 /* Using the above subfolders of Documents and Settings perhaps
2592 * makes sense from a Windows perspective.
2594 * But looking at the actual use cases of this function in GTK+
2595 * and GNOME software, what we really want is the "share"
2596 * subdirectory of the installation directory for the package
2597 * our caller is a part of.
2599 * The address parameter, if non-NULL, points to a function in the
2600 * calling module. Use that to determine that module's installation
2601 * folder, and use its "share" subfolder.
2603 * Additionally, also use the "share" subfolder of the installation
2604 * locations of GLib and the .exe file being run.
2606 * To guard against none of the above being what is really wanted,
2607 * callers of this function should have Win32-specific code to look
2608 * up their installation folder themselves, and handle a subfolder
2609 * "share" of it in the same way as the folders returned from this
2613 p = get_module_share_dir (address);
2615 g_array_append_val (data_dirs, p);
2617 if (glib_dll != NULL)
2619 gchar *glib_root = g_win32_get_package_installation_directory_of_module (glib_dll);
2620 p = g_build_filename (glib_root, "share", NULL);
2622 g_array_append_val (data_dirs, p);
2626 exe_root = g_win32_get_package_installation_directory_of_module (NULL);
2627 p = g_build_filename (exe_root, "share", NULL);
2629 g_array_append_val (data_dirs, p);
2632 retval = (gchar **) g_array_free (data_dirs, FALSE);
2636 if (hmodule != NULL)
2637 g_hash_table_insert (per_module_data_dirs, hmodule, retval);
2638 G_UNLOCK (g_utils_global);
2641 return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2647 * g_get_system_data_dirs:
2649 * Returns an ordered list of base directories in which to access
2650 * system-wide application data.
2652 * On UNIX platforms this is determined using the mechanisms described in
2653 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2654 * XDG Base Directory Specification</ulink>
2656 * On Windows the first elements in the list are the Application Data
2657 * and Documents folders for All Users. (These can be determined only
2658 * on Windows 2000 or later and are not present in the list on other
2659 * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
2660 * CSIDL_COMMON_DOCUMENTS.
2662 * Then follows the "share" subfolder in the installation folder for
2663 * the package containing the DLL that calls this function, if it can
2666 * Finally the list contains the "share" subfolder in the installation
2667 * folder for GLib, and in the installation folder for the package the
2668 * application's .exe file belongs to.
2670 * The installation folders above are determined by looking up the
2671 * folder where the module (DLL or EXE) in question is located. If the
2672 * folder's name is "bin", its parent is used, otherwise the folder
2675 * Note that on Windows the returned list can vary depending on where
2676 * this function is called.
2678 * Return value: a %NULL-terminated array of strings owned by GLib that must
2679 * not be modified or freed.
2682 G_CONST_RETURN gchar * G_CONST_RETURN *
2683 g_get_system_data_dirs (void)
2685 gchar **data_dir_vector;
2687 G_LOCK (g_utils_global);
2689 if (!g_system_data_dirs)
2692 data_dir_vector = (gchar **) g_win32_get_system_data_dirs_for_module (NULL);
2694 gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
2696 if (!data_dirs || !data_dirs[0])
2697 data_dirs = "/usr/local/share/:/usr/share/";
2699 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2702 g_system_data_dirs = data_dir_vector;
2705 data_dir_vector = g_system_data_dirs;
2707 G_UNLOCK (g_utils_global);
2709 return (G_CONST_RETURN gchar * G_CONST_RETURN *) data_dir_vector;
2713 * g_get_system_config_dirs:
2715 * Returns an ordered list of base directories in which to access
2716 * system-wide configuration information.
2718 * On UNIX platforms this is determined using the mechanisms described in
2719 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2720 * XDG Base Directory Specification</ulink>
2722 * Return value: a %NULL-terminated array of strings owned by GLib that must
2723 * not be modified or freed.
2726 G_CONST_RETURN gchar * G_CONST_RETURN *
2727 g_get_system_config_dirs (void)
2729 gchar *conf_dirs, **conf_dir_vector;
2731 G_LOCK (g_utils_global);
2733 if (!g_system_config_dirs)
2736 conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
2739 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2744 /* Return empty list */
2745 conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2748 conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
2750 if (!conf_dirs || !conf_dirs[0])
2751 conf_dirs = "/etc/xdg";
2753 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2756 g_system_config_dirs = conf_dir_vector;
2759 conf_dir_vector = g_system_config_dirs;
2760 G_UNLOCK (g_utils_global);
2762 return (G_CONST_RETURN gchar * G_CONST_RETURN *) conf_dir_vector;
2767 static GHashTable *alias_table = NULL;
2769 /* read an alias file for the locales */
2771 read_aliases (gchar *file)
2777 alias_table = g_hash_table_new (g_str_hash, g_str_equal);
2778 fp = fopen (file,"r");
2781 while (fgets (buf, 256, fp))
2787 /* Line is a comment */
2788 if ((buf[0] == '#') || (buf[0] == '\0'))
2791 /* Reads first column */
2792 for (p = buf, q = NULL; *p; p++) {
2793 if ((*p == '\t') || (*p == ' ') || (*p == ':')) {
2796 while ((*q == '\t') || (*q == ' ')) {
2802 /* The line only had one column */
2803 if (!q || *q == '\0')
2806 /* Read second column */
2807 for (p = q; *p; p++) {
2808 if ((*p == '\t') || (*p == ' ')) {
2814 /* Add to alias table if necessary */
2815 if (!g_hash_table_lookup (alias_table, buf)) {
2816 g_hash_table_insert (alias_table, g_strdup (buf), g_strdup (q));
2825 unalias_lang (char *lang)
2832 read_aliases ("/usr/share/locale/locale.alias");
2835 while ((p = g_hash_table_lookup (alias_table, lang)) && (strcmp (p, lang) != 0))
2840 static gboolean said_before = FALSE;
2842 g_warning ("Too many alias levels for a locale, "
2843 "may indicate a loop");
2852 /* Mask for components of locale spec. The ordering here is from
2853 * least significant to most significant
2857 COMPONENT_CODESET = 1 << 0,
2858 COMPONENT_TERRITORY = 1 << 1,
2859 COMPONENT_MODIFIER = 1 << 2
2862 /* Break an X/Open style locale specification into components
2865 explode_locale (const gchar *locale,
2871 const gchar *uscore_pos;
2872 const gchar *at_pos;
2873 const gchar *dot_pos;
2877 uscore_pos = strchr (locale, '_');
2878 dot_pos = strchr (uscore_pos ? uscore_pos : locale, '.');
2879 at_pos = strchr (dot_pos ? dot_pos : (uscore_pos ? uscore_pos : locale), '@');
2883 mask |= COMPONENT_MODIFIER;
2884 *modifier = g_strdup (at_pos);
2887 at_pos = locale + strlen (locale);
2891 mask |= COMPONENT_CODESET;
2892 *codeset = g_strndup (dot_pos, at_pos - dot_pos);
2899 mask |= COMPONENT_TERRITORY;
2900 *territory = g_strndup (uscore_pos, dot_pos - uscore_pos);
2903 uscore_pos = dot_pos;
2905 *language = g_strndup (locale, uscore_pos - locale);
2911 * Compute all interesting variants for a given locale name -
2912 * by stripping off different components of the value.
2914 * For simplicity, we assume that the locale is in
2915 * X/Open format: language[_territory][.codeset][@modifier]
2917 * TODO: Extend this to handle the CEN format (see the GNUlibc docs)
2918 * as well. We could just copy the code from glibc wholesale
2919 * but it is big, ugly, and complicated, so I'm reluctant
2920 * to do so when this should handle 99% of the time...
2923 _g_compute_locale_variants (const gchar *locale)
2925 GSList *retval = NULL;
2927 gchar *language = NULL;
2928 gchar *territory = NULL;
2929 gchar *codeset = NULL;
2930 gchar *modifier = NULL;
2935 g_return_val_if_fail (locale != NULL, NULL);
2937 mask = explode_locale (locale, &language, &territory, &codeset, &modifier);
2939 /* Iterate through all possible combinations, from least attractive
2940 * to most attractive.
2942 for (i = 0; i <= mask; i++)
2943 if ((i & ~mask) == 0)
2945 gchar *val = g_strconcat (language,
2946 (i & COMPONENT_TERRITORY) ? territory : "",
2947 (i & COMPONENT_CODESET) ? codeset : "",
2948 (i & COMPONENT_MODIFIER) ? modifier : "",
2950 retval = g_slist_prepend (retval, val);
2954 if (mask & COMPONENT_CODESET)
2956 if (mask & COMPONENT_TERRITORY)
2958 if (mask & COMPONENT_MODIFIER)
2964 /* The following is (partly) taken from the gettext package.
2965 Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc. */
2967 static const gchar *
2968 guess_category_value (const gchar *category_name)
2970 const gchar *retval;
2972 /* The highest priority value is the `LANGUAGE' environment
2973 variable. This is a GNU extension. */
2974 retval = g_getenv ("LANGUAGE");
2975 if ((retval != NULL) && (retval[0] != '\0'))
2978 /* `LANGUAGE' is not set. So we have to proceed with the POSIX
2979 methods of looking to `LC_ALL', `LC_xxx', and `LANG'. On some
2980 systems this can be done by the `setlocale' function itself. */
2982 /* Setting of LC_ALL overwrites all other. */
2983 retval = g_getenv ("LC_ALL");
2984 if ((retval != NULL) && (retval[0] != '\0'))
2987 /* Next comes the name of the desired category. */
2988 retval = g_getenv (category_name);
2989 if ((retval != NULL) && (retval[0] != '\0'))
2992 /* Last possibility is the LANG environment variable. */
2993 retval = g_getenv ("LANG");
2994 if ((retval != NULL) && (retval[0] != '\0'))
2997 #ifdef G_PLATFORM_WIN32
2998 /* g_win32_getlocale() first checks for LC_ALL, LC_MESSAGES and
2999 * LANG, which we already did above. Oh well. The main point of
3000 * calling g_win32_getlocale() is to get the thread's locale as used
3001 * by Windows and the Microsoft C runtime (in the "English_United
3002 * States" format) translated into the Unixish format.
3004 retval = g_win32_getlocale ();
3005 if ((retval != NULL) && (retval[0] != '\0'))
3012 typedef struct _GLanguageNamesCache GLanguageNamesCache;
3014 struct _GLanguageNamesCache {
3016 gchar **language_names;
3020 language_names_cache_free (gpointer data)
3022 GLanguageNamesCache *cache = data;
3023 g_free (cache->languages);
3024 g_strfreev (cache->language_names);
3029 * g_get_language_names:
3031 * Computes a list of applicable locale names, which can be used to
3032 * e.g. construct locale-dependent filenames or search paths. The returned
3033 * list is sorted from most desirable to least desirable and always contains
3034 * the default locale "C".
3036 * For example, if LANGUAGE=de:en_US, then the returned list is
3037 * "de", "en_US", "en", "C".
3039 * This function consults the environment variables <envar>LANGUAGE</envar>,
3040 * <envar>LC_ALL</envar>, <envar>LC_MESSAGES</envar> and <envar>LANG</envar>
3041 * to find the list of locales specified by the user.
3043 * Return value: a %NULL-terminated array of strings owned by GLib
3044 * that must not be modified or freed.
3048 G_CONST_RETURN gchar * G_CONST_RETURN *
3049 g_get_language_names (void)
3051 static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
3052 GLanguageNamesCache *cache = g_static_private_get (&cache_private);
3057 cache = g_new0 (GLanguageNamesCache, 1);
3058 g_static_private_set (&cache_private, cache, language_names_cache_free);
3061 value = guess_category_value ("LC_MESSAGES");
3065 if (!(cache->languages && strcmp (cache->languages, value) == 0))
3072 g_free (cache->languages);
3073 g_strfreev (cache->language_names);
3074 cache->languages = g_strdup (value);
3076 alist = g_strsplit (value, ":", 0);
3078 for (a = alist; *a; a++)
3080 gchar *b = unalias_lang (*a);
3081 list = g_slist_concat (list, _g_compute_locale_variants (b));
3084 list = g_slist_append (list, g_strdup ("C"));
3086 cache->language_names = languages = g_new (gchar *, g_slist_length (list) + 1);
3087 for (l = list, i = 0; l; l = l->next, i++)
3088 languages[i] = l->data;
3089 languages[i] = NULL;
3091 g_slist_free (list);
3094 return (G_CONST_RETURN gchar * G_CONST_RETURN *) cache->language_names;
3099 * @v: a #gpointer key
3101 * Converts a gpointer to a hash value.
3102 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3103 * when using pointers as keys in a #GHashTable.
3105 * Returns: a hash value corresponding to the key.
3108 g_direct_hash (gconstpointer v)
3110 return GPOINTER_TO_UINT (v);
3116 * @v2: a key to compare with @v1.
3118 * Compares two #gpointer arguments and returns %TRUE if they are equal.
3119 * It can be passed to g_hash_table_new() as the @key_equal_func
3120 * parameter, when using pointers as keys in a #GHashTable.
3122 * Returns: %TRUE if the two keys match.
3125 g_direct_equal (gconstpointer v1,
3133 * @v1: a pointer to a #gint key.
3134 * @v2: a pointer to a #gint key to compare with @v1.
3136 * Compares the two #gint values being pointed to and returns
3137 * %TRUE if they are equal.
3138 * It can be passed to g_hash_table_new() as the @key_equal_func
3139 * parameter, when using pointers to integers as keys in a #GHashTable.
3141 * Returns: %TRUE if the two keys match.
3144 g_int_equal (gconstpointer v1,
3147 return *((const gint*) v1) == *((const gint*) v2);
3152 * @v: a pointer to a #gint key
3154 * Converts a pointer to a #gint to a hash value.
3155 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3156 * when using pointers to integers values as keys in a #GHashTable.
3158 * Returns: a hash value corresponding to the key.
3161 g_int_hash (gconstpointer v)
3163 return *(const gint*) v;
3167 * g_nullify_pointer:
3168 * @nullify_location: the memory address of the pointer.
3170 * Set the pointer at the specified location to %NULL.
3173 g_nullify_pointer (gpointer *nullify_location)
3175 g_return_if_fail (nullify_location != NULL);
3177 *nullify_location = NULL;
3183 * Get the codeset for the current locale.
3185 * Return value: a newly allocated string containing the name
3186 * of the codeset. This string must be freed with g_free().
3189 g_get_codeset (void)
3191 const gchar *charset;
3193 g_get_charset (&charset);
3195 return g_strdup (charset);
3198 /* This is called from g_thread_init(). It's used to
3199 * initialize some static data in a threadsafe way.
3202 _g_utils_thread_init (void)
3204 g_get_language_names ();
3210 * _glib_get_locale_dir:
3212 * Return the path to the share\locale or lib\locale subfolder of the
3213 * GLib installation folder. The path is in the system codepage. We
3214 * have to use system codepage as bindtextdomain() doesn't have a
3218 _glib_get_locale_dir (void)
3220 gchar *install_dir = NULL, *locale_dir;
3221 gchar *retval = NULL;
3223 if (glib_dll != NULL)
3224 install_dir = g_win32_get_package_installation_directory_of_module (glib_dll);
3229 * Append "/share/locale" or "/lib/locale" depending on whether
3230 * autoconfigury detected GNU gettext or not.
3232 const char *p = GLIB_LOCALE_DIR + strlen (GLIB_LOCALE_DIR);
3238 locale_dir = g_build_filename (install_dir, p, NULL);
3240 retval = g_win32_locale_filename_from_utf8 (locale_dir);
3242 g_free (install_dir);
3243 g_free (locale_dir);
3249 return g_strdup ("");
3252 #undef GLIB_LOCALE_DIR
3254 #endif /* G_OS_WIN32 */
3258 * @str: The string to be translated
3260 * Returns the translated string from the glib translations.
3261 * This is an internal function and should only be used by
3262 * the internals of glib (such as libgio).
3264 * Returns: the transation of @str to the current locale
3266 G_CONST_RETURN gchar *
3267 glib_gettext (const gchar *str)
3269 static gboolean _glib_gettext_initialized = FALSE;
3271 if (!_glib_gettext_initialized)
3274 gchar *tmp = _glib_get_locale_dir ();
3275 bindtextdomain (GETTEXT_PACKAGE, tmp);
3278 bindtextdomain (GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
3280 # ifdef HAVE_BIND_TEXTDOMAIN_CODESET
3281 bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
3283 _glib_gettext_initialized = TRUE;
3286 return g_dgettext (GETTEXT_PACKAGE, str);
3289 #if defined (G_OS_WIN32) && !defined (_WIN64)
3291 /* Binary compatibility versions. Not for newly compiled code. */
3293 #undef g_find_program_in_path
3296 g_find_program_in_path (const gchar *program)
3298 gchar *utf8_program = g_locale_to_utf8 (program, -1, NULL, NULL, NULL);
3299 gchar *utf8_retval = g_find_program_in_path_utf8 (utf8_program);
3302 g_free (utf8_program);
3303 if (utf8_retval == NULL)
3305 retval = g_locale_from_utf8 (utf8_retval, -1, NULL, NULL, NULL);
3306 g_free (utf8_retval);
3311 #undef g_get_current_dir
3314 g_get_current_dir (void)
3316 gchar *utf8_dir = g_get_current_dir_utf8 ();
3317 gchar *dir = g_locale_from_utf8 (utf8_dir, -1, NULL, NULL, NULL);
3324 G_CONST_RETURN gchar*
3325 g_getenv (const gchar *variable)
3327 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3328 const gchar *utf8_value = g_getenv_utf8 (utf8_variable);
3332 g_free (utf8_variable);
3335 value = g_locale_from_utf8 (utf8_value, -1, NULL, NULL, NULL);
3336 quark = g_quark_from_string (value);
3339 return g_quark_to_string (quark);
3345 g_setenv (const gchar *variable,
3349 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3350 gchar *utf8_value = g_locale_to_utf8 (value, -1, NULL, NULL, NULL);
3351 gboolean retval = g_setenv_utf8 (utf8_variable, utf8_value, overwrite);
3353 g_free (utf8_variable);
3354 g_free (utf8_value);
3362 g_unsetenv (const gchar *variable)
3364 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3366 g_unsetenv_utf8 (utf8_variable);
3368 g_free (utf8_variable);
3371 #undef g_get_user_name
3373 G_CONST_RETURN gchar*
3374 g_get_user_name (void)
3376 g_get_any_init_locked ();
3377 return g_user_name_cp;
3380 #undef g_get_real_name
3382 G_CONST_RETURN gchar*
3383 g_get_real_name (void)
3385 g_get_any_init_locked ();
3386 return g_real_name_cp;
3389 #undef g_get_home_dir
3391 G_CONST_RETURN gchar*
3392 g_get_home_dir (void)
3394 g_get_any_init_locked ();
3395 return g_home_dir_cp;
3398 #undef g_get_tmp_dir
3400 G_CONST_RETURN gchar*
3401 g_get_tmp_dir (void)
3403 g_get_any_init_locked ();
3404 return g_tmp_dir_cp;
3409 #define __G_UTILS_C__
3410 #include "galiasdef.c"