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.
42 #include <ctype.h> /* For tolower() */
44 #include <sys/types.h>
49 #include <sys/types.h>
50 #ifdef HAVE_SYS_PARAM_H
51 #include <sys/param.h>
53 #ifdef HAVE_CRT_EXTERNS_H
54 #include <crt_externs.h> /* for _NSGetEnviron */
57 /* implement gutils's inline functions
59 #define G_IMPLEMENT_INLINES 1
62 #include "gprintfint.h"
63 #include "gthreadprivate.h"
68 #define G_PATH_LENGTH MAXPATHLEN
69 #elif defined (PATH_MAX)
70 #define G_PATH_LENGTH PATH_MAX
71 #elif defined (_PC_PATH_MAX)
72 #define G_PATH_LENGTH sysconf(_PC_PATH_MAX)
74 #define G_PATH_LENGTH 2048
77 #ifdef G_PLATFORM_WIN32
78 # define STRICT /* Strict typing, please */
81 # ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
82 # define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2
83 # define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4
85 # include <lmcons.h> /* For UNLEN */
86 #endif /* G_PLATFORM_WIN32 */
91 /* older SDK (e.g. msvc 5.0) does not have these*/
92 # ifndef CSIDL_MYMUSIC
93 # define CSIDL_MYMUSIC 13
95 # ifndef CSIDL_MYVIDEO
96 # define CSIDL_MYVIDEO 14
98 # ifndef CSIDL_INTERNET_CACHE
99 # define CSIDL_INTERNET_CACHE 32
101 # ifndef CSIDL_COMMON_APPDATA
102 # define CSIDL_COMMON_APPDATA 35
104 # ifndef CSIDL_COMMON_DOCUMENTS
105 # define CSIDL_COMMON_DOCUMENTS 46
107 # ifndef CSIDL_PROFILE
108 # define CSIDL_PROFILE 40
110 # include <process.h>
114 #include <CoreServices/CoreServices.h>
118 #include <langinfo.h>
121 #ifdef HAVE_BIND_TEXTDOMAIN_CODESET
125 const guint glib_major_version = GLIB_MAJOR_VERSION;
126 const guint glib_minor_version = GLIB_MINOR_VERSION;
127 const guint glib_micro_version = GLIB_MICRO_VERSION;
128 const guint glib_interface_age = GLIB_INTERFACE_AGE;
129 const guint glib_binary_age = GLIB_BINARY_AGE;
131 #ifdef G_PLATFORM_WIN32
133 G_WIN32_DLLMAIN_FOR_DLL_NAME (static, dll_name)
138 * glib_check_version:
139 * @required_major: the required major version.
140 * @required_minor: the required minor version.
141 * @required_micro: the required micro version.
143 * Checks that the GLib library in use is compatible with the
144 * given version. Generally you would pass in the constants
145 * #GLIB_MAJOR_VERSION, #GLIB_MINOR_VERSION, #GLIB_MICRO_VERSION
146 * as the three arguments to this function; that produces
147 * a check that the library in use is compatible with
148 * the version of GLib the application or module was compiled
151 * Compatibility is defined by two things: first the version
152 * of the running library is newer than the version
153 * @required_major.required_minor.@required_micro. Second
154 * the running library must be binary compatible with the
155 * version @required_major.required_minor.@required_micro
156 * (same major version.)
158 * Return value: %NULL if the GLib library is compatible with the
159 * given version, or a string describing the version mismatch.
160 * The returned string is owned by GLib and must not be modified
166 glib_check_version (guint required_major,
167 guint required_minor,
168 guint required_micro)
170 gint glib_effective_micro = 100 * GLIB_MINOR_VERSION + GLIB_MICRO_VERSION;
171 gint required_effective_micro = 100 * required_minor + required_micro;
173 if (required_major > GLIB_MAJOR_VERSION)
174 return "GLib version too old (major mismatch)";
175 if (required_major < GLIB_MAJOR_VERSION)
176 return "GLib version too new (major mismatch)";
177 if (required_effective_micro < glib_effective_micro - GLIB_BINARY_AGE)
178 return "GLib version too new (micro mismatch)";
179 if (required_effective_micro > glib_effective_micro)
180 return "GLib version too old (micro mismatch)";
184 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
187 * @dest: the destination address to copy the bytes to.
188 * @src: the source address to copy the bytes from.
189 * @len: the number of bytes to copy.
191 * Copies a block of memory @len bytes long, from @src to @dest.
192 * The source and destination areas may overlap.
194 * In order to use this function, you must include
195 * <filename>string.h</filename> yourself, because this macro will
196 * typically simply resolve to memmove() and GLib does not include
197 * <filename>string.h</filename> for you.
200 g_memmove (gpointer dest,
204 gchar* destptr = dest;
205 const gchar* srcptr = src;
206 if (src + len < dest || dest + len < src)
208 bcopy (src, dest, len);
211 else if (dest <= src)
214 *(destptr++) = *(srcptr++);
221 *(--destptr) = *(--srcptr);
224 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
232 * @func: the function to call on normal program termination.
234 * Specifies a function to be called at normal program termination.
236 * Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
237 * macro that maps to a call to the atexit() function in the C
238 * library. This means that in case the code that calls g_atexit(),
239 * i.e. atexit(), is in a DLL, the function will be called when the
240 * DLL is detached from the program. This typically makes more sense
241 * than that the function is called when the GLib DLL is detached,
242 * which happened earlier when g_atexit() was a function in the GLib
245 * The behaviour of atexit() in the context of dynamically loaded
246 * modules is not formally specified and varies wildly.
248 * On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
249 * loaded module which is unloaded before the program terminates might
250 * well cause a crash at program exit.
252 * Some POSIX systems implement atexit() like Windows, and have each
253 * dynamically loaded module maintain an own atexit chain that is
254 * called when the module is unloaded.
256 * On other POSIX systems, before a dynamically loaded module is
257 * unloaded, the registered atexit functions (if any) residing in that
258 * module are called, regardless where the code that registered them
259 * resided. This is presumably the most robust approach.
261 * As can be seen from the above, for portability it's best to avoid
262 * calling g_atexit() (or atexit()) except in the main executable of a
266 g_atexit (GVoidFunc func)
269 const gchar *error = NULL;
271 /* keep this in sync with glib.h */
273 #ifdef G_NATIVE_ATEXIT
274 result = ATEXIT (func);
276 error = g_strerror (errno);
277 #elif defined (HAVE_ATEXIT)
278 # ifdef NeXT /* @#%@! NeXTStep */
279 result = !atexit ((void (*)(void)) func);
281 error = g_strerror (errno);
283 result = atexit ((void (*)(void)) func);
285 error = g_strerror (errno);
287 #elif defined (HAVE_ON_EXIT)
288 result = on_exit ((void (*)(int, void *)) func, NULL);
290 error = g_strerror (errno);
293 error = "no implementation";
294 #endif /* G_NATIVE_ATEXIT */
297 g_error ("Could not register atexit() function: %s", error);
300 /* Based on execvp() from GNU Libc.
301 * Some of this code is cut-and-pasted into gspawn.c
305 my_strchrnul (const gchar *str,
308 gchar *p = (gchar*)str;
309 while (*p && (*p != c))
317 static gchar *inner_find_program_in_path (const gchar *program);
320 g_find_program_in_path (const gchar *program)
322 const gchar *last_dot = strrchr (program, '.');
324 if (last_dot == NULL ||
325 strchr (last_dot, '\\') != NULL ||
326 strchr (last_dot, '/') != NULL)
328 const gint program_length = strlen (program);
329 gchar *pathext = g_build_path (";",
330 ".exe;.cmd;.bat;.com",
331 g_getenv ("PATHEXT"),
334 gchar *decorated_program;
340 gchar *q = my_strchrnul (p, ';');
342 decorated_program = g_malloc (program_length + (q-p) + 1);
343 memcpy (decorated_program, program, program_length);
344 memcpy (decorated_program+program_length, p, q-p);
345 decorated_program [program_length + (q-p)] = '\0';
347 retval = inner_find_program_in_path (decorated_program);
348 g_free (decorated_program);
356 } while (*p++ != '\0');
361 return inner_find_program_in_path (program);
367 * g_find_program_in_path:
368 * @program: a program name in the GLib file name encoding
370 * Locates the first executable named @program in the user's path, in the
371 * same way that execvp() would locate it. Returns an allocated string
372 * with the absolute path name, or %NULL if the program is not found in
373 * the path. If @program is already an absolute path, returns a copy of
374 * @program if @program exists and is executable, and %NULL otherwise.
376 * On Windows, if @program does not have a file type suffix, tries
377 * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
378 * the <envar>PATHEXT</envar> environment variable.
380 * On Windows, it looks for the file in the same way as CreateProcess()
381 * would. This means first in the directory where the executing
382 * program was loaded from, then in the current directory, then in the
383 * Windows 32-bit system directory, then in the Windows directory, and
384 * finally in the directories in the <envar>PATH</envar> environment
385 * variable. If the program is found, the return value contains the
386 * full name including the type suffix.
388 * Return value: absolute path, or %NULL
392 inner_find_program_in_path (const gchar *program)
395 g_find_program_in_path (const gchar *program)
398 const gchar *path, *p;
399 gchar *name, *freeme;
401 const gchar *path_copy;
402 gchar *filename = NULL, *appdir = NULL;
403 gchar *sysdir = NULL, *windir = NULL;
405 wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
411 g_return_val_if_fail (program != NULL, NULL);
413 /* If it is an absolute path, or a relative path including subdirectories,
414 * don't look in PATH.
416 if (g_path_is_absolute (program)
417 || strchr (program, G_DIR_SEPARATOR) != NULL
419 || strchr (program, '/') != NULL
423 if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
424 !g_file_test (program, G_FILE_TEST_IS_DIR))
425 return g_strdup (program);
430 path = g_getenv ("PATH");
431 #if defined(G_OS_UNIX) || defined(G_OS_BEOS)
434 /* There is no `PATH' in the environment. The default
435 * search path in GNU libc is the current directory followed by
436 * the path `confstr' returns for `_CS_PATH'.
439 /* In GLib we put . last, for security, and don't use the
440 * unportable confstr(); UNIX98 does not actually specify
441 * what to search if PATH is unset. POSIX may, dunno.
444 path = "/bin:/usr/bin:.";
447 n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
448 if (n > 0 && n < MAXPATHLEN)
449 filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
451 n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
452 if (n > 0 && n < MAXPATHLEN)
453 sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
455 n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
456 if (n > 0 && n < MAXPATHLEN)
457 windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
461 appdir = g_path_get_dirname (filename);
465 path = g_strdup (path);
469 const gchar *tem = path;
470 path = g_strconcat (windir, ";", path, NULL);
471 g_free ((gchar *) tem);
477 const gchar *tem = path;
478 path = g_strconcat (sysdir, ";", path, NULL);
479 g_free ((gchar *) tem);
484 const gchar *tem = path;
485 path = g_strconcat (".;", path, NULL);
486 g_free ((gchar *) tem);
491 const gchar *tem = path;
492 path = g_strconcat (appdir, ";", path, NULL);
493 g_free ((gchar *) tem);
500 len = strlen (program) + 1;
501 pathlen = strlen (path);
502 freeme = name = g_malloc (pathlen + len + 1);
504 /* Copy the file name at the top, including '\0' */
505 memcpy (name + pathlen + 1, program, len);
506 name = name + pathlen;
507 /* And add the slash before the filename */
508 *name = G_DIR_SEPARATOR;
516 p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
519 /* Two adjacent colons, or a colon at the beginning or the end
520 * of `PATH' means to search the current directory.
524 startp = memcpy (name - (p - path), path, p - path);
526 if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
527 !g_file_test (startp, G_FILE_TEST_IS_DIR))
530 ret = g_strdup (startp);
533 g_free ((gchar *) path_copy);
538 while (*p++ != '\0');
542 g_free ((gchar *) path_copy);
549 debug_key_matches (const gchar *key,
553 for (; length; length--, key++, token++)
555 char k = (*key == '_') ? '-' : tolower (*key );
556 char t = (*token == '_') ? '-' : tolower (*token);
566 * g_parse_debug_string:
567 * @string: a list of debug options separated by colons, spaces, or
568 * commas; or the string "all" to set all flags, or %NULL.
569 * @keys: pointer to an array of #GDebugKey which associate
570 * strings with bit flags.
571 * @nkeys: the number of #GDebugKey<!-- -->s in the array.
573 * Parses a string containing debugging options
574 * into a %guint containing bit flags. This is used
575 * within GDK and GTK+ to parse the debug options passed on the
576 * command line or through environment variables.
578 * Returns: the combined set of bit flags.
581 g_parse_debug_string (const gchar *string,
582 const GDebugKey *keys,
591 /* this function is used by gmem.c/gslice.c initialization code,
592 * so introducing malloc dependencies here would require adaptions
593 * of those code portions.
596 if (!g_ascii_strcasecmp (string, "all"))
598 for (i=0; i<nkeys; i++)
599 result |= keys[i].value;
603 const gchar *p = string;
608 q = strpbrk (p, ":;, \t");
612 for (i = 0; i < nkeys; i++)
613 if (debug_key_matches (keys[i].key, p, q - p))
614 result |= keys[i].value;
627 * @file_name: the name of the file.
629 * Gets the name of the file without any leading directory components.
630 * It returns a pointer into the given file name string.
632 * Return value: the name of the file without any leading directory components.
634 * Deprecated:2.2: Use g_path_get_basename() instead, but notice that
635 * g_path_get_basename() allocates new memory for the returned string, unlike
636 * this function which returns a pointer into the argument.
638 G_CONST_RETURN gchar*
639 g_basename (const gchar *file_name)
641 register gchar *base;
643 g_return_val_if_fail (file_name != NULL, NULL);
645 base = strrchr (file_name, G_DIR_SEPARATOR);
649 gchar *q = strrchr (file_name, '/');
650 if (base == NULL || (q != NULL && q > base))
659 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
660 return (gchar*) file_name + 2;
661 #endif /* G_OS_WIN32 */
663 return (gchar*) file_name;
667 * g_path_get_basename:
668 * @file_name: the name of the file.
670 * Gets the last component of the filename. If @file_name ends with a
671 * directory separator it gets the component before the last slash. If
672 * @file_name consists only of directory separators (and on Windows,
673 * possibly a drive letter), a single separator is returned. If
674 * @file_name is empty, it gets ".".
676 * Return value: a newly allocated string containing the last component of
680 g_path_get_basename (const gchar *file_name)
682 register gssize base;
683 register gssize last_nonslash;
687 g_return_val_if_fail (file_name != NULL, NULL);
689 if (file_name[0] == '\0')
691 return g_strdup (".");
693 last_nonslash = strlen (file_name) - 1;
695 while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
698 if (last_nonslash == -1)
699 /* string only containing slashes */
700 return g_strdup (G_DIR_SEPARATOR_S);
703 if (last_nonslash == 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
704 /* string only containing slashes and a drive */
705 return g_strdup (G_DIR_SEPARATOR_S);
706 #endif /* G_OS_WIN32 */
708 base = last_nonslash;
710 while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
714 if (base == -1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
716 #endif /* G_OS_WIN32 */
718 len = last_nonslash - base;
719 retval = g_malloc (len + 1);
720 memcpy (retval, file_name + base + 1, len);
726 * g_path_is_absolute:
727 * @file_name: a file name.
729 * Returns %TRUE if the given @file_name is an absolute file name,
730 * i.e. it contains a full path from the root directory such as "/usr/local"
731 * on UNIX or "C:\windows" on Windows systems.
733 * Returns: %TRUE if @file_name is an absolute path.
736 g_path_is_absolute (const gchar *file_name)
738 g_return_val_if_fail (file_name != NULL, FALSE);
740 if (G_IS_DIR_SEPARATOR (file_name[0]))
744 /* Recognize drive letter on native Windows */
745 if (g_ascii_isalpha (file_name[0]) &&
746 file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
748 #endif /* G_OS_WIN32 */
755 * @file_name: a file name.
757 * Returns a pointer into @file_name after the root component, i.e. after
758 * the "/" in UNIX or "C:\" under Windows. If @file_name is not an absolute
759 * path it returns %NULL.
761 * Returns: a pointer into @file_name after the root component.
763 G_CONST_RETURN gchar*
764 g_path_skip_root (const gchar *file_name)
766 g_return_val_if_fail (file_name != NULL, NULL);
768 #ifdef G_PLATFORM_WIN32
769 /* Skip \\server\share or //server/share */
770 if (G_IS_DIR_SEPARATOR (file_name[0]) &&
771 G_IS_DIR_SEPARATOR (file_name[1]) &&
773 !G_IS_DIR_SEPARATOR (file_name[2]))
777 p = strchr (file_name + 2, G_DIR_SEPARATOR);
780 gchar *q = strchr (file_name + 2, '/');
781 if (p == NULL || (q != NULL && q < p))
791 while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
794 /* Possibly skip a backslash after the share name */
795 if (G_IS_DIR_SEPARATOR (file_name[0]))
798 return (gchar *)file_name;
803 /* Skip initial slashes */
804 if (G_IS_DIR_SEPARATOR (file_name[0]))
806 while (G_IS_DIR_SEPARATOR (file_name[0]))
808 return (gchar *)file_name;
813 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
814 return (gchar *)file_name + 3;
821 * g_path_get_dirname:
822 * @file_name: the name of the file.
824 * Gets the directory components of a file name. If the file name has no
825 * directory components "." is returned. The returned string should be
826 * freed when no longer needed.
828 * Returns: the directory components of the file.
831 g_path_get_dirname (const gchar *file_name)
833 register gchar *base;
836 g_return_val_if_fail (file_name != NULL, NULL);
838 base = strrchr (file_name, G_DIR_SEPARATOR);
841 gchar *q = strrchr (file_name, '/');
842 if (base == NULL || (q != NULL && q > base))
849 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
851 gchar drive_colon_dot[4];
853 drive_colon_dot[0] = file_name[0];
854 drive_colon_dot[1] = ':';
855 drive_colon_dot[2] = '.';
856 drive_colon_dot[3] = '\0';
858 return g_strdup (drive_colon_dot);
861 return g_strdup (".");
864 while (base > file_name && G_IS_DIR_SEPARATOR (*base))
868 /* base points to the char before the last slash.
870 * In case file_name is the root of a drive (X:\) or a child of the
871 * root of a drive (X:\foo), include the slash.
873 * In case file_name is the root share of an UNC path
874 * (\\server\share), add a slash, returning \\server\share\ .
876 * In case file_name is a direct child of a share in an UNC path
877 * (\\server\share\foo), include the slash after the share name,
878 * returning \\server\share\ .
880 if (base == file_name + 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
882 else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
883 G_IS_DIR_SEPARATOR (file_name[1]) &&
885 !G_IS_DIR_SEPARATOR (file_name[2]) &&
886 base >= file_name + 2)
888 const gchar *p = file_name + 2;
889 while (*p && !G_IS_DIR_SEPARATOR (*p))
893 len = (guint) strlen (file_name) + 1;
894 base = g_new (gchar, len + 1);
895 strcpy (base, file_name);
896 base[len-1] = G_DIR_SEPARATOR;
900 if (G_IS_DIR_SEPARATOR (*p))
903 while (*p && !G_IS_DIR_SEPARATOR (*p))
911 len = (guint) 1 + base - file_name;
913 base = g_new (gchar, len + 1);
914 g_memmove (base, file_name, len);
923 * Gets the current directory.
924 * The returned string should be freed when no longer needed. The encoding
925 * of the returned string is system defined. On Windows, it is always UTF-8.
927 * Returns: the current directory.
930 g_get_current_dir (void)
935 wchar_t dummy[2], *wdir;
938 len = GetCurrentDirectoryW (2, dummy);
939 wdir = g_new (wchar_t, len);
941 if (GetCurrentDirectoryW (len, wdir) == len - 1)
942 dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
947 dir = g_strdup ("\\");
953 gchar *buffer = NULL;
955 static gulong max_len = 0;
958 max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
960 /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
961 * and, if that wasn't bad enough, hangs in doing so.
963 #if (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
964 buffer = g_new (gchar, max_len + 1);
966 dir = getwd (buffer);
967 #else /* !sun || !HAVE_GETCWD */
968 while (max_len < G_MAXULONG / 2)
971 buffer = g_new (gchar, max_len + 1);
973 dir = getcwd (buffer, max_len);
975 if (dir || errno != ERANGE)
980 #endif /* !sun || !HAVE_GETCWD */
982 if (!dir || !*buffer)
984 /* hm, should we g_error() out here?
985 * this can happen if e.g. "./" has mode \0000
987 buffer[0] = G_DIR_SEPARATOR;
991 dir = g_strdup (buffer);
1000 * @variable: the environment variable to get, in the GLib file name encoding.
1002 * Returns the value of an environment variable. The name and value
1003 * are in the GLib file name encoding. On UNIX, this means the actual
1004 * bytes which might or might not be in some consistent character set
1005 * and encoding. On Windows, it is in UTF-8. On Windows, in case the
1006 * environment variable's value contains references to other
1007 * environment variables, they are expanded.
1009 * Return value: the value of the environment variable, or %NULL if
1010 * the environment variable is not found. The returned string may be
1011 * overwritten by the next call to g_getenv(), g_setenv() or
1014 G_CONST_RETURN gchar*
1015 g_getenv (const gchar *variable)
1019 g_return_val_if_fail (variable != NULL, NULL);
1021 return getenv (variable);
1023 #else /* G_OS_WIN32 */
1027 wchar_t dummy[2], *wname, *wvalue;
1030 g_return_val_if_fail (variable != NULL, NULL);
1031 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), NULL);
1033 /* On Windows NT, it is relatively typical that environment
1034 * variables contain references to other environment variables. If
1035 * so, use ExpandEnvironmentStrings(). (In an ideal world, such
1036 * environment variables would be stored in the Registry as
1037 * REG_EXPAND_SZ type values, and would then get automatically
1038 * expanded before a program sees them. But there is broken software
1039 * that stores environment variables as REG_SZ values even if they
1040 * contain references to other environment variables.)
1043 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1045 len = GetEnvironmentVariableW (wname, dummy, 2);
1055 wvalue = g_new (wchar_t, len);
1057 if (GetEnvironmentVariableW (wname, wvalue, len) != len - 1)
1064 if (wcschr (wvalue, L'%') != NULL)
1066 wchar_t *tem = wvalue;
1068 len = ExpandEnvironmentStringsW (wvalue, dummy, 2);
1072 wvalue = g_new (wchar_t, len);
1074 if (ExpandEnvironmentStringsW (tem, wvalue, len) != len)
1084 value = g_utf16_to_utf8 (wvalue, -1, NULL, NULL, NULL);
1089 quark = g_quark_from_string (value);
1092 return g_quark_to_string (quark);
1094 #endif /* G_OS_WIN32 */
1097 /* _g_getenv_nomalloc
1098 * this function does a getenv() without doing any kind of allocation
1099 * through glib. it's suitable for chars <= 127 only (both, for the
1100 * variable name and the contents) and for contents < 1024 chars in
1101 * length. also, it aliases "" to a NULL return value.
1104 _g_getenv_nomalloc (const gchar *variable,
1107 const gchar *retval = getenv (variable);
1108 if (retval && retval[0])
1110 gint l = strlen (retval);
1113 strncpy (buffer, retval, l);
1123 * @variable: the environment variable to set, must not contain '='.
1124 * @value: the value for to set the variable to.
1125 * @overwrite: whether to change the variable if it already exists.
1127 * Sets an environment variable. Both the variable's name and value
1128 * should be in the GLib file name encoding. On UNIX, this means that
1129 * they can be any sequence of bytes. On Windows, they should be in
1132 * Note that on some systems, when variables are overwritten, the memory
1133 * used for the previous variables and its value isn't reclaimed.
1135 * Returns: %FALSE if the environment variable couldn't be set.
1140 g_setenv (const gchar *variable,
1151 g_return_val_if_fail (variable != NULL, FALSE);
1152 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1155 result = setenv (variable, value, overwrite);
1157 if (!overwrite && getenv (variable) != NULL)
1160 /* This results in a leak when you overwrite existing
1161 * settings. It would be fairly easy to fix this by keeping
1162 * our own parallel array or hash table.
1164 string = g_strconcat (variable, "=", value, NULL);
1165 result = putenv (string);
1169 #else /* G_OS_WIN32 */
1172 wchar_t *wname, *wvalue, *wassignment;
1175 g_return_val_if_fail (variable != NULL, FALSE);
1176 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1177 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), FALSE);
1178 g_return_val_if_fail (g_utf8_validate (value, -1, NULL), FALSE);
1180 if (!overwrite && g_getenv (variable) != NULL)
1183 /* We want to (if possible) set both the environment variable copy
1184 * kept by the C runtime and the one kept by the system.
1186 * We can't use only the C runtime's putenv or _wputenv() as that
1187 * won't work for arbitrary Unicode strings in a "non-Unicode" app
1188 * (with main() and not wmain()). In a "main()" app the C runtime
1189 * initializes the C runtime's environment table by converting the
1190 * real (wide char) environment variables to system codepage, thus
1191 * breaking those that aren't representable in the system codepage.
1193 * As the C runtime's putenv() will also set the system copy, we do
1194 * the putenv() first, then call SetEnvironmentValueW ourselves.
1197 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1198 wvalue = g_utf8_to_utf16 (value, -1, NULL, NULL, NULL);
1199 tem = g_strconcat (variable, "=", value, NULL);
1200 wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1203 _wputenv (wassignment);
1204 g_free (wassignment);
1206 retval = (SetEnvironmentVariableW (wname, wvalue) != 0);
1213 #endif /* G_OS_WIN32 */
1216 #ifdef HAVE__NSGETENVIRON
1217 #define environ (*_NSGetEnviron())
1218 #elif !defined(G_OS_WIN32)
1220 /* According to the Single Unix Specification, environ is not in
1221 * any system header, although unistd.h often declares it.
1223 extern char **environ;
1228 * @variable: the environment variable to remove, must not contain '='.
1230 * Removes an environment variable from the environment.
1232 * Note that on some systems, when variables are overwritten, the memory
1233 * used for the previous variables and its value isn't reclaimed.
1234 * Furthermore, this function can't be guaranteed to operate in a
1240 g_unsetenv (const gchar *variable)
1244 #ifdef HAVE_UNSETENV
1245 g_return_if_fail (variable != NULL);
1246 g_return_if_fail (strchr (variable, '=') == NULL);
1248 unsetenv (variable);
1249 #else /* !HAVE_UNSETENV */
1253 g_return_if_fail (variable != NULL);
1254 g_return_if_fail (strchr (variable, '=') == NULL);
1256 len = strlen (variable);
1258 /* Mess directly with the environ array.
1259 * This seems to be the only portable way to do this.
1261 * Note that we remove *all* environment entries for
1262 * the variable name, not just the first.
1267 if (strncmp (*e, variable, len) != 0 || (*e)[len] != '=')
1275 #endif /* !HAVE_UNSETENV */
1277 #else /* G_OS_WIN32 */
1279 wchar_t *wname, *wassignment;
1282 g_return_if_fail (variable != NULL);
1283 g_return_if_fail (strchr (variable, '=') == NULL);
1284 g_return_if_fail (g_utf8_validate (variable, -1, NULL));
1286 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1287 tem = g_strconcat (variable, "=", NULL);
1288 wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1291 _wputenv (wassignment);
1292 g_free (wassignment);
1294 SetEnvironmentVariableW (wname, NULL);
1298 #endif /* G_OS_WIN32 */
1304 * Gets the names of all variables set in the environment.
1306 * Returns: a %NULL-terminated list of strings which must be freed
1307 * with g_strfreev().
1309 * Programs that want to be portable to Windows should typically use
1310 * this function and g_getenv() instead of using the environ array
1311 * from the C library directly. On Windows, the strings in the environ
1312 * array are in system codepage encoding, while in most of the typical
1313 * use cases for environment variables in GLib-using programs you want
1314 * the UTF-8 encoding that this function and g_getenv() provide.
1322 gchar **result, *eq;
1325 len = g_strv_length (environ);
1326 result = g_new0 (gchar *, len + 1);
1329 for (i = 0; i < len; i++)
1331 eq = strchr (environ[i], '=');
1333 result[j++] = g_strndup (environ[i], eq - environ[i]);
1340 gchar **result, *eq;
1344 p = (wchar_t *) GetEnvironmentStringsW ();
1350 q += wcslen (q) + 1;
1354 result = g_new0 (gchar *, len + 1);
1360 result[j] = g_utf16_to_utf8 (q, -1, NULL, NULL, NULL);
1361 if (result[j] != NULL)
1363 eq = strchr (result[j], '=');
1364 if (eq && eq > result[j])
1372 q += wcslen (q) + 1;
1375 FreeEnvironmentStringsW (p);
1381 G_LOCK_DEFINE_STATIC (g_utils_global);
1383 static gchar *g_tmp_dir = NULL;
1384 static gchar *g_user_name = NULL;
1385 static gchar *g_real_name = NULL;
1386 static gchar *g_home_dir = NULL;
1387 static gchar *g_host_name = NULL;
1390 /* System codepage versions of the above, kept at file level so that they,
1391 * too, are produced only once.
1393 static gchar *g_tmp_dir_cp = NULL;
1394 static gchar *g_user_name_cp = NULL;
1395 static gchar *g_real_name_cp = NULL;
1396 static gchar *g_home_dir_cp = NULL;
1399 static gchar *g_user_data_dir = NULL;
1400 static gchar **g_system_data_dirs = NULL;
1401 static gchar *g_user_cache_dir = NULL;
1402 static gchar *g_user_config_dir = NULL;
1403 static gchar **g_system_config_dirs = NULL;
1405 static gchar **g_user_special_dirs = NULL;
1407 /* fifteen minutes of fame for everybody */
1408 #define G_USER_DIRS_EXPIRE 15 * 60
1413 get_special_folder (int csidl)
1415 wchar_t path[MAX_PATH+1];
1417 LPITEMIDLIST pidl = NULL;
1419 gchar *retval = NULL;
1421 hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
1424 b = SHGetPathFromIDListW (pidl, path);
1426 retval = g_utf16_to_utf8 (path, -1, NULL, NULL, NULL);
1427 CoTaskMemFree (pidl);
1433 get_windows_directory_root (void)
1435 wchar_t wwindowsdir[MAX_PATH];
1437 if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
1439 /* Usually X:\Windows, but in terminal server environments
1440 * might be an UNC path, AFAIK.
1442 char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
1445 if (windowsdir == NULL)
1446 return g_strdup ("C:\\");
1448 p = (char *) g_path_skip_root (windowsdir);
1449 if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
1455 return g_strdup ("C:\\");
1460 /* HOLDS: g_utils_global_lock */
1462 g_get_any_init_do (void)
1464 gchar hostname[100];
1466 g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
1468 g_tmp_dir = g_strdup (g_getenv ("TMP"));
1470 g_tmp_dir = g_strdup (g_getenv ("TEMP"));
1474 g_tmp_dir = get_windows_directory_root ();
1480 g_tmp_dir = g_strdup (P_tmpdir);
1481 k = strlen (g_tmp_dir);
1482 if (k > 1 && G_IS_DIR_SEPARATOR (g_tmp_dir[k - 1]))
1483 g_tmp_dir[k - 1] = '\0';
1489 g_tmp_dir = g_strdup ("/tmp");
1491 #endif /* !G_OS_WIN32 */
1494 /* We check $HOME first for Win32, though it is a last resort for Unix
1495 * where we prefer the results of getpwuid().
1497 g_home_dir = g_strdup (g_getenv ("HOME"));
1499 /* Only believe HOME if it is an absolute path and exists */
1502 if (!(g_path_is_absolute (g_home_dir) &&
1503 g_file_test (g_home_dir, G_FILE_TEST_IS_DIR)))
1505 g_free (g_home_dir);
1510 /* In case HOME is Unix-style (it happens), convert it to
1516 while ((p = strchr (g_home_dir, '/')) != NULL)
1522 /* USERPROFILE is probably the closest equivalent to $HOME? */
1523 if (g_getenv ("USERPROFILE") != NULL)
1524 g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
1528 g_home_dir = get_special_folder (CSIDL_PROFILE);
1531 g_home_dir = get_windows_directory_root ();
1532 #endif /* G_OS_WIN32 */
1536 struct passwd *pw = NULL;
1537 gpointer buffer = NULL;
1541 # if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
1543 # ifdef _SC_GETPW_R_SIZE_MAX
1544 /* This reurns the maximum length */
1545 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
1549 # else /* _SC_GETPW_R_SIZE_MAX */
1551 # endif /* _SC_GETPW_R_SIZE_MAX */
1553 logname = (gchar *) g_getenv ("LOGNAME");
1558 /* we allocate 6 extra bytes to work around a bug in
1559 * Mac OS < 10.3. See #156446
1561 buffer = g_malloc (bufsize + 6);
1564 # ifdef HAVE_POSIX_GETPWUID_R
1566 error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
1567 if (!pw || (pw->pw_uid != getuid ())) {
1568 /* LOGNAME is lying, fall back to looking up the uid */
1569 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1572 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1574 error = error < 0 ? errno : error;
1575 # else /* HAVE_NONPOSIX_GETPWUID_R */
1576 /* HPUX 11 falls into the HAVE_POSIX_GETPWUID_R case */
1577 # if defined(_AIX) || defined(__hpux)
1578 error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1579 pw = error == 0 ? &pwd : NULL;
1582 pw = getpwnam_r (logname, &pwd, buffer, bufsize);
1583 if (!pw || (pw->pw_uid != getuid ())) {
1584 /* LOGNAME is lying, fall back to looking up the uid */
1585 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1588 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1590 error = pw ? 0 : errno;
1592 # endif /* HAVE_NONPOSIX_GETPWUID_R */
1596 /* we bail out prematurely if the user id can't be found
1597 * (should be pretty rare case actually), or if the buffer
1598 * should be sufficiently big and lookups are still not
1601 if (error == 0 || error == ENOENT)
1603 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
1604 (gulong) getuid ());
1607 if (bufsize > 32 * 1024)
1609 g_warning ("getpwuid_r(): failed due to: %s.",
1610 g_strerror (error));
1618 # endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
1623 pw = getpwuid (getuid ());
1628 g_user_name = g_strdup (pw->pw_name);
1630 if (pw->pw_gecos && *pw->pw_gecos != '\0')
1632 gchar **gecos_fields;
1635 /* split the gecos field and substitute '&' */
1636 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
1637 name_parts = g_strsplit (gecos_fields[0], "&", 0);
1638 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
1639 g_real_name = g_strjoinv (pw->pw_name, name_parts);
1640 g_strfreev (gecos_fields);
1641 g_strfreev (name_parts);
1645 g_home_dir = g_strdup (pw->pw_dir);
1650 #else /* !HAVE_PWD_H */
1654 guint len = UNLEN+1;
1655 wchar_t buffer[UNLEN+1];
1657 if (GetUserNameW (buffer, (LPDWORD) &len))
1659 g_user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
1660 g_real_name = g_strdup (g_user_name);
1663 #endif /* G_OS_WIN32 */
1665 #endif /* !HAVE_PWD_H */
1669 g_home_dir = g_strdup (g_getenv ("HOME"));
1673 /* change '\\' in %HOME% to '/' */
1674 g_strdelimit (g_home_dir, "\\",'/');
1677 g_user_name = g_strdup ("somebody");
1679 g_real_name = g_strdup ("Unknown");
1683 gboolean hostname_fail = (gethostname (hostname, sizeof (hostname)) == -1);
1685 DWORD size = sizeof (hostname);
1686 gboolean hostname_fail = (!GetComputerName (hostname, &size));
1688 g_host_name = g_strdup (hostname_fail ? "localhost" : hostname);
1692 g_tmp_dir_cp = g_locale_from_utf8 (g_tmp_dir, -1, NULL, NULL, NULL);
1693 g_user_name_cp = g_locale_from_utf8 (g_user_name, -1, NULL, NULL, NULL);
1694 g_real_name_cp = g_locale_from_utf8 (g_real_name, -1, NULL, NULL, NULL);
1697 g_tmp_dir_cp = g_strdup ("\\");
1698 if (!g_user_name_cp)
1699 g_user_name_cp = g_strdup ("somebody");
1700 if (!g_real_name_cp)
1701 g_real_name_cp = g_strdup ("Unknown");
1703 /* home_dir might be NULL, unlike tmp_dir, user_name and
1707 g_home_dir_cp = g_locale_from_utf8 (g_home_dir, -1, NULL, NULL, NULL);
1709 g_home_dir_cp = NULL;
1710 #endif /* G_OS_WIN32 */
1714 g_get_any_init (void)
1717 g_get_any_init_do ();
1721 g_get_any_init_locked (void)
1723 G_LOCK (g_utils_global);
1725 G_UNLOCK (g_utils_global);
1732 * Gets the user name of the current user. The encoding of the returned
1733 * string is system-defined. On UNIX, it might be the preferred file name
1734 * encoding, or something else, and there is no guarantee that it is even
1735 * consistent on a machine. On Windows, it is always UTF-8.
1737 * Returns: the user name of the current user.
1739 G_CONST_RETURN gchar*
1740 g_get_user_name (void)
1742 g_get_any_init_locked ();
1749 * Gets the real name of the user. This usually comes from the user's entry
1750 * in the <filename>passwd</filename> file. The encoding of the returned
1751 * string is system-defined. (On Windows, it is, however, always UTF-8.)
1752 * If the real user name cannot be determined, the string "Unknown" is
1755 * Returns: the user's real name.
1757 G_CONST_RETURN gchar*
1758 g_get_real_name (void)
1760 g_get_any_init_locked ();
1767 * Gets the current user's home directory as defined in the
1768 * password database.
1770 * Note that in contrast to traditional UNIX tools, this function
1771 * prefers <filename>passwd</filename> entries over the <envar>HOME</envar>
1772 * environment variable.
1774 * One of the reasons for this decision is that applications in many
1775 * cases need special handling to deal with the case where
1776 * <envar>HOME</envar> is
1778 * <member>Not owned by the user</member>
1779 * <member>Not writeable</member>
1780 * <member>Not even readable</member>
1782 * Since applications are in general <emphasis>not</emphasis> written
1783 * to deal with these situations it was considered better to make
1784 * g_get_homedir() not pay attention to <envar>HOME</envar> and to
1785 * return the real home directory for the user. If applications
1786 * want to pay attention to <envar>HOME</envar>, they can do:
1788 * const char *homedir = g_getenv ("HOME");
1790 * homedir = g_get_homedir (<!-- -->);
1793 * Returns: the current user's home directory
1795 G_CONST_RETURN gchar*
1796 g_get_home_dir (void)
1798 g_get_any_init_locked ();
1805 * Gets the directory to use for temporary files. This is found from
1806 * inspecting the environment variables <envar>TMPDIR</envar>,
1807 * <envar>TMP</envar>, and <envar>TEMP</envar> in that order. If none
1808 * of those are defined "/tmp" is returned on UNIX and "C:\" on Windows.
1809 * The encoding of the returned string is system-defined. On Windows,
1810 * it is always UTF-8. The return value is never %NULL.
1812 * Returns: the directory to use for temporary files.
1814 G_CONST_RETURN gchar*
1815 g_get_tmp_dir (void)
1817 g_get_any_init_locked ();
1824 * Return a name for the machine.
1826 * The returned name is not necessarily a fully-qualified domain name,
1827 * or even present in DNS or some other name service at all. It need
1828 * not even be unique on your local network or site, but usually it
1829 * is. Callers should not rely on the return value having any specific
1830 * properties like uniqueness for security purposes. Even if the name
1831 * of the machine is changed while an application is running, the
1832 * return value from this function does not change. The returned
1833 * string is owned by GLib and should not be modified or freed. If no
1834 * name can be determined, a default fixed string "localhost" is
1837 * Returns: the host name of the machine.
1842 g_get_host_name (void)
1844 g_get_any_init_locked ();
1848 G_LOCK_DEFINE_STATIC (g_prgname);
1849 static gchar *g_prgname = NULL;
1854 * Gets the name of the program. This name should <emphasis>not</emphasis>
1855 * be localized, contrast with g_get_application_name().
1856 * (If you are using GDK or GTK+ the program name is set in gdk_init(),
1857 * which is called by gtk_init(). The program name is found by taking
1858 * the last component of <literal>argv[0]</literal>.)
1860 * Returns: the name of the program. The returned string belongs
1861 * to GLib and must not be modified or freed.
1864 g_get_prgname (void)
1870 if (g_prgname == NULL)
1872 static gboolean beenhere = FALSE;
1876 gchar *utf8_buf = NULL;
1877 wchar_t buf[MAX_PATH+1];
1880 if (GetModuleFileNameW (GetModuleHandle (NULL),
1881 buf, G_N_ELEMENTS (buf)) > 0)
1882 utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
1886 g_prgname = g_path_get_basename (utf8_buf);
1893 G_UNLOCK (g_prgname);
1900 * @prgname: the name of the program.
1902 * Sets the name of the program. This name should <emphasis>not</emphasis>
1903 * be localized, contrast with g_set_application_name(). Note that for
1904 * thread-safety reasons this function can only be called once.
1907 g_set_prgname (const gchar *prgname)
1911 g_prgname = g_strdup (prgname);
1912 G_UNLOCK (g_prgname);
1915 G_LOCK_DEFINE_STATIC (g_application_name);
1916 static gchar *g_application_name = NULL;
1919 * g_get_application_name:
1921 * Gets a human-readable name for the application, as set by
1922 * g_set_application_name(). This name should be localized if
1923 * possible, and is intended for display to the user. Contrast with
1924 * g_get_prgname(), which gets a non-localized name. If
1925 * g_set_application_name() has not been called, returns the result of
1926 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1929 * Return value: human-readable application name. may return %NULL
1933 G_CONST_RETURN gchar*
1934 g_get_application_name (void)
1938 G_LOCK (g_application_name);
1939 retval = g_application_name;
1940 G_UNLOCK (g_application_name);
1943 return g_get_prgname ();
1949 * g_set_application_name:
1950 * @application_name: localized name of the application
1952 * Sets a human-readable name for the application. This name should be
1953 * localized if possible, and is intended for display to the user.
1954 * Contrast with g_set_prgname(), which sets a non-localized name.
1955 * g_set_prgname() will be called automatically by gtk_init(),
1956 * but g_set_application_name() will not.
1958 * Note that for thread safety reasons, this function can only
1961 * The application name will be used in contexts such as error messages,
1962 * or when displaying an application's name in the task list.
1967 g_set_application_name (const gchar *application_name)
1969 gboolean already_set = FALSE;
1971 G_LOCK (g_application_name);
1972 if (g_application_name)
1975 g_application_name = g_strdup (application_name);
1976 G_UNLOCK (g_application_name);
1979 g_warning ("g_set_application() name called multiple times");
1983 * g_get_user_data_dir:
1985 * Returns a base directory in which to access application data such
1986 * as icons that is customized for a particular user.
1988 * On UNIX platforms this is determined using the mechanisms described in
1989 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1990 * XDG Base Directory Specification</ulink>
1992 * Return value: a string owned by GLib that must not be modified
1996 G_CONST_RETURN gchar*
1997 g_get_user_data_dir (void)
2001 G_LOCK (g_utils_global);
2003 if (!g_user_data_dir)
2006 data_dir = get_special_folder (CSIDL_PERSONAL);
2008 data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
2010 if (data_dir && data_dir[0])
2011 data_dir = g_strdup (data_dir);
2013 if (!data_dir || !data_dir[0])
2018 data_dir = g_build_filename (g_home_dir, ".local",
2021 data_dir = g_build_filename (g_tmp_dir, g_user_name, ".local",
2025 g_user_data_dir = data_dir;
2028 data_dir = g_user_data_dir;
2030 G_UNLOCK (g_utils_global);
2036 g_init_user_config_dir (void)
2040 if (!g_user_config_dir)
2043 config_dir = get_special_folder (CSIDL_APPDATA);
2045 config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
2047 if (config_dir && config_dir[0])
2048 config_dir = g_strdup (config_dir);
2050 if (!config_dir || !config_dir[0])
2055 config_dir = g_build_filename (g_home_dir, ".config", NULL);
2057 config_dir = g_build_filename (g_tmp_dir, g_user_name, ".config", NULL);
2060 g_user_config_dir = config_dir;
2065 * g_get_user_config_dir:
2067 * Returns a base directory in which to store user-specific application
2068 * configuration information such as user preferences and settings.
2070 * On UNIX platforms this is determined using the mechanisms described in
2071 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2072 * XDG Base Directory Specification</ulink>
2074 * Return value: a string owned by GLib that must not be modified
2078 G_CONST_RETURN gchar*
2079 g_get_user_config_dir (void)
2081 G_LOCK (g_utils_global);
2083 g_init_user_config_dir ();
2085 G_UNLOCK (g_utils_global);
2087 return g_user_config_dir;
2091 * g_get_user_cache_dir:
2093 * Returns a base directory in which to store non-essential, cached
2094 * data specific to particular user.
2096 * On UNIX platforms this is determined using the mechanisms described in
2097 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2098 * XDG Base Directory Specification</ulink>
2100 * Return value: a string owned by GLib that must not be modified
2104 G_CONST_RETURN gchar*
2105 g_get_user_cache_dir (void)
2109 G_LOCK (g_utils_global);
2111 if (!g_user_cache_dir)
2114 cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
2116 cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
2118 if (cache_dir && cache_dir[0])
2119 cache_dir = g_strdup (cache_dir);
2121 if (!cache_dir || !cache_dir[0])
2126 cache_dir = g_build_filename (g_home_dir, ".cache", NULL);
2128 cache_dir = g_build_filename (g_tmp_dir, g_user_name, ".cache", NULL);
2130 g_user_cache_dir = cache_dir;
2133 cache_dir = g_user_cache_dir;
2135 G_UNLOCK (g_utils_global);
2143 find_folder (OSType type)
2145 gchar *filename = NULL;
2148 if (FSFindFolder (kUserDomain, type, kDontCreateFolder, &found) == noErr)
2150 CFURLRef url = CFURLCreateFromFSRef (kCFAllocatorSystemDefault, &found);
2154 CFStringRef path = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle);
2158 filename = g_strdup (CFStringGetCStringPtr (path, kCFStringEncodingUTF8));
2162 filename = g_new0 (gchar, CFStringGetLength (path) * 3 + 1);
2164 CFStringGetCString (path, filename,
2165 CFStringGetLength (path) * 3 + 1,
2166 kCFStringEncodingUTF8);
2180 load_user_special_dirs (void)
2182 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = find_folder (kDesktopFolderType);
2183 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = find_folder (kDocumentsFolderType);
2184 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = find_folder (kDesktopFolderType); /* XXX correct ? */
2185 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = find_folder (kMusicDocumentsFolderType);
2186 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = find_folder (kPictureDocumentsFolderType);
2187 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = NULL;
2188 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = NULL;
2189 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = find_folder (kMovieDocumentsFolderType);
2192 #endif /* HAVE_CARBON */
2194 #if defined(G_OS_WIN32)
2196 load_user_special_dirs (void)
2198 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2199 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
2200 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY); /* XXX correct ? */
2201 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
2202 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
2203 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS); /* XXX correct ? */
2204 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
2205 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
2207 #endif /* G_OS_WIN32 */
2209 static void g_init_user_config_dir (void);
2211 #if defined(G_OS_UNIX) && !defined(HAVE_CARBON)
2213 /* adapted from xdg-user-dir-lookup.c
2215 * Copyright (C) 2007 Red Hat Inc.
2217 * Permission is hereby granted, free of charge, to any person
2218 * obtaining a copy of this software and associated documentation files
2219 * (the "Software"), to deal in the Software without restriction,
2220 * including without limitation the rights to use, copy, modify, merge,
2221 * publish, distribute, sublicense, and/or sell copies of the Software,
2222 * and to permit persons to whom the Software is furnished to do so,
2223 * subject to the following conditions:
2225 * The above copyright notice and this permission notice shall be
2226 * included in all copies or substantial portions of the Software.
2228 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
2229 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
2230 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
2231 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
2232 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
2233 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
2234 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2238 load_user_special_dirs (void)
2245 g_init_user_config_dir ();
2246 config_file = g_build_filename (g_user_config_dir,
2250 if (!g_file_get_contents (config_file, &data, NULL, NULL))
2252 g_free (config_file);
2256 lines = g_strsplit (data, "\n", -1);
2257 n_lines = g_strv_length (lines);
2260 for (i = 0; i < n_lines; i++)
2262 gchar *buffer = lines[i];
2265 gboolean is_relative = FALSE;
2266 GUserDirectory directory;
2268 /* Remove newline at end */
2269 len = strlen (buffer);
2270 if (len > 0 && buffer[len - 1] == '\n')
2271 buffer[len - 1] = 0;
2274 while (*p == ' ' || *p == '\t')
2277 if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
2279 directory = G_USER_DIRECTORY_DESKTOP;
2280 p += strlen ("XDG_DESKTOP_DIR");
2282 else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
2284 directory = G_USER_DIRECTORY_DOCUMENTS;
2285 p += strlen ("XDG_DOCUMENTS_DIR");
2287 else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
2289 directory = G_USER_DIRECTORY_DOWNLOAD;
2290 p += strlen ("XDG_DOWNLOAD_DIR");
2292 else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
2294 directory = G_USER_DIRECTORY_MUSIC;
2295 p += strlen ("XDG_MUSIC_DIR");
2297 else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
2299 directory = G_USER_DIRECTORY_PICTURES;
2300 p += strlen ("XDG_PICTURES_DIR");
2302 else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
2304 directory = G_USER_DIRECTORY_PUBLIC_SHARE;
2305 p += strlen ("XDG_PUBLICSHARE_DIR");
2307 else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
2309 directory = G_USER_DIRECTORY_TEMPLATES;
2310 p += strlen ("XDG_TEMPLATES_DIR");
2312 else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
2314 directory = G_USER_DIRECTORY_VIDEOS;
2315 p += strlen ("XDG_VIDEOS_DIR");
2320 while (*p == ' ' || *p == '\t')
2327 while (*p == ' ' || *p == '\t')
2334 if (strncmp (p, "$HOME", 5) == 0)
2342 d = strrchr (p, '"');
2349 /* remove trailing slashes */
2351 if (d[len - 1] == '/')
2357 g_user_special_dirs[directory] = g_build_filename (g_home_dir, d, NULL);
2360 g_user_special_dirs[directory] = g_strdup (d);
2364 g_free (config_file);
2367 #endif /* G_OS_UNIX && !HAVE_CARBON */
2370 * g_get_user_special_dir:
2371 * @directory: the logical id of special directory
2373 * Returns the full path of a special directory using its logical id.
2375 * On Unix this is done using the XDG special user directories.
2377 * Depending on the platform, the user might be able to change the path
2378 * of the special directory without requiring the session to restart; GLib
2379 * will not reflect any change once the special directories are loaded.
2381 * Return value: the path to the specified special directory, or %NULL
2382 * if the logical id was not found. The returned string is owned by
2383 * GLib and should not be modified or freed.
2387 G_CONST_RETURN gchar *
2388 g_get_user_special_dir (GUserDirectory directory)
2390 g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
2391 directory < G_USER_N_DIRECTORIES, NULL);
2393 G_LOCK (g_utils_global);
2395 if (G_UNLIKELY (g_user_special_dirs == NULL))
2397 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
2399 load_user_special_dirs ();
2401 /* Special-case desktop for historical compatibility */
2402 if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
2406 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] =
2407 g_build_filename (g_home_dir, "Desktop", NULL);
2411 G_UNLOCK (g_utils_global);
2413 return g_user_special_dirs[directory];
2418 #undef g_get_system_data_dirs
2421 get_module_for_address (gconstpointer address)
2423 /* Holds the g_utils_global lock */
2425 static gboolean beenhere = FALSE;
2426 typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
2427 static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
2435 p_GetModuleHandleExA =
2436 (t_GetModuleHandleExA) GetProcAddress (LoadLibrary ("kernel32.dll"),
2437 "GetModuleHandleExA");
2441 if (p_GetModuleHandleExA == NULL ||
2442 !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
2443 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
2446 MEMORY_BASIC_INFORMATION mbi;
2447 VirtualQuery (address, &mbi, sizeof (mbi));
2448 hmodule = (HMODULE) mbi.AllocationBase;
2455 get_module_share_dir (gconstpointer address)
2458 gchar *filename = NULL;
2460 wchar_t wfilename[MAX_PATH];
2462 hmodule = get_module_for_address (address);
2463 if (hmodule == NULL)
2466 if (GetModuleFileNameW (hmodule, wfilename, G_N_ELEMENTS (wfilename)))
2467 filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
2469 if (filename == NULL)
2472 if ((p = strrchr (filename, G_DIR_SEPARATOR)) != NULL)
2475 p = strrchr (filename, G_DIR_SEPARATOR);
2476 if (p && (g_ascii_strcasecmp (p + 1, "bin") == 0))
2479 retval = g_build_filename (filename, "share", NULL);
2485 G_CONST_RETURN gchar * G_CONST_RETURN *
2486 g_win32_get_system_data_dirs_for_module (gconstpointer address)
2490 static GHashTable *per_module_data_dirs = NULL;
2496 G_LOCK (g_utils_global);
2497 hmodule = get_module_for_address (address);
2498 if (hmodule != NULL)
2500 if (per_module_data_dirs == NULL)
2501 per_module_data_dirs = g_hash_table_new (NULL, NULL);
2504 retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
2508 G_UNLOCK (g_utils_global);
2509 return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2515 data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
2517 /* Documents and Settings\All Users\Application Data */
2518 p = get_special_folder (CSIDL_COMMON_APPDATA);
2520 g_array_append_val (data_dirs, p);
2522 /* Documents and Settings\All Users\Documents */
2523 p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2525 g_array_append_val (data_dirs, p);
2527 /* Using the above subfolders of Documents and Settings perhaps
2528 * makes sense from a Windows perspective.
2530 * But looking at the actual use cases of this function in GTK+
2531 * and GNOME software, what we really want is the "share"
2532 * subdirectory of the installation directory for the package
2533 * our caller is a part of.
2535 * The address parameter, if non-NULL, points to a function in the
2536 * calling module. Use that to determine that module's installation
2537 * folder, and use its "share" subfolder.
2539 * Additionally, also use the "share" subfolder of the installation
2540 * locations of GLib and the .exe file being run.
2542 * To guard against none of the above being what is really wanted,
2543 * callers of this function should have Win32-specific code to look
2544 * up their installation folder themselves, and handle a subfolder
2545 * "share" of it in the same way as the folders returned from this
2549 p = get_module_share_dir (address);
2551 g_array_append_val (data_dirs, p);
2553 p = g_win32_get_package_installation_subdirectory (NULL, dll_name, "share");
2555 g_array_append_val (data_dirs, p);
2557 p = g_win32_get_package_installation_subdirectory (NULL, NULL, "share");
2559 g_array_append_val (data_dirs, p);
2561 retval = (gchar **) g_array_free (data_dirs, FALSE);
2565 if (hmodule != NULL)
2566 g_hash_table_insert (per_module_data_dirs, hmodule, retval);
2567 G_UNLOCK (g_utils_global);
2570 return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2576 * g_get_system_data_dirs:
2578 * Returns an ordered list of base directories in which to access
2579 * system-wide application data.
2581 * On UNIX platforms this is determined using the mechanisms described in
2582 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2583 * XDG Base Directory Specification</ulink>
2585 * On Windows the first elements in the list are the Application Data
2586 * and Documents folders for All Users. (These can be determined only
2587 * on Windows 2000 or later and are not present in the list on other
2588 * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
2589 * CSIDL_COMMON_DOCUMENTS.
2591 * Then follows the "share" subfolder in the installation folder for
2592 * the package containing the DLL that calls this function, if it can
2595 * Finally the list contains the "share" subfolder in the installation
2596 * folder for GLib, and in the installation folder for the package the
2597 * application's .exe file belongs to.
2599 * The installation folders above are determined by looking up the
2600 * folder where the module (DLL or EXE) in question is located. If the
2601 * folder's name is "bin", its parent is used, otherwise the folder
2604 * Note that on Windows the returned list can vary depending on where
2605 * this function is called.
2607 * Return value: a %NULL-terminated array of strings owned by GLib that must
2608 * not be modified or freed.
2611 G_CONST_RETURN gchar * G_CONST_RETURN *
2612 g_get_system_data_dirs (void)
2614 gchar **data_dir_vector;
2616 G_LOCK (g_utils_global);
2618 if (!g_system_data_dirs)
2621 data_dir_vector = (gchar **) g_win32_get_system_data_dirs_for_module (NULL);
2623 gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
2625 if (!data_dirs || !data_dirs[0])
2626 data_dirs = "/usr/local/share/:/usr/share/";
2628 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2631 g_system_data_dirs = data_dir_vector;
2634 data_dir_vector = g_system_data_dirs;
2636 G_UNLOCK (g_utils_global);
2638 return (G_CONST_RETURN gchar * G_CONST_RETURN *) data_dir_vector;
2642 * g_get_system_config_dirs:
2644 * Returns an ordered list of base directories in which to access
2645 * system-wide configuration information.
2647 * On UNIX platforms this is determined using the mechanisms described in
2648 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2649 * XDG Base Directory Specification</ulink>
2651 * Return value: a %NULL-terminated array of strings owned by GLib that must
2652 * not be modified or freed.
2655 G_CONST_RETURN gchar * G_CONST_RETURN *
2656 g_get_system_config_dirs (void)
2658 gchar *conf_dirs, **conf_dir_vector;
2660 G_LOCK (g_utils_global);
2662 if (!g_system_config_dirs)
2665 conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
2668 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2673 /* Return empty list */
2674 conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2677 conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
2679 if (!conf_dirs || !conf_dirs[0])
2680 conf_dirs = "/etc/xdg";
2682 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2685 g_system_config_dirs = conf_dir_vector;
2688 conf_dir_vector = g_system_config_dirs;
2689 G_UNLOCK (g_utils_global);
2691 return (G_CONST_RETURN gchar * G_CONST_RETURN *) conf_dir_vector;
2696 static GHashTable *alias_table = NULL;
2698 /* read an alias file for the locales */
2700 read_aliases (gchar *file)
2706 alias_table = g_hash_table_new (g_str_hash, g_str_equal);
2707 fp = fopen (file,"r");
2710 while (fgets (buf, 256, fp))
2716 /* Line is a comment */
2717 if ((buf[0] == '#') || (buf[0] == '\0'))
2720 /* Reads first column */
2721 for (p = buf, q = NULL; *p; p++) {
2722 if ((*p == '\t') || (*p == ' ') || (*p == ':')) {
2725 while ((*q == '\t') || (*q == ' ')) {
2731 /* The line only had one column */
2732 if (!q || *q == '\0')
2735 /* Read second column */
2736 for (p = q; *p; p++) {
2737 if ((*p == '\t') || (*p == ' ')) {
2743 /* Add to alias table if necessary */
2744 if (!g_hash_table_lookup (alias_table, buf)) {
2745 g_hash_table_insert (alias_table, g_strdup (buf), g_strdup (q));
2754 unalias_lang (char *lang)
2761 read_aliases ("/usr/share/locale/locale.alias");
2764 while ((p = g_hash_table_lookup (alias_table, lang)) && (strcmp (p, lang) != 0))
2769 static gboolean said_before = FALSE;
2771 g_warning ("Too many alias levels for a locale, "
2772 "may indicate a loop");
2781 /* Mask for components of locale spec. The ordering here is from
2782 * least significant to most significant
2786 COMPONENT_CODESET = 1 << 0,
2787 COMPONENT_TERRITORY = 1 << 1,
2788 COMPONENT_MODIFIER = 1 << 2
2791 /* Break an X/Open style locale specification into components
2794 explode_locale (const gchar *locale,
2800 const gchar *uscore_pos;
2801 const gchar *at_pos;
2802 const gchar *dot_pos;
2806 uscore_pos = strchr (locale, '_');
2807 dot_pos = strchr (uscore_pos ? uscore_pos : locale, '.');
2808 at_pos = strchr (dot_pos ? dot_pos : (uscore_pos ? uscore_pos : locale), '@');
2812 mask |= COMPONENT_MODIFIER;
2813 *modifier = g_strdup (at_pos);
2816 at_pos = locale + strlen (locale);
2820 mask |= COMPONENT_CODESET;
2821 *codeset = g_strndup (dot_pos, at_pos - dot_pos);
2828 mask |= COMPONENT_TERRITORY;
2829 *territory = g_strndup (uscore_pos, dot_pos - uscore_pos);
2832 uscore_pos = dot_pos;
2834 *language = g_strndup (locale, uscore_pos - locale);
2840 * Compute all interesting variants for a given locale name -
2841 * by stripping off different components of the value.
2843 * For simplicity, we assume that the locale is in
2844 * X/Open format: language[_territory][.codeset][@modifier]
2846 * TODO: Extend this to handle the CEN format (see the GNUlibc docs)
2847 * as well. We could just copy the code from glibc wholesale
2848 * but it is big, ugly, and complicated, so I'm reluctant
2849 * to do so when this should handle 99% of the time...
2852 _g_compute_locale_variants (const gchar *locale)
2854 GSList *retval = NULL;
2856 gchar *language = NULL;
2857 gchar *territory = NULL;
2858 gchar *codeset = NULL;
2859 gchar *modifier = NULL;
2864 g_return_val_if_fail (locale != NULL, NULL);
2866 mask = explode_locale (locale, &language, &territory, &codeset, &modifier);
2868 /* Iterate through all possible combinations, from least attractive
2869 * to most attractive.
2871 for (i = 0; i <= mask; i++)
2872 if ((i & ~mask) == 0)
2874 gchar *val = g_strconcat (language,
2875 (i & COMPONENT_TERRITORY) ? territory : "",
2876 (i & COMPONENT_CODESET) ? codeset : "",
2877 (i & COMPONENT_MODIFIER) ? modifier : "",
2879 retval = g_slist_prepend (retval, val);
2883 if (mask & COMPONENT_CODESET)
2885 if (mask & COMPONENT_TERRITORY)
2887 if (mask & COMPONENT_MODIFIER)
2893 /* The following is (partly) taken from the gettext package.
2894 Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc. */
2896 static const gchar *
2897 guess_category_value (const gchar *category_name)
2899 const gchar *retval;
2901 /* The highest priority value is the `LANGUAGE' environment
2902 variable. This is a GNU extension. */
2903 retval = g_getenv ("LANGUAGE");
2904 if ((retval != NULL) && (retval[0] != '\0'))
2907 /* `LANGUAGE' is not set. So we have to proceed with the POSIX
2908 methods of looking to `LC_ALL', `LC_xxx', and `LANG'. On some
2909 systems this can be done by the `setlocale' function itself. */
2911 /* Setting of LC_ALL overwrites all other. */
2912 retval = g_getenv ("LC_ALL");
2913 if ((retval != NULL) && (retval[0] != '\0'))
2916 /* Next comes the name of the desired category. */
2917 retval = g_getenv (category_name);
2918 if ((retval != NULL) && (retval[0] != '\0'))
2921 /* Last possibility is the LANG environment variable. */
2922 retval = g_getenv ("LANG");
2923 if ((retval != NULL) && (retval[0] != '\0'))
2926 #ifdef G_PLATFORM_WIN32
2927 /* g_win32_getlocale() first checks for LC_ALL, LC_MESSAGES and
2928 * LANG, which we already did above. Oh well. The main point of
2929 * calling g_win32_getlocale() is to get the thread's locale as used
2930 * by Windows and the Microsoft C runtime (in the "English_United
2931 * States" format) translated into the Unixish format.
2933 retval = g_win32_getlocale ();
2934 if ((retval != NULL) && (retval[0] != '\0'))
2941 typedef struct _GLanguageNamesCache GLanguageNamesCache;
2943 struct _GLanguageNamesCache {
2945 gchar **language_names;
2949 language_names_cache_free (gpointer data)
2951 GLanguageNamesCache *cache = data;
2952 g_free (cache->languages);
2953 g_strfreev (cache->language_names);
2958 * g_get_language_names:
2960 * Computes a list of applicable locale names, which can be used to
2961 * e.g. construct locale-dependent filenames or search paths. The returned
2962 * list is sorted from most desirable to least desirable and always contains
2963 * the default locale "C".
2965 * For example, if LANGUAGE=de:en_US, then the returned list is
2966 * "de", "en_US", "en", "C".
2968 * This function consults the environment variables <envar>LANGUAGE</envar>,
2969 * <envar>LC_ALL</envar>, <envar>LC_MESSAGES</envar> and <envar>LANG</envar>
2970 * to find the list of locales specified by the user.
2972 * Return value: a %NULL-terminated array of strings owned by GLib
2973 * that must not be modified or freed.
2977 G_CONST_RETURN gchar * G_CONST_RETURN *
2978 g_get_language_names (void)
2980 static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
2981 GLanguageNamesCache *cache = g_static_private_get (&cache_private);
2986 cache = g_new0 (GLanguageNamesCache, 1);
2987 g_static_private_set (&cache_private, cache, language_names_cache_free);
2990 value = guess_category_value ("LC_MESSAGES");
2994 if (!(cache->languages && strcmp (cache->languages, value) == 0))
3001 g_free (cache->languages);
3002 g_strfreev (cache->language_names);
3003 cache->languages = g_strdup (value);
3005 alist = g_strsplit (value, ":", 0);
3007 for (a = alist; *a; a++)
3009 gchar *b = unalias_lang (*a);
3010 list = g_slist_concat (list, _g_compute_locale_variants (b));
3013 list = g_slist_append (list, g_strdup ("C"));
3015 cache->language_names = languages = g_new (gchar *, g_slist_length (list) + 1);
3016 for (l = list, i = 0; l; l = l->next, i++)
3017 languages[i] = l->data;
3018 languages[i] = NULL;
3020 g_slist_free (list);
3023 return (G_CONST_RETURN gchar * G_CONST_RETURN *) cache->language_names;
3028 * @v: a #gpointer key
3030 * Converts a gpointer to a hash value.
3031 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3032 * when using pointers as keys in a #GHashTable.
3034 * Returns: a hash value corresponding to the key.
3037 g_direct_hash (gconstpointer v)
3039 return GPOINTER_TO_UINT (v);
3045 * @v2: a key to compare with @v1.
3047 * Compares two #gpointer arguments and returns %TRUE if they are equal.
3048 * It can be passed to g_hash_table_new() as the @key_equal_func
3049 * parameter, when using pointers as keys in a #GHashTable.
3051 * Returns: %TRUE if the two keys match.
3054 g_direct_equal (gconstpointer v1,
3062 * @v1: a pointer to a #gint key.
3063 * @v2: a pointer to a #gint key to compare with @v1.
3065 * Compares the two #gint values being pointed to and returns
3066 * %TRUE if they are equal.
3067 * It can be passed to g_hash_table_new() as the @key_equal_func
3068 * parameter, when using pointers to integers as keys in a #GHashTable.
3070 * Returns: %TRUE if the two keys match.
3073 g_int_equal (gconstpointer v1,
3076 return *((const gint*) v1) == *((const gint*) v2);
3081 * @v: a pointer to a #gint key
3083 * Converts a pointer to a #gint to a hash value.
3084 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3085 * when using pointers to integers values as keys in a #GHashTable.
3087 * Returns: a hash value corresponding to the key.
3090 g_int_hash (gconstpointer v)
3092 return *(const gint*) v;
3096 * g_nullify_pointer:
3097 * @nullify_location: the memory address of the pointer.
3099 * Set the pointer at the specified location to %NULL.
3102 g_nullify_pointer (gpointer *nullify_location)
3104 g_return_if_fail (nullify_location != NULL);
3106 *nullify_location = NULL;
3112 * Get the codeset for the current locale.
3114 * Return value: a newly allocated string containing the name
3115 * of the codeset. This string must be freed with g_free().
3118 g_get_codeset (void)
3120 const gchar *charset;
3122 g_get_charset (&charset);
3124 return g_strdup (charset);
3127 /* This is called from g_thread_init(). It's used to
3128 * initialize some static data in a threadsafe way.
3131 _g_utils_thread_init (void)
3133 g_get_language_names ();
3139 * _glib_get_locale_dir:
3141 * Return the path to the share\locale or lib\locale subfolder of the
3142 * GLib installation folder. The path is in the system codepage. We
3143 * have to use system codepage as bindtextdomain() doesn't have a
3147 _glib_get_locale_dir (void)
3149 gchar *install_dir, *locale_dir;
3150 gchar *retval = NULL;
3152 install_dir = g_win32_get_package_installation_directory (GETTEXT_PACKAGE, dll_name);
3157 * Append "/share/locale" or "/lib/locale" depending on whether
3158 * autoconfigury detected GNU gettext or not.
3160 const char *p = GLIB_LOCALE_DIR + strlen (GLIB_LOCALE_DIR);
3166 locale_dir = g_build_filename (install_dir, p, NULL);
3168 retval = g_win32_locale_filename_from_utf8 (locale_dir);
3170 g_free (install_dir);
3171 g_free (locale_dir);
3177 return g_strdup ("");
3180 #undef GLIB_LOCALE_DIR
3182 #endif /* G_OS_WIN32 */
3186 * str: The string to be translated
3188 * Returns the translated string from the glib translations.
3189 * This is an internal function and should only be used by
3190 * the internals of glib (such as libgio).
3192 * Returns: the transation of @str to the current locale
3194 G_CONST_RETURN gchar *
3195 glib_gettext (const gchar *str)
3197 static gboolean _glib_gettext_initialized = FALSE;
3199 if (!_glib_gettext_initialized)
3202 gchar *tmp = _glib_get_locale_dir ();
3203 bindtextdomain (GETTEXT_PACKAGE, tmp);
3206 bindtextdomain (GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
3208 # ifdef HAVE_BIND_TEXTDOMAIN_CODESET
3209 bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
3211 _glib_gettext_initialized = TRUE;
3214 return dgettext (GETTEXT_PACKAGE, str);
3219 /* Binary compatibility versions. Not for newly compiled code. */
3221 #undef g_find_program_in_path
3224 g_find_program_in_path (const gchar *program)
3226 gchar *utf8_program = g_locale_to_utf8 (program, -1, NULL, NULL, NULL);
3227 gchar *utf8_retval = g_find_program_in_path_utf8 (utf8_program);
3230 g_free (utf8_program);
3231 if (utf8_retval == NULL)
3233 retval = g_locale_from_utf8 (utf8_retval, -1, NULL, NULL, NULL);
3234 g_free (utf8_retval);
3239 #undef g_get_current_dir
3242 g_get_current_dir (void)
3244 gchar *utf8_dir = g_get_current_dir_utf8 ();
3245 gchar *dir = g_locale_from_utf8 (utf8_dir, -1, NULL, NULL, NULL);
3252 G_CONST_RETURN gchar*
3253 g_getenv (const gchar *variable)
3255 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3256 const gchar *utf8_value = g_getenv_utf8 (utf8_variable);
3260 g_free (utf8_variable);
3263 value = g_locale_from_utf8 (utf8_value, -1, NULL, NULL, NULL);
3264 quark = g_quark_from_string (value);
3267 return g_quark_to_string (quark);
3273 g_setenv (const gchar *variable,
3277 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3278 gchar *utf8_value = g_locale_to_utf8 (value, -1, NULL, NULL, NULL);
3279 gboolean retval = g_setenv_utf8 (utf8_variable, utf8_value, overwrite);
3281 g_free (utf8_variable);
3282 g_free (utf8_value);
3290 g_unsetenv (const gchar *variable)
3292 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3294 g_unsetenv_utf8 (utf8_variable);
3296 g_free (utf8_variable);
3299 #undef g_get_user_name
3301 G_CONST_RETURN gchar*
3302 g_get_user_name (void)
3304 g_get_any_init_locked ();
3305 return g_user_name_cp;
3308 #undef g_get_real_name
3310 G_CONST_RETURN gchar*
3311 g_get_real_name (void)
3313 g_get_any_init_locked ();
3314 return g_real_name_cp;
3317 #undef g_get_home_dir
3319 G_CONST_RETURN gchar*
3320 g_get_home_dir (void)
3322 g_get_any_init_locked ();
3323 return g_home_dir_cp;
3326 #undef g_get_tmp_dir
3328 G_CONST_RETURN gchar*
3329 g_get_tmp_dir (void)
3331 g_get_any_init_locked ();
3332 return g_tmp_dir_cp;
3337 #define __G_UTILS_C__
3338 #include "galiasdef.c"