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.
47 #include <sys/types.h>
48 #ifdef HAVE_SYS_PARAM_H
49 #include <sys/param.h>
52 /* implement gutils's inline functions
54 #define G_IMPLEMENT_INLINES 1
58 #include "gprintfint.h"
61 #define G_PATH_LENGTH MAXPATHLEN
62 #elif defined (PATH_MAX)
63 #define G_PATH_LENGTH PATH_MAX
64 #elif defined (_PC_PATH_MAX)
65 #define G_PATH_LENGTH sysconf(_PC_PATH_MAX)
67 #define G_PATH_LENGTH 2048
70 #ifdef G_PLATFORM_WIN32
71 # define STRICT /* Strict typing, please */
74 # include <lmcons.h> /* For UNLEN */
76 #endif /* G_PLATFORM_WIN32 */
87 #ifdef HAVE_BIND_TEXTDOMAIN_CODESET
91 /* G_IS_DIR_SEPARATOR probably should be made public in GLib 2.4 */
93 #define G_IS_DIR_SEPARATOR(c) (c == G_DIR_SEPARATOR || c == '/')
95 #define G_IS_DIR_SEPARATOR(c) (c == G_DIR_SEPARATOR)
98 const guint glib_major_version = GLIB_MAJOR_VERSION;
99 const guint glib_minor_version = GLIB_MINOR_VERSION;
100 const guint glib_micro_version = GLIB_MICRO_VERSION;
101 const guint glib_interface_age = GLIB_INTERFACE_AGE;
102 const guint glib_binary_age = GLIB_BINARY_AGE;
105 * glib_check_version:
106 * @required_major: the required major version.
107 * @required_minor: the required major version.
108 * @required_micro: the required major version.
110 * Checks that the GLib library in use is compatible with the
111 * given version. Generally you would pass in the constants
112 * #GLIB_MAJOR_VERSION, #GLIB_MINOR_VERSION, #GLIB_MICRO_VERSION
113 * as the three arguments to this function; that produces
114 * a check that the library in use is compatible with
115 * the version of GLib the application or module was compiled
118 * Compatibility is defined by two things: first the version
119 * of the running library is newer than the version
120 * @required_major.required_minor.@required_micro. Second
121 * the running library must be binary compatible with the
122 * version @required_major.required_minor.@required_micro
123 * (same major version.)
125 * Return value: %NULL if the GLib library is compatible with the
126 * given version, or a string describing the version mismatch.
127 * The returned string is owned by GLib and must not be modified
133 glib_check_version (guint required_major,
134 guint required_minor,
135 guint required_micro)
137 gint glib_effective_micro = 100 * GLIB_MINOR_VERSION + GLIB_MICRO_VERSION;
138 gint required_effective_micro = 100 * required_minor + required_micro;
140 if (required_major > GLIB_MAJOR_VERSION)
141 return "GLib version too old (major mismatch)";
142 if (required_major < GLIB_MAJOR_VERSION)
143 return "GLib version too new (major mismatch)";
144 if (required_effective_micro < glib_effective_micro - GLIB_BINARY_AGE)
145 return "GLib version too new (micro mismatch)";
146 if (required_effective_micro > glib_effective_micro)
147 return "GLib version too old (micro mismatch)";
151 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
153 g_memmove (gpointer dest, gconstpointer src, gulong len)
155 gchar* destptr = dest;
156 const gchar* srcptr = src;
157 if (src + len < dest || dest + len < src)
159 bcopy (src, dest, len);
162 else if (dest <= src)
165 *(destptr++) = *(srcptr++);
172 *(--destptr) = *(--srcptr);
175 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
178 g_atexit (GVoidFunc func)
181 const gchar *error = NULL;
183 /* keep this in sync with glib.h */
185 #ifdef G_NATIVE_ATEXIT
186 result = ATEXIT (func);
188 error = g_strerror (errno);
189 #elif defined (HAVE_ATEXIT)
190 # ifdef NeXT /* @#%@! NeXTStep */
191 result = !atexit ((void (*)(void)) func);
193 error = g_strerror (errno);
195 result = atexit ((void (*)(void)) func);
197 error = g_strerror (errno);
199 #elif defined (HAVE_ON_EXIT)
200 result = on_exit ((void (*)(int, void *)) func, NULL);
202 error = g_strerror (errno);
205 error = "no implementation";
206 #endif /* G_NATIVE_ATEXIT */
209 g_error ("Could not register atexit() function: %s", error);
212 /* Based on execvp() from GNU Libc.
213 * Some of this code is cut-and-pasted into gspawn.c
217 my_strchrnul (const gchar *str, gchar c)
219 gchar *p = (gchar*)str;
220 while (*p && (*p != c))
228 static gchar *inner_find_program_in_path (const gchar *program);
231 g_find_program_in_path (const gchar *program)
233 const gchar *last_dot = strrchr (program, '.');
235 if (last_dot == NULL || strchr (last_dot, '\\') != NULL)
237 const gint program_length = strlen (program);
238 const gchar *pathext = getenv ("PATHEXT");
240 gchar *decorated_program;
244 pathext = ".com;.exe;.bat";
250 p = my_strchrnul (pathext, ';');
252 decorated_program = g_malloc (program_length + (p-pathext) + 1);
253 memcpy (decorated_program, program, program_length);
254 memcpy (decorated_program+program_length, pathext, p-pathext);
255 decorated_program [program_length + (p-pathext)] = '\0';
257 retval = inner_find_program_in_path (decorated_program);
258 g_free (decorated_program);
262 } while (*p++ != '\0');
266 return inner_find_program_in_path (program);
269 #define g_find_program_in_path inner_find_program_in_path
273 * g_find_program_in_path:
274 * @program: a program name
276 * Locates the first executable named @program in the user's path, in the
277 * same way that execvp() would locate it. Returns an allocated string
278 * with the absolute path name, or NULL if the program is not found in
279 * the path. If @program is already an absolute path, returns a copy of
280 * @program if @program exists and is executable, and NULL otherwise.
282 * On Windows, if @program does not have a file type suffix, tries to
283 * append the suffixes in the PATHEXT environment variable (if that
284 * doesn't exists, the suffixes .com, .exe, and .bat) in turn, and
285 * then look for the resulting file name in the same way as
286 * CreateProcess() would. This means first in the directory where the
287 * program was loaded from, then in the current directory, then in the
288 * Windows 32-bit system directory, then in the Windows directory, and
289 * finally in the directories in the PATH environment variable. If
290 * the program is found, the return value contains the full name
291 * including the type suffix.
293 * Return value: absolute path, or NULL
299 g_find_program_in_path (const gchar *program)
301 const gchar *path, *p;
302 gchar *name, *freeme;
309 g_return_val_if_fail (program != NULL, NULL);
311 /* If it is an absolute path, or a relative path including subdirectories,
312 * don't look in PATH.
314 if (g_path_is_absolute (program)
315 || strchr (program, G_DIR_SEPARATOR) != NULL
317 || strchr (program, '/') != NULL
321 if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE))
322 return g_strdup (program);
327 path = g_getenv ("PATH");
331 /* There is no `PATH' in the environment. The default
332 * search path in GNU libc is the current directory followed by
333 * the path `confstr' returns for `_CS_PATH'.
336 /* In GLib we put . last, for security, and don't use the
337 * unportable confstr(); UNIX98 does not actually specify
338 * what to search if PATH is unset. POSIX may, dunno.
341 path = "/bin:/usr/bin:.";
346 gchar moddir[MAXPATHLEN], sysdir[MAXPATHLEN], windir[MAXPATHLEN];
348 GetModuleFileName (NULL, moddir, sizeof (moddir));
349 tmp = g_path_get_dirname (moddir);
350 GetSystemDirectory (sysdir, sizeof (sysdir));
351 GetWindowsDirectory (windir, sizeof (windir));
352 path_tmp = g_strconcat (tmp, ";.;", sysdir, ";", windir,
353 (path != NULL ? ";" : NULL),
354 (path != NULL ? path : NULL),
361 len = strlen (program) + 1;
362 pathlen = strlen (path);
363 freeme = name = g_malloc (pathlen + len + 1);
365 /* Copy the file name at the top, including '\0' */
366 memcpy (name + pathlen + 1, program, len);
367 name = name + pathlen;
368 /* And add the slash before the filename */
369 *name = G_DIR_SEPARATOR;
377 p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
380 /* Two adjacent colons, or a colon at the beginning or the end
381 * of `PATH' means to search the current directory.
385 startp = memcpy (name - (p - path), path, p - path);
387 if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE))
390 ret = g_strdup (startp);
398 while (*p++ != '\0');
409 g_parse_debug_string (const gchar *string,
410 const GDebugKey *keys,
416 g_return_val_if_fail (string != NULL, 0);
418 if (!g_ascii_strcasecmp (string, "all"))
420 for (i=0; i<nkeys; i++)
421 result |= keys[i].value;
425 const gchar *p = string;
427 gboolean done = FALSE;
438 for (i=0; i<nkeys; i++)
439 if (g_ascii_strncasecmp(keys[i].key, p, q - p) == 0 &&
440 keys[i].key[q - p] == '\0')
441 result |= keys[i].value;
452 * @file_name: the name of the file.
454 * Gets the name of the file without any leading directory components.
455 * It returns a pointer into the given file name string.
457 * Return value: the name of the file without any leading directory components.
459 * Deprecated: Use g_path_get_basename() instead, but notice that
460 * g_path_get_basename() allocates new memory for the returned string, unlike
461 * this function which returns a pointer into the argument.
463 G_CONST_RETURN gchar*
464 g_basename (const gchar *file_name)
466 register gchar *base;
468 g_return_val_if_fail (file_name != NULL, NULL);
470 base = strrchr (file_name, G_DIR_SEPARATOR);
474 gchar *q = strrchr (file_name, '/');
475 if (base == NULL || (q != NULL && q > base))
484 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
485 return (gchar*) file_name + 2;
486 #endif /* G_OS_WIN32 */
488 return (gchar*) file_name;
492 * g_path_get_basename:
493 * @file_name: the name of the file.
495 * Gets the last component of the filename. If @file_name ends with a
496 * directory separator it gets the component before the last slash. If
497 * @file_name consists only of directory separators (and on Windows,
498 * possibly a drive letter), a single separator is returned. If
499 * @file_name is empty, it gets ".".
501 * Return value: a newly allocated string containing the last component of
505 g_path_get_basename (const gchar *file_name)
507 register gssize base;
508 register gssize last_nonslash;
512 g_return_val_if_fail (file_name != NULL, NULL);
514 if (file_name[0] == '\0')
516 return g_strdup (".");
518 last_nonslash = strlen (file_name) - 1;
520 while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
523 if (last_nonslash == -1)
524 /* string only containing slashes */
525 return g_strdup (G_DIR_SEPARATOR_S);
528 if (last_nonslash == 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
529 /* string only containing slashes and a drive */
530 return g_strdup (G_DIR_SEPARATOR_S);
531 #endif /* G_OS_WIN32 */
533 base = last_nonslash;
535 while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
539 if (base == -1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
541 #endif /* G_OS_WIN32 */
543 len = last_nonslash - base;
544 retval = g_malloc (len + 1);
545 memcpy (retval, file_name + base + 1, len);
551 g_path_is_absolute (const gchar *file_name)
553 g_return_val_if_fail (file_name != NULL, FALSE);
555 if (G_IS_DIR_SEPARATOR (file_name[0]))
559 /* Recognize drive letter on native Windows */
560 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
562 #endif /* G_OS_WIN32 */
567 G_CONST_RETURN gchar*
568 g_path_skip_root (const gchar *file_name)
570 g_return_val_if_fail (file_name != NULL, NULL);
572 #ifdef G_PLATFORM_WIN32
573 /* Skip \\server\share or //server/share */
574 if (G_IS_DIR_SEPARATOR (file_name[0]) &&
575 G_IS_DIR_SEPARATOR (file_name[1]) &&
580 p = strchr (file_name + 2, G_DIR_SEPARATOR);
583 gchar *q = strchr (file_name + 2, '/');
584 if (p == NULL || (q != NULL && q < p))
594 while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
597 /* Possibly skip a backslash after the share name */
598 if (G_IS_DIR_SEPARATOR (file_name[0]))
601 return (gchar *)file_name;
606 /* Skip initial slashes */
607 if (G_IS_DIR_SEPARATOR (file_name[0]))
609 while (G_IS_DIR_SEPARATOR (file_name[0]))
611 return (gchar *)file_name;
616 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
617 return (gchar *)file_name + 3;
624 g_path_get_dirname (const gchar *file_name)
626 register gchar *base;
629 g_return_val_if_fail (file_name != NULL, NULL);
631 base = strrchr (file_name, G_DIR_SEPARATOR);
634 gchar *q = strrchr (file_name, '/');
635 if (base == NULL || (q != NULL && q > base))
642 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
644 gchar drive_colon_dot[4];
646 drive_colon_dot[0] = file_name[0];
647 drive_colon_dot[1] = ':';
648 drive_colon_dot[2] = '.';
649 drive_colon_dot[3] = '\0';
651 return g_strdup (drive_colon_dot);
654 return g_strdup (".");
657 while (base > file_name && G_IS_DIR_SEPARATOR (*base))
661 if (base == file_name + 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
665 len = (guint) 1 + base - file_name;
667 base = g_new (gchar, len + 1);
668 g_memmove (base, file_name, len);
675 g_get_current_dir (void)
677 gchar *buffer = NULL;
679 static gulong max_len = 0;
682 max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
684 /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
685 * and, if that wasn't bad enough, hangs in doing so.
687 #if (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
688 buffer = g_new (gchar, max_len + 1);
690 dir = getwd (buffer);
691 #else /* !sun || !HAVE_GETCWD */
692 while (max_len < G_MAXULONG / 2)
694 buffer = g_new (gchar, max_len + 1);
696 dir = getcwd (buffer, max_len);
698 if (dir || errno != ERANGE)
704 #endif /* !sun || !HAVE_GETCWD */
706 if (!dir || !*buffer)
708 /* hm, should we g_error() out here?
709 * this can happen if e.g. "./" has mode \0000
711 buffer[0] = G_DIR_SEPARATOR;
715 dir = g_strdup (buffer);
723 * @variable: the environment variable to get.
725 * Returns an environment variable.
727 * Return value: the value of the environment variable, or %NULL if the environment
728 * variable is not found. The returned string may be overwritten by the next call to g_getenv(),
729 * g_setenv() or g_unsetenv().
731 G_CONST_RETURN gchar*
732 g_getenv (const gchar *variable)
735 g_return_val_if_fail (variable != NULL, NULL);
737 return getenv (variable);
745 g_return_val_if_fail (variable != NULL, NULL);
747 system_env = getenv (variable);
751 /* On Windows NT, it is relatively typical that environment
752 * variables contain references to other environment variables. If
753 * so, use ExpandEnvironmentStrings(). (If all software was written
754 * in the best possible way, such environment variables would be
755 * stored in the Registry as REG_EXPAND_SZ type values, and would
756 * then get automatically expanded before the program sees them. But
757 * there is broken software that stores environment variables as
758 * REG_SZ values even if they contain references to other
759 * environment variables.
762 if (strchr (system_env, '%') == NULL)
764 /* No reference to other variable(s), return value as such. */
768 /* First check how much space we need */
769 length = ExpandEnvironmentStrings (system_env, dummy, 2);
771 expanded_env = g_malloc (length);
773 ExpandEnvironmentStrings (system_env, expanded_env, length);
775 quark = g_quark_from_string (expanded_env);
776 g_free (expanded_env);
778 return g_quark_to_string (quark);
784 * @variable: the environment variable to set, must not contain '='.
785 * @value: the value for to set the variable to.
786 * @overwrite: whether to change the variable if it already exists.
788 * Sets an environment variable.
790 * Note that on some systems, the memory used for the variable and its value
791 * can't be reclaimed later.
793 * Returns: %FALSE if the environment variable couldn't be set.
798 g_setenv (const gchar *variable,
807 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
810 result = setenv (variable, value, overwrite);
812 if (!overwrite && g_getenv (variable) != NULL)
815 /* This results in a leak when you overwrite existing
816 * settings. It would be fairly easy to fix this by keeping
817 * our own parallel array or hash table.
819 string = g_strconcat (variable, "=", value, NULL);
820 result = putenv (string);
825 #ifndef HAVE_UNSETENV
826 /* According to the Single Unix Specification, environ is not in
827 * any system header, although unistd.h often declares it.
831 * Win32 - at least msvc headers declare it so let's avoid
832 * warning C4273: '__p__environ' : inconsistent dll linkage. dllexport assumed.
834 extern char **environ;
840 * @variable: the environment variable to remove, must not contain '='.
842 * Removes an environment variable from the environment.
844 * Note that on some systems, the memory used for the variable and its value
845 * can't be reclaimed. Furthermore, this function can't be guaranteed to operate in a
851 g_unsetenv (const gchar *variable)
854 g_return_if_fail (strchr (variable, '=') == NULL);
861 g_return_if_fail (strchr (variable, '=') == NULL);
863 len = strlen (variable);
865 /* Mess directly with the environ array.
866 * This seems to be the only portable way to do this.
868 * Note that we remove *all* environment entries for
869 * the variable name, not just the first.
874 if (strncmp (*e, variable, len) != 0 || (*e)[len] != '=')
885 G_LOCK_DEFINE_STATIC (g_utils_global);
887 static gchar *g_tmp_dir = NULL;
888 static gchar *g_user_name = NULL;
889 static gchar *g_real_name = NULL;
890 static gchar *g_home_dir = NULL;
892 static gchar *g_user_data_dir = NULL;
893 static gchar **g_system_data_dirs = NULL;
894 static gchar *g_user_cache_dir = NULL;
895 static gchar *g_user_config_dir = NULL;
896 static gchar **g_system_config_dirs = NULL;
901 get_special_folder (int csidl)
905 wchar_t wc[MAX_PATH+1];
908 LPITEMIDLIST pidl = NULL;
910 gchar *retval = NULL;
912 hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
915 if (G_WIN32_HAVE_WIDECHAR_API ())
917 b = SHGetPathFromIDListW (pidl, path.wc);
919 retval = g_utf16_to_utf8 (path.wc, -1, NULL, NULL, NULL);
923 b = SHGetPathFromIDListA (pidl, path.c);
925 retval = g_locale_to_utf8 (path.c, -1, NULL, NULL, NULL);
927 CoTaskMemFree (pidl);
937 /* HOLDS: g_utils_global_lock */
939 g_get_any_init (void)
943 g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
945 g_tmp_dir = g_strdup (g_getenv ("TMP"));
947 g_tmp_dir = g_strdup (g_getenv ("TEMP"));
953 g_tmp_dir = g_strdup (P_tmpdir);
954 k = strlen (g_tmp_dir);
955 if (k > 1 && G_IS_DIR_SEPARATOR (g_tmp_dir[k - 1]))
956 g_tmp_dir[k - 1] = '\0';
963 g_tmp_dir = g_strdup ("/tmp");
964 #else /* G_OS_WIN32 */
965 g_tmp_dir = g_strdup ("C:\\");
966 #endif /* G_OS_WIN32 */
970 /* We check $HOME first for Win32, though it is a last resort for Unix
971 * where we prefer the results of getpwuid().
974 gchar *home = g_getenv ("HOME");
976 /* Only believe HOME if it is an absolute path and exists */
977 if (home && g_path_is_absolute (home) && g_file_test (home, G_FILE_TEST_IS_DIR))
978 g_home_dir = g_strdup (home);
981 /* In case HOME is Unix-style (it happens), convert it to
987 while ((p = strchr (g_home_dir, '/')) != NULL)
993 /* USERPROFILE is probably the closest equivalent to $HOME? */
994 if (getenv ("USERPROFILE") != NULL)
995 g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
999 g_home_dir = get_special_folder (CSIDL_PROFILE);
1003 /* At least at some time, HOMEDRIVE and HOMEPATH were used
1004 * to point to the home directory, I think. But on Windows
1005 * 2000 HOMEDRIVE seems to be equal to SYSTEMDRIVE, and
1006 * HOMEPATH is its root "\"?
1008 if (getenv ("HOMEDRIVE") != NULL && getenv ("HOMEPATH") != NULL)
1010 gchar *homedrive, *homepath;
1012 homedrive = g_strdup (g_getenv ("HOMEDRIVE"));
1013 homepath = g_strdup (g_getenv ("HOMEPATH"));
1015 g_home_dir = g_strconcat (homedrive, homepath, NULL);
1020 #endif /* G_OS_WIN32 */
1024 struct passwd *pw = NULL;
1025 gpointer buffer = NULL;
1028 # if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
1030 # ifdef _SC_GETPW_R_SIZE_MAX
1031 /* This reurns the maximum length */
1032 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
1036 # else /* _SC_GETPW_R_SIZE_MAX */
1038 # endif /* _SC_GETPW_R_SIZE_MAX */
1043 buffer = g_malloc (bufsize);
1046 # ifdef HAVE_POSIX_GETPWUID_R
1047 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1048 error = error < 0 ? errno : error;
1049 # else /* HAVE_NONPOSIX_GETPWUID_R */
1050 /* HPUX 11 falls into the HAVE_POSIX_GETPWUID_R case */
1051 # if defined(_AIX) || defined(__hpux)
1052 error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1053 pw = error == 0 ? &pwd : NULL;
1055 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1056 error = pw ? 0 : errno;
1058 # endif /* HAVE_NONPOSIX_GETPWUID_R */
1062 /* we bail out prematurely if the user id can't be found
1063 * (should be pretty rare case actually), or if the buffer
1064 * should be sufficiently big and lookups are still not
1067 if (error == 0 || error == ENOENT)
1069 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
1070 (gulong) getuid ());
1073 if (bufsize > 32 * 1024)
1075 g_warning ("getpwuid_r(): failed due to: %s.",
1076 g_strerror (error));
1084 # endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
1089 pw = getpwuid (getuid ());
1094 g_user_name = g_strdup (pw->pw_name);
1096 if (pw->pw_gecos && *pw->pw_gecos != '\0')
1098 gchar **gecos_fields;
1101 /* split the gecos field and substitute '&' */
1102 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
1103 name_parts = g_strsplit (gecos_fields[0], "&", 0);
1104 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
1105 g_real_name = g_strjoinv (pw->pw_name, name_parts);
1106 g_strfreev (gecos_fields);
1107 g_strfreev (name_parts);
1111 g_home_dir = g_strdup (pw->pw_dir);
1116 #else /* !HAVE_PWD_H */
1120 guint len = UNLEN+1;
1121 gchar buffer[UNLEN+1];
1123 if (GetUserName ((LPTSTR) buffer, (LPDWORD) &len))
1125 g_user_name = g_strdup (buffer);
1126 g_real_name = g_strdup (buffer);
1129 # endif /* G_OS_WIN32 */
1131 #endif /* !HAVE_PWD_H */
1134 g_home_dir = g_strdup (g_getenv ("HOME"));
1137 /* change '\\' in %HOME% to '/' */
1138 g_strdelimit (g_home_dir, "\\",'/');
1141 g_user_name = g_strdup ("somebody");
1143 g_real_name = g_strdup ("Unknown");
1147 G_CONST_RETURN gchar*
1148 g_get_user_name (void)
1150 G_LOCK (g_utils_global);
1153 G_UNLOCK (g_utils_global);
1158 G_CONST_RETURN gchar*
1159 g_get_real_name (void)
1161 G_LOCK (g_utils_global);
1164 G_UNLOCK (g_utils_global);
1169 G_CONST_RETURN gchar*
1170 g_get_home_dir (void)
1172 G_LOCK (g_utils_global);
1175 G_UNLOCK (g_utils_global);
1180 /* Return a directory to be used to store temporary files. This is the
1181 * value of the TMPDIR, TMP or TEMP environment variables (they are
1182 * checked in that order). If none of those exist, use P_tmpdir from
1183 * stdio.h. If that isn't defined, return "/tmp" on POSIXly systems,
1184 * and C:\ on Windows.
1187 G_CONST_RETURN gchar*
1188 g_get_tmp_dir (void)
1190 G_LOCK (g_utils_global);
1193 G_UNLOCK (g_utils_global);
1198 G_LOCK_DEFINE_STATIC (g_prgname);
1199 static gchar *g_prgname = NULL;
1202 g_get_prgname (void)
1208 G_UNLOCK (g_prgname);
1214 g_set_prgname (const gchar *prgname)
1218 g_prgname = g_strdup (prgname);
1219 G_UNLOCK (g_prgname);
1222 G_LOCK_DEFINE_STATIC (g_application_name);
1223 static gchar *g_application_name = NULL;
1226 * g_get_application_name:
1228 * Gets a human-readable name for the application, as set by
1229 * g_set_application_name(). This name should be localized if
1230 * possible, and is intended for display to the user. Contrast with
1231 * g_get_prgname(), which gets a non-localized name. If
1232 * g_set_application_name() has not been called, returns the result of
1233 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1236 * Return value: human-readable application name. may return %NULL
1240 G_CONST_RETURN gchar*
1241 g_get_application_name (void)
1245 G_LOCK (g_application_name);
1246 retval = g_application_name;
1247 G_UNLOCK (g_application_name);
1250 return g_get_prgname ();
1256 * g_set_application_name:
1257 * @application_name: localized name of the application
1259 * Sets a human-readable name for the application. This name should be
1260 * localized if possible, and is intended for display to the user.
1261 * Contrast with g_set_prgname(), which sets a non-localized name.
1262 * g_set_prgname() will be called automatically by gtk_init(),
1263 * but g_set_application_name() will not.
1265 * Note that for thread safety reasons, this function can only
1268 * The application name will be used in contexts such as error messages,
1269 * or when displaying an application's name in the task list.
1273 g_set_application_name (const gchar *application_name)
1275 gboolean already_set = FALSE;
1277 G_LOCK (g_application_name);
1278 if (g_application_name)
1281 g_application_name = g_strdup (application_name);
1282 G_UNLOCK (g_application_name);
1285 g_warning ("g_set_application() name called multiple times");
1289 * g_get_user_data_dir:
1291 * Returns a base directory in which to access application data such
1292 * as icons that is customized for a particular user.
1294 * On Unix platforms this is determined using the mechanisms described in
1295 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1296 * XDG Base Directory Specification</ulink>
1298 * Return value: a string owned by GLib that must not be modified
1302 G_CONST_RETURN gchar*
1303 g_get_user_data_dir (void)
1307 G_LOCK (g_utils_global);
1309 if (!g_user_data_dir)
1312 data_dir = get_special_folder (CSIDL_PERSONAL);
1314 data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
1316 if (data_dir && data_dir[0])
1317 data_dir = g_strdup (data_dir);
1323 data_dir = g_build_filename (g_home_dir, ".local",
1327 g_user_data_dir = data_dir;
1330 data_dir = g_user_data_dir;
1332 G_UNLOCK (g_utils_global);
1338 * g_get_user_config_dir:
1340 * Returns a base directory in which to store user-specific application
1341 * configuration information such as user preferences and settings.
1343 * On Unix platforms this is determined using the mechanisms described in
1344 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1345 * XDG Base Directory Specification</ulink>
1347 * Return value: a string owned by GLib that must not be modified
1351 G_CONST_RETURN gchar*
1352 g_get_user_config_dir (void)
1356 G_LOCK (g_utils_global);
1358 if (!g_user_config_dir)
1361 config_dir = get_special_folder (CSIDL_APPDATA);
1363 config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
1365 if (config_dir && config_dir[0])
1366 config_dir = g_strdup (config_dir);
1372 config_dir = g_build_filename (g_home_dir, ".config", NULL);
1375 g_user_config_dir = config_dir;
1378 config_dir = g_user_config_dir;
1380 G_UNLOCK (g_utils_global);
1386 * g_get_user_cache_dir:
1388 * Returns a base directory in which to store non-essential, cached
1389 * data specific to particular user.
1391 * On Unix platforms this is determined using the mechanisms described in
1392 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1393 * XDG Base Directory Specification</ulink>
1395 * Return value: a string owned by GLib that must not be modified
1399 G_CONST_RETURN gchar*
1400 g_get_user_cache_dir (void)
1404 G_LOCK (g_utils_global);
1406 if (!g_user_cache_dir)
1409 cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
1411 cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
1413 if (cache_dir && cache_dir[0])
1414 cache_dir = g_strdup (cache_dir);
1420 cache_dir = g_build_filename (g_home_dir, ".cache", NULL);
1423 g_user_cache_dir = cache_dir;
1426 cache_dir = g_user_cache_dir;
1428 G_UNLOCK (g_utils_global);
1434 * g_get_system_data_dirs:
1436 * Returns an ordered list of base directories in which to access
1437 * system-wide application data.
1439 * On Unix platforms this is determined using the mechanisms described in
1440 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1441 * XDG Base Directory Specification</ulink>
1443 * Return value: a %NULL-terminated array of strings owned by GLib that must
1444 * not be modified or freed.
1447 G_CONST_RETURN gchar * G_CONST_RETURN *
1448 g_get_system_data_dirs (void)
1450 gchar *data_dirs, **data_dir_vector;
1452 G_LOCK (g_utils_global);
1454 if (!g_system_data_dirs)
1457 data_dirs = g_strconcat (get_special_folder (CSIDL_COMMON_APPDATA),
1458 G_SEARCHPATH_SEPARATOR_S,
1459 get_special_folder (CSIDL_COMMON_DOCUMENTS),
1462 data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
1464 if (!data_dirs || !data_dirs[0])
1465 data_dirs = "/usr/local/share/:/usr/share/";
1467 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
1469 g_system_data_dirs = data_dir_vector;
1472 data_dir_vector = g_system_data_dirs;
1474 G_UNLOCK (g_utils_global);
1476 return (G_CONST_RETURN gchar * G_CONST_RETURN *) data_dir_vector;
1480 * g_get_system_config_dirs:
1482 * Returns an ordered list of base directories in which to access
1483 * system-wide configuration information.
1485 * On Unix platforms this is determined using the mechanisms described in
1486 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1487 * XDG Base Directory Specification</ulink>
1489 * Return value: a %NULL-terminated array of strings owned by GLib that must
1490 * not be modified or freed.
1493 G_CONST_RETURN gchar * G_CONST_RETURN *
1494 g_get_system_config_dirs (void)
1496 gchar *conf_dirs, **conf_dir_vector;
1498 G_LOCK (g_utils_global);
1500 if (!g_system_config_dirs)
1503 conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
1505 conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
1507 if (!conf_dirs || !conf_dirs[0])
1508 conf_dirs = "/etc/xdg";
1510 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
1513 conf_dir_vector = g_system_config_dirs;
1514 G_UNLOCK (g_utils_global);
1516 return (G_CONST_RETURN gchar * G_CONST_RETURN *) conf_dir_vector;
1519 static GHashTable *alias_table = NULL;
1521 /* read an alias file for the locales */
1523 read_aliases (gchar *file)
1529 alias_table = g_hash_table_new (g_str_hash, g_str_equal);
1530 fp = fopen (file,"r");
1533 while (fgets (buf, 256, fp))
1539 /* Line is a comment */
1540 if ((buf[0] == '#') || (buf[0] == '\0'))
1543 /* Reads first column */
1544 for (p = buf, q = NULL; *p; p++) {
1545 if ((*p == '\t') || (*p == ' ') || (*p == ':')) {
1548 while ((*q == '\t') || (*q == ' ')) {
1554 /* The line only had one column */
1555 if (!q || *q == '\0')
1558 /* Read second column */
1559 for (p = q; *p; p++) {
1560 if ((*p == '\t') || (*p == ' ')) {
1566 /* Add to alias table if necessary */
1567 if (!g_hash_table_lookup (alias_table, buf)) {
1568 g_hash_table_insert (alias_table, g_strdup (buf), g_strdup (q));
1575 unalias_lang (char *lang)
1581 read_aliases ("/usr/share/locale/locale.alias");
1584 while ((p = g_hash_table_lookup (alias_table, lang)) && (strcmp (p, lang) != 0))
1589 static gboolean said_before = FALSE;
1591 g_warning ("Too many alias levels for a locale, "
1592 "may indicate a loop");
1600 /* Mask for components of locale spec. The ordering here is from
1601 * least significant to most significant
1605 COMPONENT_CODESET = 1 << 0,
1606 COMPONENT_TERRITORY = 1 << 1,
1607 COMPONENT_MODIFIER = 1 << 2
1610 /* Break an X/Open style locale specification into components
1613 explode_locale (const gchar *locale,
1619 const gchar *uscore_pos;
1620 const gchar *at_pos;
1621 const gchar *dot_pos;
1625 uscore_pos = strchr (locale, '_');
1626 dot_pos = strchr (uscore_pos ? uscore_pos : locale, '.');
1627 at_pos = strchr (dot_pos ? dot_pos : (uscore_pos ? uscore_pos : locale), '@');
1631 mask |= COMPONENT_MODIFIER;
1632 *modifier = g_strdup (at_pos);
1635 at_pos = locale + strlen (locale);
1639 mask |= COMPONENT_CODESET;
1640 *codeset = g_strndup (dot_pos, at_pos - dot_pos);
1647 mask |= COMPONENT_TERRITORY;
1648 *territory = g_strndup (uscore_pos, dot_pos - uscore_pos);
1651 uscore_pos = dot_pos;
1653 *language = g_strndup (locale, uscore_pos - locale);
1659 * Compute all interesting variants for a given locale name -
1660 * by stripping off different components of the value.
1662 * For simplicity, we assume that the locale is in
1663 * X/Open format: language[_territory][.codeset][@modifier]
1665 * TODO: Extend this to handle the CEN format (see the GNUlibc docs)
1666 * as well. We could just copy the code from glibc wholesale
1667 * but it is big, ugly, and complicated, so I'm reluctant
1668 * to do so when this should handle 99% of the time...
1671 compute_locale_variants (const gchar *locale)
1673 GSList *retval = NULL;
1683 g_return_val_if_fail (locale != NULL, NULL);
1685 mask = explode_locale (locale, &language, &territory, &codeset, &modifier);
1687 /* Iterate through all possible combinations, from least attractive
1688 * to most attractive.
1690 for (i = 0; i <= mask; i++)
1691 if ((i & ~mask) == 0)
1693 gchar *val = g_strconcat (language,
1694 (i & COMPONENT_TERRITORY) ? territory : "",
1695 (i & COMPONENT_CODESET) ? codeset : "",
1696 (i & COMPONENT_MODIFIER) ? modifier : "",
1698 retval = g_slist_prepend (retval, val);
1702 if (mask & COMPONENT_CODESET)
1704 if (mask & COMPONENT_TERRITORY)
1706 if (mask & COMPONENT_MODIFIER)
1712 /* The following is (partly) taken from the gettext package.
1713 Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc. */
1715 static const gchar *
1716 guess_category_value (const gchar *category_name)
1718 const gchar *retval;
1720 /* The highest priority value is the `LANGUAGE' environment
1721 variable. This is a GNU extension. */
1722 retval = g_getenv ("LANGUAGE");
1723 if ((retval != NULL) && (retval[0] != '\0'))
1726 /* `LANGUAGE' is not set. So we have to proceed with the POSIX
1727 methods of looking to `LC_ALL', `LC_xxx', and `LANG'. On some
1728 systems this can be done by the `setlocale' function itself. */
1730 /* Setting of LC_ALL overwrites all other. */
1731 retval = g_getenv ("LC_ALL");
1732 if ((retval != NULL) && (retval[0] != '\0'))
1735 /* Next comes the name of the desired category. */
1736 retval = g_getenv (category_name);
1737 if ((retval != NULL) && (retval[0] != '\0'))
1740 /* Last possibility is the LANG environment variable. */
1741 retval = g_getenv ("LANG");
1742 if ((retval != NULL) && (retval[0] != '\0'))
1745 #ifdef G_PLATFORM_WIN32
1746 /* g_win32_getlocale() first checks for LC_ALL, LC_MESSAGES and
1747 * LANG, which we already did above. Oh well. The main point of
1748 * calling g_win32_getlocale() is to get the thread's locale as used
1749 * by Windows and the Microsoft C runtime (in the "English_United
1750 * States" format) translated into the Unixish format.
1752 retval = g_win32_getlocale ();
1753 if ((retval != NULL) && (retval[0] != '\0'))
1760 static gchar **languages = NULL;
1763 * g_get_language_names:
1765 * Computes a list of applicable locale names, which can be used to
1766 * e.g. construct locale-dependent filenames or search paths. The returned
1767 * list is sorted from most desirable to least desirable and always contains
1768 * the default locale "C".
1770 * For example, if LANGUAGE=de:en_US, then the returned list is
1771 * "de", "en_US", "en", "C".
1773 * This function consults the environment variables <envar>LANGUAGE</envar>,
1774 * <envar>LC_ALL</envar>, <envar>LC_MESSAGES</envar> and <envar>LANG</envar>
1775 * to find the list of locales specified by the user.
1777 * Return value: a %NULL-terminated array of strings owned by GLib
1778 * that must not be modified or freed.
1782 G_CONST_RETURN gchar * G_CONST_RETURN *
1783 g_get_language_names ()
1785 G_LOCK (g_utils_global);
1794 value = guess_category_value ("LC_MESSAGES");
1798 alist = g_strsplit (value, ":", 0);
1800 for (a = alist; *a; a++)
1802 gchar *b = unalias_lang (*a);
1803 list = g_slist_concat (list, compute_locale_variants (b));
1806 list = g_slist_append (list, "C");
1808 languages = g_new (gchar *, g_slist_length (list) + 1);
1809 for (l = list, i = 0; l; l = l->next, i++)
1810 languages[i] = l->data;
1811 languages[i] = NULL;
1813 g_slist_free (list);
1816 G_UNLOCK (g_utils_global);
1818 return (G_CONST_RETURN gchar * G_CONST_RETURN *) languages;
1822 g_direct_hash (gconstpointer v)
1824 return GPOINTER_TO_UINT (v);
1828 g_direct_equal (gconstpointer v1,
1835 g_int_equal (gconstpointer v1,
1838 return *((const gint*) v1) == *((const gint*) v2);
1842 g_int_hash (gconstpointer v)
1844 return *(const gint*) v;
1848 * g_nullify_pointer:
1849 * @nullify_location: the memory address of the pointer.
1851 * Set the pointer at the specified location to %NULL.
1854 g_nullify_pointer (gpointer *nullify_location)
1856 g_return_if_fail (nullify_location != NULL);
1858 *nullify_location = NULL;
1864 * Get the codeset for the current locale.
1866 * Return value: a newly allocated string containing the name
1867 * of the codeset. This string must be freed with g_free().
1870 g_get_codeset (void)
1872 const gchar *charset;
1874 g_get_charset (&charset);
1876 return g_strdup (charset);
1881 #include <libintl.h>
1883 #ifdef G_PLATFORM_WIN32
1885 G_WIN32_DLLMAIN_FOR_DLL_NAME (static, dll_name)
1887 static const gchar *
1888 _glib_get_locale_dir (void)
1890 static const gchar *cache = NULL;
1892 cache = g_win32_get_package_installation_subdirectory
1893 (GETTEXT_PACKAGE, dll_name, "lib\\locale");
1898 #undef GLIB_LOCALE_DIR
1899 #define GLIB_LOCALE_DIR _glib_get_locale_dir ()
1901 #endif /* G_PLATFORM_WIN32 */
1903 G_CONST_RETURN gchar *
1904 _glib_gettext (const gchar *str)
1906 static gboolean _glib_gettext_initialized = FALSE;
1908 if (!_glib_gettext_initialized)
1910 bindtextdomain(GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
1911 # ifdef HAVE_BIND_TEXTDOMAIN_CODESET
1912 bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
1914 _glib_gettext_initialized = TRUE;
1917 return dgettext (GETTEXT_PACKAGE, str);
1920 #endif /* ENABLE_NLS */