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 const guint glib_major_version = GLIB_MAJOR_VERSION;
92 const guint glib_minor_version = GLIB_MINOR_VERSION;
93 const guint glib_micro_version = GLIB_MICRO_VERSION;
94 const guint glib_interface_age = GLIB_INTERFACE_AGE;
95 const guint glib_binary_age = GLIB_BINARY_AGE;
99 * @required_major: the required major version.
100 * @required_minor: the required major version.
101 * @required_micro: the required major version.
103 * Checks that the GLib library in use is compatible with the
104 * given version. Generally you would pass in the constants
105 * #GLIB_MAJOR_VERSION, #GLIB_MINOR_VERSION, #GLIB_MICRO_VERSION
106 * as the three arguments to this function; that produces
107 * a check that the library in use is compatible with
108 * the version of GLib the application or module was compiled
111 * Compatibility is defined by two things: first the version
112 * of the running library is newer than the version
113 * @required_major.required_minor.@required_micro. Second
114 * the running library must be binary compatible with the
115 * version @required_major.required_minor.@required_micro
116 * (same major version.)
118 * Return value: %NULL if the GLib library is compatible with the
119 * given version, or a string describing the version mismatch.
120 * The returned string is owned by GLib and must not be modified
126 glib_check_version (guint required_major,
127 guint required_minor,
128 guint required_micro)
130 gint glib_effective_micro = 100 * GLIB_MINOR_VERSION + GLIB_MICRO_VERSION;
131 gint required_effective_micro = 100 * required_minor + required_micro;
133 if (required_major > GLIB_MAJOR_VERSION)
134 return "GLib version too old (major mismatch)";
135 if (required_major < GLIB_MAJOR_VERSION)
136 return "GLib version too new (major mismatch)";
137 if (required_effective_micro < glib_effective_micro - GLIB_BINARY_AGE)
138 return "GLib version too new (micro mismatch)";
139 if (required_effective_micro > glib_effective_micro)
140 return "GLib version too old (micro mismatch)";
144 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
146 g_memmove (gpointer dest, gconstpointer src, gulong len)
148 gchar* destptr = dest;
149 const gchar* srcptr = src;
150 if (src + len < dest || dest + len < src)
152 bcopy (src, dest, len);
155 else if (dest <= src)
158 *(destptr++) = *(srcptr++);
165 *(--destptr) = *(--srcptr);
168 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
171 g_atexit (GVoidFunc func)
174 const gchar *error = NULL;
176 /* keep this in sync with glib.h */
178 #ifdef G_NATIVE_ATEXIT
179 result = ATEXIT (func);
181 error = g_strerror (errno);
182 #elif defined (HAVE_ATEXIT)
183 # ifdef NeXT /* @#%@! NeXTStep */
184 result = !atexit ((void (*)(void)) func);
186 error = g_strerror (errno);
188 result = atexit ((void (*)(void)) func);
190 error = g_strerror (errno);
192 #elif defined (HAVE_ON_EXIT)
193 result = on_exit ((void (*)(int, void *)) func, NULL);
195 error = g_strerror (errno);
198 error = "no implementation";
199 #endif /* G_NATIVE_ATEXIT */
202 g_error ("Could not register atexit() function: %s", error);
205 /* Based on execvp() from GNU Libc.
206 * Some of this code is cut-and-pasted into gspawn.c
210 my_strchrnul (const gchar *str, gchar c)
212 gchar *p = (gchar*)str;
213 while (*p && (*p != c))
221 static gchar *inner_find_program_in_path (const gchar *program);
224 g_find_program_in_path (const gchar *program)
226 const gchar *last_dot = strrchr (program, '.');
228 if (last_dot == NULL || strchr (last_dot, '\\') != NULL)
230 const gint program_length = strlen (program);
231 const gchar *pathext = getenv ("PATHEXT");
233 gchar *decorated_program;
237 pathext = ".com;.exe;.bat";
243 p = my_strchrnul (pathext, ';');
245 decorated_program = g_malloc (program_length + (p-pathext) + 1);
246 memcpy (decorated_program, program, program_length);
247 memcpy (decorated_program+program_length, pathext, p-pathext);
248 decorated_program [program_length + (p-pathext)] = '\0';
250 retval = inner_find_program_in_path (decorated_program);
251 g_free (decorated_program);
255 } while (*p++ != '\0');
259 return inner_find_program_in_path (program);
262 #define g_find_program_in_path inner_find_program_in_path
266 * g_find_program_in_path:
267 * @program: a program name
269 * Locates the first executable named @program in the user's path, in the
270 * same way that execvp() would locate it. Returns an allocated string
271 * with the absolute path name, or NULL if the program is not found in
272 * the path. If @program is already an absolute path, returns a copy of
273 * @program if @program exists and is executable, and NULL otherwise.
275 * On Windows, if @program does not have a file type suffix, tries to
276 * append the suffixes in the PATHEXT environment variable (if that
277 * doesn't exists, the suffixes .com, .exe, and .bat) in turn, and
278 * then look for the resulting file name in the same way as
279 * CreateProcess() would. This means first in the directory where the
280 * program was loaded from, then in the current directory, then in the
281 * Windows 32-bit system directory, then in the Windows directory, and
282 * finally in the directories in the PATH environment variable. If
283 * the program is found, the return value contains the full name
284 * including the type suffix.
286 * Return value: absolute path, or NULL
292 g_find_program_in_path (const gchar *program)
294 const gchar *path, *p;
295 gchar *name, *freeme;
302 g_return_val_if_fail (program != NULL, NULL);
304 /* If it is an absolute path, or a relative path including subdirectories,
305 * don't look in PATH.
307 if (g_path_is_absolute (program)
308 || strchr (program, G_DIR_SEPARATOR) != NULL
310 || strchr (program, '/') != NULL
314 if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE))
315 return g_strdup (program);
320 path = g_getenv ("PATH");
324 /* There is no `PATH' in the environment. The default
325 * search path in GNU libc is the current directory followed by
326 * the path `confstr' returns for `_CS_PATH'.
329 /* In GLib we put . last, for security, and don't use the
330 * unportable confstr(); UNIX98 does not actually specify
331 * what to search if PATH is unset. POSIX may, dunno.
334 path = "/bin:/usr/bin:.";
339 gchar moddir[MAXPATHLEN], sysdir[MAXPATHLEN], windir[MAXPATHLEN];
341 GetModuleFileName (NULL, moddir, sizeof (moddir));
342 tmp = g_path_get_dirname (moddir);
343 GetSystemDirectory (sysdir, sizeof (sysdir));
344 GetWindowsDirectory (windir, sizeof (windir));
345 path_tmp = g_strconcat (tmp, ";.;", sysdir, ";", windir,
346 (path != NULL ? ";" : NULL),
347 (path != NULL ? path : NULL),
354 len = strlen (program) + 1;
355 pathlen = strlen (path);
356 freeme = name = g_malloc (pathlen + len + 1);
358 /* Copy the file name at the top, including '\0' */
359 memcpy (name + pathlen + 1, program, len);
360 name = name + pathlen;
361 /* And add the slash before the filename */
362 *name = G_DIR_SEPARATOR;
370 p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
373 /* Two adjacent colons, or a colon at the beginning or the end
374 * of `PATH' means to search the current directory.
378 startp = memcpy (name - (p - path), path, p - path);
380 if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE))
383 ret = g_strdup (startp);
391 while (*p++ != '\0');
402 g_parse_debug_string (const gchar *string,
403 const GDebugKey *keys,
409 g_return_val_if_fail (string != NULL, 0);
411 if (!g_ascii_strcasecmp (string, "all"))
413 for (i=0; i<nkeys; i++)
414 result |= keys[i].value;
418 const gchar *p = string;
420 gboolean done = FALSE;
431 for (i=0; i<nkeys; i++)
432 if (g_ascii_strncasecmp(keys[i].key, p, q - p) == 0 &&
433 keys[i].key[q - p] == '\0')
434 result |= keys[i].value;
445 * @file_name: the name of the file.
447 * Gets the name of the file without any leading directory components.
448 * It returns a pointer into the given file name string.
450 * Return value: the name of the file without any leading directory components.
452 * Deprecated: Use g_path_get_basename() instead, but notice that
453 * g_path_get_basename() allocates new memory for the returned string, unlike
454 * this function which returns a pointer into the argument.
456 G_CONST_RETURN gchar*
457 g_basename (const gchar *file_name)
459 register gchar *base;
461 g_return_val_if_fail (file_name != NULL, NULL);
463 base = strrchr (file_name, G_DIR_SEPARATOR);
467 gchar *q = strrchr (file_name, '/');
468 if (base == NULL || (q != NULL && q > base))
477 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
478 return (gchar*) file_name + 2;
479 #endif /* G_OS_WIN32 */
481 return (gchar*) file_name;
485 * g_path_get_basename:
486 * @file_name: the name of the file.
488 * Gets the last component of the filename. If @file_name ends with a
489 * directory separator it gets the component before the last slash. If
490 * @file_name consists only of directory separators (and on Windows,
491 * possibly a drive letter), a single separator is returned. If
492 * @file_name is empty, it gets ".".
494 * Return value: a newly allocated string containing the last component of
498 g_path_get_basename (const gchar *file_name)
500 register gssize base;
501 register gssize last_nonslash;
505 g_return_val_if_fail (file_name != NULL, NULL);
507 if (file_name[0] == '\0')
509 return g_strdup (".");
511 last_nonslash = strlen (file_name) - 1;
513 while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
516 if (last_nonslash == -1)
517 /* string only containing slashes */
518 return g_strdup (G_DIR_SEPARATOR_S);
521 if (last_nonslash == 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
522 /* string only containing slashes and a drive */
523 return g_strdup (G_DIR_SEPARATOR_S);
524 #endif /* G_OS_WIN32 */
526 base = last_nonslash;
528 while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
532 if (base == -1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
534 #endif /* G_OS_WIN32 */
536 len = last_nonslash - base;
537 retval = g_malloc (len + 1);
538 memcpy (retval, file_name + base + 1, len);
544 g_path_is_absolute (const gchar *file_name)
546 g_return_val_if_fail (file_name != NULL, FALSE);
548 if (G_IS_DIR_SEPARATOR (file_name[0]))
552 /* Recognize drive letter on native Windows */
553 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
555 #endif /* G_OS_WIN32 */
560 G_CONST_RETURN gchar*
561 g_path_skip_root (const gchar *file_name)
563 g_return_val_if_fail (file_name != NULL, NULL);
565 #ifdef G_PLATFORM_WIN32
566 /* Skip \\server\share or //server/share */
567 if (G_IS_DIR_SEPARATOR (file_name[0]) &&
568 G_IS_DIR_SEPARATOR (file_name[1]) &&
573 p = strchr (file_name + 2, G_DIR_SEPARATOR);
576 gchar *q = strchr (file_name + 2, '/');
577 if (p == NULL || (q != NULL && q < p))
587 while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
590 /* Possibly skip a backslash after the share name */
591 if (G_IS_DIR_SEPARATOR (file_name[0]))
594 return (gchar *)file_name;
599 /* Skip initial slashes */
600 if (G_IS_DIR_SEPARATOR (file_name[0]))
602 while (G_IS_DIR_SEPARATOR (file_name[0]))
604 return (gchar *)file_name;
609 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
610 return (gchar *)file_name + 3;
617 g_path_get_dirname (const gchar *file_name)
619 register gchar *base;
622 g_return_val_if_fail (file_name != NULL, NULL);
624 base = strrchr (file_name, G_DIR_SEPARATOR);
627 gchar *q = strrchr (file_name, '/');
628 if (base == NULL || (q != NULL && q > base))
635 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
637 gchar drive_colon_dot[4];
639 drive_colon_dot[0] = file_name[0];
640 drive_colon_dot[1] = ':';
641 drive_colon_dot[2] = '.';
642 drive_colon_dot[3] = '\0';
644 return g_strdup (drive_colon_dot);
647 return g_strdup (".");
650 while (base > file_name && G_IS_DIR_SEPARATOR (*base))
654 if (base == file_name + 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
658 len = (guint) 1 + base - file_name;
660 base = g_new (gchar, len + 1);
661 g_memmove (base, file_name, len);
668 g_get_current_dir (void)
670 gchar *buffer = NULL;
672 static gulong max_len = 0;
675 max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
677 /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
678 * and, if that wasn't bad enough, hangs in doing so.
680 #if (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
681 buffer = g_new (gchar, max_len + 1);
683 dir = getwd (buffer);
684 #else /* !sun || !HAVE_GETCWD */
685 while (max_len < G_MAXULONG / 2)
687 buffer = g_new (gchar, max_len + 1);
689 dir = getcwd (buffer, max_len);
691 if (dir || errno != ERANGE)
697 #endif /* !sun || !HAVE_GETCWD */
699 if (!dir || !*buffer)
701 /* hm, should we g_error() out here?
702 * this can happen if e.g. "./" has mode \0000
704 buffer[0] = G_DIR_SEPARATOR;
708 dir = g_strdup (buffer);
716 * @variable: the environment variable to get.
718 * Returns an environment variable.
720 * Return value: the value of the environment variable, or %NULL if the environment
721 * variable is not found. The returned string may be overwritten by the next call to g_getenv(),
722 * g_setenv() or g_unsetenv().
724 G_CONST_RETURN gchar*
725 g_getenv (const gchar *variable)
728 g_return_val_if_fail (variable != NULL, NULL);
730 return getenv (variable);
738 g_return_val_if_fail (variable != NULL, NULL);
740 system_env = getenv (variable);
744 /* On Windows NT, it is relatively typical that environment
745 * variables contain references to other environment variables. If
746 * so, use ExpandEnvironmentStrings(). (If all software was written
747 * in the best possible way, such environment variables would be
748 * stored in the Registry as REG_EXPAND_SZ type values, and would
749 * then get automatically expanded before the program sees them. But
750 * there is broken software that stores environment variables as
751 * REG_SZ values even if they contain references to other
752 * environment variables.
755 if (strchr (system_env, '%') == NULL)
757 /* No reference to other variable(s), return value as such. */
761 /* First check how much space we need */
762 length = ExpandEnvironmentStrings (system_env, dummy, 2);
764 expanded_env = g_malloc (length);
766 ExpandEnvironmentStrings (system_env, expanded_env, length);
768 quark = g_quark_from_string (expanded_env);
769 g_free (expanded_env);
771 return g_quark_to_string (quark);
777 * @variable: the environment variable to set, must not contain '='.
778 * @value: the value for to set the variable to.
779 * @overwrite: whether to change the variable if it already exists.
781 * Sets an environment variable.
783 * Note that on some systems, the memory used for the variable and its value
784 * can't be reclaimed later.
786 * Returns: %FALSE if the environment variable couldn't be set.
791 g_setenv (const gchar *variable,
800 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
803 result = setenv (variable, value, overwrite);
805 if (!overwrite && g_getenv (variable) != NULL)
808 /* This results in a leak when you overwrite existing
809 * settings. It would be fairly easy to fix this by keeping
810 * our own parallel array or hash table.
812 string = g_strconcat (variable, "=", value, NULL);
813 result = putenv (string);
818 #ifndef HAVE_UNSETENV
819 /* According to the Single Unix Specification, environ is not in
820 * any system header, although unistd.h often declares it.
824 * Win32 - at least msvc headers declare it so let's avoid
825 * warning C4273: '__p__environ' : inconsistent dll linkage. dllexport assumed.
827 extern char **environ;
833 * @variable: the environment variable to remove, must not contain '='.
835 * Removes an environment variable from the environment.
837 * Note that on some systems, the memory used for the variable and its value
838 * can't be reclaimed. Furthermore, this function can't be guaranteed to operate in a
844 g_unsetenv (const gchar *variable)
847 g_return_if_fail (strchr (variable, '=') == NULL);
854 g_return_if_fail (strchr (variable, '=') == NULL);
856 len = strlen (variable);
858 /* Mess directly with the environ array.
859 * This seems to be the only portable way to do this.
861 * Note that we remove *all* environment entries for
862 * the variable name, not just the first.
867 if (strncmp (*e, variable, len) != 0 || (*e)[len] != '=')
878 G_LOCK_DEFINE_STATIC (g_utils_global);
880 static gchar *g_tmp_dir = NULL;
881 static gchar *g_user_name = NULL;
882 static gchar *g_real_name = NULL;
883 static gchar *g_home_dir = NULL;
885 static gchar *g_user_data_dir = NULL;
886 static gchar **g_system_data_dirs = NULL;
887 static gchar *g_user_cache_dir = NULL;
888 static gchar *g_user_config_dir = NULL;
889 static gchar **g_system_config_dirs = NULL;
894 get_special_folder (int csidl)
898 wchar_t wc[MAX_PATH+1];
901 LPITEMIDLIST pidl = NULL;
903 gchar *retval = NULL;
905 hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
908 if (G_WIN32_HAVE_WIDECHAR_API ())
910 b = SHGetPathFromIDListW (pidl, path.wc);
912 retval = g_utf16_to_utf8 (path.wc, -1, NULL, NULL, NULL);
916 b = SHGetPathFromIDListA (pidl, path.c);
918 retval = g_locale_to_utf8 (path.c, -1, NULL, NULL, NULL);
920 CoTaskMemFree (pidl);
930 /* HOLDS: g_utils_global_lock */
932 g_get_any_init (void)
936 g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
938 g_tmp_dir = g_strdup (g_getenv ("TMP"));
940 g_tmp_dir = g_strdup (g_getenv ("TEMP"));
946 g_tmp_dir = g_strdup (P_tmpdir);
947 k = strlen (g_tmp_dir);
948 if (k > 1 && G_IS_DIR_SEPARATOR (g_tmp_dir[k - 1]))
949 g_tmp_dir[k - 1] = '\0';
956 g_tmp_dir = g_strdup ("/tmp");
957 #else /* G_OS_WIN32 */
958 g_tmp_dir = g_strdup ("C:\\");
959 #endif /* G_OS_WIN32 */
963 /* We check $HOME first for Win32, though it is a last resort for Unix
964 * where we prefer the results of getpwuid().
967 gchar *home = g_getenv ("HOME");
969 /* Only believe HOME if it is an absolute path and exists */
970 if (home && g_path_is_absolute (home) && g_file_test (home, G_FILE_TEST_IS_DIR))
971 g_home_dir = g_strdup (home);
974 /* In case HOME is Unix-style (it happens), convert it to
980 while ((p = strchr (g_home_dir, '/')) != NULL)
986 /* USERPROFILE is probably the closest equivalent to $HOME? */
987 if (getenv ("USERPROFILE") != NULL)
988 g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
992 g_home_dir = get_special_folder (CSIDL_PROFILE);
996 /* At least at some time, HOMEDRIVE and HOMEPATH were used
997 * to point to the home directory, I think. But on Windows
998 * 2000 HOMEDRIVE seems to be equal to SYSTEMDRIVE, and
999 * HOMEPATH is its root "\"?
1001 if (getenv ("HOMEDRIVE") != NULL && getenv ("HOMEPATH") != NULL)
1003 gchar *homedrive, *homepath;
1005 homedrive = g_strdup (g_getenv ("HOMEDRIVE"));
1006 homepath = g_strdup (g_getenv ("HOMEPATH"));
1008 g_home_dir = g_strconcat (homedrive, homepath, NULL);
1013 #endif /* G_OS_WIN32 */
1017 struct passwd *pw = NULL;
1018 gpointer buffer = NULL;
1021 # if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
1023 # ifdef _SC_GETPW_R_SIZE_MAX
1024 /* This reurns the maximum length */
1025 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
1029 # else /* _SC_GETPW_R_SIZE_MAX */
1031 # endif /* _SC_GETPW_R_SIZE_MAX */
1036 buffer = g_malloc (bufsize);
1039 # ifdef HAVE_POSIX_GETPWUID_R
1040 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1041 error = error < 0 ? errno : error;
1042 # else /* HAVE_NONPOSIX_GETPWUID_R */
1043 /* HPUX 11 falls into the HAVE_POSIX_GETPWUID_R case */
1044 # if defined(_AIX) || defined(__hpux)
1045 error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1046 pw = error == 0 ? &pwd : NULL;
1048 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1049 error = pw ? 0 : errno;
1051 # endif /* HAVE_NONPOSIX_GETPWUID_R */
1055 /* we bail out prematurely if the user id can't be found
1056 * (should be pretty rare case actually), or if the buffer
1057 * should be sufficiently big and lookups are still not
1060 if (error == 0 || error == ENOENT)
1062 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
1063 (gulong) getuid ());
1066 if (bufsize > 32 * 1024)
1068 g_warning ("getpwuid_r(): failed due to: %s.",
1069 g_strerror (error));
1077 # endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
1082 pw = getpwuid (getuid ());
1087 g_user_name = g_strdup (pw->pw_name);
1089 if (pw->pw_gecos && *pw->pw_gecos != '\0')
1091 gchar **gecos_fields;
1094 /* split the gecos field and substitute '&' */
1095 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
1096 name_parts = g_strsplit (gecos_fields[0], "&", 0);
1097 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
1098 g_real_name = g_strjoinv (pw->pw_name, name_parts);
1099 g_strfreev (gecos_fields);
1100 g_strfreev (name_parts);
1104 g_home_dir = g_strdup (pw->pw_dir);
1109 #else /* !HAVE_PWD_H */
1113 guint len = UNLEN+1;
1114 gchar buffer[UNLEN+1];
1116 if (GetUserName ((LPTSTR) buffer, (LPDWORD) &len))
1118 g_user_name = g_strdup (buffer);
1119 g_real_name = g_strdup (buffer);
1122 # endif /* G_OS_WIN32 */
1124 #endif /* !HAVE_PWD_H */
1127 g_home_dir = g_strdup (g_getenv ("HOME"));
1130 /* change '\\' in %HOME% to '/' */
1131 g_strdelimit (g_home_dir, "\\",'/');
1134 g_user_name = g_strdup ("somebody");
1136 g_real_name = g_strdup ("Unknown");
1140 G_CONST_RETURN gchar*
1141 g_get_user_name (void)
1143 G_LOCK (g_utils_global);
1146 G_UNLOCK (g_utils_global);
1151 G_CONST_RETURN gchar*
1152 g_get_real_name (void)
1154 G_LOCK (g_utils_global);
1157 G_UNLOCK (g_utils_global);
1162 G_CONST_RETURN gchar*
1163 g_get_home_dir (void)
1165 G_LOCK (g_utils_global);
1168 G_UNLOCK (g_utils_global);
1173 /* Return a directory to be used to store temporary files. This is the
1174 * value of the TMPDIR, TMP or TEMP environment variables (they are
1175 * checked in that order). If none of those exist, use P_tmpdir from
1176 * stdio.h. If that isn't defined, return "/tmp" on POSIXly systems,
1177 * and C:\ on Windows.
1180 G_CONST_RETURN gchar*
1181 g_get_tmp_dir (void)
1183 G_LOCK (g_utils_global);
1186 G_UNLOCK (g_utils_global);
1191 G_LOCK_DEFINE_STATIC (g_prgname);
1192 static gchar *g_prgname = NULL;
1195 g_get_prgname (void)
1201 G_UNLOCK (g_prgname);
1207 g_set_prgname (const gchar *prgname)
1211 g_prgname = g_strdup (prgname);
1212 G_UNLOCK (g_prgname);
1215 G_LOCK_DEFINE_STATIC (g_application_name);
1216 static gchar *g_application_name = NULL;
1219 * g_get_application_name:
1221 * Gets a human-readable name for the application, as set by
1222 * g_set_application_name(). This name should be localized if
1223 * possible, and is intended for display to the user. Contrast with
1224 * g_get_prgname(), which gets a non-localized name. If
1225 * g_set_application_name() has not been called, returns the result of
1226 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1229 * Return value: human-readable application name. may return %NULL
1233 G_CONST_RETURN gchar*
1234 g_get_application_name (void)
1238 G_LOCK (g_application_name);
1239 retval = g_application_name;
1240 G_UNLOCK (g_application_name);
1243 return g_get_prgname ();
1249 * g_set_application_name:
1250 * @application_name: localized name of the application
1252 * Sets a human-readable name for the application. This name should be
1253 * localized if possible, and is intended for display to the user.
1254 * Contrast with g_set_prgname(), which sets a non-localized name.
1255 * g_set_prgname() will be called automatically by gtk_init(),
1256 * but g_set_application_name() will not.
1258 * Note that for thread safety reasons, this function can only
1261 * The application name will be used in contexts such as error messages,
1262 * or when displaying an application's name in the task list.
1266 g_set_application_name (const gchar *application_name)
1268 gboolean already_set = FALSE;
1270 G_LOCK (g_application_name);
1271 if (g_application_name)
1274 g_application_name = g_strdup (application_name);
1275 G_UNLOCK (g_application_name);
1278 g_warning ("g_set_application() name called multiple times");
1282 * g_get_user_data_dir:
1284 * Returns a base directory in which to access application data such
1285 * as icons that is customized for a particular user.
1287 * On Unix platforms this is determined using the mechanisms described in
1288 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1289 * XDG Base Directory Specification</ulink>
1291 * Return value: a string owned by GLib that must not be modified
1295 G_CONST_RETURN gchar*
1296 g_get_user_data_dir (void)
1300 G_LOCK (g_utils_global);
1302 if (!g_user_data_dir)
1305 data_dir = get_special_folder (CSIDL_PERSONAL);
1307 data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
1309 if (data_dir && data_dir[0])
1310 data_dir = g_strdup (data_dir);
1316 data_dir = g_build_filename (g_home_dir, ".local",
1320 g_user_data_dir = data_dir;
1323 data_dir = g_user_data_dir;
1325 G_UNLOCK (g_utils_global);
1331 * g_get_user_config_dir:
1333 * Returns a base directory in which to store user-specific application
1334 * configuration information such as user preferences and settings.
1336 * On Unix platforms this is determined using the mechanisms described in
1337 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1338 * XDG Base Directory Specification</ulink>
1340 * Return value: a string owned by GLib that must not be modified
1344 G_CONST_RETURN gchar*
1345 g_get_user_config_dir (void)
1349 G_LOCK (g_utils_global);
1351 if (!g_user_config_dir)
1354 config_dir = get_special_folder (CSIDL_APPDATA);
1356 config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
1358 if (config_dir && config_dir[0])
1359 config_dir = g_strdup (config_dir);
1365 config_dir = g_build_filename (g_home_dir, ".config", NULL);
1368 g_user_config_dir = config_dir;
1371 config_dir = g_user_config_dir;
1373 G_UNLOCK (g_utils_global);
1379 * g_get_user_cache_dir:
1381 * Returns a base directory in which to store non-essential, cached
1382 * data specific to particular user.
1384 * On Unix platforms this is determined using the mechanisms described in
1385 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1386 * XDG Base Directory Specification</ulink>
1388 * Return value: a string owned by GLib that must not be modified
1392 G_CONST_RETURN gchar*
1393 g_get_user_cache_dir (void)
1397 G_LOCK (g_utils_global);
1399 if (!g_user_cache_dir)
1402 cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
1404 cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
1406 if (cache_dir && cache_dir[0])
1407 cache_dir = g_strdup (cache_dir);
1413 cache_dir = g_build_filename (g_home_dir, ".cache", NULL);
1416 g_user_cache_dir = cache_dir;
1419 cache_dir = g_user_cache_dir;
1421 G_UNLOCK (g_utils_global);
1427 * g_get_system_data_dirs:
1429 * Returns an ordered list of base directories in which to access
1430 * system-wide application data.
1432 * On Unix platforms this is determined using the mechanisms described in
1433 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1434 * XDG Base Directory Specification</ulink>
1436 * Return value: a %NULL-terminated array of strings owned by GLib that must
1437 * not be modified or freed.
1440 G_CONST_RETURN gchar * G_CONST_RETURN *
1441 g_get_system_data_dirs (void)
1443 gchar *data_dirs, **data_dir_vector;
1445 G_LOCK (g_utils_global);
1447 if (!g_system_data_dirs)
1450 data_dirs = g_strconcat (get_special_folder (CSIDL_COMMON_APPDATA),
1451 G_SEARCHPATH_SEPARATOR_S,
1452 get_special_folder (CSIDL_COMMON_DOCUMENTS),
1455 data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
1457 if (!data_dirs || !data_dirs[0])
1458 data_dirs = "/usr/local/share/:/usr/share/";
1460 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
1462 g_system_data_dirs = data_dir_vector;
1465 data_dir_vector = g_system_data_dirs;
1467 G_UNLOCK (g_utils_global);
1469 return (G_CONST_RETURN gchar * G_CONST_RETURN *) data_dir_vector;
1473 * g_get_system_config_dirs:
1475 * Returns an ordered list of base directories in which to access
1476 * system-wide configuration information.
1478 * On Unix platforms this is determined using the mechanisms described in
1479 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1480 * XDG Base Directory Specification</ulink>
1482 * Return value: a %NULL-terminated array of strings owned by GLib that must
1483 * not be modified or freed.
1486 G_CONST_RETURN gchar * G_CONST_RETURN *
1487 g_get_system_config_dirs (void)
1489 gchar *conf_dirs, **conf_dir_vector;
1491 G_LOCK (g_utils_global);
1493 if (!g_system_config_dirs)
1496 conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
1498 conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
1500 if (!conf_dirs || !conf_dirs[0])
1501 conf_dirs = "/etc/xdg";
1503 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
1506 conf_dir_vector = g_system_config_dirs;
1507 G_UNLOCK (g_utils_global);
1509 return (G_CONST_RETURN gchar * G_CONST_RETURN *) conf_dir_vector;
1512 static GHashTable *alias_table = NULL;
1514 /* read an alias file for the locales */
1516 read_aliases (gchar *file)
1522 alias_table = g_hash_table_new (g_str_hash, g_str_equal);
1523 fp = fopen (file,"r");
1526 while (fgets (buf, 256, fp))
1532 /* Line is a comment */
1533 if ((buf[0] == '#') || (buf[0] == '\0'))
1536 /* Reads first column */
1537 for (p = buf, q = NULL; *p; p++) {
1538 if ((*p == '\t') || (*p == ' ') || (*p == ':')) {
1541 while ((*q == '\t') || (*q == ' ')) {
1547 /* The line only had one column */
1548 if (!q || *q == '\0')
1551 /* Read second column */
1552 for (p = q; *p; p++) {
1553 if ((*p == '\t') || (*p == ' ')) {
1559 /* Add to alias table if necessary */
1560 if (!g_hash_table_lookup (alias_table, buf)) {
1561 g_hash_table_insert (alias_table, g_strdup (buf), g_strdup (q));
1568 unalias_lang (char *lang)
1574 read_aliases ("/usr/share/locale/locale.alias");
1577 while ((p = g_hash_table_lookup (alias_table, lang)) && (strcmp (p, lang) != 0))
1582 static gboolean said_before = FALSE;
1584 g_warning ("Too many alias levels for a locale, "
1585 "may indicate a loop");
1593 /* Mask for components of locale spec. The ordering here is from
1594 * least significant to most significant
1598 COMPONENT_CODESET = 1 << 0,
1599 COMPONENT_TERRITORY = 1 << 1,
1600 COMPONENT_MODIFIER = 1 << 2
1603 /* Break an X/Open style locale specification into components
1606 explode_locale (const gchar *locale,
1612 const gchar *uscore_pos;
1613 const gchar *at_pos;
1614 const gchar *dot_pos;
1618 uscore_pos = strchr (locale, '_');
1619 dot_pos = strchr (uscore_pos ? uscore_pos : locale, '.');
1620 at_pos = strchr (dot_pos ? dot_pos : (uscore_pos ? uscore_pos : locale), '@');
1624 mask |= COMPONENT_MODIFIER;
1625 *modifier = g_strdup (at_pos);
1628 at_pos = locale + strlen (locale);
1632 mask |= COMPONENT_CODESET;
1633 *codeset = g_strndup (dot_pos, at_pos - dot_pos);
1640 mask |= COMPONENT_TERRITORY;
1641 *territory = g_strndup (uscore_pos, dot_pos - uscore_pos);
1644 uscore_pos = dot_pos;
1646 *language = g_strndup (locale, uscore_pos - locale);
1652 * Compute all interesting variants for a given locale name -
1653 * by stripping off different components of the value.
1655 * For simplicity, we assume that the locale is in
1656 * X/Open format: language[_territory][.codeset][@modifier]
1658 * TODO: Extend this to handle the CEN format (see the GNUlibc docs)
1659 * as well. We could just copy the code from glibc wholesale
1660 * but it is big, ugly, and complicated, so I'm reluctant
1661 * to do so when this should handle 99% of the time...
1664 compute_locale_variants (const gchar *locale)
1666 GSList *retval = NULL;
1676 g_return_val_if_fail (locale != NULL, NULL);
1678 mask = explode_locale (locale, &language, &territory, &codeset, &modifier);
1680 /* Iterate through all possible combinations, from least attractive
1681 * to most attractive.
1683 for (i = 0; i <= mask; i++)
1684 if ((i & ~mask) == 0)
1686 gchar *val = g_strconcat (language,
1687 (i & COMPONENT_TERRITORY) ? territory : "",
1688 (i & COMPONENT_CODESET) ? codeset : "",
1689 (i & COMPONENT_MODIFIER) ? modifier : "",
1691 retval = g_slist_prepend (retval, val);
1695 if (mask & COMPONENT_CODESET)
1697 if (mask & COMPONENT_TERRITORY)
1699 if (mask & COMPONENT_MODIFIER)
1705 /* The following is (partly) taken from the gettext package.
1706 Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc. */
1708 static const gchar *
1709 guess_category_value (const gchar *category_name)
1711 const gchar *retval;
1713 /* The highest priority value is the `LANGUAGE' environment
1714 variable. This is a GNU extension. */
1715 retval = g_getenv ("LANGUAGE");
1716 if ((retval != NULL) && (retval[0] != '\0'))
1719 /* `LANGUAGE' is not set. So we have to proceed with the POSIX
1720 methods of looking to `LC_ALL', `LC_xxx', and `LANG'. On some
1721 systems this can be done by the `setlocale' function itself. */
1723 /* Setting of LC_ALL overwrites all other. */
1724 retval = g_getenv ("LC_ALL");
1725 if ((retval != NULL) && (retval[0] != '\0'))
1728 /* Next comes the name of the desired category. */
1729 retval = g_getenv (category_name);
1730 if ((retval != NULL) && (retval[0] != '\0'))
1733 /* Last possibility is the LANG environment variable. */
1734 retval = g_getenv ("LANG");
1735 if ((retval != NULL) && (retval[0] != '\0'))
1738 #ifdef G_PLATFORM_WIN32
1739 /* g_win32_getlocale() first checks for LC_ALL, LC_MESSAGES and
1740 * LANG, which we already did above. Oh well. The main point of
1741 * calling g_win32_getlocale() is to get the thread's locale as used
1742 * by Windows and the Microsoft C runtime (in the "English_United
1743 * States" format) translated into the Unixish format.
1745 retval = g_win32_getlocale ();
1746 if ((retval != NULL) && (retval[0] != '\0'))
1753 static gchar **languages = NULL;
1756 * g_get_language_names:
1758 * Computes a list of applicable locale names, which can be used to
1759 * e.g. construct locale-dependent filenames or search paths. The returned
1760 * list is sorted from most desirable to least desirable and always contains
1761 * the default locale "C".
1763 * For example, if LANGUAGE=de:en_US, then the returned list is
1764 * "de", "en_US", "en", "C".
1766 * This function consults the environment variables <envar>LANGUAGE</envar>,
1767 * <envar>LC_ALL</envar>, <envar>LC_MESSAGES</envar> and <envar>LANG</envar>
1768 * to find the list of locales specified by the user.
1770 * Return value: a %NULL-terminated array of strings owned by GLib
1771 * that must not be modified or freed.
1775 G_CONST_RETURN gchar * G_CONST_RETURN *
1776 g_get_language_names ()
1778 G_LOCK (g_utils_global);
1787 value = guess_category_value ("LC_MESSAGES");
1791 alist = g_strsplit (value, ":", 0);
1793 for (a = alist; *a; a++)
1795 gchar *b = unalias_lang (*a);
1796 list = g_slist_concat (list, compute_locale_variants (b));
1799 list = g_slist_append (list, "C");
1801 languages = g_new (gchar *, g_slist_length (list) + 1);
1802 for (l = list, i = 0; l; l = l->next, i++)
1803 languages[i] = l->data;
1804 languages[i] = NULL;
1806 g_slist_free (list);
1809 G_UNLOCK (g_utils_global);
1811 return (G_CONST_RETURN gchar * G_CONST_RETURN *) languages;
1815 g_direct_hash (gconstpointer v)
1817 return GPOINTER_TO_UINT (v);
1821 g_direct_equal (gconstpointer v1,
1828 g_int_equal (gconstpointer v1,
1831 return *((const gint*) v1) == *((const gint*) v2);
1835 g_int_hash (gconstpointer v)
1837 return *(const gint*) v;
1841 * g_nullify_pointer:
1842 * @nullify_location: the memory address of the pointer.
1844 * Set the pointer at the specified location to %NULL.
1847 g_nullify_pointer (gpointer *nullify_location)
1849 g_return_if_fail (nullify_location != NULL);
1851 *nullify_location = NULL;
1857 * Get the codeset for the current locale.
1859 * Return value: a newly allocated string containing the name
1860 * of the codeset. This string must be freed with g_free().
1863 g_get_codeset (void)
1865 const gchar *charset;
1867 g_get_charset (&charset);
1869 return g_strdup (charset);
1874 #include <libintl.h>
1876 #ifdef G_PLATFORM_WIN32
1878 G_WIN32_DLLMAIN_FOR_DLL_NAME (static, dll_name)
1880 static const gchar *
1881 _glib_get_locale_dir (void)
1883 static const gchar *cache = NULL;
1885 cache = g_win32_get_package_installation_subdirectory
1886 (GETTEXT_PACKAGE, dll_name, "lib\\locale");
1891 #undef GLIB_LOCALE_DIR
1892 #define GLIB_LOCALE_DIR _glib_get_locale_dir ()
1894 #endif /* G_PLATFORM_WIN32 */
1896 G_CONST_RETURN gchar *
1897 _glib_gettext (const gchar *str)
1899 static gboolean _glib_gettext_initialized = FALSE;
1901 if (!_glib_gettext_initialized)
1903 bindtextdomain(GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
1904 # ifdef HAVE_BIND_TEXTDOMAIN_CODESET
1905 bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
1907 _glib_gettext_initialized = TRUE;
1910 return dgettext (GETTEXT_PACKAGE, str);
1913 #endif /* ENABLE_NLS */