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
56 #include "gprintfint.h"
59 #define G_PATH_LENGTH MAXPATHLEN
60 #elif defined (PATH_MAX)
61 #define G_PATH_LENGTH PATH_MAX
62 #elif defined (_PC_PATH_MAX)
63 #define G_PATH_LENGTH sysconf(_PC_PATH_MAX)
65 #define G_PATH_LENGTH 2048
68 #ifdef G_PLATFORM_WIN32
69 # define STRICT /* Strict typing, please */
72 # include <lmcons.h> /* For UNLEN */
73 #endif /* G_PLATFORM_WIN32 */
78 /* older SDK (e.g. msvc 5.0) does not have these*/
79 # ifndef CSIDL_INTERNET_CACHE
80 # define CSIDL_INTERNET_CACHE 32
82 # ifndef CSIDL_COMMON_APPDATA
83 # define CSIDL_COMMON_APPDATA 35
85 # ifndef CSIDL_COMMON_DOCUMENTS
86 # define CSIDL_COMMON_DOCUMENTS 46
88 # ifndef CSIDL_PROFILE
89 # define CSIDL_PROFILE 40
97 #ifdef HAVE_BIND_TEXTDOMAIN_CODESET
101 const guint glib_major_version = GLIB_MAJOR_VERSION;
102 const guint glib_minor_version = GLIB_MINOR_VERSION;
103 const guint glib_micro_version = GLIB_MICRO_VERSION;
104 const guint glib_interface_age = GLIB_INTERFACE_AGE;
105 const guint glib_binary_age = GLIB_BINARY_AGE;
108 * glib_check_version:
109 * @required_major: the required major version.
110 * @required_minor: the required major version.
111 * @required_micro: the required major version.
113 * Checks that the GLib library in use is compatible with the
114 * given version. Generally you would pass in the constants
115 * #GLIB_MAJOR_VERSION, #GLIB_MINOR_VERSION, #GLIB_MICRO_VERSION
116 * as the three arguments to this function; that produces
117 * a check that the library in use is compatible with
118 * the version of GLib the application or module was compiled
121 * Compatibility is defined by two things: first the version
122 * of the running library is newer than the version
123 * @required_major.required_minor.@required_micro. Second
124 * the running library must be binary compatible with the
125 * version @required_major.required_minor.@required_micro
126 * (same major version.)
128 * Return value: %NULL if the GLib library is compatible with the
129 * given version, or a string describing the version mismatch.
130 * The returned string is owned by GLib and must not be modified
136 glib_check_version (guint required_major,
137 guint required_minor,
138 guint required_micro)
140 gint glib_effective_micro = 100 * GLIB_MINOR_VERSION + GLIB_MICRO_VERSION;
141 gint required_effective_micro = 100 * required_minor + required_micro;
143 if (required_major > GLIB_MAJOR_VERSION)
144 return "GLib version too old (major mismatch)";
145 if (required_major < GLIB_MAJOR_VERSION)
146 return "GLib version too new (major mismatch)";
147 if (required_effective_micro < glib_effective_micro - GLIB_BINARY_AGE)
148 return "GLib version too new (micro mismatch)";
149 if (required_effective_micro > glib_effective_micro)
150 return "GLib version too old (micro mismatch)";
154 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
156 g_memmove (gpointer dest, gconstpointer src, gulong len)
158 gchar* destptr = dest;
159 const gchar* srcptr = src;
160 if (src + len < dest || dest + len < src)
162 bcopy (src, dest, len);
165 else if (dest <= src)
168 *(destptr++) = *(srcptr++);
175 *(--destptr) = *(--srcptr);
178 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
181 g_atexit (GVoidFunc func)
184 const gchar *error = NULL;
186 /* keep this in sync with glib.h */
188 #ifdef G_NATIVE_ATEXIT
189 result = ATEXIT (func);
191 error = g_strerror (errno);
192 #elif defined (HAVE_ATEXIT)
193 # ifdef NeXT /* @#%@! NeXTStep */
194 result = !atexit ((void (*)(void)) func);
196 error = g_strerror (errno);
198 result = atexit ((void (*)(void)) func);
200 error = g_strerror (errno);
202 #elif defined (HAVE_ON_EXIT)
203 result = on_exit ((void (*)(int, void *)) func, NULL);
205 error = g_strerror (errno);
208 error = "no implementation";
209 #endif /* G_NATIVE_ATEXIT */
212 g_error ("Could not register atexit() function: %s", error);
215 /* Based on execvp() from GNU Libc.
216 * Some of this code is cut-and-pasted into gspawn.c
220 my_strchrnul (const gchar *str, gchar c)
222 gchar *p = (gchar*)str;
223 while (*p && (*p != c))
231 static gchar *inner_find_program_in_path (const gchar *program);
234 g_find_program_in_path (const gchar *program)
236 const gchar *last_dot = strrchr (program, '.');
238 if (last_dot == NULL || strchr (last_dot, '\\') != NULL)
240 const gint program_length = strlen (program);
241 const gchar *pathext = getenv ("PATHEXT");
243 gchar *decorated_program;
247 pathext = ".com;.exe;.bat";
253 p = my_strchrnul (pathext, ';');
255 decorated_program = g_malloc (program_length + (p-pathext) + 1);
256 memcpy (decorated_program, program, program_length);
257 memcpy (decorated_program+program_length, pathext, p-pathext);
258 decorated_program [program_length + (p-pathext)] = '\0';
260 retval = inner_find_program_in_path (decorated_program);
261 g_free (decorated_program);
265 } while (*p++ != '\0');
269 return inner_find_program_in_path (program);
272 #define g_find_program_in_path inner_find_program_in_path
276 * g_find_program_in_path:
277 * @program: a program name
279 * Locates the first executable named @program in the user's path, in the
280 * same way that execvp() would locate it. Returns an allocated string
281 * with the absolute path name, or NULL if the program is not found in
282 * the path. If @program is already an absolute path, returns a copy of
283 * @program if @program exists and is executable, and NULL otherwise.
285 * On Windows, if @program does not have a file type suffix, tries to
286 * append the suffixes in the PATHEXT environment variable (if that
287 * doesn't exists, the suffixes .com, .exe, and .bat) in turn, and
288 * then look for the resulting file name in the same way as
289 * CreateProcess() would. This means first in the directory where the
290 * program was loaded from, then in the current directory, then in the
291 * Windows 32-bit system directory, then in the Windows directory, and
292 * finally in the directories in the PATH environment variable. If
293 * the program is found, the return value contains the full name
294 * including the type suffix.
296 * Return value: absolute path, or NULL
302 g_find_program_in_path (const gchar *program)
304 const gchar *path, *p;
305 gchar *name, *freeme;
312 g_return_val_if_fail (program != NULL, NULL);
314 /* If it is an absolute path, or a relative path including subdirectories,
315 * don't look in PATH.
317 if (g_path_is_absolute (program)
318 || strchr (program, G_DIR_SEPARATOR) != NULL
320 || strchr (program, '/') != NULL
324 if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE))
325 return g_strdup (program);
330 path = g_getenv ("PATH");
334 /* There is no `PATH' in the environment. The default
335 * search path in GNU libc is the current directory followed by
336 * the path `confstr' returns for `_CS_PATH'.
339 /* In GLib we put . last, for security, and don't use the
340 * unportable confstr(); UNIX98 does not actually specify
341 * what to search if PATH is unset. POSIX may, dunno.
344 path = "/bin:/usr/bin:.";
349 gchar moddir[MAXPATHLEN], sysdir[MAXPATHLEN], windir[MAXPATHLEN];
351 GetModuleFileName (NULL, moddir, sizeof (moddir));
352 tmp = g_path_get_dirname (moddir);
353 GetSystemDirectory (sysdir, sizeof (sysdir));
354 GetWindowsDirectory (windir, sizeof (windir));
355 path_tmp = g_strconcat (tmp, ";.;", sysdir, ";", windir,
356 (path != NULL ? ";" : NULL),
357 (path != NULL ? path : NULL),
364 len = strlen (program) + 1;
365 pathlen = strlen (path);
366 freeme = name = g_malloc (pathlen + len + 1);
368 /* Copy the file name at the top, including '\0' */
369 memcpy (name + pathlen + 1, program, len);
370 name = name + pathlen;
371 /* And add the slash before the filename */
372 *name = G_DIR_SEPARATOR;
380 p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
383 /* Two adjacent colons, or a colon at the beginning or the end
384 * of `PATH' means to search the current directory.
388 startp = memcpy (name - (p - path), path, p - path);
390 if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE))
393 ret = g_strdup (startp);
401 while (*p++ != '\0');
412 g_parse_debug_string (const gchar *string,
413 const GDebugKey *keys,
419 g_return_val_if_fail (string != NULL, 0);
421 if (!g_ascii_strcasecmp (string, "all"))
423 for (i=0; i<nkeys; i++)
424 result |= keys[i].value;
428 const gchar *p = string;
430 gboolean done = FALSE;
441 for (i=0; i<nkeys; i++)
442 if (g_ascii_strncasecmp (keys[i].key, p, q - p) == 0 &&
443 keys[i].key[q - p] == '\0')
444 result |= keys[i].value;
455 * @file_name: the name of the file.
457 * Gets the name of the file without any leading directory components.
458 * It returns a pointer into the given file name string.
460 * Return value: the name of the file without any leading directory components.
462 * Deprecated: Use g_path_get_basename() instead, but notice that
463 * g_path_get_basename() allocates new memory for the returned string, unlike
464 * this function which returns a pointer into the argument.
466 G_CONST_RETURN gchar*
467 g_basename (const gchar *file_name)
469 register gchar *base;
471 g_return_val_if_fail (file_name != NULL, NULL);
473 base = strrchr (file_name, G_DIR_SEPARATOR);
477 gchar *q = strrchr (file_name, '/');
478 if (base == NULL || (q != NULL && q > base))
487 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
488 return (gchar*) file_name + 2;
489 #endif /* G_OS_WIN32 */
491 return (gchar*) file_name;
495 * g_path_get_basename:
496 * @file_name: the name of the file.
498 * Gets the last component of the filename. If @file_name ends with a
499 * directory separator it gets the component before the last slash. If
500 * @file_name consists only of directory separators (and on Windows,
501 * possibly a drive letter), a single separator is returned. If
502 * @file_name is empty, it gets ".".
504 * Return value: a newly allocated string containing the last component of
508 g_path_get_basename (const gchar *file_name)
510 register gssize base;
511 register gssize last_nonslash;
515 g_return_val_if_fail (file_name != NULL, NULL);
517 if (file_name[0] == '\0')
519 return g_strdup (".");
521 last_nonslash = strlen (file_name) - 1;
523 while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
526 if (last_nonslash == -1)
527 /* string only containing slashes */
528 return g_strdup (G_DIR_SEPARATOR_S);
531 if (last_nonslash == 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
532 /* string only containing slashes and a drive */
533 return g_strdup (G_DIR_SEPARATOR_S);
534 #endif /* G_OS_WIN32 */
536 base = last_nonslash;
538 while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
542 if (base == -1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
544 #endif /* G_OS_WIN32 */
546 len = last_nonslash - base;
547 retval = g_malloc (len + 1);
548 memcpy (retval, file_name + base + 1, len);
554 g_path_is_absolute (const gchar *file_name)
556 g_return_val_if_fail (file_name != NULL, FALSE);
558 if (G_IS_DIR_SEPARATOR (file_name[0]))
562 /* Recognize drive letter on native Windows */
563 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
565 #endif /* G_OS_WIN32 */
570 G_CONST_RETURN gchar*
571 g_path_skip_root (const gchar *file_name)
573 g_return_val_if_fail (file_name != NULL, NULL);
575 #ifdef G_PLATFORM_WIN32
576 /* Skip \\server\share or //server/share */
577 if (G_IS_DIR_SEPARATOR (file_name[0]) &&
578 G_IS_DIR_SEPARATOR (file_name[1]) &&
583 p = strchr (file_name + 2, G_DIR_SEPARATOR);
586 gchar *q = strchr (file_name + 2, '/');
587 if (p == NULL || (q != NULL && q < p))
597 while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
600 /* Possibly skip a backslash after the share name */
601 if (G_IS_DIR_SEPARATOR (file_name[0]))
604 return (gchar *)file_name;
609 /* Skip initial slashes */
610 if (G_IS_DIR_SEPARATOR (file_name[0]))
612 while (G_IS_DIR_SEPARATOR (file_name[0]))
614 return (gchar *)file_name;
619 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
620 return (gchar *)file_name + 3;
627 g_path_get_dirname (const gchar *file_name)
629 register gchar *base;
632 g_return_val_if_fail (file_name != NULL, NULL);
634 base = strrchr (file_name, G_DIR_SEPARATOR);
637 gchar *q = strrchr (file_name, '/');
638 if (base == NULL || (q != NULL && q > base))
645 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
647 gchar drive_colon_dot[4];
649 drive_colon_dot[0] = file_name[0];
650 drive_colon_dot[1] = ':';
651 drive_colon_dot[2] = '.';
652 drive_colon_dot[3] = '\0';
654 return g_strdup (drive_colon_dot);
657 return g_strdup (".");
660 while (base > file_name && G_IS_DIR_SEPARATOR (*base))
664 if (base == file_name + 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
668 len = (guint) 1 + base - file_name;
670 base = g_new (gchar, len + 1);
671 g_memmove (base, file_name, len);
678 g_get_current_dir (void)
680 gchar *buffer = NULL;
682 static gulong max_len = 0;
685 max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
687 /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
688 * and, if that wasn't bad enough, hangs in doing so.
690 #if (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
691 buffer = g_new (gchar, max_len + 1);
693 dir = getwd (buffer);
694 #else /* !sun || !HAVE_GETCWD */
695 while (max_len < G_MAXULONG / 2)
697 buffer = g_new (gchar, max_len + 1);
699 dir = getcwd (buffer, max_len);
701 if (dir || errno != ERANGE)
707 #endif /* !sun || !HAVE_GETCWD */
709 if (!dir || !*buffer)
711 /* hm, should we g_error() out here?
712 * this can happen if e.g. "./" has mode \0000
714 buffer[0] = G_DIR_SEPARATOR;
719 dir = g_locale_to_utf8 (buffer, -1, NULL, NULL, NULL);
721 dir = g_strdup (buffer);
730 #undef g_get_current_dir
732 /* Binary compatibility version. Not for newly compiled code. */
735 g_get_current_dir (void)
737 gchar *utf8_dir = g_get_current_dir_utf8 ();
738 gchar *dir = g_locale_from_utf8 (utf8_dir, -1, NULL, NULL, NULL);
747 * @variable: the environment variable to get.
749 * Returns an environment variable.
751 * Return value: the value of the environment variable, or %NULL if the environment
752 * variable is not found. The returned string may be overwritten by the next call to g_getenv(),
753 * g_setenv() or g_unsetenv().
755 G_CONST_RETURN gchar*
756 g_getenv (const gchar *variable)
759 g_return_val_if_fail (variable != NULL, NULL);
761 return getenv (variable);
769 g_return_val_if_fail (variable != NULL, NULL);
771 system_env = getenv (variable);
775 /* On Windows NT, it is relatively typical that environment
776 * variables contain references to other environment variables. If
777 * so, use ExpandEnvironmentStrings(). (If all software was written
778 * in the best possible way, such environment variables would be
779 * stored in the Registry as REG_EXPAND_SZ type values, and would
780 * then get automatically expanded before the program sees them. But
781 * there is broken software that stores environment variables as
782 * REG_SZ values even if they contain references to other
783 * environment variables.
786 if (strchr (system_env, '%') == NULL)
788 /* No reference to other variable(s), return value as such. */
792 /* First check how much space we need */
793 length = ExpandEnvironmentStrings (system_env, dummy, 2);
795 expanded_env = g_malloc (length);
797 ExpandEnvironmentStrings (system_env, expanded_env, length);
799 quark = g_quark_from_string (expanded_env);
800 g_free (expanded_env);
802 return g_quark_to_string (quark);
808 * @variable: the environment variable to set, must not contain '='.
809 * @value: the value for to set the variable to.
810 * @overwrite: whether to change the variable if it already exists.
812 * Sets an environment variable.
814 * Note that on some systems, the memory used for the variable and its value
815 * can't be reclaimed later.
817 * Returns: %FALSE if the environment variable couldn't be set.
822 g_setenv (const gchar *variable,
831 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
834 result = setenv (variable, value, overwrite);
836 if (!overwrite && g_getenv (variable) != NULL)
839 /* This results in a leak when you overwrite existing
840 * settings. It would be fairly easy to fix this by keeping
841 * our own parallel array or hash table.
843 string = g_strconcat (variable, "=", value, NULL);
844 result = putenv (string);
849 #ifndef HAVE_UNSETENV
850 /* According to the Single Unix Specification, environ is not in
851 * any system header, although unistd.h often declares it.
855 * Win32 - at least msvc headers declare it so let's avoid
856 * warning C4273: '__p__environ' : inconsistent dll linkage. dllexport assumed.
858 extern char **environ;
864 * @variable: the environment variable to remove, must not contain '='.
866 * Removes an environment variable from the environment.
868 * Note that on some systems, the memory used for the variable and its value
869 * can't be reclaimed. Furthermore, this function can't be guaranteed to operate in a
875 g_unsetenv (const gchar *variable)
878 g_return_if_fail (strchr (variable, '=') == NULL);
885 g_return_if_fail (strchr (variable, '=') == NULL);
887 len = strlen (variable);
889 /* Mess directly with the environ array.
890 * This seems to be the only portable way to do this.
892 * Note that we remove *all* environment entries for
893 * the variable name, not just the first.
898 if (strncmp (*e, variable, len) != 0 || (*e)[len] != '=')
909 G_LOCK_DEFINE_STATIC (g_utils_global);
911 static gchar *g_tmp_dir = NULL;
912 static gchar *g_user_name = NULL;
913 static gchar *g_real_name = NULL;
914 static gchar *g_home_dir = NULL;
916 static gchar *g_user_data_dir = NULL;
917 static gchar **g_system_data_dirs = NULL;
918 static gchar *g_user_cache_dir = NULL;
919 static gchar *g_user_config_dir = NULL;
920 static gchar **g_system_config_dirs = NULL;
925 get_special_folder (int csidl)
929 wchar_t wc[MAX_PATH+1];
932 LPITEMIDLIST pidl = NULL;
934 gchar *retval = NULL;
936 hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
939 if (G_WIN32_HAVE_WIDECHAR_API ())
941 b = SHGetPathFromIDListW (pidl, path.wc);
943 retval = g_utf16_to_utf8 (path.wc, -1, NULL, NULL, NULL);
947 b = SHGetPathFromIDListA (pidl, path.c);
949 retval = g_locale_to_utf8 (path.c, -1, NULL, NULL, NULL);
951 CoTaskMemFree (pidl);
958 /* HOLDS: g_utils_global_lock */
960 g_get_any_init (void)
964 g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
966 g_tmp_dir = g_strdup (g_getenv ("TMP"));
968 g_tmp_dir = g_strdup (g_getenv ("TEMP"));
974 g_tmp_dir = g_strdup (P_tmpdir);
975 k = strlen (g_tmp_dir);
976 if (k > 1 && G_IS_DIR_SEPARATOR (g_tmp_dir[k - 1]))
977 g_tmp_dir[k - 1] = '\0';
984 g_tmp_dir = g_strdup ("/tmp");
985 #else /* G_OS_WIN32 */
986 g_tmp_dir = g_strdup ("C:\\");
987 #endif /* G_OS_WIN32 */
991 /* We check $HOME first for Win32, though it is a last resort for Unix
992 * where we prefer the results of getpwuid().
995 gchar *home = g_getenv ("HOME");
997 /* Only believe HOME if it is an absolute path and exists */
998 if (home && g_path_is_absolute (home) && g_file_test (home, G_FILE_TEST_IS_DIR))
999 g_home_dir = g_strdup (home);
1002 /* In case HOME is Unix-style (it happens), convert it to
1008 while ((p = strchr (g_home_dir, '/')) != NULL)
1014 /* USERPROFILE is probably the closest equivalent to $HOME? */
1015 if (getenv ("USERPROFILE") != NULL)
1016 g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
1020 g_home_dir = get_special_folder (CSIDL_PROFILE);
1024 /* At least at some time, HOMEDRIVE and HOMEPATH were used
1025 * to point to the home directory, I think. But on Windows
1026 * 2000 HOMEDRIVE seems to be equal to SYSTEMDRIVE, and
1027 * HOMEPATH is its root "\"?
1029 if (getenv ("HOMEDRIVE") != NULL && getenv ("HOMEPATH") != NULL)
1031 gchar *homedrive, *homepath;
1033 homedrive = g_strdup (g_getenv ("HOMEDRIVE"));
1034 homepath = g_strdup (g_getenv ("HOMEPATH"));
1036 g_home_dir = g_strconcat (homedrive, homepath, NULL);
1041 #endif /* G_OS_WIN32 */
1045 struct passwd *pw = NULL;
1046 gpointer buffer = NULL;
1049 # if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
1051 # ifdef _SC_GETPW_R_SIZE_MAX
1052 /* This reurns the maximum length */
1053 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
1057 # else /* _SC_GETPW_R_SIZE_MAX */
1059 # endif /* _SC_GETPW_R_SIZE_MAX */
1064 /* we allocate 6 extra bytes to work around a bug in
1065 * Mac OS < 10.3. See #156446
1067 buffer = g_malloc (bufsize + 6);
1070 # ifdef HAVE_POSIX_GETPWUID_R
1071 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1072 error = error < 0 ? errno : error;
1073 # else /* HAVE_NONPOSIX_GETPWUID_R */
1074 /* HPUX 11 falls into the HAVE_POSIX_GETPWUID_R case */
1075 # if defined(_AIX) || defined(__hpux)
1076 error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1077 pw = error == 0 ? &pwd : NULL;
1079 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1080 error = pw ? 0 : errno;
1082 # endif /* HAVE_NONPOSIX_GETPWUID_R */
1086 /* we bail out prematurely if the user id can't be found
1087 * (should be pretty rare case actually), or if the buffer
1088 * should be sufficiently big and lookups are still not
1091 if (error == 0 || error == ENOENT)
1093 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
1094 (gulong) getuid ());
1097 if (bufsize > 32 * 1024)
1099 g_warning ("getpwuid_r(): failed due to: %s.",
1100 g_strerror (error));
1108 # endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
1113 pw = getpwuid (getuid ());
1118 g_user_name = g_strdup (pw->pw_name);
1120 if (pw->pw_gecos && *pw->pw_gecos != '\0')
1122 gchar **gecos_fields;
1125 /* split the gecos field and substitute '&' */
1126 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
1127 name_parts = g_strsplit (gecos_fields[0], "&", 0);
1128 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
1129 g_real_name = g_strjoinv (pw->pw_name, name_parts);
1130 g_strfreev (gecos_fields);
1131 g_strfreev (name_parts);
1135 g_home_dir = g_strdup (pw->pw_dir);
1140 #else /* !HAVE_PWD_H */
1144 guint len = UNLEN+1;
1145 gchar buffer[UNLEN+1];
1147 if (GetUserName ((LPTSTR) buffer, (LPDWORD) &len))
1149 g_user_name = g_strdup (buffer);
1150 g_real_name = g_strdup (buffer);
1153 # endif /* G_OS_WIN32 */
1155 #endif /* !HAVE_PWD_H */
1158 g_home_dir = g_strdup (g_getenv ("HOME"));
1161 /* change '\\' in %HOME% to '/' */
1162 g_strdelimit (g_home_dir, "\\",'/');
1165 g_user_name = g_strdup ("somebody");
1167 g_real_name = g_strdup ("Unknown");
1171 G_CONST_RETURN gchar*
1172 g_get_user_name (void)
1174 G_LOCK (g_utils_global);
1177 G_UNLOCK (g_utils_global);
1182 G_CONST_RETURN gchar*
1183 g_get_real_name (void)
1185 G_LOCK (g_utils_global);
1188 G_UNLOCK (g_utils_global);
1193 G_CONST_RETURN gchar*
1194 g_get_home_dir (void)
1196 G_LOCK (g_utils_global);
1199 G_UNLOCK (g_utils_global);
1206 #undef g_get_home_dir
1208 G_CONST_RETURN gchar*
1209 g_get_home_dir (void)
1211 static gchar *home_dir = NULL;
1213 G_LOCK (g_utils_global);
1216 if (!home_dir && g_home_dir)
1217 home_dir = g_locale_from_utf8 (g_home_dir, -1, NULL, NULL, NULL);
1218 G_UNLOCK (g_utils_global);
1225 /* Return a directory to be used to store temporary files. This is the
1226 * value of the TMPDIR, TMP or TEMP environment variables (they are
1227 * checked in that order). If none of those exist, use P_tmpdir from
1228 * stdio.h. If that isn't defined, return "/tmp" on POSIXly systems,
1229 * and C:\ on Windows.
1232 G_CONST_RETURN gchar*
1233 g_get_tmp_dir (void)
1235 G_LOCK (g_utils_global);
1238 G_UNLOCK (g_utils_global);
1245 #undef g_get_tmp_dir
1247 G_CONST_RETURN gchar*
1248 g_get_tmp_dir (void)
1250 static gchar *tmp_dir = NULL;
1252 G_LOCK (g_utils_global);
1256 tmp_dir = g_locale_from_utf8 (g_tmp_dir, -1, NULL, NULL, NULL);
1258 if (tmp_dir == NULL)
1260 G_UNLOCK (g_utils_global);
1267 G_LOCK_DEFINE_STATIC (g_prgname);
1268 static gchar *g_prgname = NULL;
1271 g_get_prgname (void)
1277 G_UNLOCK (g_prgname);
1283 g_set_prgname (const gchar *prgname)
1287 g_prgname = g_strdup (prgname);
1288 G_UNLOCK (g_prgname);
1291 G_LOCK_DEFINE_STATIC (g_application_name);
1292 static gchar *g_application_name = NULL;
1295 * g_get_application_name:
1297 * Gets a human-readable name for the application, as set by
1298 * g_set_application_name(). This name should be localized if
1299 * possible, and is intended for display to the user. Contrast with
1300 * g_get_prgname(), which gets a non-localized name. If
1301 * g_set_application_name() has not been called, returns the result of
1302 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1305 * Return value: human-readable application name. may return %NULL
1309 G_CONST_RETURN gchar*
1310 g_get_application_name (void)
1314 G_LOCK (g_application_name);
1315 retval = g_application_name;
1316 G_UNLOCK (g_application_name);
1319 return g_get_prgname ();
1325 * g_set_application_name:
1326 * @application_name: localized name of the application
1328 * Sets a human-readable name for the application. This name should be
1329 * localized if possible, and is intended for display to the user.
1330 * Contrast with g_set_prgname(), which sets a non-localized name.
1331 * g_set_prgname() will be called automatically by gtk_init(),
1332 * but g_set_application_name() will not.
1334 * Note that for thread safety reasons, this function can only
1337 * The application name will be used in contexts such as error messages,
1338 * or when displaying an application's name in the task list.
1342 g_set_application_name (const gchar *application_name)
1344 gboolean already_set = FALSE;
1346 G_LOCK (g_application_name);
1347 if (g_application_name)
1350 g_application_name = g_strdup (application_name);
1351 G_UNLOCK (g_application_name);
1354 g_warning ("g_set_application() name called multiple times");
1358 * g_get_user_data_dir:
1360 * Returns a base directory in which to access application data such
1361 * as icons that is customized for a particular user.
1363 * On Unix platforms this is determined using the mechanisms described in
1364 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1365 * XDG Base Directory Specification</ulink>
1367 * Return value: a string owned by GLib that must not be modified
1371 G_CONST_RETURN gchar*
1372 g_get_user_data_dir (void)
1376 G_LOCK (g_utils_global);
1378 if (!g_user_data_dir)
1381 data_dir = get_special_folder (CSIDL_PERSONAL);
1383 data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
1386 if (data_dir && data_dir[0])
1387 data_dir = g_strdup (data_dir);
1393 data_dir = g_build_filename (g_home_dir, ".local",
1397 g_user_data_dir = data_dir;
1400 data_dir = g_user_data_dir;
1402 G_UNLOCK (g_utils_global);
1408 * g_get_user_config_dir:
1410 * Returns a base directory in which to store user-specific application
1411 * configuration information such as user preferences and settings.
1413 * On Unix platforms this is determined using the mechanisms described in
1414 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1415 * XDG Base Directory Specification</ulink>
1417 * Return value: a string owned by GLib that must not be modified
1421 G_CONST_RETURN gchar*
1422 g_get_user_config_dir (void)
1426 G_LOCK (g_utils_global);
1428 if (!g_user_config_dir)
1431 config_dir = get_special_folder (CSIDL_APPDATA);
1433 config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
1436 if (config_dir && config_dir[0])
1437 config_dir = g_strdup (config_dir);
1443 config_dir = g_build_filename (g_home_dir, ".config", NULL);
1445 g_user_config_dir = config_dir;
1448 config_dir = g_user_config_dir;
1450 G_UNLOCK (g_utils_global);
1456 * g_get_user_cache_dir:
1458 * Returns a base directory in which to store non-essential, cached
1459 * data specific to particular user.
1461 * On Unix platforms this is determined using the mechanisms described in
1462 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1463 * XDG Base Directory Specification</ulink>
1465 * Return value: a string owned by GLib that must not be modified
1469 G_CONST_RETURN gchar*
1470 g_get_user_cache_dir (void)
1474 G_LOCK (g_utils_global);
1476 if (!g_user_cache_dir)
1479 cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
1481 cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
1483 if (cache_dir && cache_dir[0])
1484 cache_dir = g_strdup (cache_dir);
1490 cache_dir = g_build_filename (g_home_dir, ".cache", NULL);
1492 g_user_cache_dir = cache_dir;
1495 cache_dir = g_user_cache_dir;
1497 G_UNLOCK (g_utils_global);
1503 * g_get_system_data_dirs:
1505 * Returns an ordered list of base directories in which to access
1506 * system-wide application data.
1508 * On Unix platforms this is determined using the mechanisms described in
1509 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1510 * XDG Base Directory Specification</ulink>
1512 * Return value: a %NULL-terminated array of strings owned by GLib that must
1513 * not be modified or freed.
1516 G_CONST_RETURN gchar * G_CONST_RETURN *
1517 g_get_system_data_dirs (void)
1519 gchar *data_dirs, **data_dir_vector;
1521 G_LOCK (g_utils_global);
1523 if (!g_system_data_dirs)
1526 data_dirs = g_strconcat (get_special_folder (CSIDL_COMMON_APPDATA),
1527 G_SEARCHPATH_SEPARATOR_S,
1528 get_special_folder (CSIDL_COMMON_DOCUMENTS),
1531 data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
1533 if (!data_dirs || !data_dirs[0])
1534 data_dirs = "/usr/local/share/:/usr/share/";
1536 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
1538 g_system_data_dirs = data_dir_vector;
1541 data_dir_vector = g_system_data_dirs;
1543 G_UNLOCK (g_utils_global);
1545 return (G_CONST_RETURN gchar * G_CONST_RETURN *) data_dir_vector;
1549 * g_get_system_config_dirs:
1551 * Returns an ordered list of base directories in which to access
1552 * system-wide configuration information.
1554 * On Unix platforms this is determined using the mechanisms described in
1555 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1556 * XDG Base Directory Specification</ulink>
1558 * Return value: a %NULL-terminated array of strings owned by GLib that must
1559 * not be modified or freed.
1562 G_CONST_RETURN gchar * G_CONST_RETURN *
1563 g_get_system_config_dirs (void)
1565 gchar *conf_dirs, **conf_dir_vector;
1567 G_LOCK (g_utils_global);
1569 if (!g_system_config_dirs)
1572 conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
1574 conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
1576 if (!conf_dirs || !conf_dirs[0])
1577 conf_dirs = "/etc/xdg";
1579 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
1582 conf_dir_vector = g_system_config_dirs;
1583 G_UNLOCK (g_utils_global);
1585 return (G_CONST_RETURN gchar * G_CONST_RETURN *) conf_dir_vector;
1588 static GHashTable *alias_table = NULL;
1590 /* read an alias file for the locales */
1592 read_aliases (gchar *file)
1598 alias_table = g_hash_table_new (g_str_hash, g_str_equal);
1599 fp = fopen (file,"r");
1602 while (fgets (buf, 256, fp))
1608 /* Line is a comment */
1609 if ((buf[0] == '#') || (buf[0] == '\0'))
1612 /* Reads first column */
1613 for (p = buf, q = NULL; *p; p++) {
1614 if ((*p == '\t') || (*p == ' ') || (*p == ':')) {
1617 while ((*q == '\t') || (*q == ' ')) {
1623 /* The line only had one column */
1624 if (!q || *q == '\0')
1627 /* Read second column */
1628 for (p = q; *p; p++) {
1629 if ((*p == '\t') || (*p == ' ')) {
1635 /* Add to alias table if necessary */
1636 if (!g_hash_table_lookup (alias_table, buf)) {
1637 g_hash_table_insert (alias_table, g_strdup (buf), g_strdup (q));
1644 unalias_lang (char *lang)
1650 read_aliases ("/usr/share/locale/locale.alias");
1653 while ((p = g_hash_table_lookup (alias_table, lang)) && (strcmp (p, lang) != 0))
1658 static gboolean said_before = FALSE;
1660 g_warning ("Too many alias levels for a locale, "
1661 "may indicate a loop");
1669 /* Mask for components of locale spec. The ordering here is from
1670 * least significant to most significant
1674 COMPONENT_CODESET = 1 << 0,
1675 COMPONENT_TERRITORY = 1 << 1,
1676 COMPONENT_MODIFIER = 1 << 2
1679 /* Break an X/Open style locale specification into components
1682 explode_locale (const gchar *locale,
1688 const gchar *uscore_pos;
1689 const gchar *at_pos;
1690 const gchar *dot_pos;
1694 uscore_pos = strchr (locale, '_');
1695 dot_pos = strchr (uscore_pos ? uscore_pos : locale, '.');
1696 at_pos = strchr (dot_pos ? dot_pos : (uscore_pos ? uscore_pos : locale), '@');
1700 mask |= COMPONENT_MODIFIER;
1701 *modifier = g_strdup (at_pos);
1704 at_pos = locale + strlen (locale);
1708 mask |= COMPONENT_CODESET;
1709 *codeset = g_strndup (dot_pos, at_pos - dot_pos);
1716 mask |= COMPONENT_TERRITORY;
1717 *territory = g_strndup (uscore_pos, dot_pos - uscore_pos);
1720 uscore_pos = dot_pos;
1722 *language = g_strndup (locale, uscore_pos - locale);
1728 * Compute all interesting variants for a given locale name -
1729 * by stripping off different components of the value.
1731 * For simplicity, we assume that the locale is in
1732 * X/Open format: language[_territory][.codeset][@modifier]
1734 * TODO: Extend this to handle the CEN format (see the GNUlibc docs)
1735 * as well. We could just copy the code from glibc wholesale
1736 * but it is big, ugly, and complicated, so I'm reluctant
1737 * to do so when this should handle 99% of the time...
1740 _g_compute_locale_variants (const gchar *locale)
1742 GSList *retval = NULL;
1752 g_return_val_if_fail (locale != NULL, NULL);
1754 mask = explode_locale (locale, &language, &territory, &codeset, &modifier);
1756 /* Iterate through all possible combinations, from least attractive
1757 * to most attractive.
1759 for (i = 0; i <= mask; i++)
1760 if ((i & ~mask) == 0)
1762 gchar *val = g_strconcat (language,
1763 (i & COMPONENT_TERRITORY) ? territory : "",
1764 (i & COMPONENT_CODESET) ? codeset : "",
1765 (i & COMPONENT_MODIFIER) ? modifier : "",
1767 retval = g_slist_prepend (retval, val);
1771 if (mask & COMPONENT_CODESET)
1773 if (mask & COMPONENT_TERRITORY)
1775 if (mask & COMPONENT_MODIFIER)
1781 /* The following is (partly) taken from the gettext package.
1782 Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc. */
1784 static const gchar *
1785 guess_category_value (const gchar *category_name)
1787 const gchar *retval;
1789 /* The highest priority value is the `LANGUAGE' environment
1790 variable. This is a GNU extension. */
1791 retval = g_getenv ("LANGUAGE");
1792 if ((retval != NULL) && (retval[0] != '\0'))
1795 /* `LANGUAGE' is not set. So we have to proceed with the POSIX
1796 methods of looking to `LC_ALL', `LC_xxx', and `LANG'. On some
1797 systems this can be done by the `setlocale' function itself. */
1799 /* Setting of LC_ALL overwrites all other. */
1800 retval = g_getenv ("LC_ALL");
1801 if ((retval != NULL) && (retval[0] != '\0'))
1804 /* Next comes the name of the desired category. */
1805 retval = g_getenv (category_name);
1806 if ((retval != NULL) && (retval[0] != '\0'))
1809 /* Last possibility is the LANG environment variable. */
1810 retval = g_getenv ("LANG");
1811 if ((retval != NULL) && (retval[0] != '\0'))
1814 #ifdef G_PLATFORM_WIN32
1815 /* g_win32_getlocale() first checks for LC_ALL, LC_MESSAGES and
1816 * LANG, which we already did above. Oh well. The main point of
1817 * calling g_win32_getlocale() is to get the thread's locale as used
1818 * by Windows and the Microsoft C runtime (in the "English_United
1819 * States" format) translated into the Unixish format.
1821 retval = g_win32_getlocale ();
1822 if ((retval != NULL) && (retval[0] != '\0'))
1829 static gchar **languages = NULL;
1832 * g_get_language_names:
1834 * Computes a list of applicable locale names, which can be used to
1835 * e.g. construct locale-dependent filenames or search paths. The returned
1836 * list is sorted from most desirable to least desirable and always contains
1837 * the default locale "C".
1839 * For example, if LANGUAGE=de:en_US, then the returned list is
1840 * "de", "en_US", "en", "C".
1842 * This function consults the environment variables <envar>LANGUAGE</envar>,
1843 * <envar>LC_ALL</envar>, <envar>LC_MESSAGES</envar> and <envar>LANG</envar>
1844 * to find the list of locales specified by the user.
1846 * Return value: a %NULL-terminated array of strings owned by GLib
1847 * that must not be modified or freed.
1851 G_CONST_RETURN gchar * G_CONST_RETURN *
1852 g_get_language_names (void)
1854 G_LOCK (g_utils_global);
1863 value = guess_category_value ("LC_MESSAGES");
1867 alist = g_strsplit (value, ":", 0);
1869 for (a = alist; *a; a++)
1871 gchar *b = unalias_lang (*a);
1872 list = g_slist_concat (list, _g_compute_locale_variants (b));
1875 list = g_slist_append (list, "C");
1877 languages = g_new (gchar *, g_slist_length (list) + 1);
1878 for (l = list, i = 0; l; l = l->next, i++)
1879 languages[i] = l->data;
1880 languages[i] = NULL;
1882 g_slist_free (list);
1885 G_UNLOCK (g_utils_global);
1887 return (G_CONST_RETURN gchar * G_CONST_RETURN *) languages;
1891 g_direct_hash (gconstpointer v)
1893 return GPOINTER_TO_UINT (v);
1897 g_direct_equal (gconstpointer v1,
1904 g_int_equal (gconstpointer v1,
1907 return *((const gint*) v1) == *((const gint*) v2);
1911 g_int_hash (gconstpointer v)
1913 return *(const gint*) v;
1917 * g_nullify_pointer:
1918 * @nullify_location: the memory address of the pointer.
1920 * Set the pointer at the specified location to %NULL.
1923 g_nullify_pointer (gpointer *nullify_location)
1925 g_return_if_fail (nullify_location != NULL);
1927 *nullify_location = NULL;
1933 * Get the codeset for the current locale.
1935 * Return value: a newly allocated string containing the name
1936 * of the codeset. This string must be freed with g_free().
1939 g_get_codeset (void)
1941 const gchar *charset;
1943 g_get_charset (&charset);
1945 return g_strdup (charset);
1950 #include <libintl.h>
1952 #ifdef G_PLATFORM_WIN32
1954 G_WIN32_DLLMAIN_FOR_DLL_NAME (static, dll_name)
1956 static const gchar *
1957 _glib_get_locale_dir (void)
1959 static const gchar *cache = NULL;
1961 cache = g_win32_get_package_installation_subdirectory
1962 (GETTEXT_PACKAGE, dll_name, "lib\\locale");
1967 #undef GLIB_LOCALE_DIR
1968 #define GLIB_LOCALE_DIR _glib_get_locale_dir ()
1970 #endif /* G_PLATFORM_WIN32 */
1972 G_CONST_RETURN gchar *
1973 _glib_gettext (const gchar *str)
1975 static gboolean _glib_gettext_initialized = FALSE;
1977 if (!_glib_gettext_initialized)
1979 bindtextdomain(GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
1980 # ifdef HAVE_BIND_TEXTDOMAIN_CODESET
1981 bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
1983 _glib_gettext_initialized = TRUE;
1986 return dgettext (GETTEXT_PACKAGE, str);
1989 #endif /* ENABLE_NLS */