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_MYPICTURES
105 # define CSIDL_MYPICTURES 0x27
107 # ifndef CSIDL_COMMON_DOCUMENTS
108 # define CSIDL_COMMON_DOCUMENTS 46
110 # ifndef CSIDL_PROFILE
111 # define CSIDL_PROFILE 40
113 # include <process.h>
117 #include <CoreServices/CoreServices.h>
121 #include <langinfo.h>
124 #ifdef HAVE_BIND_TEXTDOMAIN_CODESET
128 const guint glib_major_version = GLIB_MAJOR_VERSION;
129 const guint glib_minor_version = GLIB_MINOR_VERSION;
130 const guint glib_micro_version = GLIB_MICRO_VERSION;
131 const guint glib_interface_age = GLIB_INTERFACE_AGE;
132 const guint glib_binary_age = GLIB_BINARY_AGE;
134 #ifdef G_PLATFORM_WIN32
136 G_WIN32_DLLMAIN_FOR_DLL_NAME (static, dll_name)
141 * glib_check_version:
142 * @required_major: the required major version.
143 * @required_minor: the required minor version.
144 * @required_micro: the required micro version.
146 * Checks that the GLib library in use is compatible with the
147 * given version. Generally you would pass in the constants
148 * #GLIB_MAJOR_VERSION, #GLIB_MINOR_VERSION, #GLIB_MICRO_VERSION
149 * as the three arguments to this function; that produces
150 * a check that the library in use is compatible with
151 * the version of GLib the application or module was compiled
154 * Compatibility is defined by two things: first the version
155 * of the running library is newer than the version
156 * @required_major.required_minor.@required_micro. Second
157 * the running library must be binary compatible with the
158 * version @required_major.required_minor.@required_micro
159 * (same major version.)
161 * Return value: %NULL if the GLib library is compatible with the
162 * given version, or a string describing the version mismatch.
163 * The returned string is owned by GLib and must not be modified
169 glib_check_version (guint required_major,
170 guint required_minor,
171 guint required_micro)
173 gint glib_effective_micro = 100 * GLIB_MINOR_VERSION + GLIB_MICRO_VERSION;
174 gint required_effective_micro = 100 * required_minor + required_micro;
176 if (required_major > GLIB_MAJOR_VERSION)
177 return "GLib version too old (major mismatch)";
178 if (required_major < GLIB_MAJOR_VERSION)
179 return "GLib version too new (major mismatch)";
180 if (required_effective_micro < glib_effective_micro - GLIB_BINARY_AGE)
181 return "GLib version too new (micro mismatch)";
182 if (required_effective_micro > glib_effective_micro)
183 return "GLib version too old (micro mismatch)";
187 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
190 * @dest: the destination address to copy the bytes to.
191 * @src: the source address to copy the bytes from.
192 * @len: the number of bytes to copy.
194 * Copies a block of memory @len bytes long, from @src to @dest.
195 * The source and destination areas may overlap.
197 * In order to use this function, you must include
198 * <filename>string.h</filename> yourself, because this macro will
199 * typically simply resolve to memmove() and GLib does not include
200 * <filename>string.h</filename> for you.
203 g_memmove (gpointer dest,
207 gchar* destptr = dest;
208 const gchar* srcptr = src;
209 if (src + len < dest || dest + len < src)
211 bcopy (src, dest, len);
214 else if (dest <= src)
217 *(destptr++) = *(srcptr++);
224 *(--destptr) = *(--srcptr);
227 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
235 * @func: the function to call on normal program termination.
237 * Specifies a function to be called at normal program termination.
239 * Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
240 * macro that maps to a call to the atexit() function in the C
241 * library. This means that in case the code that calls g_atexit(),
242 * i.e. atexit(), is in a DLL, the function will be called when the
243 * DLL is detached from the program. This typically makes more sense
244 * than that the function is called when the GLib DLL is detached,
245 * which happened earlier when g_atexit() was a function in the GLib
248 * The behaviour of atexit() in the context of dynamically loaded
249 * modules is not formally specified and varies wildly.
251 * On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
252 * loaded module which is unloaded before the program terminates might
253 * well cause a crash at program exit.
255 * Some POSIX systems implement atexit() like Windows, and have each
256 * dynamically loaded module maintain an own atexit chain that is
257 * called when the module is unloaded.
259 * On other POSIX systems, before a dynamically loaded module is
260 * unloaded, the registered atexit functions (if any) residing in that
261 * module are called, regardless where the code that registered them
262 * resided. This is presumably the most robust approach.
264 * As can be seen from the above, for portability it's best to avoid
265 * calling g_atexit() (or atexit()) except in the main executable of a
269 g_atexit (GVoidFunc func)
272 const gchar *error = NULL;
274 /* keep this in sync with glib.h */
276 #ifdef G_NATIVE_ATEXIT
277 result = ATEXIT (func);
279 error = g_strerror (errno);
280 #elif defined (HAVE_ATEXIT)
281 # ifdef NeXT /* @#%@! NeXTStep */
282 result = !atexit ((void (*)(void)) func);
284 error = g_strerror (errno);
286 result = atexit ((void (*)(void)) func);
288 error = g_strerror (errno);
290 #elif defined (HAVE_ON_EXIT)
291 result = on_exit ((void (*)(int, void *)) func, NULL);
293 error = g_strerror (errno);
296 error = "no implementation";
297 #endif /* G_NATIVE_ATEXIT */
300 g_error ("Could not register atexit() function: %s", error);
303 /* Based on execvp() from GNU Libc.
304 * Some of this code is cut-and-pasted into gspawn.c
308 my_strchrnul (const gchar *str,
311 gchar *p = (gchar*)str;
312 while (*p && (*p != c))
320 static gchar *inner_find_program_in_path (const gchar *program);
323 g_find_program_in_path (const gchar *program)
325 const gchar *last_dot = strrchr (program, '.');
327 if (last_dot == NULL ||
328 strchr (last_dot, '\\') != NULL ||
329 strchr (last_dot, '/') != NULL)
331 const gint program_length = strlen (program);
332 gchar *pathext = g_build_path (";",
333 ".exe;.cmd;.bat;.com",
334 g_getenv ("PATHEXT"),
337 gchar *decorated_program;
343 gchar *q = my_strchrnul (p, ';');
345 decorated_program = g_malloc (program_length + (q-p) + 1);
346 memcpy (decorated_program, program, program_length);
347 memcpy (decorated_program+program_length, p, q-p);
348 decorated_program [program_length + (q-p)] = '\0';
350 retval = inner_find_program_in_path (decorated_program);
351 g_free (decorated_program);
359 } while (*p++ != '\0');
364 return inner_find_program_in_path (program);
370 * g_find_program_in_path:
371 * @program: a program name in the GLib file name encoding
373 * Locates the first executable named @program in the user's path, in the
374 * same way that execvp() would locate it. Returns an allocated string
375 * with the absolute path name, or %NULL if the program is not found in
376 * the path. If @program is already an absolute path, returns a copy of
377 * @program if @program exists and is executable, and %NULL otherwise.
379 * On Windows, if @program does not have a file type suffix, tries
380 * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
381 * the <envar>PATHEXT</envar> environment variable.
383 * On Windows, it looks for the file in the same way as CreateProcess()
384 * would. This means first in the directory where the executing
385 * program was loaded from, then in the current directory, then in the
386 * Windows 32-bit system directory, then in the Windows directory, and
387 * finally in the directories in the <envar>PATH</envar> environment
388 * variable. If the program is found, the return value contains the
389 * full name including the type suffix.
391 * Return value: absolute path, or %NULL
395 inner_find_program_in_path (const gchar *program)
398 g_find_program_in_path (const gchar *program)
401 const gchar *path, *p;
402 gchar *name, *freeme;
404 const gchar *path_copy;
405 gchar *filename = NULL, *appdir = NULL;
406 gchar *sysdir = NULL, *windir = NULL;
408 wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
414 g_return_val_if_fail (program != NULL, NULL);
416 /* If it is an absolute path, or a relative path including subdirectories,
417 * don't look in PATH.
419 if (g_path_is_absolute (program)
420 || strchr (program, G_DIR_SEPARATOR) != NULL
422 || strchr (program, '/') != NULL
426 if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
427 !g_file_test (program, G_FILE_TEST_IS_DIR))
428 return g_strdup (program);
433 path = g_getenv ("PATH");
434 #if defined(G_OS_UNIX) || defined(G_OS_BEOS)
437 /* There is no `PATH' in the environment. The default
438 * search path in GNU libc is the current directory followed by
439 * the path `confstr' returns for `_CS_PATH'.
442 /* In GLib we put . last, for security, and don't use the
443 * unportable confstr(); UNIX98 does not actually specify
444 * what to search if PATH is unset. POSIX may, dunno.
447 path = "/bin:/usr/bin:.";
450 n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
451 if (n > 0 && n < MAXPATHLEN)
452 filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
454 n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
455 if (n > 0 && n < MAXPATHLEN)
456 sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
458 n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
459 if (n > 0 && n < MAXPATHLEN)
460 windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
464 appdir = g_path_get_dirname (filename);
468 path = g_strdup (path);
472 const gchar *tem = path;
473 path = g_strconcat (windir, ";", path, NULL);
474 g_free ((gchar *) tem);
480 const gchar *tem = path;
481 path = g_strconcat (sysdir, ";", path, NULL);
482 g_free ((gchar *) tem);
487 const gchar *tem = path;
488 path = g_strconcat (".;", path, NULL);
489 g_free ((gchar *) tem);
494 const gchar *tem = path;
495 path = g_strconcat (appdir, ";", path, NULL);
496 g_free ((gchar *) tem);
503 len = strlen (program) + 1;
504 pathlen = strlen (path);
505 freeme = name = g_malloc (pathlen + len + 1);
507 /* Copy the file name at the top, including '\0' */
508 memcpy (name + pathlen + 1, program, len);
509 name = name + pathlen;
510 /* And add the slash before the filename */
511 *name = G_DIR_SEPARATOR;
519 p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
522 /* Two adjacent colons, or a colon at the beginning or the end
523 * of `PATH' means to search the current directory.
527 startp = memcpy (name - (p - path), path, p - path);
529 if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
530 !g_file_test (startp, G_FILE_TEST_IS_DIR))
533 ret = g_strdup (startp);
536 g_free ((gchar *) path_copy);
541 while (*p++ != '\0');
545 g_free ((gchar *) path_copy);
552 debug_key_matches (const gchar *key,
556 for (; length; length--, key++, token++)
558 char k = (*key == '_') ? '-' : tolower (*key );
559 char t = (*token == '_') ? '-' : tolower (*token);
569 * g_parse_debug_string:
570 * @string: a list of debug options separated by colons, spaces, or
571 * commas; or the string "all" to set all flags, or %NULL.
572 * @keys: pointer to an array of #GDebugKey which associate
573 * strings with bit flags.
574 * @nkeys: the number of #GDebugKey<!-- -->s in the array.
576 * Parses a string containing debugging options
577 * into a %guint containing bit flags. This is used
578 * within GDK and GTK+ to parse the debug options passed on the
579 * command line or through environment variables.
581 * Returns: the combined set of bit flags.
584 g_parse_debug_string (const gchar *string,
585 const GDebugKey *keys,
594 /* this function is used by gmem.c/gslice.c initialization code,
595 * so introducing malloc dependencies here would require adaptions
596 * of those code portions.
599 if (!g_ascii_strcasecmp (string, "all"))
601 for (i=0; i<nkeys; i++)
602 result |= keys[i].value;
606 const gchar *p = string;
611 q = strpbrk (p, ":;, \t");
615 for (i = 0; i < nkeys; i++)
616 if (debug_key_matches (keys[i].key, p, q - p))
617 result |= keys[i].value;
630 * @file_name: the name of the file.
632 * Gets the name of the file without any leading directory components.
633 * It returns a pointer into the given file name string.
635 * Return value: the name of the file without any leading directory components.
637 * Deprecated:2.2: Use g_path_get_basename() instead, but notice that
638 * g_path_get_basename() allocates new memory for the returned string, unlike
639 * this function which returns a pointer into the argument.
641 G_CONST_RETURN gchar*
642 g_basename (const gchar *file_name)
644 register gchar *base;
646 g_return_val_if_fail (file_name != NULL, NULL);
648 base = strrchr (file_name, G_DIR_SEPARATOR);
652 gchar *q = strrchr (file_name, '/');
653 if (base == NULL || (q != NULL && q > base))
662 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
663 return (gchar*) file_name + 2;
664 #endif /* G_OS_WIN32 */
666 return (gchar*) file_name;
670 * g_path_get_basename:
671 * @file_name: the name of the file.
673 * Gets the last component of the filename. If @file_name ends with a
674 * directory separator it gets the component before the last slash. If
675 * @file_name consists only of directory separators (and on Windows,
676 * possibly a drive letter), a single separator is returned. If
677 * @file_name is empty, it gets ".".
679 * Return value: a newly allocated string containing the last component of
683 g_path_get_basename (const gchar *file_name)
685 register gssize base;
686 register gssize last_nonslash;
690 g_return_val_if_fail (file_name != NULL, NULL);
692 if (file_name[0] == '\0')
694 return g_strdup (".");
696 last_nonslash = strlen (file_name) - 1;
698 while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
701 if (last_nonslash == -1)
702 /* string only containing slashes */
703 return g_strdup (G_DIR_SEPARATOR_S);
706 if (last_nonslash == 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
707 /* string only containing slashes and a drive */
708 return g_strdup (G_DIR_SEPARATOR_S);
709 #endif /* G_OS_WIN32 */
711 base = last_nonslash;
713 while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
717 if (base == -1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
719 #endif /* G_OS_WIN32 */
721 len = last_nonslash - base;
722 retval = g_malloc (len + 1);
723 memcpy (retval, file_name + base + 1, len);
729 * g_path_is_absolute:
730 * @file_name: a file name.
732 * Returns %TRUE if the given @file_name is an absolute file name,
733 * i.e. it contains a full path from the root directory such as "/usr/local"
734 * on UNIX or "C:\windows" on Windows systems.
736 * Returns: %TRUE if @file_name is an absolute path.
739 g_path_is_absolute (const gchar *file_name)
741 g_return_val_if_fail (file_name != NULL, FALSE);
743 if (G_IS_DIR_SEPARATOR (file_name[0]))
747 /* Recognize drive letter on native Windows */
748 if (g_ascii_isalpha (file_name[0]) &&
749 file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
751 #endif /* G_OS_WIN32 */
758 * @file_name: a file name.
760 * Returns a pointer into @file_name after the root component, i.e. after
761 * the "/" in UNIX or "C:\" under Windows. If @file_name is not an absolute
762 * path it returns %NULL.
764 * Returns: a pointer into @file_name after the root component.
766 G_CONST_RETURN gchar*
767 g_path_skip_root (const gchar *file_name)
769 g_return_val_if_fail (file_name != NULL, NULL);
771 #ifdef G_PLATFORM_WIN32
772 /* Skip \\server\share or //server/share */
773 if (G_IS_DIR_SEPARATOR (file_name[0]) &&
774 G_IS_DIR_SEPARATOR (file_name[1]) &&
776 !G_IS_DIR_SEPARATOR (file_name[2]))
780 p = strchr (file_name + 2, G_DIR_SEPARATOR);
783 gchar *q = strchr (file_name + 2, '/');
784 if (p == NULL || (q != NULL && q < p))
794 while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
797 /* Possibly skip a backslash after the share name */
798 if (G_IS_DIR_SEPARATOR (file_name[0]))
801 return (gchar *)file_name;
806 /* Skip initial slashes */
807 if (G_IS_DIR_SEPARATOR (file_name[0]))
809 while (G_IS_DIR_SEPARATOR (file_name[0]))
811 return (gchar *)file_name;
816 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
817 return (gchar *)file_name + 3;
824 * g_path_get_dirname:
825 * @file_name: the name of the file.
827 * Gets the directory components of a file name. If the file name has no
828 * directory components "." is returned. The returned string should be
829 * freed when no longer needed.
831 * Returns: the directory components of the file.
834 g_path_get_dirname (const gchar *file_name)
836 register gchar *base;
839 g_return_val_if_fail (file_name != NULL, NULL);
841 base = strrchr (file_name, G_DIR_SEPARATOR);
844 gchar *q = strrchr (file_name, '/');
845 if (base == NULL || (q != NULL && q > base))
852 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
854 gchar drive_colon_dot[4];
856 drive_colon_dot[0] = file_name[0];
857 drive_colon_dot[1] = ':';
858 drive_colon_dot[2] = '.';
859 drive_colon_dot[3] = '\0';
861 return g_strdup (drive_colon_dot);
864 return g_strdup (".");
867 while (base > file_name && G_IS_DIR_SEPARATOR (*base))
871 /* base points to the char before the last slash.
873 * In case file_name is the root of a drive (X:\) or a child of the
874 * root of a drive (X:\foo), include the slash.
876 * In case file_name is the root share of an UNC path
877 * (\\server\share), add a slash, returning \\server\share\ .
879 * In case file_name is a direct child of a share in an UNC path
880 * (\\server\share\foo), include the slash after the share name,
881 * returning \\server\share\ .
883 if (base == file_name + 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
885 else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
886 G_IS_DIR_SEPARATOR (file_name[1]) &&
888 !G_IS_DIR_SEPARATOR (file_name[2]) &&
889 base >= file_name + 2)
891 const gchar *p = file_name + 2;
892 while (*p && !G_IS_DIR_SEPARATOR (*p))
896 len = (guint) strlen (file_name) + 1;
897 base = g_new (gchar, len + 1);
898 strcpy (base, file_name);
899 base[len-1] = G_DIR_SEPARATOR;
903 if (G_IS_DIR_SEPARATOR (*p))
906 while (*p && !G_IS_DIR_SEPARATOR (*p))
914 len = (guint) 1 + base - file_name;
916 base = g_new (gchar, len + 1);
917 g_memmove (base, file_name, len);
926 * Gets the current directory.
927 * The returned string should be freed when no longer needed. The encoding
928 * of the returned string is system defined. On Windows, it is always UTF-8.
930 * Returns: the current directory.
933 g_get_current_dir (void)
938 wchar_t dummy[2], *wdir;
941 len = GetCurrentDirectoryW (2, dummy);
942 wdir = g_new (wchar_t, len);
944 if (GetCurrentDirectoryW (len, wdir) == len - 1)
945 dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
950 dir = g_strdup ("\\");
956 gchar *buffer = NULL;
958 static gulong max_len = 0;
961 max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
963 /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
964 * and, if that wasn't bad enough, hangs in doing so.
966 #if (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
967 buffer = g_new (gchar, max_len + 1);
969 dir = getwd (buffer);
970 #else /* !sun || !HAVE_GETCWD */
971 while (max_len < G_MAXULONG / 2)
974 buffer = g_new (gchar, max_len + 1);
976 dir = getcwd (buffer, max_len);
978 if (dir || errno != ERANGE)
983 #endif /* !sun || !HAVE_GETCWD */
985 if (!dir || !*buffer)
987 /* hm, should we g_error() out here?
988 * this can happen if e.g. "./" has mode \0000
990 buffer[0] = G_DIR_SEPARATOR;
994 dir = g_strdup (buffer);
1003 * @variable: the environment variable to get, in the GLib file name encoding.
1005 * Returns the value of an environment variable. The name and value
1006 * are in the GLib file name encoding. On UNIX, this means the actual
1007 * bytes which might or might not be in some consistent character set
1008 * and encoding. On Windows, it is in UTF-8. On Windows, in case the
1009 * environment variable's value contains references to other
1010 * environment variables, they are expanded.
1012 * Return value: the value of the environment variable, or %NULL if
1013 * the environment variable is not found. The returned string may be
1014 * overwritten by the next call to g_getenv(), g_setenv() or
1017 G_CONST_RETURN gchar*
1018 g_getenv (const gchar *variable)
1022 g_return_val_if_fail (variable != NULL, NULL);
1024 return getenv (variable);
1026 #else /* G_OS_WIN32 */
1030 wchar_t dummy[2], *wname, *wvalue;
1033 g_return_val_if_fail (variable != NULL, NULL);
1034 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), NULL);
1036 /* On Windows NT, it is relatively typical that environment
1037 * variables contain references to other environment variables. If
1038 * so, use ExpandEnvironmentStrings(). (In an ideal world, such
1039 * environment variables would be stored in the Registry as
1040 * REG_EXPAND_SZ type values, and would then get automatically
1041 * expanded before a program sees them. But there is broken software
1042 * that stores environment variables as REG_SZ values even if they
1043 * contain references to other environment variables.)
1046 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1048 len = GetEnvironmentVariableW (wname, dummy, 2);
1058 wvalue = g_new (wchar_t, len);
1060 if (GetEnvironmentVariableW (wname, wvalue, len) != len - 1)
1067 if (wcschr (wvalue, L'%') != NULL)
1069 wchar_t *tem = wvalue;
1071 len = ExpandEnvironmentStringsW (wvalue, dummy, 2);
1075 wvalue = g_new (wchar_t, len);
1077 if (ExpandEnvironmentStringsW (tem, wvalue, len) != len)
1087 value = g_utf16_to_utf8 (wvalue, -1, NULL, NULL, NULL);
1092 quark = g_quark_from_string (value);
1095 return g_quark_to_string (quark);
1097 #endif /* G_OS_WIN32 */
1100 /* _g_getenv_nomalloc
1101 * this function does a getenv() without doing any kind of allocation
1102 * through glib. it's suitable for chars <= 127 only (both, for the
1103 * variable name and the contents) and for contents < 1024 chars in
1104 * length. also, it aliases "" to a NULL return value.
1107 _g_getenv_nomalloc (const gchar *variable,
1110 const gchar *retval = getenv (variable);
1111 if (retval && retval[0])
1113 gint l = strlen (retval);
1116 strncpy (buffer, retval, l);
1126 * @variable: the environment variable to set, must not contain '='.
1127 * @value: the value for to set the variable to.
1128 * @overwrite: whether to change the variable if it already exists.
1130 * Sets an environment variable. Both the variable's name and value
1131 * should be in the GLib file name encoding. On UNIX, this means that
1132 * they can be any sequence of bytes. On Windows, they should be in
1135 * Note that on some systems, when variables are overwritten, the memory
1136 * used for the previous variables and its value isn't reclaimed.
1138 * Returns: %FALSE if the environment variable couldn't be set.
1143 g_setenv (const gchar *variable,
1154 g_return_val_if_fail (variable != NULL, FALSE);
1155 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1158 result = setenv (variable, value, overwrite);
1160 if (!overwrite && getenv (variable) != NULL)
1163 /* This results in a leak when you overwrite existing
1164 * settings. It would be fairly easy to fix this by keeping
1165 * our own parallel array or hash table.
1167 string = g_strconcat (variable, "=", value, NULL);
1168 result = putenv (string);
1172 #else /* G_OS_WIN32 */
1175 wchar_t *wname, *wvalue, *wassignment;
1178 g_return_val_if_fail (variable != NULL, FALSE);
1179 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1180 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), FALSE);
1181 g_return_val_if_fail (g_utf8_validate (value, -1, NULL), FALSE);
1183 if (!overwrite && g_getenv (variable) != NULL)
1186 /* We want to (if possible) set both the environment variable copy
1187 * kept by the C runtime and the one kept by the system.
1189 * We can't use only the C runtime's putenv or _wputenv() as that
1190 * won't work for arbitrary Unicode strings in a "non-Unicode" app
1191 * (with main() and not wmain()). In a "main()" app the C runtime
1192 * initializes the C runtime's environment table by converting the
1193 * real (wide char) environment variables to system codepage, thus
1194 * breaking those that aren't representable in the system codepage.
1196 * As the C runtime's putenv() will also set the system copy, we do
1197 * the putenv() first, then call SetEnvironmentValueW ourselves.
1200 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1201 wvalue = g_utf8_to_utf16 (value, -1, NULL, NULL, NULL);
1202 tem = g_strconcat (variable, "=", value, NULL);
1203 wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1206 _wputenv (wassignment);
1207 g_free (wassignment);
1209 retval = (SetEnvironmentVariableW (wname, wvalue) != 0);
1216 #endif /* G_OS_WIN32 */
1219 #ifdef HAVE__NSGETENVIRON
1220 #define environ (*_NSGetEnviron())
1221 #elif !defined(G_OS_WIN32)
1223 /* According to the Single Unix Specification, environ is not in
1224 * any system header, although unistd.h often declares it.
1226 extern char **environ;
1231 * @variable: the environment variable to remove, must not contain '='.
1233 * Removes an environment variable from the environment.
1235 * Note that on some systems, when variables are overwritten, the memory
1236 * used for the previous variables and its value isn't reclaimed.
1237 * Furthermore, this function can't be guaranteed to operate in a
1243 g_unsetenv (const gchar *variable)
1247 #ifdef HAVE_UNSETENV
1248 g_return_if_fail (variable != NULL);
1249 g_return_if_fail (strchr (variable, '=') == NULL);
1251 unsetenv (variable);
1252 #else /* !HAVE_UNSETENV */
1256 g_return_if_fail (variable != NULL);
1257 g_return_if_fail (strchr (variable, '=') == NULL);
1259 len = strlen (variable);
1261 /* Mess directly with the environ array.
1262 * This seems to be the only portable way to do this.
1264 * Note that we remove *all* environment entries for
1265 * the variable name, not just the first.
1270 if (strncmp (*e, variable, len) != 0 || (*e)[len] != '=')
1278 #endif /* !HAVE_UNSETENV */
1280 #else /* G_OS_WIN32 */
1282 wchar_t *wname, *wassignment;
1285 g_return_if_fail (variable != NULL);
1286 g_return_if_fail (strchr (variable, '=') == NULL);
1287 g_return_if_fail (g_utf8_validate (variable, -1, NULL));
1289 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1290 tem = g_strconcat (variable, "=", NULL);
1291 wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1294 _wputenv (wassignment);
1295 g_free (wassignment);
1297 SetEnvironmentVariableW (wname, NULL);
1301 #endif /* G_OS_WIN32 */
1307 * Gets the names of all variables set in the environment.
1309 * Returns: a %NULL-terminated list of strings which must be freed
1310 * with g_strfreev().
1312 * Programs that want to be portable to Windows should typically use
1313 * this function and g_getenv() instead of using the environ array
1314 * from the C library directly. On Windows, the strings in the environ
1315 * array are in system codepage encoding, while in most of the typical
1316 * use cases for environment variables in GLib-using programs you want
1317 * the UTF-8 encoding that this function and g_getenv() provide.
1325 gchar **result, *eq;
1328 len = g_strv_length (environ);
1329 result = g_new0 (gchar *, len + 1);
1332 for (i = 0; i < len; i++)
1334 eq = strchr (environ[i], '=');
1336 result[j++] = g_strndup (environ[i], eq - environ[i]);
1343 gchar **result, *eq;
1347 p = (wchar_t *) GetEnvironmentStringsW ();
1353 q += wcslen (q) + 1;
1357 result = g_new0 (gchar *, len + 1);
1363 result[j] = g_utf16_to_utf8 (q, -1, NULL, NULL, NULL);
1364 if (result[j] != NULL)
1366 eq = strchr (result[j], '=');
1367 if (eq && eq > result[j])
1375 q += wcslen (q) + 1;
1378 FreeEnvironmentStringsW (p);
1384 G_LOCK_DEFINE_STATIC (g_utils_global);
1386 static gchar *g_tmp_dir = NULL;
1387 static gchar *g_user_name = NULL;
1388 static gchar *g_real_name = NULL;
1389 static gchar *g_home_dir = NULL;
1390 static gchar *g_host_name = NULL;
1393 /* System codepage versions of the above, kept at file level so that they,
1394 * too, are produced only once.
1396 static gchar *g_tmp_dir_cp = NULL;
1397 static gchar *g_user_name_cp = NULL;
1398 static gchar *g_real_name_cp = NULL;
1399 static gchar *g_home_dir_cp = NULL;
1402 static gchar *g_user_data_dir = NULL;
1403 static gchar **g_system_data_dirs = NULL;
1404 static gchar *g_user_cache_dir = NULL;
1405 static gchar *g_user_config_dir = NULL;
1406 static gchar **g_system_config_dirs = NULL;
1408 static gchar **g_user_special_dirs = NULL;
1410 /* fifteen minutes of fame for everybody */
1411 #define G_USER_DIRS_EXPIRE 15 * 60
1416 get_special_folder (int csidl)
1418 wchar_t path[MAX_PATH+1];
1420 LPITEMIDLIST pidl = NULL;
1422 gchar *retval = NULL;
1424 hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
1427 b = SHGetPathFromIDListW (pidl, path);
1429 retval = g_utf16_to_utf8 (path, -1, NULL, NULL, NULL);
1430 CoTaskMemFree (pidl);
1436 get_windows_directory_root (void)
1438 wchar_t wwindowsdir[MAX_PATH];
1440 if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
1442 /* Usually X:\Windows, but in terminal server environments
1443 * might be an UNC path, AFAIK.
1445 char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
1448 if (windowsdir == NULL)
1449 return g_strdup ("C:\\");
1451 p = (char *) g_path_skip_root (windowsdir);
1452 if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
1458 return g_strdup ("C:\\");
1463 /* HOLDS: g_utils_global_lock */
1465 g_get_any_init_do (void)
1467 gchar hostname[100];
1469 g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
1471 g_tmp_dir = g_strdup (g_getenv ("TMP"));
1473 g_tmp_dir = g_strdup (g_getenv ("TEMP"));
1477 g_tmp_dir = get_windows_directory_root ();
1483 g_tmp_dir = g_strdup (P_tmpdir);
1484 k = strlen (g_tmp_dir);
1485 if (k > 1 && G_IS_DIR_SEPARATOR (g_tmp_dir[k - 1]))
1486 g_tmp_dir[k - 1] = '\0';
1492 g_tmp_dir = g_strdup ("/tmp");
1494 #endif /* !G_OS_WIN32 */
1497 /* We check $HOME first for Win32, though it is a last resort for Unix
1498 * where we prefer the results of getpwuid().
1500 g_home_dir = g_strdup (g_getenv ("HOME"));
1502 /* Only believe HOME if it is an absolute path and exists */
1505 if (!(g_path_is_absolute (g_home_dir) &&
1506 g_file_test (g_home_dir, G_FILE_TEST_IS_DIR)))
1508 g_free (g_home_dir);
1513 /* In case HOME is Unix-style (it happens), convert it to
1519 while ((p = strchr (g_home_dir, '/')) != NULL)
1525 /* USERPROFILE is probably the closest equivalent to $HOME? */
1526 if (g_getenv ("USERPROFILE") != NULL)
1527 g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
1531 g_home_dir = get_special_folder (CSIDL_PROFILE);
1534 g_home_dir = get_windows_directory_root ();
1535 #endif /* G_OS_WIN32 */
1539 struct passwd *pw = NULL;
1540 gpointer buffer = NULL;
1544 # if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
1546 # ifdef _SC_GETPW_R_SIZE_MAX
1547 /* This reurns the maximum length */
1548 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
1552 # else /* _SC_GETPW_R_SIZE_MAX */
1554 # endif /* _SC_GETPW_R_SIZE_MAX */
1556 logname = (gchar *) g_getenv ("LOGNAME");
1561 /* we allocate 6 extra bytes to work around a bug in
1562 * Mac OS < 10.3. See #156446
1564 buffer = g_malloc (bufsize + 6);
1567 # ifdef HAVE_POSIX_GETPWUID_R
1569 error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
1570 if (!pw || (pw->pw_uid != getuid ())) {
1571 /* LOGNAME is lying, fall back to looking up the uid */
1572 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1575 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1577 error = error < 0 ? errno : error;
1578 # else /* HAVE_NONPOSIX_GETPWUID_R */
1579 /* HPUX 11 falls into the HAVE_POSIX_GETPWUID_R case */
1580 # if defined(_AIX) || defined(__hpux)
1581 error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1582 pw = error == 0 ? &pwd : NULL;
1585 pw = getpwnam_r (logname, &pwd, buffer, bufsize);
1586 if (!pw || (pw->pw_uid != getuid ())) {
1587 /* LOGNAME is lying, fall back to looking up the uid */
1588 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1591 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1593 error = pw ? 0 : errno;
1595 # endif /* HAVE_NONPOSIX_GETPWUID_R */
1599 /* we bail out prematurely if the user id can't be found
1600 * (should be pretty rare case actually), or if the buffer
1601 * should be sufficiently big and lookups are still not
1604 if (error == 0 || error == ENOENT)
1606 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
1607 (gulong) getuid ());
1610 if (bufsize > 32 * 1024)
1612 g_warning ("getpwuid_r(): failed due to: %s.",
1613 g_strerror (error));
1621 # endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
1626 pw = getpwuid (getuid ());
1631 g_user_name = g_strdup (pw->pw_name);
1633 if (pw->pw_gecos && *pw->pw_gecos != '\0')
1635 gchar **gecos_fields;
1638 /* split the gecos field and substitute '&' */
1639 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
1640 name_parts = g_strsplit (gecos_fields[0], "&", 0);
1641 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
1642 g_real_name = g_strjoinv (pw->pw_name, name_parts);
1643 g_strfreev (gecos_fields);
1644 g_strfreev (name_parts);
1648 g_home_dir = g_strdup (pw->pw_dir);
1653 #else /* !HAVE_PWD_H */
1657 guint len = UNLEN+1;
1658 wchar_t buffer[UNLEN+1];
1660 if (GetUserNameW (buffer, (LPDWORD) &len))
1662 g_user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
1663 g_real_name = g_strdup (g_user_name);
1666 #endif /* G_OS_WIN32 */
1668 #endif /* !HAVE_PWD_H */
1672 g_home_dir = g_strdup (g_getenv ("HOME"));
1676 /* change '\\' in %HOME% to '/' */
1677 g_strdelimit (g_home_dir, "\\",'/');
1680 g_user_name = g_strdup ("somebody");
1682 g_real_name = g_strdup ("Unknown");
1686 gboolean hostname_fail = (gethostname (hostname, sizeof (hostname)) == -1);
1688 DWORD size = sizeof (hostname);
1689 gboolean hostname_fail = (!GetComputerName (hostname, &size));
1691 g_host_name = g_strdup (hostname_fail ? "localhost" : hostname);
1695 g_tmp_dir_cp = g_locale_from_utf8 (g_tmp_dir, -1, NULL, NULL, NULL);
1696 g_user_name_cp = g_locale_from_utf8 (g_user_name, -1, NULL, NULL, NULL);
1697 g_real_name_cp = g_locale_from_utf8 (g_real_name, -1, NULL, NULL, NULL);
1700 g_tmp_dir_cp = g_strdup ("\\");
1701 if (!g_user_name_cp)
1702 g_user_name_cp = g_strdup ("somebody");
1703 if (!g_real_name_cp)
1704 g_real_name_cp = g_strdup ("Unknown");
1706 /* home_dir might be NULL, unlike tmp_dir, user_name and
1710 g_home_dir_cp = g_locale_from_utf8 (g_home_dir, -1, NULL, NULL, NULL);
1712 g_home_dir_cp = NULL;
1713 #endif /* G_OS_WIN32 */
1717 g_get_any_init (void)
1720 g_get_any_init_do ();
1724 g_get_any_init_locked (void)
1726 G_LOCK (g_utils_global);
1728 G_UNLOCK (g_utils_global);
1735 * Gets the user name of the current user. The encoding of the returned
1736 * string is system-defined. On UNIX, it might be the preferred file name
1737 * encoding, or something else, and there is no guarantee that it is even
1738 * consistent on a machine. On Windows, it is always UTF-8.
1740 * Returns: the user name of the current user.
1742 G_CONST_RETURN gchar*
1743 g_get_user_name (void)
1745 g_get_any_init_locked ();
1752 * Gets the real name of the user. This usually comes from the user's entry
1753 * in the <filename>passwd</filename> file. The encoding of the returned
1754 * string is system-defined. (On Windows, it is, however, always UTF-8.)
1755 * If the real user name cannot be determined, the string "Unknown" is
1758 * Returns: the user's real name.
1760 G_CONST_RETURN gchar*
1761 g_get_real_name (void)
1763 g_get_any_init_locked ();
1770 * Gets the current user's home directory as defined in the
1771 * password database.
1773 * Note that in contrast to traditional UNIX tools, this function
1774 * prefers <filename>passwd</filename> entries over the <envar>HOME</envar>
1775 * environment variable.
1777 * One of the reasons for this decision is that applications in many
1778 * cases need special handling to deal with the case where
1779 * <envar>HOME</envar> is
1781 * <member>Not owned by the user</member>
1782 * <member>Not writeable</member>
1783 * <member>Not even readable</member>
1785 * Since applications are in general <emphasis>not</emphasis> written
1786 * to deal with these situations it was considered better to make
1787 * g_get_homedir() not pay attention to <envar>HOME</envar> and to
1788 * return the real home directory for the user. If applications
1789 * want to pay attention to <envar>HOME</envar>, they can do:
1791 * const char *homedir = g_getenv ("HOME");
1793 * homedir = g_get_homedir (<!-- -->);
1796 * Returns: the current user's home directory
1798 G_CONST_RETURN gchar*
1799 g_get_home_dir (void)
1801 g_get_any_init_locked ();
1808 * Gets the directory to use for temporary files. This is found from
1809 * inspecting the environment variables <envar>TMPDIR</envar>,
1810 * <envar>TMP</envar>, and <envar>TEMP</envar> in that order. If none
1811 * of those are defined "/tmp" is returned on UNIX and "C:\" on Windows.
1812 * The encoding of the returned string is system-defined. On Windows,
1813 * it is always UTF-8. The return value is never %NULL.
1815 * Returns: the directory to use for temporary files.
1817 G_CONST_RETURN gchar*
1818 g_get_tmp_dir (void)
1820 g_get_any_init_locked ();
1827 * Return a name for the machine.
1829 * The returned name is not necessarily a fully-qualified domain name,
1830 * or even present in DNS or some other name service at all. It need
1831 * not even be unique on your local network or site, but usually it
1832 * is. Callers should not rely on the return value having any specific
1833 * properties like uniqueness for security purposes. Even if the name
1834 * of the machine is changed while an application is running, the
1835 * return value from this function does not change. The returned
1836 * string is owned by GLib and should not be modified or freed. If no
1837 * name can be determined, a default fixed string "localhost" is
1840 * Returns: the host name of the machine.
1845 g_get_host_name (void)
1847 g_get_any_init_locked ();
1851 G_LOCK_DEFINE_STATIC (g_prgname);
1852 static gchar *g_prgname = NULL;
1857 * Gets the name of the program. This name should <emphasis>not</emphasis>
1858 * be localized, contrast with g_get_application_name().
1859 * (If you are using GDK or GTK+ the program name is set in gdk_init(),
1860 * which is called by gtk_init(). The program name is found by taking
1861 * the last component of <literal>argv[0]</literal>.)
1863 * Returns: the name of the program. The returned string belongs
1864 * to GLib and must not be modified or freed.
1867 g_get_prgname (void)
1873 if (g_prgname == NULL)
1875 static gboolean beenhere = FALSE;
1879 gchar *utf8_buf = NULL;
1880 wchar_t buf[MAX_PATH+1];
1883 if (GetModuleFileNameW (GetModuleHandle (NULL),
1884 buf, G_N_ELEMENTS (buf)) > 0)
1885 utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
1889 g_prgname = g_path_get_basename (utf8_buf);
1896 G_UNLOCK (g_prgname);
1903 * @prgname: the name of the program.
1905 * Sets the name of the program. This name should <emphasis>not</emphasis>
1906 * be localized, contrast with g_set_application_name(). Note that for
1907 * thread-safety reasons this function can only be called once.
1910 g_set_prgname (const gchar *prgname)
1914 g_prgname = g_strdup (prgname);
1915 G_UNLOCK (g_prgname);
1918 G_LOCK_DEFINE_STATIC (g_application_name);
1919 static gchar *g_application_name = NULL;
1922 * g_get_application_name:
1924 * Gets a human-readable name for the application, as set by
1925 * g_set_application_name(). This name should be localized if
1926 * possible, and is intended for display to the user. Contrast with
1927 * g_get_prgname(), which gets a non-localized name. If
1928 * g_set_application_name() has not been called, returns the result of
1929 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1932 * Return value: human-readable application name. may return %NULL
1936 G_CONST_RETURN gchar*
1937 g_get_application_name (void)
1941 G_LOCK (g_application_name);
1942 retval = g_application_name;
1943 G_UNLOCK (g_application_name);
1946 return g_get_prgname ();
1952 * g_set_application_name:
1953 * @application_name: localized name of the application
1955 * Sets a human-readable name for the application. This name should be
1956 * localized if possible, and is intended for display to the user.
1957 * Contrast with g_set_prgname(), which sets a non-localized name.
1958 * g_set_prgname() will be called automatically by gtk_init(),
1959 * but g_set_application_name() will not.
1961 * Note that for thread safety reasons, this function can only
1964 * The application name will be used in contexts such as error messages,
1965 * or when displaying an application's name in the task list.
1970 g_set_application_name (const gchar *application_name)
1972 gboolean already_set = FALSE;
1974 G_LOCK (g_application_name);
1975 if (g_application_name)
1978 g_application_name = g_strdup (application_name);
1979 G_UNLOCK (g_application_name);
1982 g_warning ("g_set_application() name called multiple times");
1986 * g_get_user_data_dir:
1988 * Returns a base directory in which to access application data such
1989 * as icons that is customized for a particular user.
1991 * On UNIX platforms this is determined using the mechanisms described in
1992 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1993 * XDG Base Directory Specification</ulink>
1995 * Return value: a string owned by GLib that must not be modified
1999 G_CONST_RETURN gchar*
2000 g_get_user_data_dir (void)
2004 G_LOCK (g_utils_global);
2006 if (!g_user_data_dir)
2009 data_dir = get_special_folder (CSIDL_PERSONAL);
2011 data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
2013 if (data_dir && data_dir[0])
2014 data_dir = g_strdup (data_dir);
2016 if (!data_dir || !data_dir[0])
2021 data_dir = g_build_filename (g_home_dir, ".local",
2024 data_dir = g_build_filename (g_tmp_dir, g_user_name, ".local",
2028 g_user_data_dir = data_dir;
2031 data_dir = g_user_data_dir;
2033 G_UNLOCK (g_utils_global);
2039 g_init_user_config_dir (void)
2043 if (!g_user_config_dir)
2046 config_dir = get_special_folder (CSIDL_APPDATA);
2048 config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
2050 if (config_dir && config_dir[0])
2051 config_dir = g_strdup (config_dir);
2053 if (!config_dir || !config_dir[0])
2058 config_dir = g_build_filename (g_home_dir, ".config", NULL);
2060 config_dir = g_build_filename (g_tmp_dir, g_user_name, ".config", NULL);
2063 g_user_config_dir = config_dir;
2068 * g_get_user_config_dir:
2070 * Returns a base directory in which to store user-specific application
2071 * configuration information such as user preferences and settings.
2073 * On UNIX platforms this is determined using the mechanisms described in
2074 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2075 * XDG Base Directory Specification</ulink>
2077 * Return value: a string owned by GLib that must not be modified
2081 G_CONST_RETURN gchar*
2082 g_get_user_config_dir (void)
2084 G_LOCK (g_utils_global);
2086 g_init_user_config_dir ();
2088 G_UNLOCK (g_utils_global);
2090 return g_user_config_dir;
2094 * g_get_user_cache_dir:
2096 * Returns a base directory in which to store non-essential, cached
2097 * data specific to particular user.
2099 * On UNIX platforms this is determined using the mechanisms described in
2100 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2101 * XDG Base Directory Specification</ulink>
2103 * Return value: a string owned by GLib that must not be modified
2107 G_CONST_RETURN gchar*
2108 g_get_user_cache_dir (void)
2112 G_LOCK (g_utils_global);
2114 if (!g_user_cache_dir)
2117 cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
2119 cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
2121 if (cache_dir && cache_dir[0])
2122 cache_dir = g_strdup (cache_dir);
2124 if (!cache_dir || !cache_dir[0])
2129 cache_dir = g_build_filename (g_home_dir, ".cache", NULL);
2131 cache_dir = g_build_filename (g_tmp_dir, g_user_name, ".cache", NULL);
2133 g_user_cache_dir = cache_dir;
2136 cache_dir = g_user_cache_dir;
2138 G_UNLOCK (g_utils_global);
2146 find_folder (OSType type)
2148 gchar *filename = NULL;
2151 if (FSFindFolder (kUserDomain, type, kDontCreateFolder, &found) == noErr)
2153 CFURLRef url = CFURLCreateFromFSRef (kCFAllocatorSystemDefault, &found);
2157 CFStringRef path = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle);
2161 filename = g_strdup (CFStringGetCStringPtr (path, kCFStringEncodingUTF8));
2165 filename = g_new0 (gchar, CFStringGetLength (path) * 3 + 1);
2167 CFStringGetCString (path, filename,
2168 CFStringGetLength (path) * 3 + 1,
2169 kCFStringEncodingUTF8);
2183 load_user_special_dirs (void)
2185 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = find_folder (kDesktopFolderType);
2186 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = find_folder (kDocumentsFolderType);
2187 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = find_folder (kDesktopFolderType); /* XXX correct ? */
2188 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = find_folder (kMusicDocumentsFolderType);
2189 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = find_folder (kPictureDocumentsFolderType);
2190 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = NULL;
2191 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = NULL;
2192 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = find_folder (kMovieDocumentsFolderType);
2195 #endif /* HAVE_CARBON */
2197 #if defined(G_OS_WIN32)
2199 load_user_special_dirs (void)
2201 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2202 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
2203 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY); /* XXX correct ? */
2204 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
2205 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
2206 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS); /* XXX correct ? */
2207 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
2208 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
2210 #endif /* G_OS_WIN32 */
2212 static void g_init_user_config_dir (void);
2214 #if defined(G_OS_UNIX) && !defined(HAVE_CARBON)
2216 /* adapted from xdg-user-dir-lookup.c
2218 * Copyright (C) 2007 Red Hat Inc.
2220 * Permission is hereby granted, free of charge, to any person
2221 * obtaining a copy of this software and associated documentation files
2222 * (the "Software"), to deal in the Software without restriction,
2223 * including without limitation the rights to use, copy, modify, merge,
2224 * publish, distribute, sublicense, and/or sell copies of the Software,
2225 * and to permit persons to whom the Software is furnished to do so,
2226 * subject to the following conditions:
2228 * The above copyright notice and this permission notice shall be
2229 * included in all copies or substantial portions of the Software.
2231 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
2232 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
2233 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
2234 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
2235 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
2236 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
2237 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2241 load_user_special_dirs (void)
2248 g_init_user_config_dir ();
2249 config_file = g_build_filename (g_user_config_dir,
2253 if (!g_file_get_contents (config_file, &data, NULL, NULL))
2255 g_free (config_file);
2259 lines = g_strsplit (data, "\n", -1);
2260 n_lines = g_strv_length (lines);
2263 for (i = 0; i < n_lines; i++)
2265 gchar *buffer = lines[i];
2268 gboolean is_relative = FALSE;
2269 GUserDirectory directory;
2271 /* Remove newline at end */
2272 len = strlen (buffer);
2273 if (len > 0 && buffer[len - 1] == '\n')
2274 buffer[len - 1] = 0;
2277 while (*p == ' ' || *p == '\t')
2280 if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
2282 directory = G_USER_DIRECTORY_DESKTOP;
2283 p += strlen ("XDG_DESKTOP_DIR");
2285 else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
2287 directory = G_USER_DIRECTORY_DOCUMENTS;
2288 p += strlen ("XDG_DOCUMENTS_DIR");
2290 else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
2292 directory = G_USER_DIRECTORY_DOWNLOAD;
2293 p += strlen ("XDG_DOWNLOAD_DIR");
2295 else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
2297 directory = G_USER_DIRECTORY_MUSIC;
2298 p += strlen ("XDG_MUSIC_DIR");
2300 else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
2302 directory = G_USER_DIRECTORY_PICTURES;
2303 p += strlen ("XDG_PICTURES_DIR");
2305 else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
2307 directory = G_USER_DIRECTORY_PUBLIC_SHARE;
2308 p += strlen ("XDG_PUBLICSHARE_DIR");
2310 else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
2312 directory = G_USER_DIRECTORY_TEMPLATES;
2313 p += strlen ("XDG_TEMPLATES_DIR");
2315 else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
2317 directory = G_USER_DIRECTORY_VIDEOS;
2318 p += strlen ("XDG_VIDEOS_DIR");
2323 while (*p == ' ' || *p == '\t')
2330 while (*p == ' ' || *p == '\t')
2337 if (strncmp (p, "$HOME", 5) == 0)
2345 d = strrchr (p, '"');
2352 /* remove trailing slashes */
2354 if (d[len - 1] == '/')
2360 g_user_special_dirs[directory] = g_build_filename (g_home_dir, d, NULL);
2363 g_user_special_dirs[directory] = g_strdup (d);
2367 g_free (config_file);
2370 #endif /* G_OS_UNIX && !HAVE_CARBON */
2373 * g_get_user_special_dir:
2374 * @directory: the logical id of special directory
2376 * Returns the full path of a special directory using its logical id.
2378 * On Unix this is done using the XDG special user directories.
2380 * Depending on the platform, the user might be able to change the path
2381 * of the special directory without requiring the session to restart; GLib
2382 * will not reflect any change once the special directories are loaded.
2384 * Return value: the path to the specified special directory, or %NULL
2385 * if the logical id was not found. The returned string is owned by
2386 * GLib and should not be modified or freed.
2390 G_CONST_RETURN gchar *
2391 g_get_user_special_dir (GUserDirectory directory)
2393 g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
2394 directory < G_USER_N_DIRECTORIES, NULL);
2396 G_LOCK (g_utils_global);
2398 if (G_UNLIKELY (g_user_special_dirs == NULL))
2400 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
2402 load_user_special_dirs ();
2404 /* Special-case desktop for historical compatibility */
2405 if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
2409 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] =
2410 g_build_filename (g_home_dir, "Desktop", NULL);
2414 G_UNLOCK (g_utils_global);
2416 return g_user_special_dirs[directory];
2421 #undef g_get_system_data_dirs
2424 get_module_for_address (gconstpointer address)
2426 /* Holds the g_utils_global lock */
2428 static gboolean beenhere = FALSE;
2429 typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
2430 static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
2438 p_GetModuleHandleExA =
2439 (t_GetModuleHandleExA) GetProcAddress (LoadLibrary ("kernel32.dll"),
2440 "GetModuleHandleExA");
2444 if (p_GetModuleHandleExA == NULL ||
2445 !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
2446 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
2449 MEMORY_BASIC_INFORMATION mbi;
2450 VirtualQuery (address, &mbi, sizeof (mbi));
2451 hmodule = (HMODULE) mbi.AllocationBase;
2458 get_module_share_dir (gconstpointer address)
2461 gchar *filename = NULL;
2463 wchar_t wfilename[MAX_PATH];
2465 hmodule = get_module_for_address (address);
2466 if (hmodule == NULL)
2469 if (GetModuleFileNameW (hmodule, wfilename, G_N_ELEMENTS (wfilename)))
2470 filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
2472 if (filename == NULL)
2475 if ((p = strrchr (filename, G_DIR_SEPARATOR)) != NULL)
2478 p = strrchr (filename, G_DIR_SEPARATOR);
2479 if (p && (g_ascii_strcasecmp (p + 1, "bin") == 0))
2482 retval = g_build_filename (filename, "share", NULL);
2488 G_CONST_RETURN gchar * G_CONST_RETURN *
2489 g_win32_get_system_data_dirs_for_module (gconstpointer address)
2493 static GHashTable *per_module_data_dirs = NULL;
2499 G_LOCK (g_utils_global);
2500 hmodule = get_module_for_address (address);
2501 if (hmodule != NULL)
2503 if (per_module_data_dirs == NULL)
2504 per_module_data_dirs = g_hash_table_new (NULL, NULL);
2507 retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
2511 G_UNLOCK (g_utils_global);
2512 return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2518 data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
2520 /* Documents and Settings\All Users\Application Data */
2521 p = get_special_folder (CSIDL_COMMON_APPDATA);
2523 g_array_append_val (data_dirs, p);
2525 /* Documents and Settings\All Users\Documents */
2526 p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2528 g_array_append_val (data_dirs, p);
2530 /* Using the above subfolders of Documents and Settings perhaps
2531 * makes sense from a Windows perspective.
2533 * But looking at the actual use cases of this function in GTK+
2534 * and GNOME software, what we really want is the "share"
2535 * subdirectory of the installation directory for the package
2536 * our caller is a part of.
2538 * The address parameter, if non-NULL, points to a function in the
2539 * calling module. Use that to determine that module's installation
2540 * folder, and use its "share" subfolder.
2542 * Additionally, also use the "share" subfolder of the installation
2543 * locations of GLib and the .exe file being run.
2545 * To guard against none of the above being what is really wanted,
2546 * callers of this function should have Win32-specific code to look
2547 * up their installation folder themselves, and handle a subfolder
2548 * "share" of it in the same way as the folders returned from this
2552 p = get_module_share_dir (address);
2554 g_array_append_val (data_dirs, p);
2556 p = g_win32_get_package_installation_subdirectory (NULL, dll_name, "share");
2558 g_array_append_val (data_dirs, p);
2560 p = g_win32_get_package_installation_subdirectory (NULL, NULL, "share");
2562 g_array_append_val (data_dirs, p);
2564 retval = (gchar **) g_array_free (data_dirs, FALSE);
2568 if (hmodule != NULL)
2569 g_hash_table_insert (per_module_data_dirs, hmodule, retval);
2570 G_UNLOCK (g_utils_global);
2573 return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2579 * g_get_system_data_dirs:
2581 * Returns an ordered list of base directories in which to access
2582 * system-wide application data.
2584 * On UNIX platforms this is determined using the mechanisms described in
2585 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2586 * XDG Base Directory Specification</ulink>
2588 * On Windows the first elements in the list are the Application Data
2589 * and Documents folders for All Users. (These can be determined only
2590 * on Windows 2000 or later and are not present in the list on other
2591 * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
2592 * CSIDL_COMMON_DOCUMENTS.
2594 * Then follows the "share" subfolder in the installation folder for
2595 * the package containing the DLL that calls this function, if it can
2598 * Finally the list contains the "share" subfolder in the installation
2599 * folder for GLib, and in the installation folder for the package the
2600 * application's .exe file belongs to.
2602 * The installation folders above are determined by looking up the
2603 * folder where the module (DLL or EXE) in question is located. If the
2604 * folder's name is "bin", its parent is used, otherwise the folder
2607 * Note that on Windows the returned list can vary depending on where
2608 * this function is called.
2610 * Return value: a %NULL-terminated array of strings owned by GLib that must
2611 * not be modified or freed.
2614 G_CONST_RETURN gchar * G_CONST_RETURN *
2615 g_get_system_data_dirs (void)
2617 gchar **data_dir_vector;
2619 G_LOCK (g_utils_global);
2621 if (!g_system_data_dirs)
2624 data_dir_vector = (gchar **) g_win32_get_system_data_dirs_for_module (NULL);
2626 gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
2628 if (!data_dirs || !data_dirs[0])
2629 data_dirs = "/usr/local/share/:/usr/share/";
2631 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2634 g_system_data_dirs = data_dir_vector;
2637 data_dir_vector = g_system_data_dirs;
2639 G_UNLOCK (g_utils_global);
2641 return (G_CONST_RETURN gchar * G_CONST_RETURN *) data_dir_vector;
2645 * g_get_system_config_dirs:
2647 * Returns an ordered list of base directories in which to access
2648 * system-wide configuration information.
2650 * On UNIX platforms this is determined using the mechanisms described in
2651 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2652 * XDG Base Directory Specification</ulink>
2654 * Return value: a %NULL-terminated array of strings owned by GLib that must
2655 * not be modified or freed.
2658 G_CONST_RETURN gchar * G_CONST_RETURN *
2659 g_get_system_config_dirs (void)
2661 gchar *conf_dirs, **conf_dir_vector;
2663 G_LOCK (g_utils_global);
2665 if (!g_system_config_dirs)
2668 conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
2671 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2676 /* Return empty list */
2677 conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2680 conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
2682 if (!conf_dirs || !conf_dirs[0])
2683 conf_dirs = "/etc/xdg";
2685 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2688 g_system_config_dirs = conf_dir_vector;
2691 conf_dir_vector = g_system_config_dirs;
2692 G_UNLOCK (g_utils_global);
2694 return (G_CONST_RETURN gchar * G_CONST_RETURN *) conf_dir_vector;
2699 static GHashTable *alias_table = NULL;
2701 /* read an alias file for the locales */
2703 read_aliases (gchar *file)
2709 alias_table = g_hash_table_new (g_str_hash, g_str_equal);
2710 fp = fopen (file,"r");
2713 while (fgets (buf, 256, fp))
2719 /* Line is a comment */
2720 if ((buf[0] == '#') || (buf[0] == '\0'))
2723 /* Reads first column */
2724 for (p = buf, q = NULL; *p; p++) {
2725 if ((*p == '\t') || (*p == ' ') || (*p == ':')) {
2728 while ((*q == '\t') || (*q == ' ')) {
2734 /* The line only had one column */
2735 if (!q || *q == '\0')
2738 /* Read second column */
2739 for (p = q; *p; p++) {
2740 if ((*p == '\t') || (*p == ' ')) {
2746 /* Add to alias table if necessary */
2747 if (!g_hash_table_lookup (alias_table, buf)) {
2748 g_hash_table_insert (alias_table, g_strdup (buf), g_strdup (q));
2757 unalias_lang (char *lang)
2764 read_aliases ("/usr/share/locale/locale.alias");
2767 while ((p = g_hash_table_lookup (alias_table, lang)) && (strcmp (p, lang) != 0))
2772 static gboolean said_before = FALSE;
2774 g_warning ("Too many alias levels for a locale, "
2775 "may indicate a loop");
2784 /* Mask for components of locale spec. The ordering here is from
2785 * least significant to most significant
2789 COMPONENT_CODESET = 1 << 0,
2790 COMPONENT_TERRITORY = 1 << 1,
2791 COMPONENT_MODIFIER = 1 << 2
2794 /* Break an X/Open style locale specification into components
2797 explode_locale (const gchar *locale,
2803 const gchar *uscore_pos;
2804 const gchar *at_pos;
2805 const gchar *dot_pos;
2809 uscore_pos = strchr (locale, '_');
2810 dot_pos = strchr (uscore_pos ? uscore_pos : locale, '.');
2811 at_pos = strchr (dot_pos ? dot_pos : (uscore_pos ? uscore_pos : locale), '@');
2815 mask |= COMPONENT_MODIFIER;
2816 *modifier = g_strdup (at_pos);
2819 at_pos = locale + strlen (locale);
2823 mask |= COMPONENT_CODESET;
2824 *codeset = g_strndup (dot_pos, at_pos - dot_pos);
2831 mask |= COMPONENT_TERRITORY;
2832 *territory = g_strndup (uscore_pos, dot_pos - uscore_pos);
2835 uscore_pos = dot_pos;
2837 *language = g_strndup (locale, uscore_pos - locale);
2843 * Compute all interesting variants for a given locale name -
2844 * by stripping off different components of the value.
2846 * For simplicity, we assume that the locale is in
2847 * X/Open format: language[_territory][.codeset][@modifier]
2849 * TODO: Extend this to handle the CEN format (see the GNUlibc docs)
2850 * as well. We could just copy the code from glibc wholesale
2851 * but it is big, ugly, and complicated, so I'm reluctant
2852 * to do so when this should handle 99% of the time...
2855 _g_compute_locale_variants (const gchar *locale)
2857 GSList *retval = NULL;
2859 gchar *language = NULL;
2860 gchar *territory = NULL;
2861 gchar *codeset = NULL;
2862 gchar *modifier = NULL;
2867 g_return_val_if_fail (locale != NULL, NULL);
2869 mask = explode_locale (locale, &language, &territory, &codeset, &modifier);
2871 /* Iterate through all possible combinations, from least attractive
2872 * to most attractive.
2874 for (i = 0; i <= mask; i++)
2875 if ((i & ~mask) == 0)
2877 gchar *val = g_strconcat (language,
2878 (i & COMPONENT_TERRITORY) ? territory : "",
2879 (i & COMPONENT_CODESET) ? codeset : "",
2880 (i & COMPONENT_MODIFIER) ? modifier : "",
2882 retval = g_slist_prepend (retval, val);
2886 if (mask & COMPONENT_CODESET)
2888 if (mask & COMPONENT_TERRITORY)
2890 if (mask & COMPONENT_MODIFIER)
2896 /* The following is (partly) taken from the gettext package.
2897 Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc. */
2899 static const gchar *
2900 guess_category_value (const gchar *category_name)
2902 const gchar *retval;
2904 /* The highest priority value is the `LANGUAGE' environment
2905 variable. This is a GNU extension. */
2906 retval = g_getenv ("LANGUAGE");
2907 if ((retval != NULL) && (retval[0] != '\0'))
2910 /* `LANGUAGE' is not set. So we have to proceed with the POSIX
2911 methods of looking to `LC_ALL', `LC_xxx', and `LANG'. On some
2912 systems this can be done by the `setlocale' function itself. */
2914 /* Setting of LC_ALL overwrites all other. */
2915 retval = g_getenv ("LC_ALL");
2916 if ((retval != NULL) && (retval[0] != '\0'))
2919 /* Next comes the name of the desired category. */
2920 retval = g_getenv (category_name);
2921 if ((retval != NULL) && (retval[0] != '\0'))
2924 /* Last possibility is the LANG environment variable. */
2925 retval = g_getenv ("LANG");
2926 if ((retval != NULL) && (retval[0] != '\0'))
2929 #ifdef G_PLATFORM_WIN32
2930 /* g_win32_getlocale() first checks for LC_ALL, LC_MESSAGES and
2931 * LANG, which we already did above. Oh well. The main point of
2932 * calling g_win32_getlocale() is to get the thread's locale as used
2933 * by Windows and the Microsoft C runtime (in the "English_United
2934 * States" format) translated into the Unixish format.
2936 retval = g_win32_getlocale ();
2937 if ((retval != NULL) && (retval[0] != '\0'))
2944 typedef struct _GLanguageNamesCache GLanguageNamesCache;
2946 struct _GLanguageNamesCache {
2948 gchar **language_names;
2952 language_names_cache_free (gpointer data)
2954 GLanguageNamesCache *cache = data;
2955 g_free (cache->languages);
2956 g_strfreev (cache->language_names);
2961 * g_get_language_names:
2963 * Computes a list of applicable locale names, which can be used to
2964 * e.g. construct locale-dependent filenames or search paths. The returned
2965 * list is sorted from most desirable to least desirable and always contains
2966 * the default locale "C".
2968 * For example, if LANGUAGE=de:en_US, then the returned list is
2969 * "de", "en_US", "en", "C".
2971 * This function consults the environment variables <envar>LANGUAGE</envar>,
2972 * <envar>LC_ALL</envar>, <envar>LC_MESSAGES</envar> and <envar>LANG</envar>
2973 * to find the list of locales specified by the user.
2975 * Return value: a %NULL-terminated array of strings owned by GLib
2976 * that must not be modified or freed.
2980 G_CONST_RETURN gchar * G_CONST_RETURN *
2981 g_get_language_names (void)
2983 static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
2984 GLanguageNamesCache *cache = g_static_private_get (&cache_private);
2989 cache = g_new0 (GLanguageNamesCache, 1);
2990 g_static_private_set (&cache_private, cache, language_names_cache_free);
2993 value = guess_category_value ("LC_MESSAGES");
2997 if (!(cache->languages && strcmp (cache->languages, value) == 0))
3004 g_free (cache->languages);
3005 g_strfreev (cache->language_names);
3006 cache->languages = g_strdup (value);
3008 alist = g_strsplit (value, ":", 0);
3010 for (a = alist; *a; a++)
3012 gchar *b = unalias_lang (*a);
3013 list = g_slist_concat (list, _g_compute_locale_variants (b));
3016 list = g_slist_append (list, g_strdup ("C"));
3018 cache->language_names = languages = g_new (gchar *, g_slist_length (list) + 1);
3019 for (l = list, i = 0; l; l = l->next, i++)
3020 languages[i] = l->data;
3021 languages[i] = NULL;
3023 g_slist_free (list);
3026 return (G_CONST_RETURN gchar * G_CONST_RETURN *) cache->language_names;
3031 * @v: a #gpointer key
3033 * Converts a gpointer to a hash value.
3034 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3035 * when using pointers as keys in a #GHashTable.
3037 * Returns: a hash value corresponding to the key.
3040 g_direct_hash (gconstpointer v)
3042 return GPOINTER_TO_UINT (v);
3048 * @v2: a key to compare with @v1.
3050 * Compares two #gpointer arguments and returns %TRUE if they are equal.
3051 * It can be passed to g_hash_table_new() as the @key_equal_func
3052 * parameter, when using pointers as keys in a #GHashTable.
3054 * Returns: %TRUE if the two keys match.
3057 g_direct_equal (gconstpointer v1,
3065 * @v1: a pointer to a #gint key.
3066 * @v2: a pointer to a #gint key to compare with @v1.
3068 * Compares the two #gint values being pointed to and returns
3069 * %TRUE if they are equal.
3070 * It can be passed to g_hash_table_new() as the @key_equal_func
3071 * parameter, when using pointers to integers as keys in a #GHashTable.
3073 * Returns: %TRUE if the two keys match.
3076 g_int_equal (gconstpointer v1,
3079 return *((const gint*) v1) == *((const gint*) v2);
3084 * @v: a pointer to a #gint key
3086 * Converts a pointer to a #gint to a hash value.
3087 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3088 * when using pointers to integers values as keys in a #GHashTable.
3090 * Returns: a hash value corresponding to the key.
3093 g_int_hash (gconstpointer v)
3095 return *(const gint*) v;
3099 * g_nullify_pointer:
3100 * @nullify_location: the memory address of the pointer.
3102 * Set the pointer at the specified location to %NULL.
3105 g_nullify_pointer (gpointer *nullify_location)
3107 g_return_if_fail (nullify_location != NULL);
3109 *nullify_location = NULL;
3115 * Get the codeset for the current locale.
3117 * Return value: a newly allocated string containing the name
3118 * of the codeset. This string must be freed with g_free().
3121 g_get_codeset (void)
3123 const gchar *charset;
3125 g_get_charset (&charset);
3127 return g_strdup (charset);
3130 /* This is called from g_thread_init(). It's used to
3131 * initialize some static data in a threadsafe way.
3134 _g_utils_thread_init (void)
3136 g_get_language_names ();
3142 * _glib_get_locale_dir:
3144 * Return the path to the share\locale or lib\locale subfolder of the
3145 * GLib installation folder. The path is in the system codepage. We
3146 * have to use system codepage as bindtextdomain() doesn't have a
3150 _glib_get_locale_dir (void)
3152 gchar *install_dir, *locale_dir;
3153 gchar *retval = NULL;
3155 install_dir = g_win32_get_package_installation_directory (GETTEXT_PACKAGE, dll_name);
3160 * Append "/share/locale" or "/lib/locale" depending on whether
3161 * autoconfigury detected GNU gettext or not.
3163 const char *p = GLIB_LOCALE_DIR + strlen (GLIB_LOCALE_DIR);
3169 locale_dir = g_build_filename (install_dir, p, NULL);
3171 retval = g_win32_locale_filename_from_utf8 (locale_dir);
3173 g_free (install_dir);
3174 g_free (locale_dir);
3180 return g_strdup ("");
3183 #undef GLIB_LOCALE_DIR
3185 #endif /* G_OS_WIN32 */
3189 * @str: The string to be translated
3191 * Returns the translated string from the glib translations.
3192 * This is an internal function and should only be used by
3193 * the internals of glib (such as libgio).
3195 * Returns: the transation of @str to the current locale
3197 G_CONST_RETURN gchar *
3198 glib_gettext (const gchar *str)
3200 static gboolean _glib_gettext_initialized = FALSE;
3202 if (!_glib_gettext_initialized)
3205 gchar *tmp = _glib_get_locale_dir ();
3206 bindtextdomain (GETTEXT_PACKAGE, tmp);
3209 bindtextdomain (GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
3211 # ifdef HAVE_BIND_TEXTDOMAIN_CODESET
3212 bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
3214 _glib_gettext_initialized = TRUE;
3217 return dgettext (GETTEXT_PACKAGE, str);
3222 /* Binary compatibility versions. Not for newly compiled code. */
3224 #undef g_find_program_in_path
3227 g_find_program_in_path (const gchar *program)
3229 gchar *utf8_program = g_locale_to_utf8 (program, -1, NULL, NULL, NULL);
3230 gchar *utf8_retval = g_find_program_in_path_utf8 (utf8_program);
3233 g_free (utf8_program);
3234 if (utf8_retval == NULL)
3236 retval = g_locale_from_utf8 (utf8_retval, -1, NULL, NULL, NULL);
3237 g_free (utf8_retval);
3242 #undef g_get_current_dir
3245 g_get_current_dir (void)
3247 gchar *utf8_dir = g_get_current_dir_utf8 ();
3248 gchar *dir = g_locale_from_utf8 (utf8_dir, -1, NULL, NULL, NULL);
3255 G_CONST_RETURN gchar*
3256 g_getenv (const gchar *variable)
3258 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3259 const gchar *utf8_value = g_getenv_utf8 (utf8_variable);
3263 g_free (utf8_variable);
3266 value = g_locale_from_utf8 (utf8_value, -1, NULL, NULL, NULL);
3267 quark = g_quark_from_string (value);
3270 return g_quark_to_string (quark);
3276 g_setenv (const gchar *variable,
3280 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3281 gchar *utf8_value = g_locale_to_utf8 (value, -1, NULL, NULL, NULL);
3282 gboolean retval = g_setenv_utf8 (utf8_variable, utf8_value, overwrite);
3284 g_free (utf8_variable);
3285 g_free (utf8_value);
3293 g_unsetenv (const gchar *variable)
3295 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3297 g_unsetenv_utf8 (utf8_variable);
3299 g_free (utf8_variable);
3302 #undef g_get_user_name
3304 G_CONST_RETURN gchar*
3305 g_get_user_name (void)
3307 g_get_any_init_locked ();
3308 return g_user_name_cp;
3311 #undef g_get_real_name
3313 G_CONST_RETURN gchar*
3314 g_get_real_name (void)
3316 g_get_any_init_locked ();
3317 return g_real_name_cp;
3320 #undef g_get_home_dir
3322 G_CONST_RETURN gchar*
3323 g_get_home_dir (void)
3325 g_get_any_init_locked ();
3326 return g_home_dir_cp;
3329 #undef g_get_tmp_dir
3331 G_CONST_RETURN gchar*
3332 g_get_tmp_dir (void)
3334 g_get_any_init_locked ();
3335 return g_tmp_dir_cp;
3340 #define __G_UTILS_C__
3341 #include "galiasdef.c"