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.
45 #include <sys/types.h>
46 #ifdef HAVE_SYS_PARAM_H
47 #include <sys/param.h>
50 /* implement gutils's inline functions
52 #define G_IMPLEMENT_INLINES 1
55 #include "gprintfint.h"
56 #include "gthreadinit.h"
60 #define G_PATH_LENGTH MAXPATHLEN
61 #elif defined (PATH_MAX)
62 #define G_PATH_LENGTH PATH_MAX
63 #elif defined (_PC_PATH_MAX)
64 #define G_PATH_LENGTH sysconf(_PC_PATH_MAX)
66 #define G_PATH_LENGTH 2048
69 #ifdef G_PLATFORM_WIN32
70 # define STRICT /* Strict typing, please */
73 # include <lmcons.h> /* For UNLEN */
74 #endif /* G_PLATFORM_WIN32 */
79 /* older SDK (e.g. msvc 5.0) does not have these*/
80 # ifndef CSIDL_INTERNET_CACHE
81 # define CSIDL_INTERNET_CACHE 32
83 # ifndef CSIDL_COMMON_APPDATA
84 # define CSIDL_COMMON_APPDATA 35
86 # ifndef CSIDL_COMMON_DOCUMENTS
87 # define CSIDL_COMMON_DOCUMENTS 46
89 # ifndef CSIDL_PROFILE
90 # define CSIDL_PROFILE 40
98 #ifdef HAVE_BIND_TEXTDOMAIN_CODESET
102 const guint glib_major_version = GLIB_MAJOR_VERSION;
103 const guint glib_minor_version = GLIB_MINOR_VERSION;
104 const guint glib_micro_version = GLIB_MICRO_VERSION;
105 const guint glib_interface_age = GLIB_INTERFACE_AGE;
106 const guint glib_binary_age = GLIB_BINARY_AGE;
109 * glib_check_version:
110 * @required_major: the required major version.
111 * @required_minor: the required major version.
112 * @required_micro: the required major version.
114 * Checks that the GLib library in use is compatible with the
115 * given version. Generally you would pass in the constants
116 * #GLIB_MAJOR_VERSION, #GLIB_MINOR_VERSION, #GLIB_MICRO_VERSION
117 * as the three arguments to this function; that produces
118 * a check that the library in use is compatible with
119 * the version of GLib the application or module was compiled
122 * Compatibility is defined by two things: first the version
123 * of the running library is newer than the version
124 * @required_major.required_minor.@required_micro. Second
125 * the running library must be binary compatible with the
126 * version @required_major.required_minor.@required_micro
127 * (same major version.)
129 * Return value: %NULL if the GLib library is compatible with the
130 * given version, or a string describing the version mismatch.
131 * The returned string is owned by GLib and must not be modified
137 glib_check_version (guint required_major,
138 guint required_minor,
139 guint required_micro)
141 gint glib_effective_micro = 100 * GLIB_MINOR_VERSION + GLIB_MICRO_VERSION;
142 gint required_effective_micro = 100 * required_minor + required_micro;
144 if (required_major > GLIB_MAJOR_VERSION)
145 return "GLib version too old (major mismatch)";
146 if (required_major < GLIB_MAJOR_VERSION)
147 return "GLib version too new (major mismatch)";
148 if (required_effective_micro < glib_effective_micro - GLIB_BINARY_AGE)
149 return "GLib version too new (micro mismatch)";
150 if (required_effective_micro > glib_effective_micro)
151 return "GLib version too old (micro mismatch)";
155 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
158 * @dest: the destination address to copy the bytes to.
159 * @src: the source address to copy the bytes from.
160 * @len: the number of bytes to copy.
162 * Copies a block of memory @len bytes long, from @src to @dest.
163 * The source and destination areas may overlap.
165 * In order to use this function, you must include
166 * <filename>string.h</filename> yourself, because this macro will
167 * typically simply resolve to memmove() and GLib does not include
168 * <filename>string.h</filename> for you.
171 g_memmove (gpointer dest,
175 gchar* destptr = dest;
176 const gchar* srcptr = src;
177 if (src + len < dest || dest + len < src)
179 bcopy (src, dest, len);
182 else if (dest <= src)
185 *(destptr++) = *(srcptr++);
192 *(--destptr) = *(--srcptr);
195 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
199 * @func: the function to call on normal program termination.
201 * Specifies a function to be called at normal program termination.
204 g_atexit (GVoidFunc func)
207 const gchar *error = NULL;
209 /* keep this in sync with glib.h */
211 #ifdef G_NATIVE_ATEXIT
212 result = ATEXIT (func);
214 error = g_strerror (errno);
215 #elif defined (HAVE_ATEXIT)
216 # ifdef NeXT /* @#%@! NeXTStep */
217 result = !atexit ((void (*)(void)) func);
219 error = g_strerror (errno);
221 result = atexit ((void (*)(void)) func);
223 error = g_strerror (errno);
225 #elif defined (HAVE_ON_EXIT)
226 result = on_exit ((void (*)(int, void *)) func, NULL);
228 error = g_strerror (errno);
231 error = "no implementation";
232 #endif /* G_NATIVE_ATEXIT */
235 g_error ("Could not register atexit() function: %s", error);
238 /* Based on execvp() from GNU Libc.
239 * Some of this code is cut-and-pasted into gspawn.c
243 my_strchrnul (const gchar *str,
246 gchar *p = (gchar*)str;
247 while (*p && (*p != c))
255 static gchar *inner_find_program_in_path (const gchar *program);
258 g_find_program_in_path (const gchar *program)
260 const gchar *last_dot = strrchr (program, '.');
262 if (last_dot == NULL ||
263 strchr (last_dot, '\\') != NULL ||
264 strchr (last_dot, '/') != NULL)
266 const gint program_length = strlen (program);
267 gchar *pathext = g_build_path (";",
268 ".exe;.cmd;.bat;.com",
269 g_getenv ("PATHEXT"),
272 gchar *decorated_program;
278 gchar *q = my_strchrnul (p, ';');
280 decorated_program = g_malloc (program_length + (q-p) + 1);
281 memcpy (decorated_program, program, program_length);
282 memcpy (decorated_program+program_length, p, q-p);
283 decorated_program [program_length + (q-p)] = '\0';
285 retval = inner_find_program_in_path (decorated_program);
286 g_free (decorated_program);
294 } while (*p++ != '\0');
299 return inner_find_program_in_path (program);
305 * g_find_program_in_path:
306 * @program: a program name in the GLib file name encoding
308 * Locates the first executable named @program in the user's path, in the
309 * same way that execvp() would locate it. Returns an allocated string
310 * with the absolute path name, or %NULL if the program is not found in
311 * the path. If @program is already an absolute path, returns a copy of
312 * @program if @program exists and is executable, and %NULL otherwise.
314 * On Windows, if @program does not have a file type suffix, tries
315 * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
316 * the <envar>PATHEXT</envar> environment variable.
318 * On Windows, it looks for the file in the same way as CreateProcess()
319 * would. This means first in the directory where the executing
320 * program was loaded from, then in the current directory, then in the
321 * Windows 32-bit system directory, then in the Windows directory, and
322 * finally in the directories in the <envar>PATH</envar> environment
323 * variable. If the program is found, the return value contains the
324 * full name including the type suffix.
326 * Return value: absolute path, or %NULL
330 inner_find_program_in_path (const gchar *program)
333 g_find_program_in_path (const gchar *program)
336 const gchar *path, *p;
337 gchar *name, *freeme;
339 const gchar *path_copy;
340 gchar *filename = NULL, *appdir = NULL;
341 gchar *sysdir = NULL, *windir = NULL;
346 g_return_val_if_fail (program != NULL, NULL);
348 /* If it is an absolute path, or a relative path including subdirectories,
349 * don't look in PATH.
351 if (g_path_is_absolute (program)
352 || strchr (program, G_DIR_SEPARATOR) != NULL
354 || strchr (program, '/') != NULL
358 if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
359 !g_file_test (program, G_FILE_TEST_IS_DIR))
360 return g_strdup (program);
365 path = g_getenv ("PATH");
369 /* There is no `PATH' in the environment. The default
370 * search path in GNU libc is the current directory followed by
371 * the path `confstr' returns for `_CS_PATH'.
374 /* In GLib we put . last, for security, and don't use the
375 * unportable confstr(); UNIX98 does not actually specify
376 * what to search if PATH is unset. POSIX may, dunno.
379 path = "/bin:/usr/bin:.";
382 if (G_WIN32_HAVE_WIDECHAR_API ())
385 wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
388 n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
389 if (n > 0 && n < MAXPATHLEN)
390 filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
392 n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
393 if (n > 0 && n < MAXPATHLEN)
394 sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
396 n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
397 if (n > 0 && n < MAXPATHLEN)
398 windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
403 gchar cpfilename[MAXPATHLEN], cpsysdir[MAXPATHLEN],
404 cpwindir[MAXPATHLEN];
406 n = GetModuleFileNameA (NULL, cpfilename, MAXPATHLEN);
407 if (n > 0 && n < MAXPATHLEN)
408 filename = g_locale_to_utf8 (cpfilename, -1, NULL, NULL, NULL);
410 n = GetSystemDirectoryA (cpsysdir, MAXPATHLEN);
411 if (n > 0 && n < MAXPATHLEN)
412 sysdir = g_locale_to_utf8 (cpsysdir, -1, NULL, NULL, NULL);
414 n = GetWindowsDirectoryA (cpwindir, MAXPATHLEN);
415 if (n > 0 && n < MAXPATHLEN)
416 windir = g_locale_to_utf8 (cpwindir, -1, NULL, NULL, NULL);
421 appdir = g_path_get_dirname (filename);
425 path = g_strdup (path);
429 const gchar *tem = path;
430 path = g_strconcat (windir, ";", path, NULL);
431 g_free ((gchar *) tem);
437 const gchar *tem = path;
438 path = g_strconcat (sysdir, ";", path, NULL);
439 g_free ((gchar *) tem);
444 const gchar *tem = path;
445 path = g_strconcat (".;", path, NULL);
446 g_free ((gchar *) tem);
451 const gchar *tem = path;
452 path = g_strconcat (appdir, ";", path, NULL);
453 g_free ((gchar *) tem);
460 len = strlen (program) + 1;
461 pathlen = strlen (path);
462 freeme = name = g_malloc (pathlen + len + 1);
464 /* Copy the file name at the top, including '\0' */
465 memcpy (name + pathlen + 1, program, len);
466 name = name + pathlen;
467 /* And add the slash before the filename */
468 *name = G_DIR_SEPARATOR;
476 p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
479 /* Two adjacent colons, or a colon at the beginning or the end
480 * of `PATH' means to search the current directory.
484 startp = memcpy (name - (p - path), path, p - path);
486 if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
487 !g_file_test (startp, G_FILE_TEST_IS_DIR))
490 ret = g_strdup (startp);
493 g_free ((gchar *) path_copy);
498 while (*p++ != '\0');
502 g_free ((gchar *) path_copy);
509 * g_parse_debug_string:
510 * @string: a list of debug options separated by ':' or "all"
512 * @keys: pointer to an array of #GDebugKey which associate
513 * strings with bit flags.
514 * @nkeys: the number of #GDebugKey<!-- -->s in the array.
516 * Parses a string containing debugging options separated
517 * by ':' into a %guint containing bit flags. This is used
518 * within GDK and GTK+ to parse the debug options passed on the
519 * command line or through environment variables.
521 * Returns: the combined set of bit flags.
524 g_parse_debug_string (const gchar *string,
525 const GDebugKey *keys,
531 g_return_val_if_fail (string != NULL, 0);
533 if (!g_ascii_strcasecmp (string, "all"))
535 for (i=0; i<nkeys; i++)
536 result |= keys[i].value;
540 const gchar *p = string;
542 gboolean done = FALSE;
553 for (i=0; i<nkeys; i++)
554 if (g_ascii_strncasecmp (keys[i].key, p, q - p) == 0 &&
555 keys[i].key[q - p] == '\0')
556 result |= keys[i].value;
567 * @file_name: the name of the file.
569 * Gets the name of the file without any leading directory components.
570 * It returns a pointer into the given file name string.
572 * Return value: the name of the file without any leading directory components.
574 * Deprecated: Use g_path_get_basename() instead, but notice that
575 * g_path_get_basename() allocates new memory for the returned string, unlike
576 * this function which returns a pointer into the argument.
578 G_CONST_RETURN gchar*
579 g_basename (const gchar *file_name)
581 register gchar *base;
583 g_return_val_if_fail (file_name != NULL, NULL);
585 base = strrchr (file_name, G_DIR_SEPARATOR);
589 gchar *q = strrchr (file_name, '/');
590 if (base == NULL || (q != NULL && q > base))
599 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
600 return (gchar*) file_name + 2;
601 #endif /* G_OS_WIN32 */
603 return (gchar*) file_name;
607 * g_path_get_basename:
608 * @file_name: the name of the file.
610 * Gets the last component of the filename. If @file_name ends with a
611 * directory separator it gets the component before the last slash. If
612 * @file_name consists only of directory separators (and on Windows,
613 * possibly a drive letter), a single separator is returned. If
614 * @file_name is empty, it gets ".".
616 * Return value: a newly allocated string containing the last component of
620 g_path_get_basename (const gchar *file_name)
622 register gssize base;
623 register gssize last_nonslash;
627 g_return_val_if_fail (file_name != NULL, NULL);
629 if (file_name[0] == '\0')
631 return g_strdup (".");
633 last_nonslash = strlen (file_name) - 1;
635 while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
638 if (last_nonslash == -1)
639 /* string only containing slashes */
640 return g_strdup (G_DIR_SEPARATOR_S);
643 if (last_nonslash == 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
644 /* string only containing slashes and a drive */
645 return g_strdup (G_DIR_SEPARATOR_S);
646 #endif /* G_OS_WIN32 */
648 base = last_nonslash;
650 while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
654 if (base == -1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
656 #endif /* G_OS_WIN32 */
658 len = last_nonslash - base;
659 retval = g_malloc (len + 1);
660 memcpy (retval, file_name + base + 1, len);
666 * g_path_is_absolute:
667 * @file_name: a file name.
669 * Returns %TRUE if the given @file_name is an absolute file name,
670 * i.e. it contains a full path from the root directory such as "/usr/local"
671 * on UNIX or "C:\windows" on Windows systems.
673 * Returns: %TRUE if @file_name is an absolute path.
676 g_path_is_absolute (const gchar *file_name)
678 g_return_val_if_fail (file_name != NULL, FALSE);
680 if (G_IS_DIR_SEPARATOR (file_name[0]))
684 /* Recognize drive letter on native Windows */
685 if (g_ascii_isalpha (file_name[0]) &&
686 file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
688 #endif /* G_OS_WIN32 */
695 * @file_name: a file name.
697 * Returns a pointer into @file_name after the root component, i.e. after
698 * the "/" in UNIX or "C:\" under Windows. If @file_name is not an absolute
699 * path it returns %NULL.
701 * Returns: a pointer into @file_name after the root component.
703 G_CONST_RETURN gchar*
704 g_path_skip_root (const gchar *file_name)
706 g_return_val_if_fail (file_name != NULL, NULL);
708 #ifdef G_PLATFORM_WIN32
709 /* Skip \\server\share or //server/share */
710 if (G_IS_DIR_SEPARATOR (file_name[0]) &&
711 G_IS_DIR_SEPARATOR (file_name[1]) &&
713 !G_IS_DIR_SEPARATOR (file_name[2]))
717 p = strchr (file_name + 2, G_DIR_SEPARATOR);
720 gchar *q = strchr (file_name + 2, '/');
721 if (p == NULL || (q != NULL && q < p))
731 while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
734 /* Possibly skip a backslash after the share name */
735 if (G_IS_DIR_SEPARATOR (file_name[0]))
738 return (gchar *)file_name;
743 /* Skip initial slashes */
744 if (G_IS_DIR_SEPARATOR (file_name[0]))
746 while (G_IS_DIR_SEPARATOR (file_name[0]))
748 return (gchar *)file_name;
753 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
754 return (gchar *)file_name + 3;
761 * g_path_get_dirname:
762 * @file_name: the name of the file.
764 * Gets the directory components of a file name. If the file name has no
765 * directory components "." is returned. The returned string should be
766 * freed when no longer needed.
768 * Returns: the directory components of the file.
771 g_path_get_dirname (const gchar *file_name)
773 register gchar *base;
776 g_return_val_if_fail (file_name != NULL, NULL);
778 base = strrchr (file_name, G_DIR_SEPARATOR);
781 gchar *q = strrchr (file_name, '/');
782 if (base == NULL || (q != NULL && q > base))
789 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
791 gchar drive_colon_dot[4];
793 drive_colon_dot[0] = file_name[0];
794 drive_colon_dot[1] = ':';
795 drive_colon_dot[2] = '.';
796 drive_colon_dot[3] = '\0';
798 return g_strdup (drive_colon_dot);
801 return g_strdup (".");
804 while (base > file_name && G_IS_DIR_SEPARATOR (*base))
808 /* base points to the char before the last slash.
810 * In case file_name is the root of a drive (X:\) or a child of the
811 * root of a drive (X:\foo), include the slash.
813 * In case file_name is the root share of an UNC path
814 * (\\server\share), add a slash, returning \\server\share\ .
816 * In case file_name is a direct child of a share in an UNC path
817 * (\\server\share\foo), include the slash after the share name,
818 * returning \\server\share\ .
820 if (base == file_name + 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
822 else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
823 G_IS_DIR_SEPARATOR (file_name[1]) &&
825 !G_IS_DIR_SEPARATOR (file_name[2]) &&
826 base >= file_name + 2)
828 const gchar *p = file_name + 2;
829 while (*p && !G_IS_DIR_SEPARATOR (*p))
833 len = (guint) strlen (file_name) + 1;
834 base = g_new (gchar, len + 1);
835 strcpy (base, file_name);
836 base[len-1] = G_DIR_SEPARATOR;
840 if (G_IS_DIR_SEPARATOR (*p))
843 while (*p && !G_IS_DIR_SEPARATOR (*p))
851 len = (guint) 1 + base - file_name;
853 base = g_new (gchar, len + 1);
854 g_memmove (base, file_name, len);
863 * Gets the current directory.
864 * The returned string should be freed when no longer needed. The encoding
865 * of the returned string is system defined. On Windows, it is always UTF-8.
867 * Returns: the current directory.
870 g_get_current_dir (void)
876 if (G_WIN32_HAVE_WIDECHAR_API ())
878 wchar_t dummy[2], *wdir;
881 len = GetCurrentDirectoryW (2, dummy);
882 wdir = g_new (wchar_t, len);
884 if (GetCurrentDirectoryW (len, wdir) == len - 1)
885 dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
891 gchar dummy[2], *cpdir;
894 len = GetCurrentDirectoryA (2, dummy);
895 cpdir = g_new (gchar, len);
897 if (GetCurrentDirectoryA (len, cpdir) == len - 1)
898 dir = g_locale_to_utf8 (cpdir, -1, NULL, NULL, NULL);
904 dir = g_strdup ("\\");
910 gchar *buffer = NULL;
912 static gulong max_len = 0;
915 max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
917 /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
918 * and, if that wasn't bad enough, hangs in doing so.
920 #if (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
921 buffer = g_new (gchar, max_len + 1);
923 dir = getwd (buffer);
924 #else /* !sun || !HAVE_GETCWD */
925 while (max_len < G_MAXULONG / 2)
927 buffer = g_new (gchar, max_len + 1);
929 dir = getcwd (buffer, max_len);
931 if (dir || errno != ERANGE)
937 #endif /* !sun || !HAVE_GETCWD */
939 if (!dir || !*buffer)
941 /* hm, should we g_error() out here?
942 * this can happen if e.g. "./" has mode \0000
944 buffer[0] = G_DIR_SEPARATOR;
948 dir = g_strdup (buffer);
957 * @variable: the environment variable to get, in the GLib file name encoding.
959 * Returns the value of an environment variable. The name and value
960 * are in the GLib file name encoding. On UNIX, this means the actual
961 * bytes which might or might not be in some consistent character set
962 * and encoding. On Windows, it is in UTF-8. On Windows, in case the
963 * environment variable's value contains references to other
964 * environment variables, they are expanded.
966 * Return value: the value of the environment variable, or %NULL if
967 * the environment variable is not found. The returned string may be
968 * overwritten by the next call to g_getenv(), g_setenv() or
971 G_CONST_RETURN gchar*
972 g_getenv (const gchar *variable)
976 g_return_val_if_fail (variable != NULL, NULL);
978 return getenv (variable);
980 #else /* G_OS_WIN32 */
985 g_return_val_if_fail (variable != NULL, NULL);
986 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), NULL);
988 /* On Windows NT, it is relatively typical that environment
989 * variables contain references to other environment variables. If
990 * so, use ExpandEnvironmentStrings(). (In an ideal world, such
991 * environment variables would be stored in the Registry as
992 * REG_EXPAND_SZ type values, and would then get automatically
993 * expanded before a program sees them. But there is broken software
994 * that stores environment variables as REG_SZ values even if they
995 * contain references to other environment variables.)
998 if (G_WIN32_HAVE_WIDECHAR_API ())
1000 wchar_t dummy[2], *wname, *wvalue;
1003 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1005 len = GetEnvironmentVariableW (wname, dummy, 2);
1015 wvalue = g_new (wchar_t, len);
1017 if (GetEnvironmentVariableW (wname, wvalue, len) != len - 1)
1024 if (wcschr (wvalue, L'%') != NULL)
1026 wchar_t *tem = wvalue;
1028 len = ExpandEnvironmentStringsW (wvalue, dummy, 2);
1032 wvalue = g_new (wchar_t, len);
1034 if (ExpandEnvironmentStringsW (tem, wvalue, len) != len)
1044 value = g_utf16_to_utf8 (wvalue, -1, NULL, NULL, NULL);
1051 gchar dummy[3], *cpname, *cpvalue;
1054 cpname = g_locale_from_utf8 (variable, -1, NULL, NULL, NULL);
1056 g_return_val_if_fail (cpname != NULL, NULL);
1058 len = GetEnvironmentVariableA (cpname, dummy, 2);
1068 cpvalue = g_new (gchar, len);
1070 if (GetEnvironmentVariableA (cpname, cpvalue, len) != len - 1)
1077 if (strchr (cpvalue, '%') != NULL)
1079 gchar *tem = cpvalue;
1081 len = ExpandEnvironmentStringsA (cpvalue, dummy, 3);
1085 cpvalue = g_new (gchar, len);
1087 if (ExpandEnvironmentStringsA (tem, cpvalue, len) != len)
1097 value = g_locale_to_utf8 (cpvalue, -1, NULL, NULL, NULL);
1103 quark = g_quark_from_string (value);
1106 return g_quark_to_string (quark);
1108 #endif /* G_OS_WIN32 */
1113 * @variable: the environment variable to set, must not contain '='.
1114 * @value: the value for to set the variable to.
1115 * @overwrite: whether to change the variable if it already exists.
1117 * Sets an environment variable. Both the variable's name and value
1118 * should be in the GLib file name encoding. On UNIX, this means that
1119 * they can be any sequence of bytes. On Windows, they should be in
1122 * Note that on some systems, when variables are overwritten, the memory
1123 * used for the previous variables and its value isn't reclaimed.
1125 * Returns: %FALSE if the environment variable couldn't be set.
1130 g_setenv (const gchar *variable,
1141 g_return_val_if_fail (variable != NULL, FALSE);
1142 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1145 result = setenv (variable, value, overwrite);
1147 if (!overwrite && getenv (variable) != NULL)
1150 /* This results in a leak when you overwrite existing
1151 * settings. It would be fairly easy to fix this by keeping
1152 * our own parallel array or hash table.
1154 string = g_strconcat (variable, "=", value, NULL);
1155 result = putenv (string);
1159 #else /* G_OS_WIN32 */
1163 g_return_val_if_fail (variable != NULL, FALSE);
1164 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1165 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), FALSE);
1166 g_return_val_if_fail (g_utf8_validate (value, -1, NULL), FALSE);
1168 if (!overwrite && g_getenv (variable) != NULL)
1171 /* We want to (if possible) set both the environment variable copy
1172 * kept by the C runtime and the one kept by the system.
1174 * We can't use only the C runtime's putenv or _wputenv() as that
1175 * won't work for arbitrary Unicode strings in a "non-Unicode" app
1176 * (with main() and not wmain()). In a "main()" app the C runtime
1177 * initializes the C runtime's environment table by converting the
1178 * real (wide char) environment variables to system codepage, thus
1179 * breaking those that aren't representable in the system codepage.
1181 * As the C runtime's putenv() will also set the system copy, we do
1182 * the putenv() first, then call SetEnvironmentValueW ourselves.
1185 if (G_WIN32_HAVE_WIDECHAR_API ())
1187 wchar_t *wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1188 wchar_t *wvalue = g_utf8_to_utf16 (value, -1, NULL, NULL, NULL);
1189 gchar *tem = g_strconcat (variable, "=", value, NULL);
1190 wchar_t *wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1193 _wputenv (wassignment);
1194 g_free (wassignment);
1196 retval = (SetEnvironmentVariableW (wname, wvalue) != 0);
1203 /* In the non-Unicode case (Win9x), just putenv() is good
1206 gchar *tem = g_strconcat (variable, "=", value, NULL);
1207 gchar *cpassignment = g_locale_from_utf8 (tem, -1, NULL, NULL, NULL);
1211 retval = (putenv (cpassignment) == 0);
1213 g_free (cpassignment);
1218 #endif /* 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;
1232 * @variable: the environment variable to remove, must not contain '='.
1234 * Removes an environment variable from the environment.
1236 * Note that on some systems, when variables are overwritten, the memory
1237 * used for the previous variables and its value isn't reclaimed.
1238 * Furthermore, this function can't be guaranteed to operate in a
1244 g_unsetenv (const gchar *variable)
1248 #ifdef HAVE_UNSETENV
1249 g_return_if_fail (variable != NULL);
1250 g_return_if_fail (strchr (variable, '=') == NULL);
1252 unsetenv (variable);
1253 #else /* !HAVE_UNSETENV */
1257 g_return_if_fail (variable != NULL);
1258 g_return_if_fail (strchr (variable, '=') == NULL);
1260 len = strlen (variable);
1262 /* Mess directly with the environ array.
1263 * This seems to be the only portable way to do this.
1265 * Note that we remove *all* environment entries for
1266 * the variable name, not just the first.
1271 if (strncmp (*e, variable, len) != 0 || (*e)[len] != '=')
1279 #endif /* !HAVE_UNSETENV */
1281 #else /* G_OS_WIN32 */
1283 g_return_if_fail (variable != NULL);
1284 g_return_if_fail (strchr (variable, '=') == NULL);
1285 g_return_if_fail (g_utf8_validate (variable, -1, NULL));
1287 if (G_WIN32_HAVE_WIDECHAR_API ())
1289 wchar_t *wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1290 gchar *tem = g_strconcat (variable, "=", NULL);
1291 wchar_t *wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1294 _wputenv (wassignment);
1295 g_free (wassignment);
1297 SetEnvironmentVariableW (wname, NULL);
1303 /* In the non-Unicode case (Win9x), just putenv() is good
1306 gchar *tem = g_strconcat (variable, "=", NULL);
1307 gchar *cpassignment = g_locale_from_utf8 (tem, -1, NULL, NULL, NULL);
1311 putenv (cpassignment);
1313 g_free (cpassignment);
1316 #endif /* G_OS_WIN32 */
1322 * Gets the names of all variables set in the environment.
1324 * Return: a NUL-terminated list of strings which must be freed
1325 * with g_strfreev().
1332 gchar **result, *eq;
1335 len = g_strv_length (environ);
1336 result = g_new0 (gchar *, len + 1);
1338 for (i = 0; i < len; i++)
1340 eq = strchr (environ[i], '=');
1341 result[i] = g_strndup (environ[i], eq - environ[i]);
1349 G_LOCK_DEFINE_STATIC (g_utils_global);
1351 static gchar *g_tmp_dir = NULL;
1352 static gchar *g_user_name = NULL;
1353 static gchar *g_real_name = NULL;
1354 static gchar *g_home_dir = NULL;
1357 /* System codepage versions of the above, kept at file level so that they,
1358 * too, are produced only once.
1360 static gchar *g_tmp_dir_cp = NULL;
1361 static gchar *g_user_name_cp = NULL;
1362 static gchar *g_real_name_cp = NULL;
1363 static gchar *g_home_dir_cp = NULL;
1366 static gchar *g_user_data_dir = NULL;
1367 static gchar **g_system_data_dirs = NULL;
1368 static gchar *g_user_cache_dir = NULL;
1369 static gchar *g_user_config_dir = NULL;
1370 static gchar **g_system_config_dirs = NULL;
1375 get_special_folder (int csidl)
1379 wchar_t wc[MAX_PATH+1];
1382 LPITEMIDLIST pidl = NULL;
1384 gchar *retval = NULL;
1386 hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
1389 if (G_WIN32_HAVE_WIDECHAR_API ())
1391 b = SHGetPathFromIDListW (pidl, path.wc);
1393 retval = g_utf16_to_utf8 (path.wc, -1, NULL, NULL, NULL);
1397 b = SHGetPathFromIDListA (pidl, path.c);
1399 retval = g_locale_to_utf8 (path.c, -1, NULL, NULL, NULL);
1401 CoTaskMemFree (pidl);
1408 /* HOLDS: g_utils_global_lock */
1410 g_get_any_init (void)
1414 g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
1416 g_tmp_dir = g_strdup (g_getenv ("TMP"));
1418 g_tmp_dir = g_strdup (g_getenv ("TEMP"));
1424 g_tmp_dir = g_strdup (P_tmpdir);
1425 k = strlen (g_tmp_dir);
1426 if (k > 1 && G_IS_DIR_SEPARATOR (g_tmp_dir[k - 1]))
1427 g_tmp_dir[k - 1] = '\0';
1434 g_tmp_dir = g_strdup ("/tmp");
1435 #else /* G_OS_WIN32 */
1436 g_tmp_dir = g_strdup ("\\");
1437 #endif /* G_OS_WIN32 */
1441 /* We check $HOME first for Win32, though it is a last resort for Unix
1442 * where we prefer the results of getpwuid().
1444 g_home_dir = g_strdup (g_getenv ("HOME"));
1446 /* Only believe HOME if it is an absolute path and exists */
1449 if (!(g_path_is_absolute (g_home_dir) &&
1450 g_file_test (g_home_dir, G_FILE_TEST_IS_DIR)))
1452 g_free (g_home_dir);
1457 /* In case HOME is Unix-style (it happens), convert it to
1463 while ((p = strchr (g_home_dir, '/')) != NULL)
1469 /* USERPROFILE is probably the closest equivalent to $HOME? */
1470 if (g_getenv ("USERPROFILE") != NULL)
1471 g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
1475 g_home_dir = get_special_folder (CSIDL_PROFILE);
1479 /* At least at some time, HOMEDRIVE and HOMEPATH were used
1480 * to point to the home directory, I think. But on Windows
1481 * 2000 HOMEDRIVE seems to be equal to SYSTEMDRIVE, and
1482 * HOMEPATH is its root "\"?
1484 if (g_getenv ("HOMEDRIVE") != NULL && g_getenv ("HOMEPATH") != NULL)
1485 g_home_dir = g_strconcat (g_getenv ("HOMEDRIVE"),
1486 g_getenv ("HOMEPATH"),
1489 #endif /* G_OS_WIN32 */
1493 struct passwd *pw = NULL;
1494 gpointer buffer = NULL;
1497 # if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
1499 # ifdef _SC_GETPW_R_SIZE_MAX
1500 /* This reurns the maximum length */
1501 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
1505 # else /* _SC_GETPW_R_SIZE_MAX */
1507 # endif /* _SC_GETPW_R_SIZE_MAX */
1512 /* we allocate 6 extra bytes to work around a bug in
1513 * Mac OS < 10.3. See #156446
1515 buffer = g_malloc (bufsize + 6);
1518 # ifdef HAVE_POSIX_GETPWUID_R
1519 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1520 error = error < 0 ? errno : error;
1521 # else /* HAVE_NONPOSIX_GETPWUID_R */
1522 /* HPUX 11 falls into the HAVE_POSIX_GETPWUID_R case */
1523 # if defined(_AIX) || defined(__hpux)
1524 error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1525 pw = error == 0 ? &pwd : NULL;
1527 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1528 error = pw ? 0 : errno;
1530 # endif /* HAVE_NONPOSIX_GETPWUID_R */
1534 /* we bail out prematurely if the user id can't be found
1535 * (should be pretty rare case actually), or if the buffer
1536 * should be sufficiently big and lookups are still not
1539 if (error == 0 || error == ENOENT)
1541 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
1542 (gulong) getuid ());
1545 if (bufsize > 32 * 1024)
1547 g_warning ("getpwuid_r(): failed due to: %s.",
1548 g_strerror (error));
1556 # endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
1561 pw = getpwuid (getuid ());
1566 g_user_name = g_strdup (pw->pw_name);
1568 if (pw->pw_gecos && *pw->pw_gecos != '\0')
1570 gchar **gecos_fields;
1573 /* split the gecos field and substitute '&' */
1574 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
1575 name_parts = g_strsplit (gecos_fields[0], "&", 0);
1576 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
1577 g_real_name = g_strjoinv (pw->pw_name, name_parts);
1578 g_strfreev (gecos_fields);
1579 g_strfreev (name_parts);
1583 g_home_dir = g_strdup (pw->pw_dir);
1588 #else /* !HAVE_PWD_H */
1591 if (G_WIN32_HAVE_WIDECHAR_API ())
1593 guint len = UNLEN+1;
1594 wchar_t buffer[UNLEN+1];
1596 if (GetUserNameW (buffer, (LPDWORD) &len))
1598 g_user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
1599 g_real_name = g_strdup (g_user_name);
1604 guint len = UNLEN+1;
1605 char buffer[UNLEN+1];
1607 if (GetUserNameA (buffer, (LPDWORD) &len))
1609 g_user_name = g_locale_to_utf8 (buffer, -1, NULL, NULL, NULL);
1610 g_real_name = g_strdup (g_user_name);
1613 #endif /* G_OS_WIN32 */
1615 #endif /* !HAVE_PWD_H */
1619 g_home_dir = g_strdup (g_getenv ("HOME"));
1623 /* change '\\' in %HOME% to '/' */
1624 g_strdelimit (g_home_dir, "\\",'/');
1627 g_user_name = g_strdup ("somebody");
1629 g_real_name = g_strdup ("Unknown");
1632 g_tmp_dir_cp = g_locale_from_utf8 (g_tmp_dir, -1, NULL, NULL, NULL);
1633 g_user_name_cp = g_locale_from_utf8 (g_user_name, -1, NULL, NULL, NULL);
1634 g_real_name_cp = g_locale_from_utf8 (g_real_name, -1, NULL, NULL, NULL);
1637 g_tmp_dir_cp = g_strdup ("\\");
1638 if (!g_user_name_cp)
1639 g_user_name_cp = g_strdup ("somebody");
1640 if (!g_real_name_cp)
1641 g_real_name_cp = g_strdup ("Unknown");
1643 /* home_dir might be NULL, unlike tmp_dir, user_name and
1647 g_home_dir_cp = g_locale_from_utf8 (g_home_dir, -1, NULL, NULL, NULL);
1649 g_home_dir_cp = NULL;
1650 #endif /* G_OS_WIN32 */
1657 * Gets the user name of the current user. The encoding of the returned
1658 * string is system-defined. On UNIX, it might be the preferred file name
1659 * encoding, or something else, and there is no guarantee that it is even
1660 * consistent on a machine. On Windows, it is always UTF-8.
1662 * Returns: the user name of the current user.
1664 G_CONST_RETURN gchar*
1665 g_get_user_name (void)
1667 G_LOCK (g_utils_global);
1670 G_UNLOCK (g_utils_global);
1678 * Gets the real name of the user. This usually comes from the user's entry
1679 * in the <filename>passwd</filename> file. The encoding of the returned
1680 * string is system-defined. (On Windows, it is, however, always UTF-8.)
1681 * If the real user name cannot be determined, the string "Unknown" is
1684 * Returns: the user's real name.
1686 G_CONST_RETURN gchar*
1687 g_get_real_name (void)
1689 G_LOCK (g_utils_global);
1692 G_UNLOCK (g_utils_global);
1700 * Gets the current user's home directory.
1702 * Note that in contrast to traditional UNIX tools, this function
1703 * prefers <filename>passwd</filename> entries over the <envar>HOME</envar>
1704 * environment variable.
1706 * Returns: the current user's home directory.
1708 G_CONST_RETURN gchar*
1709 g_get_home_dir (void)
1711 G_LOCK (g_utils_global);
1714 G_UNLOCK (g_utils_global);
1722 * Gets the directory to use for temporary files. This is found from
1723 * inspecting the environment variables <envar>TMPDIR</envar>,
1724 * <envar>TMP</envar>, and <envar>TEMP</envar> in that order. If none
1725 * of those are defined "/tmp" is returned on UNIX and "C:\" on Windows.
1726 * The encoding of the returned string is system-defined. On Windows,
1727 * it is always UTF-8. The return value is never %NULL.
1729 * Returns: the directory to use for temporary files.
1731 G_CONST_RETURN gchar*
1732 g_get_tmp_dir (void)
1734 G_LOCK (g_utils_global);
1737 G_UNLOCK (g_utils_global);
1742 G_LOCK_DEFINE_STATIC (g_prgname);
1743 static gchar *g_prgname = NULL;
1748 * Gets the name of the program. This name should <emphasis>not</emphasis>
1749 * be localized, contrast with g_get_application_name().
1750 * (If you are using GDK or GTK+ the program name is set in gdk_init(),
1751 * which is called by gtk_init(). The program name is found by taking
1752 * the last component of <literal>argv[0]</literal>.)
1754 * Returns: the name of the program. The returned string belongs
1755 * to GLib and must not be modified or freed.
1758 g_get_prgname (void)
1764 if (g_prgname == NULL)
1766 static gboolean beenhere = FALSE;
1770 gchar *utf8_buf = NULL;
1773 if (G_WIN32_HAVE_WIDECHAR_API ())
1775 wchar_t buf[MAX_PATH+1];
1776 if (GetModuleFileNameW (GetModuleHandle (NULL),
1777 buf, G_N_ELEMENTS (buf)) > 0)
1778 utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
1782 gchar buf[MAX_PATH+1];
1783 if (GetModuleFileNameA (GetModuleHandle (NULL),
1784 buf, G_N_ELEMENTS (buf)) > 0)
1785 utf8_buf = g_locale_to_utf8 (buf, -1, NULL, NULL, NULL);
1789 g_prgname = g_path_get_basename (utf8_buf);
1796 G_UNLOCK (g_prgname);
1803 * @prgname: the name of the program.
1805 * Sets the name of the program. This name should <emphasis>not</emphasis>
1806 * be localized, contrast with g_set_application_name(). Note that for
1807 * thread-safety reasons this function can only be called once.
1810 g_set_prgname (const gchar *prgname)
1814 g_prgname = g_strdup (prgname);
1815 G_UNLOCK (g_prgname);
1818 G_LOCK_DEFINE_STATIC (g_application_name);
1819 static gchar *g_application_name = NULL;
1822 * g_get_application_name:
1824 * Gets a human-readable name for the application, as set by
1825 * g_set_application_name(). This name should be localized if
1826 * possible, and is intended for display to the user. Contrast with
1827 * g_get_prgname(), which gets a non-localized name. If
1828 * g_set_application_name() has not been called, returns the result of
1829 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1832 * Return value: human-readable application name. may return %NULL
1836 G_CONST_RETURN gchar*
1837 g_get_application_name (void)
1841 G_LOCK (g_application_name);
1842 retval = g_application_name;
1843 G_UNLOCK (g_application_name);
1846 return g_get_prgname ();
1852 * g_set_application_name:
1853 * @application_name: localized name of the application
1855 * Sets a human-readable name for the application. This name should be
1856 * localized if possible, and is intended for display to the user.
1857 * Contrast with g_set_prgname(), which sets a non-localized name.
1858 * g_set_prgname() will be called automatically by gtk_init(),
1859 * but g_set_application_name() will not.
1861 * Note that for thread safety reasons, this function can only
1864 * The application name will be used in contexts such as error messages,
1865 * or when displaying an application's name in the task list.
1869 g_set_application_name (const gchar *application_name)
1871 gboolean already_set = FALSE;
1873 G_LOCK (g_application_name);
1874 if (g_application_name)
1877 g_application_name = g_strdup (application_name);
1878 G_UNLOCK (g_application_name);
1881 g_warning ("g_set_application() name called multiple times");
1885 * g_get_user_data_dir:
1887 * Returns a base directory in which to access application data such
1888 * as icons that is customized for a particular user.
1890 * On UNIX platforms this is determined using the mechanisms described in
1891 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1892 * XDG Base Directory Specification</ulink>
1894 * Return value: a string owned by GLib that must not be modified
1898 G_CONST_RETURN gchar*
1899 g_get_user_data_dir (void)
1903 G_LOCK (g_utils_global);
1905 if (!g_user_data_dir)
1908 data_dir = get_special_folder (CSIDL_PERSONAL);
1910 data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
1912 if (data_dir && data_dir[0])
1913 data_dir = g_strdup (data_dir);
1915 if (!data_dir || !data_dir[0])
1921 data_dir = g_build_filename (g_home_dir, ".local",
1924 data_dir = g_build_filename (g_tmp_dir, g_user_name, ".local",
1928 g_user_data_dir = data_dir;
1931 data_dir = g_user_data_dir;
1933 G_UNLOCK (g_utils_global);
1939 * g_get_user_config_dir:
1941 * Returns a base directory in which to store user-specific application
1942 * configuration information such as user preferences and settings.
1944 * On UNIX platforms this is determined using the mechanisms described in
1945 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1946 * XDG Base Directory Specification</ulink>
1948 * Return value: a string owned by GLib that must not be modified
1952 G_CONST_RETURN gchar*
1953 g_get_user_config_dir (void)
1957 G_LOCK (g_utils_global);
1959 if (!g_user_config_dir)
1962 config_dir = get_special_folder (CSIDL_APPDATA);
1964 config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
1966 if (config_dir && config_dir[0])
1967 config_dir = g_strdup (config_dir);
1969 if (!config_dir || !config_dir[0])
1975 config_dir = g_build_filename (g_home_dir, ".config", NULL);
1977 config_dir = g_build_filename (g_tmp_dir, g_user_name, ".config", NULL);
1979 g_user_config_dir = config_dir;
1982 config_dir = g_user_config_dir;
1984 G_UNLOCK (g_utils_global);
1990 * g_get_user_cache_dir:
1992 * Returns a base directory in which to store non-essential, cached
1993 * data specific to particular user.
1995 * On UNIX platforms this is determined using the mechanisms described in
1996 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1997 * XDG Base Directory Specification</ulink>
1999 * Return value: a string owned by GLib that must not be modified
2003 G_CONST_RETURN gchar*
2004 g_get_user_cache_dir (void)
2008 G_LOCK (g_utils_global);
2010 if (!g_user_cache_dir)
2013 cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
2015 cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
2017 if (cache_dir && cache_dir[0])
2018 cache_dir = g_strdup (cache_dir);
2020 if (!cache_dir || !cache_dir[0])
2026 cache_dir = g_build_filename (g_home_dir, ".cache", NULL);
2028 cache_dir = g_build_filename (g_tmp_dir, g_user_name, ".cache", NULL);
2030 g_user_cache_dir = cache_dir;
2033 cache_dir = g_user_cache_dir;
2035 G_UNLOCK (g_utils_global);
2041 * g_get_system_data_dirs:
2043 * Returns an ordered list of base directories in which to access
2044 * system-wide application data.
2046 * On UNIX platforms this is determined using the mechanisms described in
2047 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2048 * XDG Base Directory Specification</ulink>
2050 * Return value: a %NULL-terminated array of strings owned by GLib that must
2051 * not be modified or freed.
2054 G_CONST_RETURN gchar * G_CONST_RETURN *
2055 g_get_system_data_dirs (void)
2057 gchar *data_dirs, **data_dir_vector;
2059 G_LOCK (g_utils_global);
2061 if (!g_system_data_dirs)
2064 char *appdata = get_special_folder (CSIDL_COMMON_APPDATA);
2065 char *docs = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2067 if (appdata && docs)
2069 data_dirs = g_strconcat (appdata,
2070 G_SEARCHPATH_SEPARATOR_S,
2077 data_dirs = appdata;
2085 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2090 /* Punt, return empty list */
2091 data_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2094 data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
2096 if (!data_dirs || !data_dirs[0])
2097 data_dirs = "/usr/local/share/:/usr/share/";
2099 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2102 g_system_data_dirs = data_dir_vector;
2105 data_dir_vector = g_system_data_dirs;
2107 G_UNLOCK (g_utils_global);
2109 return (G_CONST_RETURN gchar * G_CONST_RETURN *) data_dir_vector;
2113 * g_get_system_config_dirs:
2115 * Returns an ordered list of base directories in which to access
2116 * system-wide configuration information.
2118 * On UNIX platforms this is determined using the mechanisms described in
2119 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2120 * XDG Base Directory Specification</ulink>
2122 * Return value: a %NULL-terminated array of strings owned by GLib that must
2123 * not be modified or freed.
2126 G_CONST_RETURN gchar * G_CONST_RETURN *
2127 g_get_system_config_dirs (void)
2129 gchar *conf_dirs, **conf_dir_vector;
2131 G_LOCK (g_utils_global);
2133 if (!g_system_config_dirs)
2136 conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
2139 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2144 /* Return empty list */
2145 conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2148 conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
2150 if (!conf_dirs || !conf_dirs[0])
2151 conf_dirs = "/etc/xdg";
2153 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2156 g_system_config_dirs = conf_dir_vector;
2159 conf_dir_vector = g_system_config_dirs;
2160 G_UNLOCK (g_utils_global);
2162 return (G_CONST_RETURN gchar * G_CONST_RETURN *) conf_dir_vector;
2165 static GHashTable *alias_table = NULL;
2167 /* read an alias file for the locales */
2169 read_aliases (gchar *file)
2175 alias_table = g_hash_table_new (g_str_hash, g_str_equal);
2176 fp = fopen (file,"r");
2179 while (fgets (buf, 256, fp))
2185 /* Line is a comment */
2186 if ((buf[0] == '#') || (buf[0] == '\0'))
2189 /* Reads first column */
2190 for (p = buf, q = NULL; *p; p++) {
2191 if ((*p == '\t') || (*p == ' ') || (*p == ':')) {
2194 while ((*q == '\t') || (*q == ' ')) {
2200 /* The line only had one column */
2201 if (!q || *q == '\0')
2204 /* Read second column */
2205 for (p = q; *p; p++) {
2206 if ((*p == '\t') || (*p == ' ')) {
2212 /* Add to alias table if necessary */
2213 if (!g_hash_table_lookup (alias_table, buf)) {
2214 g_hash_table_insert (alias_table, g_strdup (buf), g_strdup (q));
2221 unalias_lang (char *lang)
2227 read_aliases ("/usr/share/locale/locale.alias");
2230 while ((p = g_hash_table_lookup (alias_table, lang)) && (strcmp (p, lang) != 0))
2235 static gboolean said_before = FALSE;
2237 g_warning ("Too many alias levels for a locale, "
2238 "may indicate a loop");
2246 /* Mask for components of locale spec. The ordering here is from
2247 * least significant to most significant
2251 COMPONENT_CODESET = 1 << 0,
2252 COMPONENT_TERRITORY = 1 << 1,
2253 COMPONENT_MODIFIER = 1 << 2
2256 /* Break an X/Open style locale specification into components
2259 explode_locale (const gchar *locale,
2265 const gchar *uscore_pos;
2266 const gchar *at_pos;
2267 const gchar *dot_pos;
2271 uscore_pos = strchr (locale, '_');
2272 dot_pos = strchr (uscore_pos ? uscore_pos : locale, '.');
2273 at_pos = strchr (dot_pos ? dot_pos : (uscore_pos ? uscore_pos : locale), '@');
2277 mask |= COMPONENT_MODIFIER;
2278 *modifier = g_strdup (at_pos);
2281 at_pos = locale + strlen (locale);
2285 mask |= COMPONENT_CODESET;
2286 *codeset = g_strndup (dot_pos, at_pos - dot_pos);
2293 mask |= COMPONENT_TERRITORY;
2294 *territory = g_strndup (uscore_pos, dot_pos - uscore_pos);
2297 uscore_pos = dot_pos;
2299 *language = g_strndup (locale, uscore_pos - locale);
2305 * Compute all interesting variants for a given locale name -
2306 * by stripping off different components of the value.
2308 * For simplicity, we assume that the locale is in
2309 * X/Open format: language[_territory][.codeset][@modifier]
2311 * TODO: Extend this to handle the CEN format (see the GNUlibc docs)
2312 * as well. We could just copy the code from glibc wholesale
2313 * but it is big, ugly, and complicated, so I'm reluctant
2314 * to do so when this should handle 99% of the time...
2317 _g_compute_locale_variants (const gchar *locale)
2319 GSList *retval = NULL;
2329 g_return_val_if_fail (locale != NULL, NULL);
2331 mask = explode_locale (locale, &language, &territory, &codeset, &modifier);
2333 /* Iterate through all possible combinations, from least attractive
2334 * to most attractive.
2336 for (i = 0; i <= mask; i++)
2337 if ((i & ~mask) == 0)
2339 gchar *val = g_strconcat (language,
2340 (i & COMPONENT_TERRITORY) ? territory : "",
2341 (i & COMPONENT_CODESET) ? codeset : "",
2342 (i & COMPONENT_MODIFIER) ? modifier : "",
2344 retval = g_slist_prepend (retval, val);
2348 if (mask & COMPONENT_CODESET)
2350 if (mask & COMPONENT_TERRITORY)
2352 if (mask & COMPONENT_MODIFIER)
2358 /* The following is (partly) taken from the gettext package.
2359 Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc. */
2361 static const gchar *
2362 guess_category_value (const gchar *category_name)
2364 const gchar *retval;
2366 /* The highest priority value is the `LANGUAGE' environment
2367 variable. This is a GNU extension. */
2368 retval = g_getenv ("LANGUAGE");
2369 if ((retval != NULL) && (retval[0] != '\0'))
2372 /* `LANGUAGE' is not set. So we have to proceed with the POSIX
2373 methods of looking to `LC_ALL', `LC_xxx', and `LANG'. On some
2374 systems this can be done by the `setlocale' function itself. */
2376 /* Setting of LC_ALL overwrites all other. */
2377 retval = g_getenv ("LC_ALL");
2378 if ((retval != NULL) && (retval[0] != '\0'))
2381 /* Next comes the name of the desired category. */
2382 retval = g_getenv (category_name);
2383 if ((retval != NULL) && (retval[0] != '\0'))
2386 /* Last possibility is the LANG environment variable. */
2387 retval = g_getenv ("LANG");
2388 if ((retval != NULL) && (retval[0] != '\0'))
2391 #ifdef G_PLATFORM_WIN32
2392 /* g_win32_getlocale() first checks for LC_ALL, LC_MESSAGES and
2393 * LANG, which we already did above. Oh well. The main point of
2394 * calling g_win32_getlocale() is to get the thread's locale as used
2395 * by Windows and the Microsoft C runtime (in the "English_United
2396 * States" format) translated into the Unixish format.
2398 retval = g_win32_getlocale ();
2399 if ((retval != NULL) && (retval[0] != '\0'))
2406 typedef struct _GLanguageNamesCache GLanguageNamesCache;
2408 struct _GLanguageNamesCache {
2410 gchar **language_names;
2414 language_names_cache_free (gpointer data)
2416 GLanguageNamesCache *cache = data;
2417 g_free (cache->languages);
2418 g_strfreev (cache->language_names);
2423 * g_get_language_names:
2425 * Computes a list of applicable locale names, which can be used to
2426 * e.g. construct locale-dependent filenames or search paths. The returned
2427 * list is sorted from most desirable to least desirable and always contains
2428 * the default locale "C".
2430 * For example, if LANGUAGE=de:en_US, then the returned list is
2431 * "de", "en_US", "en", "C".
2433 * This function consults the environment variables <envar>LANGUAGE</envar>,
2434 * <envar>LC_ALL</envar>, <envar>LC_MESSAGES</envar> and <envar>LANG</envar>
2435 * to find the list of locales specified by the user.
2437 * Return value: a %NULL-terminated array of strings owned by GLib
2438 * that must not be modified or freed.
2442 G_CONST_RETURN gchar * G_CONST_RETURN *
2443 g_get_language_names (void)
2445 static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
2446 GLanguageNamesCache *cache = g_static_private_get (&cache_private);
2451 cache = g_new0 (GLanguageNamesCache, 1);
2452 g_static_private_set (&cache_private, cache, language_names_cache_free);
2455 value = guess_category_value ("LC_MESSAGES");
2459 if (!(cache->languages && strcmp (cache->languages, value) == 0))
2466 g_free (cache->languages);
2467 g_strfreev (cache->language_names);
2468 cache->languages = g_strdup (value);
2470 alist = g_strsplit (value, ":", 0);
2472 for (a = alist; *a; a++)
2474 gchar *b = unalias_lang (*a);
2475 list = g_slist_concat (list, _g_compute_locale_variants (b));
2478 list = g_slist_append (list, g_strdup ("C"));
2480 cache->language_names = languages = g_new (gchar *, g_slist_length (list) + 1);
2481 for (l = list, i = 0; l; l = l->next, i++)
2482 languages[i] = l->data;
2483 languages[i] = NULL;
2485 g_slist_free (list);
2488 return (G_CONST_RETURN gchar * G_CONST_RETURN *) cache->language_names;
2493 * @v: a #gpointer key
2495 * Converts a gpointer to a hash value.
2496 * It can be passed to g_hash_table_new() as the @hash_func parameter,
2497 * when using pointers as keys in a #GHashTable.
2499 * Returns: a hash value corresponding to the key.
2502 g_direct_hash (gconstpointer v)
2504 return GPOINTER_TO_UINT (v);
2510 * @v2: a key to compare with @v1.
2512 * Compares two #gpointer arguments and returns %TRUE if they are equal.
2513 * It can be passed to g_hash_table_new() as the @key_equal_func
2514 * parameter, when using pointers as keys in a #GHashTable.
2516 * Returns: %TRUE if the two keys match.
2519 g_direct_equal (gconstpointer v1,
2527 * @v1: a pointer to a #gint key.
2528 * @v2: a pointer to a #gint key to compare with @v1.
2530 * Compares the two #gint values being pointed to and returns
2531 * %TRUE if they are equal.
2532 * It can be passed to g_hash_table_new() as the @key_equal_func
2533 * parameter, when using pointers to integers as keys in a #GHashTable.
2535 * Returns: %TRUE if the two keys match.
2538 g_int_equal (gconstpointer v1,
2541 return *((const gint*) v1) == *((const gint*) v2);
2546 * @v: a pointer to a #gint key
2548 * Converts a pointer to a #gint to a hash value.
2549 * It can be passed to g_hash_table_new() as the @hash_func parameter,
2550 * when using pointers to integers values as keys in a #GHashTable.
2552 * Returns: a hash value corresponding to the key.
2555 g_int_hash (gconstpointer v)
2557 return *(const gint*) v;
2561 * g_nullify_pointer:
2562 * @nullify_location: the memory address of the pointer.
2564 * Set the pointer at the specified location to %NULL.
2567 g_nullify_pointer (gpointer *nullify_location)
2569 g_return_if_fail (nullify_location != NULL);
2571 *nullify_location = NULL;
2577 * Get the codeset for the current locale.
2579 * Return value: a newly allocated string containing the name
2580 * of the codeset. This string must be freed with g_free().
2583 g_get_codeset (void)
2585 const gchar *charset;
2587 g_get_charset (&charset);
2589 return g_strdup (charset);
2592 /* This is called from g_thread_init(). It's used to
2593 * initialize some static data in a threadsafe way.
2596 _g_utils_thread_init (void)
2598 g_get_language_names ();
2603 #include <libintl.h>
2605 #ifdef G_PLATFORM_WIN32
2607 G_WIN32_DLLMAIN_FOR_DLL_NAME (static, dll_name)
2609 static const gchar *
2610 _glib_get_locale_dir (void)
2612 static const gchar *cache = NULL;
2614 cache = g_win32_get_package_installation_subdirectory
2615 (GETTEXT_PACKAGE, dll_name, "lib\\locale");
2620 #undef GLIB_LOCALE_DIR
2621 #define GLIB_LOCALE_DIR _glib_get_locale_dir ()
2623 #endif /* G_PLATFORM_WIN32 */
2625 G_CONST_RETURN gchar *
2626 _glib_gettext (const gchar *str)
2628 static gboolean _glib_gettext_initialized = FALSE;
2630 if (!_glib_gettext_initialized)
2632 bindtextdomain(GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
2633 # ifdef HAVE_BIND_TEXTDOMAIN_CODESET
2634 bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
2636 _glib_gettext_initialized = TRUE;
2639 return dgettext (GETTEXT_PACKAGE, str);
2642 #endif /* ENABLE_NLS */
2646 /* Binary compatibility versions. Not for newly compiled code. */
2648 #undef g_find_program_in_path
2651 g_find_program_in_path (const gchar *program)
2653 gchar *utf8_program = g_locale_to_utf8 (program, -1, NULL, NULL, NULL);
2654 gchar *utf8_retval = g_find_program_in_path_utf8 (utf8_program);
2657 g_free (utf8_program);
2658 if (utf8_retval == NULL)
2660 retval = g_locale_from_utf8 (utf8_retval, -1, NULL, NULL, NULL);
2661 g_free (utf8_retval);
2666 #undef g_get_current_dir
2669 g_get_current_dir (void)
2671 gchar *utf8_dir = g_get_current_dir_utf8 ();
2672 gchar *dir = g_locale_from_utf8 (utf8_dir, -1, NULL, NULL, NULL);
2679 G_CONST_RETURN gchar*
2680 g_getenv (const gchar *variable)
2682 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
2683 const gchar *utf8_value = g_getenv_utf8 (utf8_variable);
2687 g_free (utf8_variable);
2690 value = g_locale_from_utf8 (utf8_value, -1, NULL, NULL, NULL);
2691 quark = g_quark_from_string (value);
2694 return g_quark_to_string (quark);
2700 g_setenv (const gchar *variable,
2704 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
2705 gchar *utf8_value = g_locale_to_utf8 (value, -1, NULL, NULL, NULL);
2706 gboolean retval = g_setenv_utf8 (utf8_variable, utf8_value, overwrite);
2708 g_free (utf8_variable);
2709 g_free (utf8_value);
2717 g_unsetenv (const gchar *variable)
2719 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
2721 g_unsetenv_utf8 (utf8_variable);
2723 g_free (utf8_variable);
2726 #undef g_get_user_name
2728 G_CONST_RETURN gchar*
2729 g_get_user_name (void)
2731 G_LOCK (g_utils_global);
2734 G_UNLOCK (g_utils_global);
2736 return g_user_name_cp;
2739 #undef g_get_real_name
2741 G_CONST_RETURN gchar*
2742 g_get_real_name (void)
2744 G_LOCK (g_utils_global);
2747 G_UNLOCK (g_utils_global);
2749 return g_real_name_cp;
2752 #undef g_get_home_dir
2754 G_CONST_RETURN gchar*
2755 g_get_home_dir (void)
2757 G_LOCK (g_utils_global);
2760 G_UNLOCK (g_utils_global);
2762 return g_home_dir_cp;
2765 #undef g_get_tmp_dir
2767 G_CONST_RETURN gchar*
2768 g_get_tmp_dir (void)
2770 G_LOCK (g_utils_global);
2773 G_UNLOCK (g_utils_global);
2775 return g_tmp_dir_cp;
2780 #define __G_UTILS_C__
2781 #include "galiasdef.c"