1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1998 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the
16 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 * Boston, MA 02111-1307, USA.
21 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
22 * file for a list of people on the GLib Team. See the ChangeLog
23 * files for a list of changes. These files are distributed with
24 * GLib at ftp://ftp.gtk.org/pub/gtk/.
28 * MT safe for the unix part, FIXME: make the win32 part MT safe as well.
41 #include <ctype.h> /* For tolower() */
43 #include <sys/types.h>
48 #include <sys/types.h>
49 #ifdef HAVE_SYS_PARAM_H
50 #include <sys/param.h>
52 #ifdef HAVE_CRT_EXTERNS_H
53 #include <crt_externs.h> /* for _NSGetEnviron */
56 /* implement gutils's inline functions
58 #define G_IMPLEMENT_INLINES 1
61 #include "gprintfint.h"
62 #include "gthreadprivate.h"
67 #define G_PATH_LENGTH MAXPATHLEN
68 #elif defined (PATH_MAX)
69 #define G_PATH_LENGTH PATH_MAX
70 #elif defined (_PC_PATH_MAX)
71 #define G_PATH_LENGTH sysconf(_PC_PATH_MAX)
73 #define G_PATH_LENGTH 2048
76 #ifdef G_PLATFORM_WIN32
77 # define STRICT /* Strict typing, please */
80 # ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
81 # define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2
82 # define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4
84 # include <lmcons.h> /* For UNLEN */
85 #endif /* G_PLATFORM_WIN32 */
90 /* older SDK (e.g. msvc 5.0) does not have these*/
91 # ifndef CSIDL_MYMUSIC
92 # define CSIDL_MYMUSIC 13
94 # ifndef CSIDL_MYVIDEO
95 # define CSIDL_MYVIDEO 14
97 # ifndef CSIDL_INTERNET_CACHE
98 # define CSIDL_INTERNET_CACHE 32
100 # ifndef CSIDL_COMMON_APPDATA
101 # define CSIDL_COMMON_APPDATA 35
103 # ifndef CSIDL_MYPICTURES
104 # define CSIDL_MYPICTURES 0x27
106 # ifndef CSIDL_COMMON_DOCUMENTS
107 # define CSIDL_COMMON_DOCUMENTS 46
109 # ifndef CSIDL_PROFILE
110 # define CSIDL_PROFILE 40
112 # include <process.h>
116 #include <CoreServices/CoreServices.h>
120 #include <langinfo.h>
123 #ifdef HAVE_BIND_TEXTDOMAIN_CODESET
127 const guint glib_major_version = GLIB_MAJOR_VERSION;
128 const guint glib_minor_version = GLIB_MINOR_VERSION;
129 const guint glib_micro_version = GLIB_MICRO_VERSION;
130 const guint glib_interface_age = GLIB_INTERFACE_AGE;
131 const guint glib_binary_age = GLIB_BINARY_AGE;
133 #ifdef G_PLATFORM_WIN32
135 static HMODULE glib_dll = NULL;
140 DllMain (HINSTANCE hinstDLL,
144 if (fdwReason == DLL_PROCESS_ATTACH)
153 _glib_get_installation_directory (void)
156 if (glib_dll == NULL)
159 /* In a static build of GLib just use the application's .exe file's
160 * installation directory...
162 return g_win32_get_package_installation_directory_of_module (glib_dll);
168 * glib_check_version:
169 * @required_major: the required major version.
170 * @required_minor: the required minor version.
171 * @required_micro: the required micro version.
173 * Checks that the GLib library in use is compatible with the
174 * given version. Generally you would pass in the constants
175 * #GLIB_MAJOR_VERSION, #GLIB_MINOR_VERSION, #GLIB_MICRO_VERSION
176 * as the three arguments to this function; that produces
177 * a check that the library in use is compatible with
178 * the version of GLib the application or module was compiled
181 * Compatibility is defined by two things: first the version
182 * of the running library is newer than the version
183 * @required_major.required_minor.@required_micro. Second
184 * the running library must be binary compatible with the
185 * version @required_major.required_minor.@required_micro
186 * (same major version.)
188 * Return value: %NULL if the GLib library is compatible with the
189 * given version, or a string describing the version mismatch.
190 * The returned string is owned by GLib and must not be modified
196 glib_check_version (guint required_major,
197 guint required_minor,
198 guint required_micro)
200 gint glib_effective_micro = 100 * GLIB_MINOR_VERSION + GLIB_MICRO_VERSION;
201 gint required_effective_micro = 100 * required_minor + required_micro;
203 if (required_major > GLIB_MAJOR_VERSION)
204 return "GLib version too old (major mismatch)";
205 if (required_major < GLIB_MAJOR_VERSION)
206 return "GLib version too new (major mismatch)";
207 if (required_effective_micro < glib_effective_micro - GLIB_BINARY_AGE)
208 return "GLib version too new (micro mismatch)";
209 if (required_effective_micro > glib_effective_micro)
210 return "GLib version too old (micro mismatch)";
214 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
217 * @dest: the destination address to copy the bytes to.
218 * @src: the source address to copy the bytes from.
219 * @len: the number of bytes to copy.
221 * Copies a block of memory @len bytes long, from @src to @dest.
222 * The source and destination areas may overlap.
224 * In order to use this function, you must include
225 * <filename>string.h</filename> yourself, because this macro will
226 * typically simply resolve to memmove() and GLib does not include
227 * <filename>string.h</filename> for you.
230 g_memmove (gpointer dest,
234 gchar* destptr = dest;
235 const gchar* srcptr = src;
236 if (src + len < dest || dest + len < src)
238 bcopy (src, dest, len);
241 else if (dest <= src)
244 *(destptr++) = *(srcptr++);
251 *(--destptr) = *(--srcptr);
254 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
262 * @func: the function to call on normal program termination.
264 * Specifies a function to be called at normal program termination.
266 * Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
267 * macro that maps to a call to the atexit() function in the C
268 * library. This means that in case the code that calls g_atexit(),
269 * i.e. atexit(), is in a DLL, the function will be called when the
270 * DLL is detached from the program. This typically makes more sense
271 * than that the function is called when the GLib DLL is detached,
272 * which happened earlier when g_atexit() was a function in the GLib
275 * The behaviour of atexit() in the context of dynamically loaded
276 * modules is not formally specified and varies wildly.
278 * On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
279 * loaded module which is unloaded before the program terminates might
280 * well cause a crash at program exit.
282 * Some POSIX systems implement atexit() like Windows, and have each
283 * dynamically loaded module maintain an own atexit chain that is
284 * called when the module is unloaded.
286 * On other POSIX systems, before a dynamically loaded module is
287 * unloaded, the registered atexit functions (if any) residing in that
288 * module are called, regardless where the code that registered them
289 * resided. This is presumably the most robust approach.
291 * As can be seen from the above, for portability it's best to avoid
292 * calling g_atexit() (or atexit()) except in the main executable of a
296 g_atexit (GVoidFunc func)
299 const gchar *error = NULL;
301 /* keep this in sync with glib.h */
303 #ifdef G_NATIVE_ATEXIT
304 result = ATEXIT (func);
306 error = g_strerror (errno);
307 #elif defined (HAVE_ATEXIT)
308 # ifdef NeXT /* @#%@! NeXTStep */
309 result = !atexit ((void (*)(void)) func);
311 error = g_strerror (errno);
313 result = atexit ((void (*)(void)) func);
315 error = g_strerror (errno);
317 #elif defined (HAVE_ON_EXIT)
318 result = on_exit ((void (*)(int, void *)) func, NULL);
320 error = g_strerror (errno);
323 error = "no implementation";
324 #endif /* G_NATIVE_ATEXIT */
327 g_error ("Could not register atexit() function: %s", error);
330 /* Based on execvp() from GNU Libc.
331 * Some of this code is cut-and-pasted into gspawn.c
335 my_strchrnul (const gchar *str,
338 gchar *p = (gchar*)str;
339 while (*p && (*p != c))
347 static gchar *inner_find_program_in_path (const gchar *program);
350 g_find_program_in_path (const gchar *program)
352 const gchar *last_dot = strrchr (program, '.');
354 if (last_dot == NULL ||
355 strchr (last_dot, '\\') != NULL ||
356 strchr (last_dot, '/') != NULL)
358 const gint program_length = strlen (program);
359 gchar *pathext = g_build_path (";",
360 ".exe;.cmd;.bat;.com",
361 g_getenv ("PATHEXT"),
364 gchar *decorated_program;
370 gchar *q = my_strchrnul (p, ';');
372 decorated_program = g_malloc (program_length + (q-p) + 1);
373 memcpy (decorated_program, program, program_length);
374 memcpy (decorated_program+program_length, p, q-p);
375 decorated_program [program_length + (q-p)] = '\0';
377 retval = inner_find_program_in_path (decorated_program);
378 g_free (decorated_program);
386 } while (*p++ != '\0');
391 return inner_find_program_in_path (program);
397 * g_find_program_in_path:
398 * @program: a program name in the GLib file name encoding
400 * Locates the first executable named @program in the user's path, in the
401 * same way that execvp() would locate it. Returns an allocated string
402 * with the absolute path name, or %NULL if the program is not found in
403 * the path. If @program is already an absolute path, returns a copy of
404 * @program if @program exists and is executable, and %NULL otherwise.
406 * On Windows, if @program does not have a file type suffix, tries
407 * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
408 * the <envar>PATHEXT</envar> environment variable.
410 * On Windows, it looks for the file in the same way as CreateProcess()
411 * would. This means first in the directory where the executing
412 * program was loaded from, then in the current directory, then in the
413 * Windows 32-bit system directory, then in the Windows directory, and
414 * finally in the directories in the <envar>PATH</envar> environment
415 * variable. If the program is found, the return value contains the
416 * full name including the type suffix.
418 * Return value: absolute path, or %NULL
422 inner_find_program_in_path (const gchar *program)
425 g_find_program_in_path (const gchar *program)
428 const gchar *path, *p;
429 gchar *name, *freeme;
431 const gchar *path_copy;
432 gchar *filename = NULL, *appdir = NULL;
433 gchar *sysdir = NULL, *windir = NULL;
435 wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
441 g_return_val_if_fail (program != NULL, NULL);
443 /* If it is an absolute path, or a relative path including subdirectories,
444 * don't look in PATH.
446 if (g_path_is_absolute (program)
447 || strchr (program, G_DIR_SEPARATOR) != NULL
449 || strchr (program, '/') != NULL
453 if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
454 !g_file_test (program, G_FILE_TEST_IS_DIR))
455 return g_strdup (program);
460 path = g_getenv ("PATH");
461 #if defined(G_OS_UNIX) || defined(G_OS_BEOS)
464 /* There is no `PATH' in the environment. The default
465 * search path in GNU libc is the current directory followed by
466 * the path `confstr' returns for `_CS_PATH'.
469 /* In GLib we put . last, for security, and don't use the
470 * unportable confstr(); UNIX98 does not actually specify
471 * what to search if PATH is unset. POSIX may, dunno.
474 path = "/bin:/usr/bin:.";
477 n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
478 if (n > 0 && n < MAXPATHLEN)
479 filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
481 n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
482 if (n > 0 && n < MAXPATHLEN)
483 sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
485 n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
486 if (n > 0 && n < MAXPATHLEN)
487 windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
491 appdir = g_path_get_dirname (filename);
495 path = g_strdup (path);
499 const gchar *tem = path;
500 path = g_strconcat (windir, ";", path, NULL);
501 g_free ((gchar *) tem);
507 const gchar *tem = path;
508 path = g_strconcat (sysdir, ";", path, NULL);
509 g_free ((gchar *) tem);
514 const gchar *tem = path;
515 path = g_strconcat (".;", path, NULL);
516 g_free ((gchar *) tem);
521 const gchar *tem = path;
522 path = g_strconcat (appdir, ";", path, NULL);
523 g_free ((gchar *) tem);
530 len = strlen (program) + 1;
531 pathlen = strlen (path);
532 freeme = name = g_malloc (pathlen + len + 1);
534 /* Copy the file name at the top, including '\0' */
535 memcpy (name + pathlen + 1, program, len);
536 name = name + pathlen;
537 /* And add the slash before the filename */
538 *name = G_DIR_SEPARATOR;
546 p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
549 /* Two adjacent colons, or a colon at the beginning or the end
550 * of `PATH' means to search the current directory.
554 startp = memcpy (name - (p - path), path, p - path);
556 if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
557 !g_file_test (startp, G_FILE_TEST_IS_DIR))
560 ret = g_strdup (startp);
563 g_free ((gchar *) path_copy);
568 while (*p++ != '\0');
572 g_free ((gchar *) path_copy);
579 debug_key_matches (const gchar *key,
583 for (; length; length--, key++, token++)
585 char k = (*key == '_') ? '-' : tolower (*key );
586 char t = (*token == '_') ? '-' : tolower (*token);
596 * g_parse_debug_string:
597 * @string: a list of debug options separated by colons, spaces, or
598 * commas; or the string "all" to set all flags, or %NULL.
599 * @keys: pointer to an array of #GDebugKey which associate
600 * strings with bit flags.
601 * @nkeys: the number of #GDebugKey<!-- -->s in the array.
603 * Parses a string containing debugging options
604 * into a %guint containing bit flags. This is used
605 * within GDK and GTK+ to parse the debug options passed on the
606 * command line or through environment variables.
608 * Returns: the combined set of bit flags.
611 g_parse_debug_string (const gchar *string,
612 const GDebugKey *keys,
621 /* this function is used by gmem.c/gslice.c initialization code,
622 * so introducing malloc dependencies here would require adaptions
623 * of those code portions.
626 if (!g_ascii_strcasecmp (string, "all"))
628 for (i=0; i<nkeys; i++)
629 result |= keys[i].value;
633 const gchar *p = string;
638 q = strpbrk (p, ":;, \t");
642 for (i = 0; i < nkeys; i++)
643 if (debug_key_matches (keys[i].key, p, q - p))
644 result |= keys[i].value;
657 * @file_name: the name of the file.
659 * Gets the name of the file without any leading directory components.
660 * It returns a pointer into the given file name string.
662 * Return value: the name of the file without any leading directory components.
664 * Deprecated:2.2: Use g_path_get_basename() instead, but notice that
665 * g_path_get_basename() allocates new memory for the returned string, unlike
666 * this function which returns a pointer into the argument.
668 G_CONST_RETURN gchar*
669 g_basename (const gchar *file_name)
671 register gchar *base;
673 g_return_val_if_fail (file_name != NULL, NULL);
675 base = strrchr (file_name, G_DIR_SEPARATOR);
679 gchar *q = strrchr (file_name, '/');
680 if (base == NULL || (q != NULL && q > base))
689 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
690 return (gchar*) file_name + 2;
691 #endif /* G_OS_WIN32 */
693 return (gchar*) file_name;
697 * g_path_get_basename:
698 * @file_name: the name of the file.
700 * Gets the last component of the filename. If @file_name ends with a
701 * directory separator it gets the component before the last slash. If
702 * @file_name consists only of directory separators (and on Windows,
703 * possibly a drive letter), a single separator is returned. If
704 * @file_name is empty, it gets ".".
706 * Return value: a newly allocated string containing the last component of
710 g_path_get_basename (const gchar *file_name)
712 register gssize base;
713 register gssize last_nonslash;
717 g_return_val_if_fail (file_name != NULL, NULL);
719 if (file_name[0] == '\0')
721 return g_strdup (".");
723 last_nonslash = strlen (file_name) - 1;
725 while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
728 if (last_nonslash == -1)
729 /* string only containing slashes */
730 return g_strdup (G_DIR_SEPARATOR_S);
733 if (last_nonslash == 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
734 /* string only containing slashes and a drive */
735 return g_strdup (G_DIR_SEPARATOR_S);
736 #endif /* G_OS_WIN32 */
738 base = last_nonslash;
740 while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
744 if (base == -1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
746 #endif /* G_OS_WIN32 */
748 len = last_nonslash - base;
749 retval = g_malloc (len + 1);
750 memcpy (retval, file_name + base + 1, len);
756 * g_path_is_absolute:
757 * @file_name: a file name.
759 * Returns %TRUE if the given @file_name is an absolute file name,
760 * i.e. it contains a full path from the root directory such as "/usr/local"
761 * on UNIX or "C:\windows" on Windows systems.
763 * Returns: %TRUE if @file_name is an absolute path.
766 g_path_is_absolute (const gchar *file_name)
768 g_return_val_if_fail (file_name != NULL, FALSE);
770 if (G_IS_DIR_SEPARATOR (file_name[0]))
774 /* Recognize drive letter on native Windows */
775 if (g_ascii_isalpha (file_name[0]) &&
776 file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
778 #endif /* G_OS_WIN32 */
785 * @file_name: a file name.
787 * Returns a pointer into @file_name after the root component, i.e. after
788 * the "/" in UNIX or "C:\" under Windows. If @file_name is not an absolute
789 * path it returns %NULL.
791 * Returns: a pointer into @file_name after the root component.
793 G_CONST_RETURN gchar*
794 g_path_skip_root (const gchar *file_name)
796 g_return_val_if_fail (file_name != NULL, NULL);
798 #ifdef G_PLATFORM_WIN32
799 /* Skip \\server\share or //server/share */
800 if (G_IS_DIR_SEPARATOR (file_name[0]) &&
801 G_IS_DIR_SEPARATOR (file_name[1]) &&
803 !G_IS_DIR_SEPARATOR (file_name[2]))
807 p = strchr (file_name + 2, G_DIR_SEPARATOR);
810 gchar *q = strchr (file_name + 2, '/');
811 if (p == NULL || (q != NULL && q < p))
821 while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
824 /* Possibly skip a backslash after the share name */
825 if (G_IS_DIR_SEPARATOR (file_name[0]))
828 return (gchar *)file_name;
833 /* Skip initial slashes */
834 if (G_IS_DIR_SEPARATOR (file_name[0]))
836 while (G_IS_DIR_SEPARATOR (file_name[0]))
838 return (gchar *)file_name;
843 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
844 return (gchar *)file_name + 3;
851 * g_path_get_dirname:
852 * @file_name: the name of the file.
854 * Gets the directory components of a file name. If the file name has no
855 * directory components "." is returned. The returned string should be
856 * freed when no longer needed.
858 * Returns: the directory components of the file.
861 g_path_get_dirname (const gchar *file_name)
863 register gchar *base;
866 g_return_val_if_fail (file_name != NULL, NULL);
868 base = strrchr (file_name, G_DIR_SEPARATOR);
871 gchar *q = strrchr (file_name, '/');
872 if (base == NULL || (q != NULL && q > base))
879 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
881 gchar drive_colon_dot[4];
883 drive_colon_dot[0] = file_name[0];
884 drive_colon_dot[1] = ':';
885 drive_colon_dot[2] = '.';
886 drive_colon_dot[3] = '\0';
888 return g_strdup (drive_colon_dot);
891 return g_strdup (".");
894 while (base > file_name && G_IS_DIR_SEPARATOR (*base))
898 /* base points to the char before the last slash.
900 * In case file_name is the root of a drive (X:\) or a child of the
901 * root of a drive (X:\foo), include the slash.
903 * In case file_name is the root share of an UNC path
904 * (\\server\share), add a slash, returning \\server\share\ .
906 * In case file_name is a direct child of a share in an UNC path
907 * (\\server\share\foo), include the slash after the share name,
908 * returning \\server\share\ .
910 if (base == file_name + 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
912 else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
913 G_IS_DIR_SEPARATOR (file_name[1]) &&
915 !G_IS_DIR_SEPARATOR (file_name[2]) &&
916 base >= file_name + 2)
918 const gchar *p = file_name + 2;
919 while (*p && !G_IS_DIR_SEPARATOR (*p))
923 len = (guint) strlen (file_name) + 1;
924 base = g_new (gchar, len + 1);
925 strcpy (base, file_name);
926 base[len-1] = G_DIR_SEPARATOR;
930 if (G_IS_DIR_SEPARATOR (*p))
933 while (*p && !G_IS_DIR_SEPARATOR (*p))
941 len = (guint) 1 + base - file_name;
943 base = g_new (gchar, len + 1);
944 g_memmove (base, file_name, len);
953 * Gets the current directory.
954 * The returned string should be freed when no longer needed. The encoding
955 * of the returned string is system defined. On Windows, it is always UTF-8.
957 * Returns: the current directory.
960 g_get_current_dir (void)
965 wchar_t dummy[2], *wdir;
968 len = GetCurrentDirectoryW (2, dummy);
969 wdir = g_new (wchar_t, len);
971 if (GetCurrentDirectoryW (len, wdir) == len - 1)
972 dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
977 dir = g_strdup ("\\");
983 gchar *buffer = NULL;
985 static gulong max_len = 0;
988 max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
990 /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
991 * and, if that wasn't bad enough, hangs in doing so.
993 #if (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
994 buffer = g_new (gchar, max_len + 1);
996 dir = getwd (buffer);
997 #else /* !sun || !HAVE_GETCWD */
998 while (max_len < G_MAXULONG / 2)
1001 buffer = g_new (gchar, max_len + 1);
1003 dir = getcwd (buffer, max_len);
1005 if (dir || errno != ERANGE)
1010 #endif /* !sun || !HAVE_GETCWD */
1012 if (!dir || !*buffer)
1014 /* hm, should we g_error() out here?
1015 * this can happen if e.g. "./" has mode \0000
1017 buffer[0] = G_DIR_SEPARATOR;
1021 dir = g_strdup (buffer);
1030 * @variable: the environment variable to get, in the GLib file name encoding.
1032 * Returns the value of an environment variable. The name and value
1033 * are in the GLib file name encoding. On UNIX, this means the actual
1034 * bytes which might or might not be in some consistent character set
1035 * and encoding. On Windows, it is in UTF-8. On Windows, in case the
1036 * environment variable's value contains references to other
1037 * environment variables, they are expanded.
1039 * Return value: the value of the environment variable, or %NULL if
1040 * the environment variable is not found. The returned string may be
1041 * overwritten by the next call to g_getenv(), g_setenv() or
1044 G_CONST_RETURN gchar*
1045 g_getenv (const gchar *variable)
1049 g_return_val_if_fail (variable != NULL, NULL);
1051 return getenv (variable);
1053 #else /* G_OS_WIN32 */
1057 wchar_t dummy[2], *wname, *wvalue;
1060 g_return_val_if_fail (variable != NULL, NULL);
1061 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), NULL);
1063 /* On Windows NT, it is relatively typical that environment
1064 * variables contain references to other environment variables. If
1065 * so, use ExpandEnvironmentStrings(). (In an ideal world, such
1066 * environment variables would be stored in the Registry as
1067 * REG_EXPAND_SZ type values, and would then get automatically
1068 * expanded before a program sees them. But there is broken software
1069 * that stores environment variables as REG_SZ values even if they
1070 * contain references to other environment variables.)
1073 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1075 len = GetEnvironmentVariableW (wname, dummy, 2);
1085 wvalue = g_new (wchar_t, len);
1087 if (GetEnvironmentVariableW (wname, wvalue, len) != len - 1)
1094 if (wcschr (wvalue, L'%') != NULL)
1096 wchar_t *tem = wvalue;
1098 len = ExpandEnvironmentStringsW (wvalue, dummy, 2);
1102 wvalue = g_new (wchar_t, len);
1104 if (ExpandEnvironmentStringsW (tem, wvalue, len) != len)
1114 value = g_utf16_to_utf8 (wvalue, -1, NULL, NULL, NULL);
1119 quark = g_quark_from_string (value);
1122 return g_quark_to_string (quark);
1124 #endif /* G_OS_WIN32 */
1127 /* _g_getenv_nomalloc
1128 * this function does a getenv() without doing any kind of allocation
1129 * through glib. it's suitable for chars <= 127 only (both, for the
1130 * variable name and the contents) and for contents < 1024 chars in
1131 * length. also, it aliases "" to a NULL return value.
1134 _g_getenv_nomalloc (const gchar *variable,
1137 const gchar *retval = getenv (variable);
1138 if (retval && retval[0])
1140 gint l = strlen (retval);
1143 strncpy (buffer, retval, l);
1153 * @variable: the environment variable to set, must not contain '='.
1154 * @value: the value for to set the variable to.
1155 * @overwrite: whether to change the variable if it already exists.
1157 * Sets an environment variable. Both the variable's name and value
1158 * should be in the GLib file name encoding. On UNIX, this means that
1159 * they can be any sequence of bytes. On Windows, they should be in
1162 * Note that on some systems, when variables are overwritten, the memory
1163 * used for the previous variables and its value isn't reclaimed.
1165 * Returns: %FALSE if the environment variable couldn't be set.
1170 g_setenv (const gchar *variable,
1181 g_return_val_if_fail (variable != NULL, FALSE);
1182 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1185 result = setenv (variable, value, overwrite);
1187 if (!overwrite && getenv (variable) != NULL)
1190 /* This results in a leak when you overwrite existing
1191 * settings. It would be fairly easy to fix this by keeping
1192 * our own parallel array or hash table.
1194 string = g_strconcat (variable, "=", value, NULL);
1195 result = putenv (string);
1199 #else /* G_OS_WIN32 */
1202 wchar_t *wname, *wvalue, *wassignment;
1205 g_return_val_if_fail (variable != NULL, FALSE);
1206 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1207 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), FALSE);
1208 g_return_val_if_fail (g_utf8_validate (value, -1, NULL), FALSE);
1210 if (!overwrite && g_getenv (variable) != NULL)
1213 /* We want to (if possible) set both the environment variable copy
1214 * kept by the C runtime and the one kept by the system.
1216 * We can't use only the C runtime's putenv or _wputenv() as that
1217 * won't work for arbitrary Unicode strings in a "non-Unicode" app
1218 * (with main() and not wmain()). In a "main()" app the C runtime
1219 * initializes the C runtime's environment table by converting the
1220 * real (wide char) environment variables to system codepage, thus
1221 * breaking those that aren't representable in the system codepage.
1223 * As the C runtime's putenv() will also set the system copy, we do
1224 * the putenv() first, then call SetEnvironmentValueW ourselves.
1227 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1228 wvalue = g_utf8_to_utf16 (value, -1, NULL, NULL, NULL);
1229 tem = g_strconcat (variable, "=", value, NULL);
1230 wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1233 _wputenv (wassignment);
1234 g_free (wassignment);
1236 retval = (SetEnvironmentVariableW (wname, wvalue) != 0);
1243 #endif /* G_OS_WIN32 */
1246 #ifdef HAVE__NSGETENVIRON
1247 #define environ (*_NSGetEnviron())
1248 #elif !defined(G_OS_WIN32)
1250 /* According to the Single Unix Specification, environ is not in
1251 * any system header, although unistd.h often declares it.
1253 extern char **environ;
1258 * @variable: the environment variable to remove, must not contain '='.
1260 * Removes an environment variable from the environment.
1262 * Note that on some systems, when variables are overwritten, the memory
1263 * used for the previous variables and its value isn't reclaimed.
1264 * Furthermore, this function can't be guaranteed to operate in a
1270 g_unsetenv (const gchar *variable)
1274 #ifdef HAVE_UNSETENV
1275 g_return_if_fail (variable != NULL);
1276 g_return_if_fail (strchr (variable, '=') == NULL);
1278 unsetenv (variable);
1279 #else /* !HAVE_UNSETENV */
1283 g_return_if_fail (variable != NULL);
1284 g_return_if_fail (strchr (variable, '=') == NULL);
1286 len = strlen (variable);
1288 /* Mess directly with the environ array.
1289 * This seems to be the only portable way to do this.
1291 * Note that we remove *all* environment entries for
1292 * the variable name, not just the first.
1297 if (strncmp (*e, variable, len) != 0 || (*e)[len] != '=')
1305 #endif /* !HAVE_UNSETENV */
1307 #else /* G_OS_WIN32 */
1309 wchar_t *wname, *wassignment;
1312 g_return_if_fail (variable != NULL);
1313 g_return_if_fail (strchr (variable, '=') == NULL);
1314 g_return_if_fail (g_utf8_validate (variable, -1, NULL));
1316 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1317 tem = g_strconcat (variable, "=", NULL);
1318 wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1321 _wputenv (wassignment);
1322 g_free (wassignment);
1324 SetEnvironmentVariableW (wname, NULL);
1328 #endif /* G_OS_WIN32 */
1334 * Gets the names of all variables set in the environment.
1336 * Returns: a %NULL-terminated list of strings which must be freed
1337 * with g_strfreev().
1339 * Programs that want to be portable to Windows should typically use
1340 * this function and g_getenv() instead of using the environ array
1341 * from the C library directly. On Windows, the strings in the environ
1342 * array are in system codepage encoding, while in most of the typical
1343 * use cases for environment variables in GLib-using programs you want
1344 * the UTF-8 encoding that this function and g_getenv() provide.
1352 gchar **result, *eq;
1355 len = g_strv_length (environ);
1356 result = g_new0 (gchar *, len + 1);
1359 for (i = 0; i < len; i++)
1361 eq = strchr (environ[i], '=');
1363 result[j++] = g_strndup (environ[i], eq - environ[i]);
1370 gchar **result, *eq;
1374 p = (wchar_t *) GetEnvironmentStringsW ();
1380 q += wcslen (q) + 1;
1384 result = g_new0 (gchar *, len + 1);
1390 result[j] = g_utf16_to_utf8 (q, -1, NULL, NULL, NULL);
1391 if (result[j] != NULL)
1393 eq = strchr (result[j], '=');
1394 if (eq && eq > result[j])
1402 q += wcslen (q) + 1;
1405 FreeEnvironmentStringsW (p);
1411 G_LOCK_DEFINE_STATIC (g_utils_global);
1413 static gchar *g_tmp_dir = NULL;
1414 static gchar *g_user_name = NULL;
1415 static gchar *g_real_name = NULL;
1416 static gchar *g_home_dir = NULL;
1417 static gchar *g_host_name = NULL;
1420 /* System codepage versions of the above, kept at file level so that they,
1421 * too, are produced only once.
1423 static gchar *g_tmp_dir_cp = NULL;
1424 static gchar *g_user_name_cp = NULL;
1425 static gchar *g_real_name_cp = NULL;
1426 static gchar *g_home_dir_cp = NULL;
1429 static gchar *g_user_data_dir = NULL;
1430 static gchar **g_system_data_dirs = NULL;
1431 static gchar *g_user_cache_dir = NULL;
1432 static gchar *g_user_config_dir = NULL;
1433 static gchar **g_system_config_dirs = NULL;
1435 static gchar **g_user_special_dirs = NULL;
1437 /* fifteen minutes of fame for everybody */
1438 #define G_USER_DIRS_EXPIRE 15 * 60
1443 get_special_folder (int csidl)
1445 wchar_t path[MAX_PATH+1];
1447 LPITEMIDLIST pidl = NULL;
1449 gchar *retval = NULL;
1451 hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
1454 b = SHGetPathFromIDListW (pidl, path);
1456 retval = g_utf16_to_utf8 (path, -1, NULL, NULL, NULL);
1457 CoTaskMemFree (pidl);
1463 get_windows_directory_root (void)
1465 wchar_t wwindowsdir[MAX_PATH];
1467 if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
1469 /* Usually X:\Windows, but in terminal server environments
1470 * might be an UNC path, AFAIK.
1472 char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
1475 if (windowsdir == NULL)
1476 return g_strdup ("C:\\");
1478 p = (char *) g_path_skip_root (windowsdir);
1479 if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
1485 return g_strdup ("C:\\");
1490 /* HOLDS: g_utils_global_lock */
1492 g_get_any_init_do (void)
1494 gchar hostname[100];
1496 g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
1498 g_tmp_dir = g_strdup (g_getenv ("TMP"));
1500 g_tmp_dir = g_strdup (g_getenv ("TEMP"));
1504 g_tmp_dir = get_windows_directory_root ();
1510 g_tmp_dir = g_strdup (P_tmpdir);
1511 k = strlen (g_tmp_dir);
1512 if (k > 1 && G_IS_DIR_SEPARATOR (g_tmp_dir[k - 1]))
1513 g_tmp_dir[k - 1] = '\0';
1519 g_tmp_dir = g_strdup ("/tmp");
1521 #endif /* !G_OS_WIN32 */
1524 /* We check $HOME first for Win32, though it is a last resort for Unix
1525 * where we prefer the results of getpwuid().
1527 g_home_dir = g_strdup (g_getenv ("HOME"));
1529 /* Only believe HOME if it is an absolute path and exists */
1532 if (!(g_path_is_absolute (g_home_dir) &&
1533 g_file_test (g_home_dir, G_FILE_TEST_IS_DIR)))
1535 g_free (g_home_dir);
1540 /* In case HOME is Unix-style (it happens), convert it to
1546 while ((p = strchr (g_home_dir, '/')) != NULL)
1552 /* USERPROFILE is probably the closest equivalent to $HOME? */
1553 if (g_getenv ("USERPROFILE") != NULL)
1554 g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
1558 g_home_dir = get_special_folder (CSIDL_PROFILE);
1561 g_home_dir = get_windows_directory_root ();
1562 #endif /* G_OS_WIN32 */
1566 struct passwd *pw = NULL;
1567 gpointer buffer = NULL;
1571 # if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
1573 # ifdef _SC_GETPW_R_SIZE_MAX
1574 /* This reurns the maximum length */
1575 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
1579 # else /* _SC_GETPW_R_SIZE_MAX */
1581 # endif /* _SC_GETPW_R_SIZE_MAX */
1583 logname = (gchar *) g_getenv ("LOGNAME");
1588 /* we allocate 6 extra bytes to work around a bug in
1589 * Mac OS < 10.3. See #156446
1591 buffer = g_malloc (bufsize + 6);
1594 # ifdef HAVE_POSIX_GETPWUID_R
1596 error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
1597 if (!pw || (pw->pw_uid != getuid ())) {
1598 /* LOGNAME is lying, fall back to looking up the uid */
1599 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1602 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1604 error = error < 0 ? errno : error;
1605 # else /* HAVE_NONPOSIX_GETPWUID_R */
1606 /* HPUX 11 falls into the HAVE_POSIX_GETPWUID_R case */
1607 # if defined(_AIX) || defined(__hpux)
1608 error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1609 pw = error == 0 ? &pwd : NULL;
1612 pw = getpwnam_r (logname, &pwd, buffer, bufsize);
1613 if (!pw || (pw->pw_uid != getuid ())) {
1614 /* LOGNAME is lying, fall back to looking up the uid */
1615 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1618 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1620 error = pw ? 0 : errno;
1622 # endif /* HAVE_NONPOSIX_GETPWUID_R */
1626 /* we bail out prematurely if the user id can't be found
1627 * (should be pretty rare case actually), or if the buffer
1628 * should be sufficiently big and lookups are still not
1631 if (error == 0 || error == ENOENT)
1633 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
1634 (gulong) getuid ());
1637 if (bufsize > 32 * 1024)
1639 g_warning ("getpwuid_r(): failed due to: %s.",
1640 g_strerror (error));
1648 # endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
1653 pw = getpwuid (getuid ());
1658 g_user_name = g_strdup (pw->pw_name);
1660 if (pw->pw_gecos && *pw->pw_gecos != '\0')
1662 gchar **gecos_fields;
1665 /* split the gecos field and substitute '&' */
1666 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
1667 name_parts = g_strsplit (gecos_fields[0], "&", 0);
1668 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
1669 g_real_name = g_strjoinv (pw->pw_name, name_parts);
1670 g_strfreev (gecos_fields);
1671 g_strfreev (name_parts);
1675 g_home_dir = g_strdup (pw->pw_dir);
1680 #else /* !HAVE_PWD_H */
1684 guint len = UNLEN+1;
1685 wchar_t buffer[UNLEN+1];
1687 if (GetUserNameW (buffer, (LPDWORD) &len))
1689 g_user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
1690 g_real_name = g_strdup (g_user_name);
1693 #endif /* G_OS_WIN32 */
1695 #endif /* !HAVE_PWD_H */
1699 g_home_dir = g_strdup (g_getenv ("HOME"));
1703 /* change '\\' in %HOME% to '/' */
1704 g_strdelimit (g_home_dir, "\\",'/');
1707 g_user_name = g_strdup ("somebody");
1709 g_real_name = g_strdup ("Unknown");
1713 gboolean hostname_fail = (gethostname (hostname, sizeof (hostname)) == -1);
1715 DWORD size = sizeof (hostname);
1716 gboolean hostname_fail = (!GetComputerName (hostname, &size));
1718 g_host_name = g_strdup (hostname_fail ? "localhost" : hostname);
1722 g_tmp_dir_cp = g_locale_from_utf8 (g_tmp_dir, -1, NULL, NULL, NULL);
1723 g_user_name_cp = g_locale_from_utf8 (g_user_name, -1, NULL, NULL, NULL);
1724 g_real_name_cp = g_locale_from_utf8 (g_real_name, -1, NULL, NULL, NULL);
1727 g_tmp_dir_cp = g_strdup ("\\");
1728 if (!g_user_name_cp)
1729 g_user_name_cp = g_strdup ("somebody");
1730 if (!g_real_name_cp)
1731 g_real_name_cp = g_strdup ("Unknown");
1733 /* home_dir might be NULL, unlike tmp_dir, user_name and
1737 g_home_dir_cp = g_locale_from_utf8 (g_home_dir, -1, NULL, NULL, NULL);
1739 g_home_dir_cp = NULL;
1740 #endif /* G_OS_WIN32 */
1744 g_get_any_init (void)
1747 g_get_any_init_do ();
1751 g_get_any_init_locked (void)
1753 G_LOCK (g_utils_global);
1755 G_UNLOCK (g_utils_global);
1762 * Gets the user name of the current user. The encoding of the returned
1763 * string is system-defined. On UNIX, it might be the preferred file name
1764 * encoding, or something else, and there is no guarantee that it is even
1765 * consistent on a machine. On Windows, it is always UTF-8.
1767 * Returns: the user name of the current user.
1769 G_CONST_RETURN gchar*
1770 g_get_user_name (void)
1772 g_get_any_init_locked ();
1779 * Gets the real name of the user. This usually comes from the user's entry
1780 * in the <filename>passwd</filename> file. The encoding of the returned
1781 * string is system-defined. (On Windows, it is, however, always UTF-8.)
1782 * If the real user name cannot be determined, the string "Unknown" is
1785 * Returns: the user's real name.
1787 G_CONST_RETURN gchar*
1788 g_get_real_name (void)
1790 g_get_any_init_locked ();
1797 * Gets the current user's home directory as defined in the
1798 * password database.
1800 * Note that in contrast to traditional UNIX tools, this function
1801 * prefers <filename>passwd</filename> entries over the <envar>HOME</envar>
1802 * environment variable.
1804 * One of the reasons for this decision is that applications in many
1805 * cases need special handling to deal with the case where
1806 * <envar>HOME</envar> is
1808 * <member>Not owned by the user</member>
1809 * <member>Not writeable</member>
1810 * <member>Not even readable</member>
1812 * Since applications are in general <emphasis>not</emphasis> written
1813 * to deal with these situations it was considered better to make
1814 * g_get_homedir() not pay attention to <envar>HOME</envar> and to
1815 * return the real home directory for the user. If applications
1816 * want to pay attention to <envar>HOME</envar>, they can do:
1818 * const char *homedir = g_getenv ("HOME");
1820 * homedir = g_get_homedir (<!-- -->);
1823 * Returns: the current user's home directory
1825 G_CONST_RETURN gchar*
1826 g_get_home_dir (void)
1828 g_get_any_init_locked ();
1835 * Gets the directory to use for temporary files. This is found from
1836 * inspecting the environment variables <envar>TMPDIR</envar>,
1837 * <envar>TMP</envar>, and <envar>TEMP</envar> in that order. If none
1838 * of those are defined "/tmp" is returned on UNIX and "C:\" on Windows.
1839 * The encoding of the returned string is system-defined. On Windows,
1840 * it is always UTF-8. The return value is never %NULL.
1842 * Returns: the directory to use for temporary files.
1844 G_CONST_RETURN gchar*
1845 g_get_tmp_dir (void)
1847 g_get_any_init_locked ();
1854 * Return a name for the machine.
1856 * The returned name is not necessarily a fully-qualified domain name,
1857 * or even present in DNS or some other name service at all. It need
1858 * not even be unique on your local network or site, but usually it
1859 * is. Callers should not rely on the return value having any specific
1860 * properties like uniqueness for security purposes. Even if the name
1861 * of the machine is changed while an application is running, the
1862 * return value from this function does not change. The returned
1863 * string is owned by GLib and should not be modified or freed. If no
1864 * name can be determined, a default fixed string "localhost" is
1867 * Returns: the host name of the machine.
1872 g_get_host_name (void)
1874 g_get_any_init_locked ();
1878 G_LOCK_DEFINE_STATIC (g_prgname);
1879 static gchar *g_prgname = NULL;
1884 * Gets the name of the program. This name should <emphasis>not</emphasis>
1885 * be localized, contrast with g_get_application_name().
1886 * (If you are using GDK or GTK+ the program name is set in gdk_init(),
1887 * which is called by gtk_init(). The program name is found by taking
1888 * the last component of <literal>argv[0]</literal>.)
1890 * Returns: the name of the program. The returned string belongs
1891 * to GLib and must not be modified or freed.
1894 g_get_prgname (void)
1900 if (g_prgname == NULL)
1902 static gboolean beenhere = FALSE;
1906 gchar *utf8_buf = NULL;
1907 wchar_t buf[MAX_PATH+1];
1910 if (GetModuleFileNameW (GetModuleHandle (NULL),
1911 buf, G_N_ELEMENTS (buf)) > 0)
1912 utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
1916 g_prgname = g_path_get_basename (utf8_buf);
1923 G_UNLOCK (g_prgname);
1930 * @prgname: the name of the program.
1932 * Sets the name of the program. This name should <emphasis>not</emphasis>
1933 * be localized, contrast with g_set_application_name(). Note that for
1934 * thread-safety reasons this function can only be called once.
1937 g_set_prgname (const gchar *prgname)
1941 g_prgname = g_strdup (prgname);
1942 G_UNLOCK (g_prgname);
1945 G_LOCK_DEFINE_STATIC (g_application_name);
1946 static gchar *g_application_name = NULL;
1949 * g_get_application_name:
1951 * Gets a human-readable name for the application, as set by
1952 * g_set_application_name(). This name should be localized if
1953 * possible, and is intended for display to the user. Contrast with
1954 * g_get_prgname(), which gets a non-localized name. If
1955 * g_set_application_name() has not been called, returns the result of
1956 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1959 * Return value: human-readable application name. may return %NULL
1963 G_CONST_RETURN gchar*
1964 g_get_application_name (void)
1968 G_LOCK (g_application_name);
1969 retval = g_application_name;
1970 G_UNLOCK (g_application_name);
1973 return g_get_prgname ();
1979 * g_set_application_name:
1980 * @application_name: localized name of the application
1982 * Sets a human-readable name for the application. This name should be
1983 * localized if possible, and is intended for display to the user.
1984 * Contrast with g_set_prgname(), which sets a non-localized name.
1985 * g_set_prgname() will be called automatically by gtk_init(),
1986 * but g_set_application_name() will not.
1988 * Note that for thread safety reasons, this function can only
1991 * The application name will be used in contexts such as error messages,
1992 * or when displaying an application's name in the task list.
1997 g_set_application_name (const gchar *application_name)
1999 gboolean already_set = FALSE;
2001 G_LOCK (g_application_name);
2002 if (g_application_name)
2005 g_application_name = g_strdup (application_name);
2006 G_UNLOCK (g_application_name);
2009 g_warning ("g_set_application() name called multiple times");
2013 * g_get_user_data_dir:
2015 * Returns a base directory in which to access application data such
2016 * as icons that is customized for a particular user.
2018 * On UNIX platforms this is determined using the mechanisms described in
2019 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2020 * XDG Base Directory Specification</ulink>
2022 * Return value: a string owned by GLib that must not be modified
2026 G_CONST_RETURN gchar*
2027 g_get_user_data_dir (void)
2031 G_LOCK (g_utils_global);
2033 if (!g_user_data_dir)
2036 data_dir = get_special_folder (CSIDL_PERSONAL);
2038 data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
2040 if (data_dir && data_dir[0])
2041 data_dir = g_strdup (data_dir);
2043 if (!data_dir || !data_dir[0])
2048 data_dir = g_build_filename (g_home_dir, ".local",
2051 data_dir = g_build_filename (g_tmp_dir, g_user_name, ".local",
2055 g_user_data_dir = data_dir;
2058 data_dir = g_user_data_dir;
2060 G_UNLOCK (g_utils_global);
2066 g_init_user_config_dir (void)
2070 if (!g_user_config_dir)
2073 config_dir = get_special_folder (CSIDL_APPDATA);
2075 config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
2077 if (config_dir && config_dir[0])
2078 config_dir = g_strdup (config_dir);
2080 if (!config_dir || !config_dir[0])
2085 config_dir = g_build_filename (g_home_dir, ".config", NULL);
2087 config_dir = g_build_filename (g_tmp_dir, g_user_name, ".config", NULL);
2090 g_user_config_dir = config_dir;
2095 * g_get_user_config_dir:
2097 * Returns a base directory in which to store user-specific application
2098 * configuration information such as user preferences and settings.
2100 * On UNIX platforms this is determined using the mechanisms described in
2101 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2102 * XDG Base Directory Specification</ulink>
2104 * Return value: a string owned by GLib that must not be modified
2108 G_CONST_RETURN gchar*
2109 g_get_user_config_dir (void)
2111 G_LOCK (g_utils_global);
2113 g_init_user_config_dir ();
2115 G_UNLOCK (g_utils_global);
2117 return g_user_config_dir;
2121 * g_get_user_cache_dir:
2123 * Returns a base directory in which to store non-essential, cached
2124 * data specific to particular user.
2126 * On UNIX platforms this is determined using the mechanisms described in
2127 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2128 * XDG Base Directory Specification</ulink>
2130 * Return value: a string owned by GLib that must not be modified
2134 G_CONST_RETURN gchar*
2135 g_get_user_cache_dir (void)
2139 G_LOCK (g_utils_global);
2141 if (!g_user_cache_dir)
2144 cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
2146 cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
2148 if (cache_dir && cache_dir[0])
2149 cache_dir = g_strdup (cache_dir);
2151 if (!cache_dir || !cache_dir[0])
2156 cache_dir = g_build_filename (g_home_dir, ".cache", NULL);
2158 cache_dir = g_build_filename (g_tmp_dir, g_user_name, ".cache", NULL);
2160 g_user_cache_dir = cache_dir;
2163 cache_dir = g_user_cache_dir;
2165 G_UNLOCK (g_utils_global);
2173 find_folder (OSType type)
2175 gchar *filename = NULL;
2178 if (FSFindFolder (kUserDomain, type, kDontCreateFolder, &found) == noErr)
2180 CFURLRef url = CFURLCreateFromFSRef (kCFAllocatorSystemDefault, &found);
2184 CFStringRef path = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle);
2188 filename = g_strdup (CFStringGetCStringPtr (path, kCFStringEncodingUTF8));
2192 filename = g_new0 (gchar, CFStringGetLength (path) * 3 + 1);
2194 CFStringGetCString (path, filename,
2195 CFStringGetLength (path) * 3 + 1,
2196 kCFStringEncodingUTF8);
2210 load_user_special_dirs (void)
2212 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = find_folder (kDesktopFolderType);
2213 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = find_folder (kDocumentsFolderType);
2214 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = find_folder (kDesktopFolderType); /* XXX correct ? */
2215 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = find_folder (kMusicDocumentsFolderType);
2216 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = find_folder (kPictureDocumentsFolderType);
2217 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = NULL;
2218 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = NULL;
2219 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = find_folder (kMovieDocumentsFolderType);
2222 #endif /* HAVE_CARBON */
2224 #if defined(G_OS_WIN32)
2226 load_user_special_dirs (void)
2228 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2229 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
2230 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY); /* XXX correct ? */
2231 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
2232 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
2233 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS); /* XXX correct ? */
2234 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
2235 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
2237 #endif /* G_OS_WIN32 */
2239 static void g_init_user_config_dir (void);
2241 #if defined(G_OS_UNIX) && !defined(HAVE_CARBON)
2243 /* adapted from xdg-user-dir-lookup.c
2245 * Copyright (C) 2007 Red Hat Inc.
2247 * Permission is hereby granted, free of charge, to any person
2248 * obtaining a copy of this software and associated documentation files
2249 * (the "Software"), to deal in the Software without restriction,
2250 * including without limitation the rights to use, copy, modify, merge,
2251 * publish, distribute, sublicense, and/or sell copies of the Software,
2252 * and to permit persons to whom the Software is furnished to do so,
2253 * subject to the following conditions:
2255 * The above copyright notice and this permission notice shall be
2256 * included in all copies or substantial portions of the Software.
2258 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
2259 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
2260 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
2261 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
2262 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
2263 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
2264 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2268 load_user_special_dirs (void)
2275 g_init_user_config_dir ();
2276 config_file = g_build_filename (g_user_config_dir,
2280 if (!g_file_get_contents (config_file, &data, NULL, NULL))
2282 g_free (config_file);
2286 lines = g_strsplit (data, "\n", -1);
2287 n_lines = g_strv_length (lines);
2290 for (i = 0; i < n_lines; i++)
2292 gchar *buffer = lines[i];
2295 gboolean is_relative = FALSE;
2296 GUserDirectory directory;
2298 /* Remove newline at end */
2299 len = strlen (buffer);
2300 if (len > 0 && buffer[len - 1] == '\n')
2301 buffer[len - 1] = 0;
2304 while (*p == ' ' || *p == '\t')
2307 if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
2309 directory = G_USER_DIRECTORY_DESKTOP;
2310 p += strlen ("XDG_DESKTOP_DIR");
2312 else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
2314 directory = G_USER_DIRECTORY_DOCUMENTS;
2315 p += strlen ("XDG_DOCUMENTS_DIR");
2317 else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
2319 directory = G_USER_DIRECTORY_DOWNLOAD;
2320 p += strlen ("XDG_DOWNLOAD_DIR");
2322 else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
2324 directory = G_USER_DIRECTORY_MUSIC;
2325 p += strlen ("XDG_MUSIC_DIR");
2327 else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
2329 directory = G_USER_DIRECTORY_PICTURES;
2330 p += strlen ("XDG_PICTURES_DIR");
2332 else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
2334 directory = G_USER_DIRECTORY_PUBLIC_SHARE;
2335 p += strlen ("XDG_PUBLICSHARE_DIR");
2337 else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
2339 directory = G_USER_DIRECTORY_TEMPLATES;
2340 p += strlen ("XDG_TEMPLATES_DIR");
2342 else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
2344 directory = G_USER_DIRECTORY_VIDEOS;
2345 p += strlen ("XDG_VIDEOS_DIR");
2350 while (*p == ' ' || *p == '\t')
2357 while (*p == ' ' || *p == '\t')
2364 if (strncmp (p, "$HOME", 5) == 0)
2372 d = strrchr (p, '"');
2379 /* remove trailing slashes */
2381 if (d[len - 1] == '/')
2387 g_user_special_dirs[directory] = g_build_filename (g_home_dir, d, NULL);
2390 g_user_special_dirs[directory] = g_strdup (d);
2394 g_free (config_file);
2397 #endif /* G_OS_UNIX && !HAVE_CARBON */
2400 * g_get_user_special_dir:
2401 * @directory: the logical id of special directory
2403 * Returns the full path of a special directory using its logical id.
2405 * On Unix this is done using the XDG special user directories.
2407 * Depending on the platform, the user might be able to change the path
2408 * of the special directory without requiring the session to restart; GLib
2409 * will not reflect any change once the special directories are loaded.
2411 * Return value: the path to the specified special directory, or %NULL
2412 * if the logical id was not found. The returned string is owned by
2413 * GLib and should not be modified or freed.
2417 G_CONST_RETURN gchar *
2418 g_get_user_special_dir (GUserDirectory directory)
2420 g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
2421 directory < G_USER_N_DIRECTORIES, NULL);
2423 G_LOCK (g_utils_global);
2425 if (G_UNLIKELY (g_user_special_dirs == NULL))
2427 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
2429 load_user_special_dirs ();
2431 /* Special-case desktop for historical compatibility */
2432 if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
2436 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] =
2437 g_build_filename (g_home_dir, "Desktop", NULL);
2441 G_UNLOCK (g_utils_global);
2443 return g_user_special_dirs[directory];
2448 #undef g_get_system_data_dirs
2451 get_module_for_address (gconstpointer address)
2453 /* Holds the g_utils_global lock */
2455 static gboolean beenhere = FALSE;
2456 typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
2457 static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
2458 HMODULE hmodule = NULL;
2465 p_GetModuleHandleExA =
2466 (t_GetModuleHandleExA) GetProcAddress (LoadLibrary ("kernel32.dll"),
2467 "GetModuleHandleExA");
2471 if (p_GetModuleHandleExA == NULL ||
2472 !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
2473 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
2476 MEMORY_BASIC_INFORMATION mbi;
2477 VirtualQuery (address, &mbi, sizeof (mbi));
2478 hmodule = (HMODULE) mbi.AllocationBase;
2485 get_module_share_dir (gconstpointer address)
2491 hmodule = get_module_for_address (address);
2492 if (hmodule == NULL)
2495 filename = g_win32_get_package_installation_directory_of_module (hmodule);
2496 retval = g_build_filename (filename, "share", NULL);
2502 G_CONST_RETURN gchar * G_CONST_RETURN *
2503 g_win32_get_system_data_dirs_for_module (gconstpointer address)
2507 static GHashTable *per_module_data_dirs = NULL;
2514 G_LOCK (g_utils_global);
2515 hmodule = get_module_for_address (address);
2516 if (hmodule != NULL)
2518 if (per_module_data_dirs == NULL)
2519 per_module_data_dirs = g_hash_table_new (NULL, NULL);
2522 retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
2526 G_UNLOCK (g_utils_global);
2527 return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2533 data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
2535 /* Documents and Settings\All Users\Application Data */
2536 p = get_special_folder (CSIDL_COMMON_APPDATA);
2538 g_array_append_val (data_dirs, p);
2540 /* Documents and Settings\All Users\Documents */
2541 p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2543 g_array_append_val (data_dirs, p);
2545 /* Using the above subfolders of Documents and Settings perhaps
2546 * makes sense from a Windows perspective.
2548 * But looking at the actual use cases of this function in GTK+
2549 * and GNOME software, what we really want is the "share"
2550 * subdirectory of the installation directory for the package
2551 * our caller is a part of.
2553 * The address parameter, if non-NULL, points to a function in the
2554 * calling module. Use that to determine that module's installation
2555 * folder, and use its "share" subfolder.
2557 * Additionally, also use the "share" subfolder of the installation
2558 * locations of GLib and the .exe file being run.
2560 * To guard against none of the above being what is really wanted,
2561 * callers of this function should have Win32-specific code to look
2562 * up their installation folder themselves, and handle a subfolder
2563 * "share" of it in the same way as the folders returned from this
2567 p = get_module_share_dir (address);
2569 g_array_append_val (data_dirs, p);
2571 if (glib_dll != NULL)
2573 gchar *glib_root = g_win32_get_package_installation_directory_of_module (glib_dll);
2574 p = g_build_filename (glib_root, "share", NULL);
2576 g_array_append_val (data_dirs, p);
2580 exe_root = g_win32_get_package_installation_directory_of_module (NULL);
2581 p = g_build_filename (exe_root, "share", NULL);
2583 g_array_append_val (data_dirs, p);
2586 retval = (gchar **) g_array_free (data_dirs, FALSE);
2590 if (hmodule != NULL)
2591 g_hash_table_insert (per_module_data_dirs, hmodule, retval);
2592 G_UNLOCK (g_utils_global);
2595 return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2601 * g_get_system_data_dirs:
2603 * Returns an ordered list of base directories in which to access
2604 * system-wide application data.
2606 * On UNIX platforms this is determined using the mechanisms described in
2607 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2608 * XDG Base Directory Specification</ulink>
2610 * On Windows the first elements in the list are the Application Data
2611 * and Documents folders for All Users. (These can be determined only
2612 * on Windows 2000 or later and are not present in the list on other
2613 * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
2614 * CSIDL_COMMON_DOCUMENTS.
2616 * Then follows the "share" subfolder in the installation folder for
2617 * the package containing the DLL that calls this function, if it can
2620 * Finally the list contains the "share" subfolder in the installation
2621 * folder for GLib, and in the installation folder for the package the
2622 * application's .exe file belongs to.
2624 * The installation folders above are determined by looking up the
2625 * folder where the module (DLL or EXE) in question is located. If the
2626 * folder's name is "bin", its parent is used, otherwise the folder
2629 * Note that on Windows the returned list can vary depending on where
2630 * this function is called.
2632 * Return value: a %NULL-terminated array of strings owned by GLib that must
2633 * not be modified or freed.
2636 G_CONST_RETURN gchar * G_CONST_RETURN *
2637 g_get_system_data_dirs (void)
2639 gchar **data_dir_vector;
2641 G_LOCK (g_utils_global);
2643 if (!g_system_data_dirs)
2646 data_dir_vector = (gchar **) g_win32_get_system_data_dirs_for_module (NULL);
2648 gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
2650 if (!data_dirs || !data_dirs[0])
2651 data_dirs = "/usr/local/share/:/usr/share/";
2653 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2656 g_system_data_dirs = data_dir_vector;
2659 data_dir_vector = g_system_data_dirs;
2661 G_UNLOCK (g_utils_global);
2663 return (G_CONST_RETURN gchar * G_CONST_RETURN *) data_dir_vector;
2667 * g_get_system_config_dirs:
2669 * Returns an ordered list of base directories in which to access
2670 * system-wide configuration information.
2672 * On UNIX platforms this is determined using the mechanisms described in
2673 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2674 * XDG Base Directory Specification</ulink>
2676 * Return value: a %NULL-terminated array of strings owned by GLib that must
2677 * not be modified or freed.
2680 G_CONST_RETURN gchar * G_CONST_RETURN *
2681 g_get_system_config_dirs (void)
2683 gchar *conf_dirs, **conf_dir_vector;
2685 G_LOCK (g_utils_global);
2687 if (!g_system_config_dirs)
2690 conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
2693 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2698 /* Return empty list */
2699 conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2702 conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
2704 if (!conf_dirs || !conf_dirs[0])
2705 conf_dirs = "/etc/xdg";
2707 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2710 g_system_config_dirs = conf_dir_vector;
2713 conf_dir_vector = g_system_config_dirs;
2714 G_UNLOCK (g_utils_global);
2716 return (G_CONST_RETURN gchar * G_CONST_RETURN *) conf_dir_vector;
2721 static GHashTable *alias_table = NULL;
2723 /* read an alias file for the locales */
2725 read_aliases (gchar *file)
2731 alias_table = g_hash_table_new (g_str_hash, g_str_equal);
2732 fp = fopen (file,"r");
2735 while (fgets (buf, 256, fp))
2741 /* Line is a comment */
2742 if ((buf[0] == '#') || (buf[0] == '\0'))
2745 /* Reads first column */
2746 for (p = buf, q = NULL; *p; p++) {
2747 if ((*p == '\t') || (*p == ' ') || (*p == ':')) {
2750 while ((*q == '\t') || (*q == ' ')) {
2756 /* The line only had one column */
2757 if (!q || *q == '\0')
2760 /* Read second column */
2761 for (p = q; *p; p++) {
2762 if ((*p == '\t') || (*p == ' ')) {
2768 /* Add to alias table if necessary */
2769 if (!g_hash_table_lookup (alias_table, buf)) {
2770 g_hash_table_insert (alias_table, g_strdup (buf), g_strdup (q));
2779 unalias_lang (char *lang)
2786 read_aliases ("/usr/share/locale/locale.alias");
2789 while ((p = g_hash_table_lookup (alias_table, lang)) && (strcmp (p, lang) != 0))
2794 static gboolean said_before = FALSE;
2796 g_warning ("Too many alias levels for a locale, "
2797 "may indicate a loop");
2806 /* Mask for components of locale spec. The ordering here is from
2807 * least significant to most significant
2811 COMPONENT_CODESET = 1 << 0,
2812 COMPONENT_TERRITORY = 1 << 1,
2813 COMPONENT_MODIFIER = 1 << 2
2816 /* Break an X/Open style locale specification into components
2819 explode_locale (const gchar *locale,
2825 const gchar *uscore_pos;
2826 const gchar *at_pos;
2827 const gchar *dot_pos;
2831 uscore_pos = strchr (locale, '_');
2832 dot_pos = strchr (uscore_pos ? uscore_pos : locale, '.');
2833 at_pos = strchr (dot_pos ? dot_pos : (uscore_pos ? uscore_pos : locale), '@');
2837 mask |= COMPONENT_MODIFIER;
2838 *modifier = g_strdup (at_pos);
2841 at_pos = locale + strlen (locale);
2845 mask |= COMPONENT_CODESET;
2846 *codeset = g_strndup (dot_pos, at_pos - dot_pos);
2853 mask |= COMPONENT_TERRITORY;
2854 *territory = g_strndup (uscore_pos, dot_pos - uscore_pos);
2857 uscore_pos = dot_pos;
2859 *language = g_strndup (locale, uscore_pos - locale);
2865 * Compute all interesting variants for a given locale name -
2866 * by stripping off different components of the value.
2868 * For simplicity, we assume that the locale is in
2869 * X/Open format: language[_territory][.codeset][@modifier]
2871 * TODO: Extend this to handle the CEN format (see the GNUlibc docs)
2872 * as well. We could just copy the code from glibc wholesale
2873 * but it is big, ugly, and complicated, so I'm reluctant
2874 * to do so when this should handle 99% of the time...
2877 _g_compute_locale_variants (const gchar *locale)
2879 GSList *retval = NULL;
2881 gchar *language = NULL;
2882 gchar *territory = NULL;
2883 gchar *codeset = NULL;
2884 gchar *modifier = NULL;
2889 g_return_val_if_fail (locale != NULL, NULL);
2891 mask = explode_locale (locale, &language, &territory, &codeset, &modifier);
2893 /* Iterate through all possible combinations, from least attractive
2894 * to most attractive.
2896 for (i = 0; i <= mask; i++)
2897 if ((i & ~mask) == 0)
2899 gchar *val = g_strconcat (language,
2900 (i & COMPONENT_TERRITORY) ? territory : "",
2901 (i & COMPONENT_CODESET) ? codeset : "",
2902 (i & COMPONENT_MODIFIER) ? modifier : "",
2904 retval = g_slist_prepend (retval, val);
2908 if (mask & COMPONENT_CODESET)
2910 if (mask & COMPONENT_TERRITORY)
2912 if (mask & COMPONENT_MODIFIER)
2918 /* The following is (partly) taken from the gettext package.
2919 Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc. */
2921 static const gchar *
2922 guess_category_value (const gchar *category_name)
2924 const gchar *retval;
2926 /* The highest priority value is the `LANGUAGE' environment
2927 variable. This is a GNU extension. */
2928 retval = g_getenv ("LANGUAGE");
2929 if ((retval != NULL) && (retval[0] != '\0'))
2932 /* `LANGUAGE' is not set. So we have to proceed with the POSIX
2933 methods of looking to `LC_ALL', `LC_xxx', and `LANG'. On some
2934 systems this can be done by the `setlocale' function itself. */
2936 /* Setting of LC_ALL overwrites all other. */
2937 retval = g_getenv ("LC_ALL");
2938 if ((retval != NULL) && (retval[0] != '\0'))
2941 /* Next comes the name of the desired category. */
2942 retval = g_getenv (category_name);
2943 if ((retval != NULL) && (retval[0] != '\0'))
2946 /* Last possibility is the LANG environment variable. */
2947 retval = g_getenv ("LANG");
2948 if ((retval != NULL) && (retval[0] != '\0'))
2951 #ifdef G_PLATFORM_WIN32
2952 /* g_win32_getlocale() first checks for LC_ALL, LC_MESSAGES and
2953 * LANG, which we already did above. Oh well. The main point of
2954 * calling g_win32_getlocale() is to get the thread's locale as used
2955 * by Windows and the Microsoft C runtime (in the "English_United
2956 * States" format) translated into the Unixish format.
2958 retval = g_win32_getlocale ();
2959 if ((retval != NULL) && (retval[0] != '\0'))
2966 typedef struct _GLanguageNamesCache GLanguageNamesCache;
2968 struct _GLanguageNamesCache {
2970 gchar **language_names;
2974 language_names_cache_free (gpointer data)
2976 GLanguageNamesCache *cache = data;
2977 g_free (cache->languages);
2978 g_strfreev (cache->language_names);
2983 * g_get_language_names:
2985 * Computes a list of applicable locale names, which can be used to
2986 * e.g. construct locale-dependent filenames or search paths. The returned
2987 * list is sorted from most desirable to least desirable and always contains
2988 * the default locale "C".
2990 * For example, if LANGUAGE=de:en_US, then the returned list is
2991 * "de", "en_US", "en", "C".
2993 * This function consults the environment variables <envar>LANGUAGE</envar>,
2994 * <envar>LC_ALL</envar>, <envar>LC_MESSAGES</envar> and <envar>LANG</envar>
2995 * to find the list of locales specified by the user.
2997 * Return value: a %NULL-terminated array of strings owned by GLib
2998 * that must not be modified or freed.
3002 G_CONST_RETURN gchar * G_CONST_RETURN *
3003 g_get_language_names (void)
3005 static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
3006 GLanguageNamesCache *cache = g_static_private_get (&cache_private);
3011 cache = g_new0 (GLanguageNamesCache, 1);
3012 g_static_private_set (&cache_private, cache, language_names_cache_free);
3015 value = guess_category_value ("LC_MESSAGES");
3019 if (!(cache->languages && strcmp (cache->languages, value) == 0))
3026 g_free (cache->languages);
3027 g_strfreev (cache->language_names);
3028 cache->languages = g_strdup (value);
3030 alist = g_strsplit (value, ":", 0);
3032 for (a = alist; *a; a++)
3034 gchar *b = unalias_lang (*a);
3035 list = g_slist_concat (list, _g_compute_locale_variants (b));
3038 list = g_slist_append (list, g_strdup ("C"));
3040 cache->language_names = languages = g_new (gchar *, g_slist_length (list) + 1);
3041 for (l = list, i = 0; l; l = l->next, i++)
3042 languages[i] = l->data;
3043 languages[i] = NULL;
3045 g_slist_free (list);
3048 return (G_CONST_RETURN gchar * G_CONST_RETURN *) cache->language_names;
3053 * @v: a #gpointer key
3055 * Converts a gpointer to a hash value.
3056 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3057 * when using pointers as keys in a #GHashTable.
3059 * Returns: a hash value corresponding to the key.
3062 g_direct_hash (gconstpointer v)
3064 return GPOINTER_TO_UINT (v);
3070 * @v2: a key to compare with @v1.
3072 * Compares two #gpointer arguments and returns %TRUE if they are equal.
3073 * It can be passed to g_hash_table_new() as the @key_equal_func
3074 * parameter, when using pointers as keys in a #GHashTable.
3076 * Returns: %TRUE if the two keys match.
3079 g_direct_equal (gconstpointer v1,
3087 * @v1: a pointer to a #gint key.
3088 * @v2: a pointer to a #gint key to compare with @v1.
3090 * Compares the two #gint values being pointed to and returns
3091 * %TRUE if they are equal.
3092 * It can be passed to g_hash_table_new() as the @key_equal_func
3093 * parameter, when using pointers to integers as keys in a #GHashTable.
3095 * Returns: %TRUE if the two keys match.
3098 g_int_equal (gconstpointer v1,
3101 return *((const gint*) v1) == *((const gint*) v2);
3106 * @v: a pointer to a #gint key
3108 * Converts a pointer to a #gint to a hash value.
3109 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3110 * when using pointers to integers values as keys in a #GHashTable.
3112 * Returns: a hash value corresponding to the key.
3115 g_int_hash (gconstpointer v)
3117 return *(const gint*) v;
3121 * g_nullify_pointer:
3122 * @nullify_location: the memory address of the pointer.
3124 * Set the pointer at the specified location to %NULL.
3127 g_nullify_pointer (gpointer *nullify_location)
3129 g_return_if_fail (nullify_location != NULL);
3131 *nullify_location = NULL;
3137 * Get the codeset for the current locale.
3139 * Return value: a newly allocated string containing the name
3140 * of the codeset. This string must be freed with g_free().
3143 g_get_codeset (void)
3145 const gchar *charset;
3147 g_get_charset (&charset);
3149 return g_strdup (charset);
3152 /* This is called from g_thread_init(). It's used to
3153 * initialize some static data in a threadsafe way.
3156 _g_utils_thread_init (void)
3158 g_get_language_names ();
3164 * _glib_get_locale_dir:
3166 * Return the path to the share\locale or lib\locale subfolder of the
3167 * GLib installation folder. The path is in the system codepage. We
3168 * have to use system codepage as bindtextdomain() doesn't have a
3172 _glib_get_locale_dir (void)
3174 gchar *install_dir = NULL, *locale_dir;
3175 gchar *retval = NULL;
3177 if (glib_dll != NULL)
3178 install_dir = g_win32_get_package_installation_directory_of_module (glib_dll);
3183 * Append "/share/locale" or "/lib/locale" depending on whether
3184 * autoconfigury detected GNU gettext or not.
3186 const char *p = GLIB_LOCALE_DIR + strlen (GLIB_LOCALE_DIR);
3192 locale_dir = g_build_filename (install_dir, p, NULL);
3194 retval = g_win32_locale_filename_from_utf8 (locale_dir);
3196 g_free (install_dir);
3197 g_free (locale_dir);
3203 return g_strdup ("");
3206 #undef GLIB_LOCALE_DIR
3208 #endif /* G_OS_WIN32 */
3212 * @str: The string to be translated
3214 * Returns the translated string from the glib translations.
3215 * This is an internal function and should only be used by
3216 * the internals of glib (such as libgio).
3218 * Returns: the transation of @str to the current locale
3220 G_CONST_RETURN gchar *
3221 glib_gettext (const gchar *str)
3223 static gboolean _glib_gettext_initialized = FALSE;
3225 if (!_glib_gettext_initialized)
3228 gchar *tmp = _glib_get_locale_dir ();
3229 bindtextdomain (GETTEXT_PACKAGE, tmp);
3232 bindtextdomain (GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
3234 # ifdef HAVE_BIND_TEXTDOMAIN_CODESET
3235 bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
3237 _glib_gettext_initialized = TRUE;
3240 return dgettext (GETTEXT_PACKAGE, str);
3245 /* Binary compatibility versions. Not for newly compiled code. */
3247 #undef g_find_program_in_path
3250 g_find_program_in_path (const gchar *program)
3252 gchar *utf8_program = g_locale_to_utf8 (program, -1, NULL, NULL, NULL);
3253 gchar *utf8_retval = g_find_program_in_path_utf8 (utf8_program);
3256 g_free (utf8_program);
3257 if (utf8_retval == NULL)
3259 retval = g_locale_from_utf8 (utf8_retval, -1, NULL, NULL, NULL);
3260 g_free (utf8_retval);
3265 #undef g_get_current_dir
3268 g_get_current_dir (void)
3270 gchar *utf8_dir = g_get_current_dir_utf8 ();
3271 gchar *dir = g_locale_from_utf8 (utf8_dir, -1, NULL, NULL, NULL);
3278 G_CONST_RETURN gchar*
3279 g_getenv (const gchar *variable)
3281 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3282 const gchar *utf8_value = g_getenv_utf8 (utf8_variable);
3286 g_free (utf8_variable);
3289 value = g_locale_from_utf8 (utf8_value, -1, NULL, NULL, NULL);
3290 quark = g_quark_from_string (value);
3293 return g_quark_to_string (quark);
3299 g_setenv (const gchar *variable,
3303 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3304 gchar *utf8_value = g_locale_to_utf8 (value, -1, NULL, NULL, NULL);
3305 gboolean retval = g_setenv_utf8 (utf8_variable, utf8_value, overwrite);
3307 g_free (utf8_variable);
3308 g_free (utf8_value);
3316 g_unsetenv (const gchar *variable)
3318 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3320 g_unsetenv_utf8 (utf8_variable);
3322 g_free (utf8_variable);
3325 #undef g_get_user_name
3327 G_CONST_RETURN gchar*
3328 g_get_user_name (void)
3330 g_get_any_init_locked ();
3331 return g_user_name_cp;
3334 #undef g_get_real_name
3336 G_CONST_RETURN gchar*
3337 g_get_real_name (void)
3339 g_get_any_init_locked ();
3340 return g_real_name_cp;
3343 #undef g_get_home_dir
3345 G_CONST_RETURN gchar*
3346 g_get_home_dir (void)
3348 g_get_any_init_locked ();
3349 return g_home_dir_cp;
3352 #undef g_get_tmp_dir
3354 G_CONST_RETURN gchar*
3355 g_get_tmp_dir (void)
3357 g_get_any_init_locked ();
3358 return g_tmp_dir_cp;
3363 #define __G_UTILS_C__
3364 #include "galiasdef.c"