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"
66 #define G_PATH_LENGTH MAXPATHLEN
67 #elif defined (PATH_MAX)
68 #define G_PATH_LENGTH PATH_MAX
69 #elif defined (_PC_PATH_MAX)
70 #define G_PATH_LENGTH sysconf(_PC_PATH_MAX)
72 #define G_PATH_LENGTH 2048
75 #ifdef G_PLATFORM_WIN32
76 # define STRICT /* Strict typing, please */
79 # ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
80 # define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2
81 # define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4
83 # include <lmcons.h> /* For UNLEN */
84 #endif /* G_PLATFORM_WIN32 */
89 /* older SDK (e.g. msvc 5.0) does not have these*/
90 # ifndef CSIDL_MYMUSIC
91 # define CSIDL_MYMUSIC 13
93 # ifndef CSIDL_MYVIDEO
94 # define CSIDL_MYVIDEO 14
96 # ifndef CSIDL_INTERNET_CACHE
97 # define CSIDL_INTERNET_CACHE 32
99 # ifndef CSIDL_COMMON_APPDATA
100 # define CSIDL_COMMON_APPDATA 35
102 # ifndef CSIDL_COMMON_DOCUMENTS
103 # define CSIDL_COMMON_DOCUMENTS 46
105 # ifndef CSIDL_PROFILE
106 # define CSIDL_PROFILE 40
108 # include <process.h>
112 #include <CoreServices/CoreServices.h>
116 #include <langinfo.h>
119 #ifdef HAVE_BIND_TEXTDOMAIN_CODESET
123 const guint glib_major_version = GLIB_MAJOR_VERSION;
124 const guint glib_minor_version = GLIB_MINOR_VERSION;
125 const guint glib_micro_version = GLIB_MICRO_VERSION;
126 const guint glib_interface_age = GLIB_INTERFACE_AGE;
127 const guint glib_binary_age = GLIB_BINARY_AGE;
129 #ifdef G_PLATFORM_WIN32
131 G_WIN32_DLLMAIN_FOR_DLL_NAME (static, dll_name)
136 * glib_check_version:
137 * @required_major: the required major version.
138 * @required_minor: the required minor version.
139 * @required_micro: the required micro version.
141 * Checks that the GLib library in use is compatible with the
142 * given version. Generally you would pass in the constants
143 * #GLIB_MAJOR_VERSION, #GLIB_MINOR_VERSION, #GLIB_MICRO_VERSION
144 * as the three arguments to this function; that produces
145 * a check that the library in use is compatible with
146 * the version of GLib the application or module was compiled
149 * Compatibility is defined by two things: first the version
150 * of the running library is newer than the version
151 * @required_major.required_minor.@required_micro. Second
152 * the running library must be binary compatible with the
153 * version @required_major.required_minor.@required_micro
154 * (same major version.)
156 * Return value: %NULL if the GLib library is compatible with the
157 * given version, or a string describing the version mismatch.
158 * The returned string is owned by GLib and must not be modified
164 glib_check_version (guint required_major,
165 guint required_minor,
166 guint required_micro)
168 gint glib_effective_micro = 100 * GLIB_MINOR_VERSION + GLIB_MICRO_VERSION;
169 gint required_effective_micro = 100 * required_minor + required_micro;
171 if (required_major > GLIB_MAJOR_VERSION)
172 return "GLib version too old (major mismatch)";
173 if (required_major < GLIB_MAJOR_VERSION)
174 return "GLib version too new (major mismatch)";
175 if (required_effective_micro < glib_effective_micro - GLIB_BINARY_AGE)
176 return "GLib version too new (micro mismatch)";
177 if (required_effective_micro > glib_effective_micro)
178 return "GLib version too old (micro mismatch)";
182 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
185 * @dest: the destination address to copy the bytes to.
186 * @src: the source address to copy the bytes from.
187 * @len: the number of bytes to copy.
189 * Copies a block of memory @len bytes long, from @src to @dest.
190 * The source and destination areas may overlap.
192 * In order to use this function, you must include
193 * <filename>string.h</filename> yourself, because this macro will
194 * typically simply resolve to memmove() and GLib does not include
195 * <filename>string.h</filename> for you.
198 g_memmove (gpointer dest,
202 gchar* destptr = dest;
203 const gchar* srcptr = src;
204 if (src + len < dest || dest + len < src)
206 bcopy (src, dest, len);
209 else if (dest <= src)
212 *(destptr++) = *(srcptr++);
219 *(--destptr) = *(--srcptr);
222 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
230 * @func: the function to call on normal program termination.
232 * Specifies a function to be called at normal program termination.
234 * Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
235 * macro that maps to a call to the atexit() function in the C
236 * library. This means that in case the code that calls g_atexit(),
237 * i.e. atexit(), is in a DLL, the function will be called when the
238 * DLL is detached from the program. This typically makes more sense
239 * than that the function is called when the GLib DLL is detached,
240 * which happened earlier when g_atexit() was a function in the GLib
243 * The behaviour of atexit() in the context of dynamically loaded
244 * modules is not formally specified and varies wildly.
246 * On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
247 * loaded module which is unloaded before the program terminates might
248 * well cause a crash at program exit.
250 * Some POSIX systems implement atexit() like Windows, and have each
251 * dynamically loaded module maintain an own atexit chain that is
252 * called when the module is unloaded.
254 * On other POSIX systems, before a dynamically loaded module is
255 * unloaded, the registered atexit functions (if any) residing in that
256 * module are called, regardless where the code that registered them
257 * resided. This is presumably the most robust approach.
259 * As can be seen from the above, for portability it's best to avoid
260 * calling g_atexit() (or atexit()) except in the main executable of a
264 g_atexit (GVoidFunc func)
267 const gchar *error = NULL;
269 /* keep this in sync with glib.h */
271 #ifdef G_NATIVE_ATEXIT
272 result = ATEXIT (func);
274 error = g_strerror (errno);
275 #elif defined (HAVE_ATEXIT)
276 # ifdef NeXT /* @#%@! NeXTStep */
277 result = !atexit ((void (*)(void)) func);
279 error = g_strerror (errno);
281 result = atexit ((void (*)(void)) func);
283 error = g_strerror (errno);
285 #elif defined (HAVE_ON_EXIT)
286 result = on_exit ((void (*)(int, void *)) func, NULL);
288 error = g_strerror (errno);
291 error = "no implementation";
292 #endif /* G_NATIVE_ATEXIT */
295 g_error ("Could not register atexit() function: %s", error);
298 /* Based on execvp() from GNU Libc.
299 * Some of this code is cut-and-pasted into gspawn.c
303 my_strchrnul (const gchar *str,
306 gchar *p = (gchar*)str;
307 while (*p && (*p != c))
315 static gchar *inner_find_program_in_path (const gchar *program);
318 g_find_program_in_path (const gchar *program)
320 const gchar *last_dot = strrchr (program, '.');
322 if (last_dot == NULL ||
323 strchr (last_dot, '\\') != NULL ||
324 strchr (last_dot, '/') != NULL)
326 const gint program_length = strlen (program);
327 gchar *pathext = g_build_path (";",
328 ".exe;.cmd;.bat;.com",
329 g_getenv ("PATHEXT"),
332 gchar *decorated_program;
338 gchar *q = my_strchrnul (p, ';');
340 decorated_program = g_malloc (program_length + (q-p) + 1);
341 memcpy (decorated_program, program, program_length);
342 memcpy (decorated_program+program_length, p, q-p);
343 decorated_program [program_length + (q-p)] = '\0';
345 retval = inner_find_program_in_path (decorated_program);
346 g_free (decorated_program);
354 } while (*p++ != '\0');
359 return inner_find_program_in_path (program);
365 * g_find_program_in_path:
366 * @program: a program name in the GLib file name encoding
368 * Locates the first executable named @program in the user's path, in the
369 * same way that execvp() would locate it. Returns an allocated string
370 * with the absolute path name, or %NULL if the program is not found in
371 * the path. If @program is already an absolute path, returns a copy of
372 * @program if @program exists and is executable, and %NULL otherwise.
374 * On Windows, if @program does not have a file type suffix, tries
375 * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
376 * the <envar>PATHEXT</envar> environment variable.
378 * On Windows, it looks for the file in the same way as CreateProcess()
379 * would. This means first in the directory where the executing
380 * program was loaded from, then in the current directory, then in the
381 * Windows 32-bit system directory, then in the Windows directory, and
382 * finally in the directories in the <envar>PATH</envar> environment
383 * variable. If the program is found, the return value contains the
384 * full name including the type suffix.
386 * Return value: absolute path, or %NULL
390 inner_find_program_in_path (const gchar *program)
393 g_find_program_in_path (const gchar *program)
396 const gchar *path, *p;
397 gchar *name, *freeme;
399 const gchar *path_copy;
400 gchar *filename = NULL, *appdir = NULL;
401 gchar *sysdir = NULL, *windir = NULL;
403 wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
409 g_return_val_if_fail (program != NULL, NULL);
411 /* If it is an absolute path, or a relative path including subdirectories,
412 * don't look in PATH.
414 if (g_path_is_absolute (program)
415 || strchr (program, G_DIR_SEPARATOR) != NULL
417 || strchr (program, '/') != NULL
421 if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
422 !g_file_test (program, G_FILE_TEST_IS_DIR))
423 return g_strdup (program);
428 path = g_getenv ("PATH");
429 #if defined(G_OS_UNIX) || defined(G_OS_BEOS)
432 /* There is no `PATH' in the environment. The default
433 * search path in GNU libc is the current directory followed by
434 * the path `confstr' returns for `_CS_PATH'.
437 /* In GLib we put . last, for security, and don't use the
438 * unportable confstr(); UNIX98 does not actually specify
439 * what to search if PATH is unset. POSIX may, dunno.
442 path = "/bin:/usr/bin:.";
445 n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
446 if (n > 0 && n < MAXPATHLEN)
447 filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
449 n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
450 if (n > 0 && n < MAXPATHLEN)
451 sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
453 n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
454 if (n > 0 && n < MAXPATHLEN)
455 windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
459 appdir = g_path_get_dirname (filename);
463 path = g_strdup (path);
467 const gchar *tem = path;
468 path = g_strconcat (windir, ";", path, NULL);
469 g_free ((gchar *) tem);
475 const gchar *tem = path;
476 path = g_strconcat (sysdir, ";", path, NULL);
477 g_free ((gchar *) tem);
482 const gchar *tem = path;
483 path = g_strconcat (".;", path, NULL);
484 g_free ((gchar *) tem);
489 const gchar *tem = path;
490 path = g_strconcat (appdir, ";", path, NULL);
491 g_free ((gchar *) tem);
498 len = strlen (program) + 1;
499 pathlen = strlen (path);
500 freeme = name = g_malloc (pathlen + len + 1);
502 /* Copy the file name at the top, including '\0' */
503 memcpy (name + pathlen + 1, program, len);
504 name = name + pathlen;
505 /* And add the slash before the filename */
506 *name = G_DIR_SEPARATOR;
514 p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
517 /* Two adjacent colons, or a colon at the beginning or the end
518 * of `PATH' means to search the current directory.
522 startp = memcpy (name - (p - path), path, p - path);
524 if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
525 !g_file_test (startp, G_FILE_TEST_IS_DIR))
528 ret = g_strdup (startp);
531 g_free ((gchar *) path_copy);
536 while (*p++ != '\0');
540 g_free ((gchar *) path_copy);
547 debug_key_matches (const gchar *key,
551 for (; length; length--, key++, token++)
553 char k = (*key == '_') ? '-' : tolower (*key );
554 char t = (*token == '_') ? '-' : tolower (*token);
564 * g_parse_debug_string:
565 * @string: a list of debug options separated by colons, spaces, or
566 * commas; or the string "all" to set all flags.
567 * @keys: pointer to an array of #GDebugKey which associate
568 * strings with bit flags.
569 * @nkeys: the number of #GDebugKey<!-- -->s in the array.
571 * Parses a string containing debugging options
572 * into a %guint containing bit flags. This is used
573 * within GDK and GTK+ to parse the debug options passed on the
574 * command line or through environment variables.
576 * Returns: the combined set of bit flags.
579 g_parse_debug_string (const gchar *string,
580 const GDebugKey *keys,
586 g_return_val_if_fail (string != NULL, 0);
588 /* this function is used by gmem.c/gslice.c initialization code,
589 * so introducing malloc dependencies here would require adaptions
590 * of those code portions.
593 if (!g_ascii_strcasecmp (string, "all"))
595 for (i=0; i<nkeys; i++)
596 result |= keys[i].value;
600 const gchar *p = string;
605 q = strpbrk (p, ":;, \t");
609 for (i = 0; i < nkeys; i++)
610 if (debug_key_matches (keys[i].key, p, q - p))
611 result |= keys[i].value;
624 * @file_name: the name of the file.
626 * Gets the name of the file without any leading directory components.
627 * It returns a pointer into the given file name string.
629 * Return value: the name of the file without any leading directory components.
631 * Deprecated:2.2: Use g_path_get_basename() instead, but notice that
632 * g_path_get_basename() allocates new memory for the returned string, unlike
633 * this function which returns a pointer into the argument.
635 G_CONST_RETURN gchar*
636 g_basename (const gchar *file_name)
638 register gchar *base;
640 g_return_val_if_fail (file_name != NULL, NULL);
642 base = strrchr (file_name, G_DIR_SEPARATOR);
646 gchar *q = strrchr (file_name, '/');
647 if (base == NULL || (q != NULL && q > base))
656 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
657 return (gchar*) file_name + 2;
658 #endif /* G_OS_WIN32 */
660 return (gchar*) file_name;
664 * g_path_get_basename:
665 * @file_name: the name of the file.
667 * Gets the last component of the filename. If @file_name ends with a
668 * directory separator it gets the component before the last slash. If
669 * @file_name consists only of directory separators (and on Windows,
670 * possibly a drive letter), a single separator is returned. If
671 * @file_name is empty, it gets ".".
673 * Return value: a newly allocated string containing the last component of
677 g_path_get_basename (const gchar *file_name)
679 register gssize base;
680 register gssize last_nonslash;
684 g_return_val_if_fail (file_name != NULL, NULL);
686 if (file_name[0] == '\0')
688 return g_strdup (".");
690 last_nonslash = strlen (file_name) - 1;
692 while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
695 if (last_nonslash == -1)
696 /* string only containing slashes */
697 return g_strdup (G_DIR_SEPARATOR_S);
700 if (last_nonslash == 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
701 /* string only containing slashes and a drive */
702 return g_strdup (G_DIR_SEPARATOR_S);
703 #endif /* G_OS_WIN32 */
705 base = last_nonslash;
707 while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
711 if (base == -1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
713 #endif /* G_OS_WIN32 */
715 len = last_nonslash - base;
716 retval = g_malloc (len + 1);
717 memcpy (retval, file_name + base + 1, len);
723 * g_path_is_absolute:
724 * @file_name: a file name.
726 * Returns %TRUE if the given @file_name is an absolute file name,
727 * i.e. it contains a full path from the root directory such as "/usr/local"
728 * on UNIX or "C:\windows" on Windows systems.
730 * Returns: %TRUE if @file_name is an absolute path.
733 g_path_is_absolute (const gchar *file_name)
735 g_return_val_if_fail (file_name != NULL, FALSE);
737 if (G_IS_DIR_SEPARATOR (file_name[0]))
741 /* Recognize drive letter on native Windows */
742 if (g_ascii_isalpha (file_name[0]) &&
743 file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
745 #endif /* G_OS_WIN32 */
752 * @file_name: a file name.
754 * Returns a pointer into @file_name after the root component, i.e. after
755 * the "/" in UNIX or "C:\" under Windows. If @file_name is not an absolute
756 * path it returns %NULL.
758 * Returns: a pointer into @file_name after the root component.
760 G_CONST_RETURN gchar*
761 g_path_skip_root (const gchar *file_name)
763 g_return_val_if_fail (file_name != NULL, NULL);
765 #ifdef G_PLATFORM_WIN32
766 /* Skip \\server\share or //server/share */
767 if (G_IS_DIR_SEPARATOR (file_name[0]) &&
768 G_IS_DIR_SEPARATOR (file_name[1]) &&
770 !G_IS_DIR_SEPARATOR (file_name[2]))
774 p = strchr (file_name + 2, G_DIR_SEPARATOR);
777 gchar *q = strchr (file_name + 2, '/');
778 if (p == NULL || (q != NULL && q < p))
788 while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
791 /* Possibly skip a backslash after the share name */
792 if (G_IS_DIR_SEPARATOR (file_name[0]))
795 return (gchar *)file_name;
800 /* Skip initial slashes */
801 if (G_IS_DIR_SEPARATOR (file_name[0]))
803 while (G_IS_DIR_SEPARATOR (file_name[0]))
805 return (gchar *)file_name;
810 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
811 return (gchar *)file_name + 3;
818 * g_path_get_dirname:
819 * @file_name: the name of the file.
821 * Gets the directory components of a file name. If the file name has no
822 * directory components "." is returned. The returned string should be
823 * freed when no longer needed.
825 * Returns: the directory components of the file.
828 g_path_get_dirname (const gchar *file_name)
830 register gchar *base;
833 g_return_val_if_fail (file_name != NULL, NULL);
835 base = strrchr (file_name, G_DIR_SEPARATOR);
838 gchar *q = strrchr (file_name, '/');
839 if (base == NULL || (q != NULL && q > base))
846 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
848 gchar drive_colon_dot[4];
850 drive_colon_dot[0] = file_name[0];
851 drive_colon_dot[1] = ':';
852 drive_colon_dot[2] = '.';
853 drive_colon_dot[3] = '\0';
855 return g_strdup (drive_colon_dot);
858 return g_strdup (".");
861 while (base > file_name && G_IS_DIR_SEPARATOR (*base))
865 /* base points to the char before the last slash.
867 * In case file_name is the root of a drive (X:\) or a child of the
868 * root of a drive (X:\foo), include the slash.
870 * In case file_name is the root share of an UNC path
871 * (\\server\share), add a slash, returning \\server\share\ .
873 * In case file_name is a direct child of a share in an UNC path
874 * (\\server\share\foo), include the slash after the share name,
875 * returning \\server\share\ .
877 if (base == file_name + 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
879 else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
880 G_IS_DIR_SEPARATOR (file_name[1]) &&
882 !G_IS_DIR_SEPARATOR (file_name[2]) &&
883 base >= file_name + 2)
885 const gchar *p = file_name + 2;
886 while (*p && !G_IS_DIR_SEPARATOR (*p))
890 len = (guint) strlen (file_name) + 1;
891 base = g_new (gchar, len + 1);
892 strcpy (base, file_name);
893 base[len-1] = G_DIR_SEPARATOR;
897 if (G_IS_DIR_SEPARATOR (*p))
900 while (*p && !G_IS_DIR_SEPARATOR (*p))
908 len = (guint) 1 + base - file_name;
910 base = g_new (gchar, len + 1);
911 g_memmove (base, file_name, len);
920 * Gets the current directory.
921 * The returned string should be freed when no longer needed. The encoding
922 * of the returned string is system defined. On Windows, it is always UTF-8.
924 * Returns: the current directory.
927 g_get_current_dir (void)
932 wchar_t dummy[2], *wdir;
935 len = GetCurrentDirectoryW (2, dummy);
936 wdir = g_new (wchar_t, len);
938 if (GetCurrentDirectoryW (len, wdir) == len - 1)
939 dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
944 dir = g_strdup ("\\");
950 gchar *buffer = NULL;
952 static gulong max_len = 0;
955 max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
957 /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
958 * and, if that wasn't bad enough, hangs in doing so.
960 #if (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
961 buffer = g_new (gchar, max_len + 1);
963 dir = getwd (buffer);
964 #else /* !sun || !HAVE_GETCWD */
965 while (max_len < G_MAXULONG / 2)
967 buffer = g_new (gchar, max_len + 1);
969 dir = getcwd (buffer, max_len);
971 if (dir || errno != ERANGE)
977 #endif /* !sun || !HAVE_GETCWD */
979 if (!dir || !*buffer)
981 /* hm, should we g_error() out here?
982 * this can happen if e.g. "./" has mode \0000
984 buffer[0] = G_DIR_SEPARATOR;
988 dir = g_strdup (buffer);
997 * @variable: the environment variable to get, in the GLib file name encoding.
999 * Returns the value of an environment variable. The name and value
1000 * are in the GLib file name encoding. On UNIX, this means the actual
1001 * bytes which might or might not be in some consistent character set
1002 * and encoding. On Windows, it is in UTF-8. On Windows, in case the
1003 * environment variable's value contains references to other
1004 * environment variables, they are expanded.
1006 * Return value: the value of the environment variable, or %NULL if
1007 * the environment variable is not found. The returned string may be
1008 * overwritten by the next call to g_getenv(), g_setenv() or
1011 G_CONST_RETURN gchar*
1012 g_getenv (const gchar *variable)
1016 g_return_val_if_fail (variable != NULL, NULL);
1018 return getenv (variable);
1020 #else /* G_OS_WIN32 */
1024 wchar_t dummy[2], *wname, *wvalue;
1027 g_return_val_if_fail (variable != NULL, NULL);
1028 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), NULL);
1030 /* On Windows NT, it is relatively typical that environment
1031 * variables contain references to other environment variables. If
1032 * so, use ExpandEnvironmentStrings(). (In an ideal world, such
1033 * environment variables would be stored in the Registry as
1034 * REG_EXPAND_SZ type values, and would then get automatically
1035 * expanded before a program sees them. But there is broken software
1036 * that stores environment variables as REG_SZ values even if they
1037 * contain references to other environment variables.)
1040 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1042 len = GetEnvironmentVariableW (wname, dummy, 2);
1052 wvalue = g_new (wchar_t, len);
1054 if (GetEnvironmentVariableW (wname, wvalue, len) != len - 1)
1061 if (wcschr (wvalue, L'%') != NULL)
1063 wchar_t *tem = wvalue;
1065 len = ExpandEnvironmentStringsW (wvalue, dummy, 2);
1069 wvalue = g_new (wchar_t, len);
1071 if (ExpandEnvironmentStringsW (tem, wvalue, len) != len)
1081 value = g_utf16_to_utf8 (wvalue, -1, NULL, NULL, NULL);
1086 quark = g_quark_from_string (value);
1089 return g_quark_to_string (quark);
1091 #endif /* G_OS_WIN32 */
1094 /* _g_getenv_nomalloc
1095 * this function does a getenv() without doing any kind of allocation
1096 * through glib. it's suitable for chars <= 127 only (both, for the
1097 * variable name and the contents) and for contents < 1024 chars in
1098 * length. also, it aliases "" to a NULL return value.
1101 _g_getenv_nomalloc (const gchar *variable,
1104 const gchar *retval = getenv (variable);
1105 if (retval && retval[0])
1107 gint l = strlen (retval);
1110 strncpy (buffer, retval, l);
1120 * @variable: the environment variable to set, must not contain '='.
1121 * @value: the value for to set the variable to.
1122 * @overwrite: whether to change the variable if it already exists.
1124 * Sets an environment variable. Both the variable's name and value
1125 * should be in the GLib file name encoding. On UNIX, this means that
1126 * they can be any sequence of bytes. On Windows, they should be in
1129 * Note that on some systems, when variables are overwritten, the memory
1130 * used for the previous variables and its value isn't reclaimed.
1132 * Returns: %FALSE if the environment variable couldn't be set.
1137 g_setenv (const gchar *variable,
1148 g_return_val_if_fail (variable != NULL, FALSE);
1149 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1152 result = setenv (variable, value, overwrite);
1154 if (!overwrite && getenv (variable) != NULL)
1157 /* This results in a leak when you overwrite existing
1158 * settings. It would be fairly easy to fix this by keeping
1159 * our own parallel array or hash table.
1161 string = g_strconcat (variable, "=", value, NULL);
1162 result = putenv (string);
1166 #else /* G_OS_WIN32 */
1169 wchar_t *wname, *wvalue, *wassignment;
1172 g_return_val_if_fail (variable != NULL, FALSE);
1173 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1174 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), FALSE);
1175 g_return_val_if_fail (g_utf8_validate (value, -1, NULL), FALSE);
1177 if (!overwrite && g_getenv (variable) != NULL)
1180 /* We want to (if possible) set both the environment variable copy
1181 * kept by the C runtime and the one kept by the system.
1183 * We can't use only the C runtime's putenv or _wputenv() as that
1184 * won't work for arbitrary Unicode strings in a "non-Unicode" app
1185 * (with main() and not wmain()). In a "main()" app the C runtime
1186 * initializes the C runtime's environment table by converting the
1187 * real (wide char) environment variables to system codepage, thus
1188 * breaking those that aren't representable in the system codepage.
1190 * As the C runtime's putenv() will also set the system copy, we do
1191 * the putenv() first, then call SetEnvironmentValueW ourselves.
1194 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1195 wvalue = g_utf8_to_utf16 (value, -1, NULL, NULL, NULL);
1196 tem = g_strconcat (variable, "=", value, NULL);
1197 wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1200 _wputenv (wassignment);
1201 g_free (wassignment);
1203 retval = (SetEnvironmentVariableW (wname, wvalue) != 0);
1210 #endif /* G_OS_WIN32 */
1213 #ifdef HAVE__NSGETENVIRON
1214 #define environ (*_NSGetEnviron())
1215 #elif !defined(G_OS_WIN32)
1217 /* According to the Single Unix Specification, environ is not in
1218 * any system header, although unistd.h often declares it.
1220 extern char **environ;
1225 * @variable: the environment variable to remove, must not contain '='.
1227 * Removes an environment variable from the environment.
1229 * Note that on some systems, when variables are overwritten, the memory
1230 * used for the previous variables and its value isn't reclaimed.
1231 * Furthermore, this function can't be guaranteed to operate in a
1237 g_unsetenv (const gchar *variable)
1241 #ifdef HAVE_UNSETENV
1242 g_return_if_fail (variable != NULL);
1243 g_return_if_fail (strchr (variable, '=') == NULL);
1245 unsetenv (variable);
1246 #else /* !HAVE_UNSETENV */
1250 g_return_if_fail (variable != NULL);
1251 g_return_if_fail (strchr (variable, '=') == NULL);
1253 len = strlen (variable);
1255 /* Mess directly with the environ array.
1256 * This seems to be the only portable way to do this.
1258 * Note that we remove *all* environment entries for
1259 * the variable name, not just the first.
1264 if (strncmp (*e, variable, len) != 0 || (*e)[len] != '=')
1272 #endif /* !HAVE_UNSETENV */
1274 #else /* G_OS_WIN32 */
1276 wchar_t *wname, *wassignment;
1279 g_return_if_fail (variable != NULL);
1280 g_return_if_fail (strchr (variable, '=') == NULL);
1281 g_return_if_fail (g_utf8_validate (variable, -1, NULL));
1283 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1284 tem = g_strconcat (variable, "=", NULL);
1285 wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1288 _wputenv (wassignment);
1289 g_free (wassignment);
1291 SetEnvironmentVariableW (wname, NULL);
1295 #endif /* G_OS_WIN32 */
1301 * Gets the names of all variables set in the environment.
1303 * Returns: a %NULL-terminated list of strings which must be freed
1304 * with g_strfreev().
1306 * Programs that want to be portable to Windows should typically use
1307 * this function and g_getenv() instead of using the environ array
1308 * from the C library directly. On Windows, the strings in the environ
1309 * array are in system codepage encoding, while in most of the typical
1310 * use cases for environment variables in GLib-using programs you want
1311 * the UTF-8 encoding that this function and g_getenv() provide.
1319 gchar **result, *eq;
1322 len = g_strv_length (environ);
1323 result = g_new0 (gchar *, len + 1);
1326 for (i = 0; i < len; i++)
1328 eq = strchr (environ[i], '=');
1330 result[j++] = g_strndup (environ[i], eq - environ[i]);
1337 gchar **result, *eq;
1341 p = (wchar_t *) GetEnvironmentStringsW ();
1347 q += wcslen (q) + 1;
1351 result = g_new0 (gchar *, len + 1);
1357 result[j] = g_utf16_to_utf8 (q, -1, NULL, NULL, NULL);
1358 if (result[j] != NULL)
1360 eq = strchr (result[j], '=');
1361 if (eq && eq > result[j])
1369 q += wcslen (q) + 1;
1372 FreeEnvironmentStringsW (p);
1378 G_LOCK_DEFINE_STATIC (g_utils_global);
1380 static gchar *g_tmp_dir = NULL;
1381 static gchar *g_user_name = NULL;
1382 static gchar *g_real_name = NULL;
1383 static gchar *g_home_dir = NULL;
1384 static gchar *g_host_name = NULL;
1387 /* System codepage versions of the above, kept at file level so that they,
1388 * too, are produced only once.
1390 static gchar *g_tmp_dir_cp = NULL;
1391 static gchar *g_user_name_cp = NULL;
1392 static gchar *g_real_name_cp = NULL;
1393 static gchar *g_home_dir_cp = NULL;
1396 static gchar *g_user_data_dir = NULL;
1397 static gchar **g_system_data_dirs = NULL;
1398 static gchar *g_user_cache_dir = NULL;
1399 static gchar *g_user_config_dir = NULL;
1400 static gchar **g_system_config_dirs = NULL;
1402 static gchar **g_user_special_dirs = NULL;
1403 static time_t g_user_special_dirs_mtime = (time_t) -1;
1404 static time_t g_user_special_dirs_stat_time = (time_t) -1;
1406 /* fifteen minutes of fame for everybody */
1407 #define G_USER_DIRS_EXPIRE 15 * 60
1412 get_special_folder (int csidl)
1416 wchar_t wc[MAX_PATH+1];
1419 LPITEMIDLIST pidl = NULL;
1421 gchar *retval = NULL;
1423 hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
1426 b = SHGetPathFromIDListW (pidl, path.wc);
1428 retval = g_utf16_to_utf8 (path.wc, -1, NULL, NULL, NULL);
1429 CoTaskMemFree (pidl);
1435 get_windows_directory_root (void)
1437 wchar_t wwindowsdir[MAX_PATH];
1439 if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
1441 /* Usually X:\Windows, but in terminal server environments
1442 * might be an UNC path, AFAIK.
1444 char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
1447 if (windowsdir == NULL)
1448 return g_strdup ("C:\\");
1450 p = (char *) g_path_skip_root (windowsdir);
1451 if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
1457 return g_strdup ("C:\\");
1462 /* HOLDS: g_utils_global_lock */
1464 g_get_any_init_do (void)
1466 gchar hostname[100];
1468 g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
1470 g_tmp_dir = g_strdup (g_getenv ("TMP"));
1472 g_tmp_dir = g_strdup (g_getenv ("TEMP"));
1476 g_tmp_dir = get_windows_directory_root ();
1482 g_tmp_dir = g_strdup (P_tmpdir);
1483 k = strlen (g_tmp_dir);
1484 if (k > 1 && G_IS_DIR_SEPARATOR (g_tmp_dir[k - 1]))
1485 g_tmp_dir[k - 1] = '\0';
1491 g_tmp_dir = g_strdup ("/tmp");
1493 #endif /* !G_OS_WIN32 */
1496 /* We check $HOME first for Win32, though it is a last resort for Unix
1497 * where we prefer the results of getpwuid().
1499 g_home_dir = g_strdup (g_getenv ("HOME"));
1501 /* Only believe HOME if it is an absolute path and exists */
1504 if (!(g_path_is_absolute (g_home_dir) &&
1505 g_file_test (g_home_dir, G_FILE_TEST_IS_DIR)))
1507 g_free (g_home_dir);
1512 /* In case HOME is Unix-style (it happens), convert it to
1518 while ((p = strchr (g_home_dir, '/')) != NULL)
1524 /* USERPROFILE is probably the closest equivalent to $HOME? */
1525 if (g_getenv ("USERPROFILE") != NULL)
1526 g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
1530 g_home_dir = get_special_folder (CSIDL_PROFILE);
1533 g_home_dir = get_windows_directory_root ();
1534 #endif /* G_OS_WIN32 */
1538 struct passwd *pw = NULL;
1539 gpointer buffer = NULL;
1543 # if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
1545 # ifdef _SC_GETPW_R_SIZE_MAX
1546 /* This reurns the maximum length */
1547 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
1551 # else /* _SC_GETPW_R_SIZE_MAX */
1553 # endif /* _SC_GETPW_R_SIZE_MAX */
1555 logname = (gchar *) g_getenv ("LOGNAME");
1560 /* we allocate 6 extra bytes to work around a bug in
1561 * Mac OS < 10.3. See #156446
1563 buffer = g_malloc (bufsize + 6);
1566 # ifdef HAVE_POSIX_GETPWUID_R
1568 error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
1569 if (!pw || (pw->pw_uid != getuid ())) {
1570 /* LOGNAME is lying, fall back to looking up the uid */
1571 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1574 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1576 error = error < 0 ? errno : error;
1577 # else /* HAVE_NONPOSIX_GETPWUID_R */
1578 /* HPUX 11 falls into the HAVE_POSIX_GETPWUID_R case */
1579 # if defined(_AIX) || defined(__hpux)
1580 error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1581 pw = error == 0 ? &pwd : NULL;
1584 pw = getpwnam_r (logname, &pwd, buffer, bufsize);
1585 if (!pw || (pw->pw_uid != getuid ())) {
1586 /* LOGNAME is lying, fall back to looking up the uid */
1587 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1590 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1592 error = pw ? 0 : errno;
1594 # endif /* HAVE_NONPOSIX_GETPWUID_R */
1598 /* we bail out prematurely if the user id can't be found
1599 * (should be pretty rare case actually), or if the buffer
1600 * should be sufficiently big and lookups are still not
1603 if (error == 0 || error == ENOENT)
1605 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
1606 (gulong) getuid ());
1609 if (bufsize > 32 * 1024)
1611 g_warning ("getpwuid_r(): failed due to: %s.",
1612 g_strerror (error));
1620 # endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
1625 pw = getpwuid (getuid ());
1630 g_user_name = g_strdup (pw->pw_name);
1632 if (pw->pw_gecos && *pw->pw_gecos != '\0')
1634 gchar **gecos_fields;
1637 /* split the gecos field and substitute '&' */
1638 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
1639 name_parts = g_strsplit (gecos_fields[0], "&", 0);
1640 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
1641 g_real_name = g_strjoinv (pw->pw_name, name_parts);
1642 g_strfreev (gecos_fields);
1643 g_strfreev (name_parts);
1647 g_home_dir = g_strdup (pw->pw_dir);
1652 #else /* !HAVE_PWD_H */
1656 guint len = UNLEN+1;
1657 wchar_t buffer[UNLEN+1];
1659 if (GetUserNameW (buffer, (LPDWORD) &len))
1661 g_user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
1662 g_real_name = g_strdup (g_user_name);
1665 #endif /* G_OS_WIN32 */
1667 #endif /* !HAVE_PWD_H */
1671 g_home_dir = g_strdup (g_getenv ("HOME"));
1675 /* change '\\' in %HOME% to '/' */
1676 g_strdelimit (g_home_dir, "\\",'/');
1679 g_user_name = g_strdup ("somebody");
1681 g_real_name = g_strdup ("Unknown");
1685 gboolean hostname_fail = (gethostname (hostname, sizeof (hostname)) == -1);
1687 DWORD size = sizeof (hostname);
1688 gboolean hostname_fail = (!GetComputerName (hostname, &size));
1690 g_host_name = g_strdup (hostname_fail ? "localhost" : hostname);
1694 g_tmp_dir_cp = g_locale_from_utf8 (g_tmp_dir, -1, NULL, NULL, NULL);
1695 g_user_name_cp = g_locale_from_utf8 (g_user_name, -1, NULL, NULL, NULL);
1696 g_real_name_cp = g_locale_from_utf8 (g_real_name, -1, NULL, NULL, NULL);
1699 g_tmp_dir_cp = g_strdup ("\\");
1700 if (!g_user_name_cp)
1701 g_user_name_cp = g_strdup ("somebody");
1702 if (!g_real_name_cp)
1703 g_real_name_cp = g_strdup ("Unknown");
1705 /* home_dir might be NULL, unlike tmp_dir, user_name and
1709 g_home_dir_cp = g_locale_from_utf8 (g_home_dir, -1, NULL, NULL, NULL);
1711 g_home_dir_cp = NULL;
1712 #endif /* G_OS_WIN32 */
1716 g_get_any_init (void)
1719 g_get_any_init_do ();
1723 g_get_any_init_locked (void)
1725 G_LOCK (g_utils_global);
1727 G_UNLOCK (g_utils_global);
1734 * Gets the user name of the current user. The encoding of the returned
1735 * string is system-defined. On UNIX, it might be the preferred file name
1736 * encoding, or something else, and there is no guarantee that it is even
1737 * consistent on a machine. On Windows, it is always UTF-8.
1739 * Returns: the user name of the current user.
1741 G_CONST_RETURN gchar*
1742 g_get_user_name (void)
1744 g_get_any_init_locked ();
1751 * Gets the real name of the user. This usually comes from the user's entry
1752 * in the <filename>passwd</filename> file. The encoding of the returned
1753 * string is system-defined. (On Windows, it is, however, always UTF-8.)
1754 * If the real user name cannot be determined, the string "Unknown" is
1757 * Returns: the user's real name.
1759 G_CONST_RETURN gchar*
1760 g_get_real_name (void)
1762 g_get_any_init_locked ();
1769 * Gets the current user's home directory as defined in the
1770 * password database.
1772 * Note that in contrast to traditional UNIX tools, this function
1773 * prefers <filename>passwd</filename> entries over the <envar>HOME</envar>
1774 * environment variable.
1776 * Returns: the current user's home directory.
1778 G_CONST_RETURN gchar*
1779 g_get_home_dir (void)
1781 g_get_any_init_locked ();
1788 * Gets the directory to use for temporary files. This is found from
1789 * inspecting the environment variables <envar>TMPDIR</envar>,
1790 * <envar>TMP</envar>, and <envar>TEMP</envar> in that order. If none
1791 * of those are defined "/tmp" is returned on UNIX and "C:\" on Windows.
1792 * The encoding of the returned string is system-defined. On Windows,
1793 * it is always UTF-8. The return value is never %NULL.
1795 * Returns: the directory to use for temporary files.
1797 G_CONST_RETURN gchar*
1798 g_get_tmp_dir (void)
1800 g_get_any_init_locked ();
1807 * Return a name for the machine.
1809 * The returned name is not necessarily a fully-qualified domain name,
1810 * or even present in DNS or some other name service at all. It need
1811 * not even be unique on your local network or site, but usually it
1812 * is. Callers should not rely on the return value having any specific
1813 * properties like uniqueness for security purposes. Even if the name
1814 * of the machine is changed while an application is running, the
1815 * return value from this function does not change. The returned
1816 * string is owned by GLib and should not be modified or freed. If no
1817 * name can be determined, a default fixed string "localhost" is
1820 * Returns: the host name of the machine.
1825 g_get_host_name (void)
1827 g_get_any_init_locked ();
1831 G_LOCK_DEFINE_STATIC (g_prgname);
1832 static gchar *g_prgname = NULL;
1837 * Gets the name of the program. This name should <emphasis>not</emphasis>
1838 * be localized, contrast with g_get_application_name().
1839 * (If you are using GDK or GTK+ the program name is set in gdk_init(),
1840 * which is called by gtk_init(). The program name is found by taking
1841 * the last component of <literal>argv[0]</literal>.)
1843 * Returns: the name of the program. The returned string belongs
1844 * to GLib and must not be modified or freed.
1847 g_get_prgname (void)
1853 if (g_prgname == NULL)
1855 static gboolean beenhere = FALSE;
1859 gchar *utf8_buf = NULL;
1860 wchar_t buf[MAX_PATH+1];
1863 if (GetModuleFileNameW (GetModuleHandle (NULL),
1864 buf, G_N_ELEMENTS (buf)) > 0)
1865 utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
1869 g_prgname = g_path_get_basename (utf8_buf);
1876 G_UNLOCK (g_prgname);
1883 * @prgname: the name of the program.
1885 * Sets the name of the program. This name should <emphasis>not</emphasis>
1886 * be localized, contrast with g_set_application_name(). Note that for
1887 * thread-safety reasons this function can only be called once.
1890 g_set_prgname (const gchar *prgname)
1894 g_prgname = g_strdup (prgname);
1895 G_UNLOCK (g_prgname);
1898 G_LOCK_DEFINE_STATIC (g_application_name);
1899 static gchar *g_application_name = NULL;
1902 * g_get_application_name:
1904 * Gets a human-readable name for the application, as set by
1905 * g_set_application_name(). This name should be localized if
1906 * possible, and is intended for display to the user. Contrast with
1907 * g_get_prgname(), which gets a non-localized name. If
1908 * g_set_application_name() has not been called, returns the result of
1909 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1912 * Return value: human-readable application name. may return %NULL
1916 G_CONST_RETURN gchar*
1917 g_get_application_name (void)
1921 G_LOCK (g_application_name);
1922 retval = g_application_name;
1923 G_UNLOCK (g_application_name);
1926 return g_get_prgname ();
1932 * g_set_application_name:
1933 * @application_name: localized name of the application
1935 * Sets a human-readable name for the application. This name should be
1936 * localized if possible, and is intended for display to the user.
1937 * Contrast with g_set_prgname(), which sets a non-localized name.
1938 * g_set_prgname() will be called automatically by gtk_init(),
1939 * but g_set_application_name() will not.
1941 * Note that for thread safety reasons, this function can only
1944 * The application name will be used in contexts such as error messages,
1945 * or when displaying an application's name in the task list.
1949 g_set_application_name (const gchar *application_name)
1951 gboolean already_set = FALSE;
1953 G_LOCK (g_application_name);
1954 if (g_application_name)
1957 g_application_name = g_strdup (application_name);
1958 G_UNLOCK (g_application_name);
1961 g_warning ("g_set_application() name called multiple times");
1965 * g_get_user_data_dir:
1967 * Returns a base directory in which to access application data such
1968 * as icons that is customized for a particular user.
1970 * On UNIX platforms this is determined using the mechanisms described in
1971 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1972 * XDG Base Directory Specification</ulink>
1974 * Return value: a string owned by GLib that must not be modified
1978 G_CONST_RETURN gchar*
1979 g_get_user_data_dir (void)
1983 G_LOCK (g_utils_global);
1985 if (!g_user_data_dir)
1988 data_dir = get_special_folder (CSIDL_PERSONAL);
1990 data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
1992 if (data_dir && data_dir[0])
1993 data_dir = g_strdup (data_dir);
1995 if (!data_dir || !data_dir[0])
2000 data_dir = g_build_filename (g_home_dir, ".local",
2003 data_dir = g_build_filename (g_tmp_dir, g_user_name, ".local",
2007 g_user_data_dir = data_dir;
2010 data_dir = g_user_data_dir;
2012 G_UNLOCK (g_utils_global);
2018 g_init_user_config_dir (void)
2022 if (!g_user_config_dir)
2025 config_dir = get_special_folder (CSIDL_APPDATA);
2027 config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
2029 if (config_dir && config_dir[0])
2030 config_dir = g_strdup (config_dir);
2032 if (!config_dir || !config_dir[0])
2037 config_dir = g_build_filename (g_home_dir, ".config", NULL);
2039 config_dir = g_build_filename (g_tmp_dir, g_user_name, ".config", NULL);
2042 g_user_config_dir = config_dir;
2047 * g_get_user_config_dir:
2049 * Returns a base directory in which to store user-specific application
2050 * configuration information such as user preferences and settings.
2052 * On UNIX platforms this is determined using the mechanisms described in
2053 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2054 * XDG Base Directory Specification</ulink>
2056 * Return value: a string owned by GLib that must not be modified
2060 G_CONST_RETURN gchar*
2061 g_get_user_config_dir (void)
2063 G_LOCK (g_utils_global);
2065 g_init_user_config_dir ();
2067 G_UNLOCK (g_utils_global);
2069 return g_user_config_dir;
2073 * g_get_user_cache_dir:
2075 * Returns a base directory in which to store non-essential, cached
2076 * data specific to particular user.
2078 * On UNIX platforms this is determined using the mechanisms described in
2079 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2080 * XDG Base Directory Specification</ulink>
2082 * Return value: a string owned by GLib that must not be modified
2086 G_CONST_RETURN gchar*
2087 g_get_user_cache_dir (void)
2091 G_LOCK (g_utils_global);
2093 if (!g_user_cache_dir)
2096 cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
2098 cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
2100 if (cache_dir && cache_dir[0])
2101 cache_dir = g_strdup (cache_dir);
2103 if (!cache_dir || !cache_dir[0])
2108 cache_dir = g_build_filename (g_home_dir, ".cache", NULL);
2110 cache_dir = g_build_filename (g_tmp_dir, g_user_name, ".cache", NULL);
2112 g_user_cache_dir = cache_dir;
2115 cache_dir = g_user_cache_dir;
2117 G_UNLOCK (g_utils_global);
2125 find_folder (OSType type)
2127 gchar *filename = NULL;
2130 if (FSFindFolder (kUserDomain, type, kDontCreateFolder, &found) == noErr)
2132 CFURLRef url = CFURLCreateFromFSRef (kCFAllocatorSystemDefault, &found);
2136 CFStringRef path = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle);
2140 filename = g_strdup (CFStringGetCStringPtr (path, kCFStringEncodingUTF8));
2144 filename = g_new0 (gchar, CFStringGetLength (path) * 3 + 1);
2146 CFStringGetCString (path, filename,
2147 CFStringGetLength (path) * 3 + 1,
2148 kCFStringEncodingUTF8);
2162 load_user_special_dirs (void)
2164 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = find_folder (kDesktopFolderType);
2165 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = find_folder (kDocumentsFolderType);
2166 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = find_folder (kDesktopFolderType); /* XXX correct ? */
2167 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = find_folder (kMusicDocumentsFolderType);
2168 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = find_folder (kPictureDocumentsFolderType);
2169 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = NULL;
2170 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = NULL;
2171 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = find_folder (kMovieDocumentsFolderType);
2174 #endif /* HAVE_CARBON */
2176 #if defined(G_OS_WIN32)
2178 load_user_special_dirs (void)
2180 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2181 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
2182 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY); /* XXX correct ? */
2183 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
2184 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
2185 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS); /* XXX correct ? */
2186 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
2187 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
2189 #endif /* G_OS_WIN32 */
2191 #if defined(G_OS_WIN32) || defined(HAVE_CARBON)
2193 maybe_expire_user_special_dirs (void)
2195 /* expire the user dirs after G_USER_DIRS_EXPIRE seconds */
2199 if (now > g_user_special_dirs_mtime + G_USER_DIRS_EXPIRE &&
2200 g_user_special_dirs)
2204 for (i = 0; i < G_USER_N_DIRECTORIES; i++)
2205 g_free (g_user_special_dirs[i]);
2207 g_free (g_user_special_dirs);
2208 g_user_special_dirs = NULL;
2211 if (g_user_special_dirs == NULL)
2212 g_user_special_dirs_mtime = now;
2216 #if defined(G_OS_UNIX) && !defined(HAVE_CARBON)
2218 /* expire g_user_special_dirs if the config file
2219 * was modified between different reads
2222 maybe_expire_user_special_dirs (void)
2225 struct stat stat_buf;
2228 /* don't stat() the file more often than necessary */
2230 if (now < g_user_special_dirs_stat_time + 5)
2233 g_user_special_dirs_stat_time = now;
2235 config_file = g_build_filename (g_user_config_dir,
2239 if (stat (config_file, &stat_buf) < 0)
2242 if (stat_buf.st_mtime != g_user_special_dirs_mtime &&
2243 g_user_special_dirs != NULL)
2247 for (i = 0; i < G_USER_N_DIRECTORIES; i++)
2248 g_free (g_user_special_dirs[i]);
2250 g_free (g_user_special_dirs);
2251 g_user_special_dirs = NULL;
2254 g_user_special_dirs_mtime = stat_buf.st_mtime;
2257 g_free (config_file);
2261 static void g_init_user_config_dir (void);
2263 /* adapted from xdg-user-dir-lookup.c
2265 * Copyright (C) 2007 Red Hat Inc.
2267 * Permission is hereby granted, free of charge, to any person
2268 * obtaining a copy of this software and associated documentation files
2269 * (the "Software"), to deal in the Software without restriction,
2270 * including without limitation the rights to use, copy, modify, merge,
2271 * publish, distribute, sublicense, and/or sell copies of the Software,
2272 * and to permit persons to whom the Software is furnished to do so,
2273 * subject to the following conditions:
2275 * The above copyright notice and this permission notice shall be
2276 * included in all copies or substantial portions of the Software.
2278 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
2279 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
2280 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
2281 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
2282 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
2283 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
2284 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2288 load_user_special_dirs (void)
2295 g_init_user_config_dir ();
2296 config_file = g_build_filename (g_user_config_dir,
2300 if (!g_file_get_contents (config_file, &data, NULL, NULL))
2302 g_free (config_file);
2306 lines = g_strsplit (data, "\n", -1);
2307 n_lines = g_strv_length (lines);
2310 for (i = 0; i < n_lines; i++)
2312 gchar *buffer = lines[i];
2315 gboolean is_relative = FALSE;
2316 GUserDirectory directory;
2318 /* Remove newline at end */
2319 len = strlen (buffer);
2320 if (len > 0 && buffer[len - 1] == '\n')
2321 buffer[len - 1] = 0;
2324 while (*p == ' ' || *p == '\t')
2327 if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
2329 directory = G_USER_DIRECTORY_DESKTOP;
2330 p += strlen ("XDG_DESKTOP_DIR");
2332 else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
2334 directory = G_USER_DIRECTORY_DOCUMENTS;
2335 p += strlen ("XDG_DOCUMENTS_DIR");
2337 else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
2339 directory = G_USER_DIRECTORY_DOWNLOAD;
2340 p += strlen ("XDG_DOWNLOAD_DIR");
2342 else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
2344 directory = G_USER_DIRECTORY_MUSIC;
2345 p += strlen ("XDG_MUSIC_DIR");
2347 else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
2349 directory = G_USER_DIRECTORY_PICTURES;
2350 p += strlen ("XDG_PICTURES_DIR");
2352 else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
2354 directory = G_USER_DIRECTORY_PUBLIC_SHARE;
2355 p += strlen ("XDG_PUBLICSHARE_DIR");
2357 else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
2359 directory = G_USER_DIRECTORY_TEMPLATES;
2360 p += strlen ("XDG_TEMPLATES_DIR");
2362 else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
2364 directory = G_USER_DIRECTORY_VIDEOS;
2365 p += strlen ("XDG_VIDEOS_DIR");
2370 while (*p == ' ' || *p == '\t')
2377 while (*p == ' ' || *p == '\t')
2384 if (strncmp (p, "$HOME", 5) == 0)
2392 d = strrchr (p, '"');
2399 /* remove trailing slashes */
2401 if (d[len - 1] == '/')
2407 g_user_special_dirs[directory] = g_build_filename (g_home_dir, d, NULL);
2410 g_user_special_dirs[directory] = g_strdup (d);
2414 g_free (config_file);
2417 #endif /* G_OS_UNIX && !HAVE_CARBON */
2420 * g_get_user_special_dir:
2421 * @directory: the logical id of special directory
2423 * Returns the full path of a special directory using its logical id.
2425 * On Unix this is done using the XDG special user directories.
2427 * Return value: the path to the specified special directory, or %NULL
2428 * if the logical id was not found. The returned string is owned by
2429 * GLib and should not be modified or freed.
2433 G_CONST_RETURN gchar *
2434 g_get_user_special_dir (GUserDirectory directory)
2436 g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
2437 directory < G_USER_N_DIRECTORIES, NULL);
2439 G_LOCK (g_utils_global);
2441 maybe_expire_user_special_dirs ();
2442 if (g_user_special_dirs == NULL)
2444 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
2446 load_user_special_dirs ();
2448 /* Special-case desktop for historical compatibility */
2449 if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
2452 g_user_special_dirs[directory] = g_build_filename (g_home_dir, "Desktop", NULL);
2456 G_UNLOCK (g_utils_global);
2458 return g_user_special_dirs[directory];
2463 #undef g_get_system_data_dirs
2466 get_module_for_address (gconstpointer address)
2468 /* Holds the g_utils_global lock */
2470 static gboolean beenhere = FALSE;
2471 typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
2472 static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
2480 p_GetModuleHandleExA =
2481 (t_GetModuleHandleExA) GetProcAddress (LoadLibrary ("kernel32.dll"),
2482 "GetModuleHandleExA");
2486 if (p_GetModuleHandleExA == NULL ||
2487 !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
2488 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
2491 MEMORY_BASIC_INFORMATION mbi;
2492 VirtualQuery (address, &mbi, sizeof (mbi));
2493 hmodule = (HMODULE) mbi.AllocationBase;
2500 get_module_share_dir (gconstpointer address)
2503 gchar *filename = NULL;
2505 wchar_t wfilename[MAX_PATH];
2507 hmodule = get_module_for_address (address);
2508 if (hmodule == NULL)
2511 if (GetModuleFileNameW (hmodule, wfilename, G_N_ELEMENTS (wfilename)))
2512 filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
2514 if (filename == NULL)
2517 if ((p = strrchr (filename, G_DIR_SEPARATOR)) != NULL)
2520 p = strrchr (filename, G_DIR_SEPARATOR);
2521 if (p && (g_ascii_strcasecmp (p + 1, "bin") == 0))
2524 retval = g_build_filename (filename, "share", NULL);
2530 G_CONST_RETURN gchar * G_CONST_RETURN *
2531 g_win32_get_system_data_dirs_for_module (gconstpointer address)
2535 static GHashTable *per_module_data_dirs = NULL;
2541 G_LOCK (g_utils_global);
2542 hmodule = get_module_for_address (address);
2543 if (hmodule != NULL)
2545 if (per_module_data_dirs == NULL)
2546 per_module_data_dirs = g_hash_table_new (NULL, NULL);
2549 retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
2553 G_UNLOCK (g_utils_global);
2554 return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2560 data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
2562 /* Documents and Settings\All Users\Application Data */
2563 p = get_special_folder (CSIDL_COMMON_APPDATA);
2565 g_array_append_val (data_dirs, p);
2567 /* Documents and Settings\All Users\Documents */
2568 p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2570 g_array_append_val (data_dirs, p);
2572 /* Using the above subfolders of Documents and Settings perhaps
2573 * makes sense from a Windows perspective.
2575 * But looking at the actual use cases of this function in GTK+
2576 * and GNOME software, what we really want is the "share"
2577 * subdirectory of the installation directory for the package
2578 * our caller is a part of.
2580 * The address parameter, if non-NULL, points to a function in the
2581 * calling module. Use that to determine that module's installation
2582 * folder, and use its "share" subfolder.
2584 * Additionally, also use the "share" subfolder of the installation
2585 * locations of GLib and the .exe file being run.
2587 * To guard against none of the above being what is really wanted,
2588 * callers of this function should have Win32-specific code to look
2589 * up their installation folder themselves, and handle a subfolder
2590 * "share" of it in the same way as the folders returned from this
2594 p = get_module_share_dir (address);
2596 g_array_append_val (data_dirs, p);
2598 p = g_win32_get_package_installation_subdirectory (NULL, dll_name, "share");
2600 g_array_append_val (data_dirs, p);
2602 p = g_win32_get_package_installation_subdirectory (NULL, NULL, "share");
2604 g_array_append_val (data_dirs, p);
2606 retval = (gchar **) g_array_free (data_dirs, FALSE);
2610 if (hmodule != NULL)
2611 g_hash_table_insert (per_module_data_dirs, hmodule, retval);
2612 G_UNLOCK (g_utils_global);
2615 return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2621 * g_get_system_data_dirs:
2623 * Returns an ordered list of base directories in which to access
2624 * system-wide application data.
2626 * On UNIX platforms this is determined using the mechanisms described in
2627 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2628 * XDG Base Directory Specification</ulink>
2630 * On Windows the first elements in the list are the Application Data
2631 * and Documents folders for All Users. (These can be determined only
2632 * on Windows 2000 or later and are not present in the list on other
2633 * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
2634 * CSIDL_COMMON_DOCUMENTS.
2636 * Then follows the "share" subfolder in the installation folder for
2637 * the package containing the DLL that calls this function, if it can
2640 * Finally the list contains the "share" subfolder in the installation
2641 * folder for GLib, and in the installation folder for the package the
2642 * application's .exe file belongs to.
2644 * The installation folders above are determined by looking up the
2645 * folder where the module (DLL or EXE) in question is located. If the
2646 * folder's name is "bin", its parent is used, otherwise the folder
2649 * Note that on Windows the returned list can vary depending on where
2650 * this function is called.
2652 * Return value: a %NULL-terminated array of strings owned by GLib that must
2653 * not be modified or freed.
2656 G_CONST_RETURN gchar * G_CONST_RETURN *
2657 g_get_system_data_dirs (void)
2659 gchar **data_dir_vector;
2661 G_LOCK (g_utils_global);
2663 if (!g_system_data_dirs)
2666 data_dir_vector = (gchar **) g_win32_get_system_data_dirs_for_module (NULL);
2668 gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
2670 if (!data_dirs || !data_dirs[0])
2671 data_dirs = "/usr/local/share/:/usr/share/";
2673 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2676 g_system_data_dirs = data_dir_vector;
2679 data_dir_vector = g_system_data_dirs;
2681 G_UNLOCK (g_utils_global);
2683 return (G_CONST_RETURN gchar * G_CONST_RETURN *) data_dir_vector;
2687 * g_get_system_config_dirs:
2689 * Returns an ordered list of base directories in which to access
2690 * system-wide configuration information.
2692 * On UNIX platforms this is determined using the mechanisms described in
2693 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2694 * XDG Base Directory Specification</ulink>
2696 * Return value: a %NULL-terminated array of strings owned by GLib that must
2697 * not be modified or freed.
2700 G_CONST_RETURN gchar * G_CONST_RETURN *
2701 g_get_system_config_dirs (void)
2703 gchar *conf_dirs, **conf_dir_vector;
2705 G_LOCK (g_utils_global);
2707 if (!g_system_config_dirs)
2710 conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
2713 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2718 /* Return empty list */
2719 conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2722 conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
2724 if (!conf_dirs || !conf_dirs[0])
2725 conf_dirs = "/etc/xdg";
2727 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2730 g_system_config_dirs = conf_dir_vector;
2733 conf_dir_vector = g_system_config_dirs;
2734 G_UNLOCK (g_utils_global);
2736 return (G_CONST_RETURN gchar * G_CONST_RETURN *) conf_dir_vector;
2741 static GHashTable *alias_table = NULL;
2743 /* read an alias file for the locales */
2745 read_aliases (gchar *file)
2751 alias_table = g_hash_table_new (g_str_hash, g_str_equal);
2752 fp = fopen (file,"r");
2755 while (fgets (buf, 256, fp))
2761 /* Line is a comment */
2762 if ((buf[0] == '#') || (buf[0] == '\0'))
2765 /* Reads first column */
2766 for (p = buf, q = NULL; *p; p++) {
2767 if ((*p == '\t') || (*p == ' ') || (*p == ':')) {
2770 while ((*q == '\t') || (*q == ' ')) {
2776 /* The line only had one column */
2777 if (!q || *q == '\0')
2780 /* Read second column */
2781 for (p = q; *p; p++) {
2782 if ((*p == '\t') || (*p == ' ')) {
2788 /* Add to alias table if necessary */
2789 if (!g_hash_table_lookup (alias_table, buf)) {
2790 g_hash_table_insert (alias_table, g_strdup (buf), g_strdup (q));
2799 unalias_lang (char *lang)
2806 read_aliases ("/usr/share/locale/locale.alias");
2809 while ((p = g_hash_table_lookup (alias_table, lang)) && (strcmp (p, lang) != 0))
2814 static gboolean said_before = FALSE;
2816 g_warning ("Too many alias levels for a locale, "
2817 "may indicate a loop");
2826 /* Mask for components of locale spec. The ordering here is from
2827 * least significant to most significant
2831 COMPONENT_CODESET = 1 << 0,
2832 COMPONENT_TERRITORY = 1 << 1,
2833 COMPONENT_MODIFIER = 1 << 2
2836 /* Break an X/Open style locale specification into components
2839 explode_locale (const gchar *locale,
2845 const gchar *uscore_pos;
2846 const gchar *at_pos;
2847 const gchar *dot_pos;
2851 uscore_pos = strchr (locale, '_');
2852 dot_pos = strchr (uscore_pos ? uscore_pos : locale, '.');
2853 at_pos = strchr (dot_pos ? dot_pos : (uscore_pos ? uscore_pos : locale), '@');
2857 mask |= COMPONENT_MODIFIER;
2858 *modifier = g_strdup (at_pos);
2861 at_pos = locale + strlen (locale);
2865 mask |= COMPONENT_CODESET;
2866 *codeset = g_strndup (dot_pos, at_pos - dot_pos);
2873 mask |= COMPONENT_TERRITORY;
2874 *territory = g_strndup (uscore_pos, dot_pos - uscore_pos);
2877 uscore_pos = dot_pos;
2879 *language = g_strndup (locale, uscore_pos - locale);
2885 * Compute all interesting variants for a given locale name -
2886 * by stripping off different components of the value.
2888 * For simplicity, we assume that the locale is in
2889 * X/Open format: language[_territory][.codeset][@modifier]
2891 * TODO: Extend this to handle the CEN format (see the GNUlibc docs)
2892 * as well. We could just copy the code from glibc wholesale
2893 * but it is big, ugly, and complicated, so I'm reluctant
2894 * to do so when this should handle 99% of the time...
2897 _g_compute_locale_variants (const gchar *locale)
2899 GSList *retval = NULL;
2901 gchar *language = NULL;
2902 gchar *territory = NULL;
2903 gchar *codeset = NULL;
2904 gchar *modifier = NULL;
2909 g_return_val_if_fail (locale != NULL, NULL);
2911 mask = explode_locale (locale, &language, &territory, &codeset, &modifier);
2913 /* Iterate through all possible combinations, from least attractive
2914 * to most attractive.
2916 for (i = 0; i <= mask; i++)
2917 if ((i & ~mask) == 0)
2919 gchar *val = g_strconcat (language,
2920 (i & COMPONENT_TERRITORY) ? territory : "",
2921 (i & COMPONENT_CODESET) ? codeset : "",
2922 (i & COMPONENT_MODIFIER) ? modifier : "",
2924 retval = g_slist_prepend (retval, val);
2928 if (mask & COMPONENT_CODESET)
2930 if (mask & COMPONENT_TERRITORY)
2932 if (mask & COMPONENT_MODIFIER)
2938 /* The following is (partly) taken from the gettext package.
2939 Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc. */
2941 static const gchar *
2942 guess_category_value (const gchar *category_name)
2944 const gchar *retval;
2946 /* The highest priority value is the `LANGUAGE' environment
2947 variable. This is a GNU extension. */
2948 retval = g_getenv ("LANGUAGE");
2949 if ((retval != NULL) && (retval[0] != '\0'))
2952 /* `LANGUAGE' is not set. So we have to proceed with the POSIX
2953 methods of looking to `LC_ALL', `LC_xxx', and `LANG'. On some
2954 systems this can be done by the `setlocale' function itself. */
2956 /* Setting of LC_ALL overwrites all other. */
2957 retval = g_getenv ("LC_ALL");
2958 if ((retval != NULL) && (retval[0] != '\0'))
2961 /* Next comes the name of the desired category. */
2962 retval = g_getenv (category_name);
2963 if ((retval != NULL) && (retval[0] != '\0'))
2966 /* Last possibility is the LANG environment variable. */
2967 retval = g_getenv ("LANG");
2968 if ((retval != NULL) && (retval[0] != '\0'))
2971 #ifdef G_PLATFORM_WIN32
2972 /* g_win32_getlocale() first checks for LC_ALL, LC_MESSAGES and
2973 * LANG, which we already did above. Oh well. The main point of
2974 * calling g_win32_getlocale() is to get the thread's locale as used
2975 * by Windows and the Microsoft C runtime (in the "English_United
2976 * States" format) translated into the Unixish format.
2978 retval = g_win32_getlocale ();
2979 if ((retval != NULL) && (retval[0] != '\0'))
2986 typedef struct _GLanguageNamesCache GLanguageNamesCache;
2988 struct _GLanguageNamesCache {
2990 gchar **language_names;
2994 language_names_cache_free (gpointer data)
2996 GLanguageNamesCache *cache = data;
2997 g_free (cache->languages);
2998 g_strfreev (cache->language_names);
3003 * g_get_language_names:
3005 * Computes a list of applicable locale names, which can be used to
3006 * e.g. construct locale-dependent filenames or search paths. The returned
3007 * list is sorted from most desirable to least desirable and always contains
3008 * the default locale "C".
3010 * For example, if LANGUAGE=de:en_US, then the returned list is
3011 * "de", "en_US", "en", "C".
3013 * This function consults the environment variables <envar>LANGUAGE</envar>,
3014 * <envar>LC_ALL</envar>, <envar>LC_MESSAGES</envar> and <envar>LANG</envar>
3015 * to find the list of locales specified by the user.
3017 * Return value: a %NULL-terminated array of strings owned by GLib
3018 * that must not be modified or freed.
3022 G_CONST_RETURN gchar * G_CONST_RETURN *
3023 g_get_language_names (void)
3025 static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
3026 GLanguageNamesCache *cache = g_static_private_get (&cache_private);
3031 cache = g_new0 (GLanguageNamesCache, 1);
3032 g_static_private_set (&cache_private, cache, language_names_cache_free);
3035 value = guess_category_value ("LC_MESSAGES");
3039 if (!(cache->languages && strcmp (cache->languages, value) == 0))
3046 g_free (cache->languages);
3047 g_strfreev (cache->language_names);
3048 cache->languages = g_strdup (value);
3050 alist = g_strsplit (value, ":", 0);
3052 for (a = alist; *a; a++)
3054 gchar *b = unalias_lang (*a);
3055 list = g_slist_concat (list, _g_compute_locale_variants (b));
3058 list = g_slist_append (list, g_strdup ("C"));
3060 cache->language_names = languages = g_new (gchar *, g_slist_length (list) + 1);
3061 for (l = list, i = 0; l; l = l->next, i++)
3062 languages[i] = l->data;
3063 languages[i] = NULL;
3065 g_slist_free (list);
3068 return (G_CONST_RETURN gchar * G_CONST_RETURN *) cache->language_names;
3073 * @v: a #gpointer key
3075 * Converts a gpointer to a hash value.
3076 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3077 * when using pointers as keys in a #GHashTable.
3079 * Returns: a hash value corresponding to the key.
3082 g_direct_hash (gconstpointer v)
3084 return GPOINTER_TO_UINT (v);
3090 * @v2: a key to compare with @v1.
3092 * Compares two #gpointer arguments and returns %TRUE if they are equal.
3093 * It can be passed to g_hash_table_new() as the @key_equal_func
3094 * parameter, when using pointers as keys in a #GHashTable.
3096 * Returns: %TRUE if the two keys match.
3099 g_direct_equal (gconstpointer v1,
3107 * @v1: a pointer to a #gint key.
3108 * @v2: a pointer to a #gint key to compare with @v1.
3110 * Compares the two #gint values being pointed to and returns
3111 * %TRUE if they are equal.
3112 * It can be passed to g_hash_table_new() as the @key_equal_func
3113 * parameter, when using pointers to integers as keys in a #GHashTable.
3115 * Returns: %TRUE if the two keys match.
3118 g_int_equal (gconstpointer v1,
3121 return *((const gint*) v1) == *((const gint*) v2);
3126 * @v: a pointer to a #gint key
3128 * Converts a pointer to a #gint to a hash value.
3129 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3130 * when using pointers to integers values as keys in a #GHashTable.
3132 * Returns: a hash value corresponding to the key.
3135 g_int_hash (gconstpointer v)
3137 return *(const gint*) v;
3141 * g_nullify_pointer:
3142 * @nullify_location: the memory address of the pointer.
3144 * Set the pointer at the specified location to %NULL.
3147 g_nullify_pointer (gpointer *nullify_location)
3149 g_return_if_fail (nullify_location != NULL);
3151 *nullify_location = NULL;
3157 * Get the codeset for the current locale.
3159 * Return value: a newly allocated string containing the name
3160 * of the codeset. This string must be freed with g_free().
3163 g_get_codeset (void)
3165 const gchar *charset;
3167 g_get_charset (&charset);
3169 return g_strdup (charset);
3172 /* This is called from g_thread_init(). It's used to
3173 * initialize some static data in a threadsafe way.
3176 _g_utils_thread_init (void)
3178 g_get_language_names ();
3183 #include <libintl.h>
3188 * _glib_get_locale_dir:
3190 * Return the path to the lib\locale subfolder of the GLib
3191 * installation folder. The path is in the system codepage. We have to
3192 * use system codepage as bindtextdomain() doesn't have a UTF-8
3195 static const gchar *
3196 _glib_get_locale_dir (void)
3198 gchar *dir, *cp_dir;
3199 gchar *retval = NULL;
3201 dir = g_win32_get_package_installation_directory (GETTEXT_PACKAGE, dll_name);
3202 cp_dir = g_win32_locale_filename_from_utf8 (dir);
3207 /* Don't use g_build_filename() on pathnames in the system
3208 * codepage. In CJK locales cp_dir might end with a double-byte
3209 * character whose trailing byte is a backslash.
3211 retval = g_strconcat (cp_dir, "\\lib\\locale", NULL);
3218 return g_strdup ("");
3221 #undef GLIB_LOCALE_DIR
3222 #define GLIB_LOCALE_DIR _glib_get_locale_dir ()
3224 #endif /* G_OS_WIN32 */
3226 G_CONST_RETURN gchar *
3227 _glib_gettext (const gchar *str)
3229 static gboolean _glib_gettext_initialized = FALSE;
3231 if (!_glib_gettext_initialized)
3233 bindtextdomain(GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
3234 # ifdef HAVE_BIND_TEXTDOMAIN_CODESET
3235 bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
3237 _glib_gettext_initialized = TRUE;
3240 return dgettext (GETTEXT_PACKAGE, str);
3243 #endif /* ENABLE_NLS */
3247 /* Binary compatibility versions. Not for newly compiled code. */
3249 #undef g_find_program_in_path
3252 g_find_program_in_path (const gchar *program)
3254 gchar *utf8_program = g_locale_to_utf8 (program, -1, NULL, NULL, NULL);
3255 gchar *utf8_retval = g_find_program_in_path_utf8 (utf8_program);
3258 g_free (utf8_program);
3259 if (utf8_retval == NULL)
3261 retval = g_locale_from_utf8 (utf8_retval, -1, NULL, NULL, NULL);
3262 g_free (utf8_retval);
3267 #undef g_get_current_dir
3270 g_get_current_dir (void)
3272 gchar *utf8_dir = g_get_current_dir_utf8 ();
3273 gchar *dir = g_locale_from_utf8 (utf8_dir, -1, NULL, NULL, NULL);
3280 G_CONST_RETURN gchar*
3281 g_getenv (const gchar *variable)
3283 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3284 const gchar *utf8_value = g_getenv_utf8 (utf8_variable);
3288 g_free (utf8_variable);
3291 value = g_locale_from_utf8 (utf8_value, -1, NULL, NULL, NULL);
3292 quark = g_quark_from_string (value);
3295 return g_quark_to_string (quark);
3301 g_setenv (const gchar *variable,
3305 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3306 gchar *utf8_value = g_locale_to_utf8 (value, -1, NULL, NULL, NULL);
3307 gboolean retval = g_setenv_utf8 (utf8_variable, utf8_value, overwrite);
3309 g_free (utf8_variable);
3310 g_free (utf8_value);
3318 g_unsetenv (const gchar *variable)
3320 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3322 g_unsetenv_utf8 (utf8_variable);
3324 g_free (utf8_variable);
3327 #undef g_get_user_name
3329 G_CONST_RETURN gchar*
3330 g_get_user_name (void)
3332 g_get_any_init_locked ();
3333 return g_user_name_cp;
3336 #undef g_get_real_name
3338 G_CONST_RETURN gchar*
3339 g_get_real_name (void)
3341 g_get_any_init_locked ();
3342 return g_real_name_cp;
3345 #undef g_get_home_dir
3347 G_CONST_RETURN gchar*
3348 g_get_home_dir (void)
3350 g_get_any_init_locked ();
3351 return g_home_dir_cp;
3354 #undef g_get_tmp_dir
3356 G_CONST_RETURN gchar*
3357 g_get_tmp_dir (void)
3359 g_get_any_init_locked ();
3360 return g_tmp_dir_cp;
3365 #define __G_UTILS_C__
3366 #include "galiasdef.c"