Continue GPrivate rework
[glib.git] / glib / gutils.c
blobc7f2763b1587dc533b68e6111c2c5da340f5bb16
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/.
27 /*
28 * MT safe for the unix part, FIXME: make the win32 part MT safe as well.
31 /**
32 * SECTION:version
33 * @Title: Version Information
34 * @Short_description: Variables and functions to check the GLib version
36 * GLib provides version information, primarily useful in configure
37 * checks for builds that have a configure script. Applications will
38 * not typically use the features described here.
41 /**
42 * GLIB_MAJOR_VERSION:
44 * The major version number of the GLib library.
46 * Like #glib_major_version, but from the headers used at
47 * application compile time, rather than from the library
48 * linked against at application run time.
51 /**
52 * GLIB_MINOR_VERSION:
54 * The minor version number of the GLib library.
56 * Like #gtk_minor_version, but from the headers used at
57 * application compile time, rather than from the library
58 * linked against at application run time.
61 /**
62 * GLIB_MICRO_VERSION:
64 * The micro version number of the GLib library.
66 * Like #gtk_micro_version, but from the headers used at
67 * application compile time, rather than from the library
68 * linked against at application run time.
71 #include "config.h"
73 #ifdef HAVE_UNISTD_H
74 #include <unistd.h>
75 #endif
76 #include <stdarg.h>
77 #include <stdlib.h>
78 #include <stdio.h>
79 #include <locale.h>
80 #include <string.h>
81 #include <ctype.h> /* For tolower() */
82 #include <errno.h>
83 #include <sys/types.h>
84 #include <sys/stat.h>
85 #ifdef HAVE_PWD_H
86 #include <pwd.h>
87 #endif
88 #include <sys/types.h>
89 #ifdef HAVE_SYS_PARAM_H
90 #include <sys/param.h>
91 #endif
92 #ifdef HAVE_CRT_EXTERNS_H
93 #include <crt_externs.h> /* for _NSGetEnviron */
94 #endif
96 /* implement gutils's inline functions
98 #define G_IMPLEMENT_INLINES 1
99 #define __G_UTILS_C__
100 #include "gutils.h"
102 #include "gfileutils.h"
103 #include "ghash.h"
104 #include "gslist.h"
105 #include "gprintfint.h"
106 #include "gthread.h"
107 #include "gthreadprivate.h"
108 #include "gtestutils.h"
109 #include "gunicode.h"
110 #include "gstrfuncs.h"
111 #include "garray.h"
112 #include "glibintl.h"
114 #ifdef G_PLATFORM_WIN32
115 #include "garray.h"
116 #include "gconvert.h"
117 #include "gwin32.h"
118 #endif
122 * SECTION:misc_utils
123 * @title: Miscellaneous Utility Functions
124 * @short_description: a selection of portable utility functions
126 * These are portable utility functions.
129 #ifdef MAXPATHLEN
130 #define G_PATH_LENGTH MAXPATHLEN
131 #elif defined (PATH_MAX)
132 #define G_PATH_LENGTH PATH_MAX
133 #elif defined (_PC_PATH_MAX)
134 #define G_PATH_LENGTH sysconf(_PC_PATH_MAX)
135 #else
136 #define G_PATH_LENGTH 2048
137 #endif
139 #ifdef G_PLATFORM_WIN32
140 # define STRICT /* Strict typing, please */
141 # include <windows.h>
142 # undef STRICT
143 # ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
144 # define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2
145 # define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4
146 # endif
147 # include <lmcons.h> /* For UNLEN */
148 #endif /* G_PLATFORM_WIN32 */
150 #ifdef G_OS_WIN32
151 # include <direct.h>
152 # include <shlobj.h>
153 /* older SDK (e.g. msvc 5.0) does not have these*/
154 # ifndef CSIDL_MYMUSIC
155 # define CSIDL_MYMUSIC 13
156 # endif
157 # ifndef CSIDL_MYVIDEO
158 # define CSIDL_MYVIDEO 14
159 # endif
160 # ifndef CSIDL_INTERNET_CACHE
161 # define CSIDL_INTERNET_CACHE 32
162 # endif
163 # ifndef CSIDL_COMMON_APPDATA
164 # define CSIDL_COMMON_APPDATA 35
165 # endif
166 # ifndef CSIDL_MYPICTURES
167 # define CSIDL_MYPICTURES 0x27
168 # endif
169 # ifndef CSIDL_COMMON_DOCUMENTS
170 # define CSIDL_COMMON_DOCUMENTS 46
171 # endif
172 # ifndef CSIDL_PROFILE
173 # define CSIDL_PROFILE 40
174 # endif
175 # include <process.h>
176 #endif
178 #ifdef HAVE_CARBON
179 #include <CoreServices/CoreServices.h>
180 #endif
182 #ifdef HAVE_CODESET
183 #include <langinfo.h>
184 #endif
186 const guint glib_major_version = GLIB_MAJOR_VERSION;
187 const guint glib_minor_version = GLIB_MINOR_VERSION;
188 const guint glib_micro_version = GLIB_MICRO_VERSION;
189 const guint glib_interface_age = GLIB_INTERFACE_AGE;
190 const guint glib_binary_age = GLIB_BINARY_AGE;
192 #ifdef G_PLATFORM_WIN32
194 static HMODULE glib_dll = NULL;
196 #ifdef DLL_EXPORT
198 BOOL WINAPI
199 DllMain (HINSTANCE hinstDLL,
200 DWORD fdwReason,
201 LPVOID lpvReserved)
203 if (fdwReason == DLL_PROCESS_ATTACH)
205 glib_dll = hinstDLL;
206 g_thread_DllMain ();
209 return TRUE;
212 #endif
214 gchar *
215 _glib_get_dll_directory (void)
217 gchar *retval;
218 gchar *p;
219 wchar_t wc_fn[MAX_PATH];
221 #ifdef DLL_EXPORT
222 if (glib_dll == NULL)
223 return NULL;
224 #endif
226 /* This code is different from that in
227 * g_win32_get_package_installation_directory_of_module() in that
228 * here we return the actual folder where the GLib DLL is. We don't
229 * do the check for it being in a "bin" or "lib" subfolder and then
230 * returning the parent of that.
232 * In a statically built GLib, glib_dll will be NULL and we will
233 * thus look up the application's .exe file's location.
235 if (!GetModuleFileNameW (glib_dll, wc_fn, MAX_PATH))
236 return NULL;
238 retval = g_utf16_to_utf8 (wc_fn, -1, NULL, NULL, NULL);
240 p = strrchr (retval, G_DIR_SEPARATOR);
241 if (p == NULL)
243 /* Wtf? */
244 return NULL;
246 *p = '\0';
248 return retval;
251 #endif
254 * glib_check_version:
255 * @required_major: the required major version.
256 * @required_minor: the required minor version.
257 * @required_micro: the required micro version.
259 * Checks that the GLib library in use is compatible with the
260 * given version. Generally you would pass in the constants
261 * #GLIB_MAJOR_VERSION, #GLIB_MINOR_VERSION, #GLIB_MICRO_VERSION
262 * as the three arguments to this function; that produces
263 * a check that the library in use is compatible with
264 * the version of GLib the application or module was compiled
265 * against.
267 * Compatibility is defined by two things: first the version
268 * of the running library is newer than the version
269 * @required_major.required_minor.@required_micro. Second
270 * the running library must be binary compatible with the
271 * version @required_major.required_minor.@required_micro
272 * (same major version.)
274 * Return value: %NULL if the GLib library is compatible with the
275 * given version, or a string describing the version mismatch.
276 * The returned string is owned by GLib and must not be modified
277 * or freed.
279 * Since: 2.6
281 const gchar *
282 glib_check_version (guint required_major,
283 guint required_minor,
284 guint required_micro)
286 gint glib_effective_micro = 100 * GLIB_MINOR_VERSION + GLIB_MICRO_VERSION;
287 gint required_effective_micro = 100 * required_minor + required_micro;
289 if (required_major > GLIB_MAJOR_VERSION)
290 return "GLib version too old (major mismatch)";
291 if (required_major < GLIB_MAJOR_VERSION)
292 return "GLib version too new (major mismatch)";
293 if (required_effective_micro < glib_effective_micro - GLIB_BINARY_AGE)
294 return "GLib version too new (micro mismatch)";
295 if (required_effective_micro > glib_effective_micro)
296 return "GLib version too old (micro mismatch)";
297 return NULL;
300 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
302 * g_memmove:
303 * @dest: the destination address to copy the bytes to.
304 * @src: the source address to copy the bytes from.
305 * @len: the number of bytes to copy.
307 * Copies a block of memory @len bytes long, from @src to @dest.
308 * The source and destination areas may overlap.
310 * In order to use this function, you must include
311 * <filename>string.h</filename> yourself, because this macro will
312 * typically simply resolve to memmove() and GLib does not include
313 * <filename>string.h</filename> for you.
315 void
316 g_memmove (gpointer dest,
317 gconstpointer src,
318 gulong len)
320 gchar* destptr = dest;
321 const gchar* srcptr = src;
322 if (src + len < dest || dest + len < src)
324 bcopy (src, dest, len);
325 return;
327 else if (dest <= src)
329 while (len--)
330 *(destptr++) = *(srcptr++);
332 else
334 destptr += len;
335 srcptr += len;
336 while (len--)
337 *(--destptr) = *(--srcptr);
340 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
342 #ifdef G_OS_WIN32
343 #undef g_atexit
344 #endif
347 * g_atexit:
348 * @func: (scope async): the function to call on normal program termination.
350 * Specifies a function to be called at normal program termination.
352 * Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
353 * macro that maps to a call to the atexit() function in the C
354 * library. This means that in case the code that calls g_atexit(),
355 * i.e. atexit(), is in a DLL, the function will be called when the
356 * DLL is detached from the program. This typically makes more sense
357 * than that the function is called when the GLib DLL is detached,
358 * which happened earlier when g_atexit() was a function in the GLib
359 * DLL.
361 * The behaviour of atexit() in the context of dynamically loaded
362 * modules is not formally specified and varies wildly.
364 * On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
365 * loaded module which is unloaded before the program terminates might
366 * well cause a crash at program exit.
368 * Some POSIX systems implement atexit() like Windows, and have each
369 * dynamically loaded module maintain an own atexit chain that is
370 * called when the module is unloaded.
372 * On other POSIX systems, before a dynamically loaded module is
373 * unloaded, the registered atexit functions (if any) residing in that
374 * module are called, regardless where the code that registered them
375 * resided. This is presumably the most robust approach.
377 * As can be seen from the above, for portability it's best to avoid
378 * calling g_atexit() (or atexit()) except in the main executable of a
379 * program.
381 void
382 g_atexit (GVoidFunc func)
384 gint result;
385 const gchar *error = NULL;
387 /* keep this in sync with glib.h */
389 #ifdef G_NATIVE_ATEXIT
390 result = ATEXIT (func);
391 if (result)
392 error = g_strerror (errno);
393 #elif defined (HAVE_ATEXIT)
394 # ifdef NeXT /* @#%@! NeXTStep */
395 result = !atexit ((void (*)(void)) func);
396 if (result)
397 error = g_strerror (errno);
398 # else
399 result = atexit ((void (*)(void)) func);
400 if (result)
401 error = g_strerror (errno);
402 # endif /* NeXT */
403 #elif defined (HAVE_ON_EXIT)
404 result = on_exit ((void (*)(int, void *)) func, NULL);
405 if (result)
406 error = g_strerror (errno);
407 #else
408 result = 0;
409 error = "no implementation";
410 #endif /* G_NATIVE_ATEXIT */
412 if (error)
413 g_error ("Could not register atexit() function: %s", error);
416 /* Based on execvp() from GNU Libc.
417 * Some of this code is cut-and-pasted into gspawn.c
420 static gchar*
421 my_strchrnul (const gchar *str,
422 gchar c)
424 gchar *p = (gchar*)str;
425 while (*p && (*p != c))
426 ++p;
428 return p;
431 #ifdef G_OS_WIN32
433 static gchar *inner_find_program_in_path (const gchar *program);
435 gchar*
436 g_find_program_in_path (const gchar *program)
438 const gchar *last_dot = strrchr (program, '.');
440 if (last_dot == NULL ||
441 strchr (last_dot, '\\') != NULL ||
442 strchr (last_dot, '/') != NULL)
444 const gint program_length = strlen (program);
445 gchar *pathext = g_build_path (";",
446 ".exe;.cmd;.bat;.com",
447 g_getenv ("PATHEXT"),
448 NULL);
449 gchar *p;
450 gchar *decorated_program;
451 gchar *retval;
453 p = pathext;
456 gchar *q = my_strchrnul (p, ';');
458 decorated_program = g_malloc (program_length + (q-p) + 1);
459 memcpy (decorated_program, program, program_length);
460 memcpy (decorated_program+program_length, p, q-p);
461 decorated_program [program_length + (q-p)] = '\0';
463 retval = inner_find_program_in_path (decorated_program);
464 g_free (decorated_program);
466 if (retval != NULL)
468 g_free (pathext);
469 return retval;
471 p = q;
472 } while (*p++ != '\0');
473 g_free (pathext);
474 return NULL;
476 else
477 return inner_find_program_in_path (program);
480 #endif
483 * g_find_program_in_path:
484 * @program: a program name in the GLib file name encoding
486 * Locates the first executable named @program in the user's path, in the
487 * same way that execvp() would locate it. Returns an allocated string
488 * with the absolute path name, or %NULL if the program is not found in
489 * the path. If @program is already an absolute path, returns a copy of
490 * @program if @program exists and is executable, and %NULL otherwise.
492 * On Windows, if @program does not have a file type suffix, tries
493 * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
494 * the <envar>PATHEXT</envar> environment variable.
496 * On Windows, it looks for the file in the same way as CreateProcess()
497 * would. This means first in the directory where the executing
498 * program was loaded from, then in the current directory, then in the
499 * Windows 32-bit system directory, then in the Windows directory, and
500 * finally in the directories in the <envar>PATH</envar> environment
501 * variable. If the program is found, the return value contains the
502 * full name including the type suffix.
504 * Return value: absolute path, or %NULL
506 #ifdef G_OS_WIN32
507 static gchar *
508 inner_find_program_in_path (const gchar *program)
509 #else
510 gchar*
511 g_find_program_in_path (const gchar *program)
512 #endif
514 const gchar *path, *p;
515 gchar *name, *freeme;
516 #ifdef G_OS_WIN32
517 const gchar *path_copy;
518 gchar *filename = NULL, *appdir = NULL;
519 gchar *sysdir = NULL, *windir = NULL;
520 int n;
521 wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
522 wwindir[MAXPATHLEN];
523 #endif
524 gsize len;
525 gsize pathlen;
527 g_return_val_if_fail (program != NULL, NULL);
529 /* If it is an absolute path, or a relative path including subdirectories,
530 * don't look in PATH.
532 if (g_path_is_absolute (program)
533 || strchr (program, G_DIR_SEPARATOR) != NULL
534 #ifdef G_OS_WIN32
535 || strchr (program, '/') != NULL
536 #endif
539 if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
540 !g_file_test (program, G_FILE_TEST_IS_DIR))
541 return g_strdup (program);
542 else
543 return NULL;
546 path = g_getenv ("PATH");
547 #if defined(G_OS_UNIX) || defined(G_OS_BEOS)
548 if (path == NULL)
550 /* There is no `PATH' in the environment. The default
551 * search path in GNU libc is the current directory followed by
552 * the path `confstr' returns for `_CS_PATH'.
555 /* In GLib we put . last, for security, and don't use the
556 * unportable confstr(); UNIX98 does not actually specify
557 * what to search if PATH is unset. POSIX may, dunno.
560 path = "/bin:/usr/bin:.";
562 #else
563 n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
564 if (n > 0 && n < MAXPATHLEN)
565 filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
567 n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
568 if (n > 0 && n < MAXPATHLEN)
569 sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
571 n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
572 if (n > 0 && n < MAXPATHLEN)
573 windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
575 if (filename)
577 appdir = g_path_get_dirname (filename);
578 g_free (filename);
581 path = g_strdup (path);
583 if (windir)
585 const gchar *tem = path;
586 path = g_strconcat (windir, ";", path, NULL);
587 g_free ((gchar *) tem);
588 g_free (windir);
591 if (sysdir)
593 const gchar *tem = path;
594 path = g_strconcat (sysdir, ";", path, NULL);
595 g_free ((gchar *) tem);
596 g_free (sysdir);
600 const gchar *tem = path;
601 path = g_strconcat (".;", path, NULL);
602 g_free ((gchar *) tem);
605 if (appdir)
607 const gchar *tem = path;
608 path = g_strconcat (appdir, ";", path, NULL);
609 g_free ((gchar *) tem);
610 g_free (appdir);
613 path_copy = path;
614 #endif
616 len = strlen (program) + 1;
617 pathlen = strlen (path);
618 freeme = name = g_malloc (pathlen + len + 1);
620 /* Copy the file name at the top, including '\0' */
621 memcpy (name + pathlen + 1, program, len);
622 name = name + pathlen;
623 /* And add the slash before the filename */
624 *name = G_DIR_SEPARATOR;
626 p = path;
629 char *startp;
631 path = p;
632 p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
634 if (p == path)
635 /* Two adjacent colons, or a colon at the beginning or the end
636 * of `PATH' means to search the current directory.
638 startp = name + 1;
639 else
640 startp = memcpy (name - (p - path), path, p - path);
642 if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
643 !g_file_test (startp, G_FILE_TEST_IS_DIR))
645 gchar *ret;
646 ret = g_strdup (startp);
647 g_free (freeme);
648 #ifdef G_OS_WIN32
649 g_free ((gchar *) path_copy);
650 #endif
651 return ret;
654 while (*p++ != '\0');
656 g_free (freeme);
657 #ifdef G_OS_WIN32
658 g_free ((gchar *) path_copy);
659 #endif
661 return NULL;
664 static gboolean
665 debug_key_matches (const gchar *key,
666 const gchar *token,
667 guint length)
669 for (; length; length--, key++, token++)
671 char k = (*key == '_') ? '-' : tolower (*key );
672 char t = (*token == '_') ? '-' : tolower (*token);
674 if (k != t)
675 return FALSE;
678 return *key == '\0';
682 * g_parse_debug_string:
683 * @string: (allow-none): a list of debug options separated by colons, spaces, or
684 * commas, or %NULL.
685 * @keys: (array length=nkeys): pointer to an array of #GDebugKey which associate
686 * strings with bit flags.
687 * @nkeys: the number of #GDebugKey<!-- -->s in the array.
689 * Parses a string containing debugging options
690 * into a %guint containing bit flags. This is used
691 * within GDK and GTK+ to parse the debug options passed on the
692 * command line or through environment variables.
694 * If @string is equal to "all", all flags are set. If @string
695 * is equal to "help", all the available keys in @keys are printed
696 * out to standard error.
698 * Returns: the combined set of bit flags.
700 guint
701 g_parse_debug_string (const gchar *string,
702 const GDebugKey *keys,
703 guint nkeys)
705 guint i;
706 guint result = 0;
708 if (string == NULL)
709 return 0;
711 /* this function is used by gmem.c/gslice.c initialization code,
712 * so introducing malloc dependencies here would require adaptions
713 * of those code portions.
716 if (!g_ascii_strcasecmp (string, "all"))
718 for (i=0; i<nkeys; i++)
719 result |= keys[i].value;
721 else if (!g_ascii_strcasecmp (string, "help"))
723 /* using stdio directly for the reason stated above */
724 fprintf (stderr, "Supported debug values: ");
725 for (i=0; i<nkeys; i++)
726 fprintf (stderr, " %s", keys[i].key);
727 fprintf (stderr, "\n");
729 else
731 const gchar *p = string;
732 const gchar *q;
734 while (*p)
736 q = strpbrk (p, ":;, \t");
737 if (!q)
738 q = p + strlen(p);
740 for (i = 0; i < nkeys; i++)
741 if (debug_key_matches (keys[i].key, p, q - p))
742 result |= keys[i].value;
744 p = q;
745 if (*p)
746 p++;
750 return result;
754 * g_basename:
755 * @file_name: the name of the file.
757 * Gets the name of the file without any leading directory components.
758 * It returns a pointer into the given file name string.
760 * Return value: the name of the file without any leading directory components.
762 * Deprecated:2.2: Use g_path_get_basename() instead, but notice that
763 * g_path_get_basename() allocates new memory for the returned string, unlike
764 * this function which returns a pointer into the argument.
766 const gchar *
767 g_basename (const gchar *file_name)
769 register gchar *base;
771 g_return_val_if_fail (file_name != NULL, NULL);
773 base = strrchr (file_name, G_DIR_SEPARATOR);
775 #ifdef G_OS_WIN32
777 gchar *q = strrchr (file_name, '/');
778 if (base == NULL || (q != NULL && q > base))
779 base = q;
781 #endif
783 if (base)
784 return base + 1;
786 #ifdef G_OS_WIN32
787 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
788 return (gchar*) file_name + 2;
789 #endif /* G_OS_WIN32 */
791 return (gchar*) file_name;
795 * g_path_get_basename:
796 * @file_name: the name of the file.
798 * Gets the last component of the filename. If @file_name ends with a
799 * directory separator it gets the component before the last slash. If
800 * @file_name consists only of directory separators (and on Windows,
801 * possibly a drive letter), a single separator is returned. If
802 * @file_name is empty, it gets ".".
804 * Return value: a newly allocated string containing the last component of
805 * the filename.
807 gchar*
808 g_path_get_basename (const gchar *file_name)
810 register gssize base;
811 register gssize last_nonslash;
812 gsize len;
813 gchar *retval;
815 g_return_val_if_fail (file_name != NULL, NULL);
817 if (file_name[0] == '\0')
818 /* empty string */
819 return g_strdup (".");
821 last_nonslash = strlen (file_name) - 1;
823 while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
824 last_nonslash--;
826 if (last_nonslash == -1)
827 /* string only containing slashes */
828 return g_strdup (G_DIR_SEPARATOR_S);
830 #ifdef G_OS_WIN32
831 if (last_nonslash == 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
832 /* string only containing slashes and a drive */
833 return g_strdup (G_DIR_SEPARATOR_S);
834 #endif /* G_OS_WIN32 */
836 base = last_nonslash;
838 while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
839 base--;
841 #ifdef G_OS_WIN32
842 if (base == -1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
843 base = 1;
844 #endif /* G_OS_WIN32 */
846 len = last_nonslash - base;
847 retval = g_malloc (len + 1);
848 memcpy (retval, file_name + base + 1, len);
849 retval [len] = '\0';
850 return retval;
854 * g_path_is_absolute:
855 * @file_name: a file name.
857 * Returns %TRUE if the given @file_name is an absolute file name.
858 * Note that this is a somewhat vague concept on Windows.
860 * On POSIX systems, an absolute file name is well-defined. It always
861 * starts from the single root directory. For example "/usr/local".
863 * On Windows, the concepts of current drive and drive-specific
864 * current directory introduce vagueness. This function interprets as
865 * an absolute file name one that either begins with a directory
866 * separator such as "\Users\tml" or begins with the root on a drive,
867 * for example "C:\Windows". The first case also includes UNC paths
868 * such as "\\myserver\docs\foo". In all cases, either slashes or
869 * backslashes are accepted.
871 * Note that a file name relative to the current drive root does not
872 * truly specify a file uniquely over time and across processes, as
873 * the current drive is a per-process value and can be changed.
875 * File names relative the current directory on some specific drive,
876 * such as "D:foo/bar", are not interpreted as absolute by this
877 * function, but they obviously are not relative to the normal current
878 * directory as returned by getcwd() or g_get_current_dir()
879 * either. Such paths should be avoided, or need to be handled using
880 * Windows-specific code.
882 * Returns: %TRUE if @file_name is absolute.
884 gboolean
885 g_path_is_absolute (const gchar *file_name)
887 g_return_val_if_fail (file_name != NULL, FALSE);
889 if (G_IS_DIR_SEPARATOR (file_name[0]))
890 return TRUE;
892 #ifdef G_OS_WIN32
893 /* Recognize drive letter on native Windows */
894 if (g_ascii_isalpha (file_name[0]) &&
895 file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
896 return TRUE;
897 #endif /* G_OS_WIN32 */
899 return FALSE;
903 * g_path_skip_root:
904 * @file_name: a file name.
906 * Returns a pointer into @file_name after the root component, i.e. after
907 * the "/" in UNIX or "C:\" under Windows. If @file_name is not an absolute
908 * path it returns %NULL.
910 * Returns: a pointer into @file_name after the root component.
912 const gchar *
913 g_path_skip_root (const gchar *file_name)
915 g_return_val_if_fail (file_name != NULL, NULL);
917 #ifdef G_PLATFORM_WIN32
918 /* Skip \\server\share or //server/share */
919 if (G_IS_DIR_SEPARATOR (file_name[0]) &&
920 G_IS_DIR_SEPARATOR (file_name[1]) &&
921 file_name[2] &&
922 !G_IS_DIR_SEPARATOR (file_name[2]))
924 gchar *p;
926 p = strchr (file_name + 2, G_DIR_SEPARATOR);
927 #ifdef G_OS_WIN32
929 gchar *q = strchr (file_name + 2, '/');
930 if (p == NULL || (q != NULL && q < p))
931 p = q;
933 #endif
934 if (p &&
935 p > file_name + 2 &&
936 p[1])
938 file_name = p + 1;
940 while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
941 file_name++;
943 /* Possibly skip a backslash after the share name */
944 if (G_IS_DIR_SEPARATOR (file_name[0]))
945 file_name++;
947 return (gchar *)file_name;
950 #endif
952 /* Skip initial slashes */
953 if (G_IS_DIR_SEPARATOR (file_name[0]))
955 while (G_IS_DIR_SEPARATOR (file_name[0]))
956 file_name++;
957 return (gchar *)file_name;
960 #ifdef G_OS_WIN32
961 /* Skip X:\ */
962 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
963 return (gchar *)file_name + 3;
964 #endif
966 return NULL;
970 * g_bit_nth_lsf:
971 * @mask: a #gulong containing flags
972 * @nth_bit: the index of the bit to start the search from
974 * Find the position of the first bit set in @mask, searching
975 * from (but not including) @nth_bit upwards. Bits are numbered
976 * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
977 * usually). To start searching from the 0th bit, set @nth_bit to -1.
979 * Returns: the index of the first bit set which is higher than @nth_bit
983 * g_bit_nth_msf:
984 * @mask: a #gulong containing flags
985 * @nth_bit: the index of the bit to start the search from
987 * Find the position of the first bit set in @mask, searching
988 * from (but not including) @nth_bit downwards. Bits are numbered
989 * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
990 * usually). To start searching from the last bit, set @nth_bit to
991 * -1 or GLIB_SIZEOF_LONG * 8.
993 * Returns: the index of the first bit set which is lower than @nth_bit
997 * g_bit_storage:
998 * @number: a #guint
1000 * Gets the number of bits used to hold @number,
1001 * e.g. if @number is 4, 3 bits are needed.
1003 * Returns: the number of bits used to hold @number
1007 * g_dirname:
1008 * @file_name: the name of the file
1010 * Gets the directory components of a file name.
1011 * If the file name has no directory components "." is returned.
1012 * The returned string should be freed when no longer needed.
1014 * Returns: the directory components of the file
1016 * Deprecated: use g_path_get_dirname() instead
1020 * g_path_get_dirname:
1021 * @file_name: the name of the file.
1023 * Gets the directory components of a file name. If the file name has no
1024 * directory components "." is returned. The returned string should be
1025 * freed when no longer needed.
1027 * Returns: the directory components of the file.
1029 gchar*
1030 g_path_get_dirname (const gchar *file_name)
1032 register gchar *base;
1033 register gsize len;
1035 g_return_val_if_fail (file_name != NULL, NULL);
1037 base = strrchr (file_name, G_DIR_SEPARATOR);
1038 #ifdef G_OS_WIN32
1040 gchar *q = strrchr (file_name, '/');
1041 if (base == NULL || (q != NULL && q > base))
1042 base = q;
1044 #endif
1045 if (!base)
1047 #ifdef G_OS_WIN32
1048 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
1050 gchar drive_colon_dot[4];
1052 drive_colon_dot[0] = file_name[0];
1053 drive_colon_dot[1] = ':';
1054 drive_colon_dot[2] = '.';
1055 drive_colon_dot[3] = '\0';
1057 return g_strdup (drive_colon_dot);
1059 #endif
1060 return g_strdup (".");
1063 while (base > file_name && G_IS_DIR_SEPARATOR (*base))
1064 base--;
1066 #ifdef G_OS_WIN32
1067 /* base points to the char before the last slash.
1069 * In case file_name is the root of a drive (X:\) or a child of the
1070 * root of a drive (X:\foo), include the slash.
1072 * In case file_name is the root share of an UNC path
1073 * (\\server\share), add a slash, returning \\server\share\ .
1075 * In case file_name is a direct child of a share in an UNC path
1076 * (\\server\share\foo), include the slash after the share name,
1077 * returning \\server\share\ .
1079 if (base == file_name + 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
1080 base++;
1081 else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
1082 G_IS_DIR_SEPARATOR (file_name[1]) &&
1083 file_name[2] &&
1084 !G_IS_DIR_SEPARATOR (file_name[2]) &&
1085 base >= file_name + 2)
1087 const gchar *p = file_name + 2;
1088 while (*p && !G_IS_DIR_SEPARATOR (*p))
1089 p++;
1090 if (p == base + 1)
1092 len = (guint) strlen (file_name) + 1;
1093 base = g_new (gchar, len + 1);
1094 strcpy (base, file_name);
1095 base[len-1] = G_DIR_SEPARATOR;
1096 base[len] = 0;
1097 return base;
1099 if (G_IS_DIR_SEPARATOR (*p))
1101 p++;
1102 while (*p && !G_IS_DIR_SEPARATOR (*p))
1103 p++;
1104 if (p == base + 1)
1105 base++;
1108 #endif
1110 len = (guint) 1 + base - file_name;
1112 base = g_new (gchar, len + 1);
1113 g_memmove (base, file_name, len);
1114 base[len] = 0;
1116 return base;
1120 * g_get_current_dir:
1122 * Gets the current directory.
1123 * The returned string should be freed when no longer needed. The encoding
1124 * of the returned string is system defined. On Windows, it is always UTF-8.
1126 * Returns: the current directory.
1128 gchar*
1129 g_get_current_dir (void)
1131 #ifdef G_OS_WIN32
1133 gchar *dir = NULL;
1134 wchar_t dummy[2], *wdir;
1135 int len;
1137 len = GetCurrentDirectoryW (2, dummy);
1138 wdir = g_new (wchar_t, len);
1140 if (GetCurrentDirectoryW (len, wdir) == len - 1)
1141 dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
1143 g_free (wdir);
1145 if (dir == NULL)
1146 dir = g_strdup ("\\");
1148 return dir;
1150 #else
1152 gchar *buffer = NULL;
1153 gchar *dir = NULL;
1154 static gulong max_len = 0;
1156 if (max_len == 0)
1157 max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
1159 /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
1160 * and, if that wasn't bad enough, hangs in doing so.
1162 #if (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
1163 buffer = g_new (gchar, max_len + 1);
1164 *buffer = 0;
1165 dir = getwd (buffer);
1166 #else /* !sun || !HAVE_GETCWD */
1167 while (max_len < G_MAXULONG / 2)
1169 g_free (buffer);
1170 buffer = g_new (gchar, max_len + 1);
1171 *buffer = 0;
1172 dir = getcwd (buffer, max_len);
1174 if (dir || errno != ERANGE)
1175 break;
1177 max_len *= 2;
1179 #endif /* !sun || !HAVE_GETCWD */
1181 if (!dir || !*buffer)
1183 /* hm, should we g_error() out here?
1184 * this can happen if e.g. "./" has mode \0000
1186 buffer[0] = G_DIR_SEPARATOR;
1187 buffer[1] = 0;
1190 dir = g_strdup (buffer);
1191 g_free (buffer);
1193 return dir;
1194 #endif /* !Win32 */
1198 * g_getenv:
1199 * @variable: the environment variable to get, in the GLib file name encoding.
1201 * Returns the value of an environment variable. The name and value
1202 * are in the GLib file name encoding. On UNIX, this means the actual
1203 * bytes which might or might not be in some consistent character set
1204 * and encoding. On Windows, it is in UTF-8. On Windows, in case the
1205 * environment variable's value contains references to other
1206 * environment variables, they are expanded.
1208 * Return value: the value of the environment variable, or %NULL if
1209 * the environment variable is not found. The returned string may be
1210 * overwritten by the next call to g_getenv(), g_setenv() or
1211 * g_unsetenv().
1213 const gchar *
1214 g_getenv (const gchar *variable)
1216 #ifndef G_OS_WIN32
1218 g_return_val_if_fail (variable != NULL, NULL);
1220 return getenv (variable);
1222 #else /* G_OS_WIN32 */
1224 GQuark quark;
1225 gchar *value;
1226 wchar_t dummy[2], *wname, *wvalue;
1227 int len;
1229 g_return_val_if_fail (variable != NULL, NULL);
1230 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), NULL);
1232 /* On Windows NT, it is relatively typical that environment
1233 * variables contain references to other environment variables. If
1234 * so, use ExpandEnvironmentStrings(). (In an ideal world, such
1235 * environment variables would be stored in the Registry as
1236 * REG_EXPAND_SZ type values, and would then get automatically
1237 * expanded before a program sees them. But there is broken software
1238 * that stores environment variables as REG_SZ values even if they
1239 * contain references to other environment variables.)
1242 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1244 len = GetEnvironmentVariableW (wname, dummy, 2);
1246 if (len == 0)
1248 g_free (wname);
1249 return NULL;
1251 else if (len == 1)
1252 len = 2;
1254 wvalue = g_new (wchar_t, len);
1256 if (GetEnvironmentVariableW (wname, wvalue, len) != len - 1)
1258 g_free (wname);
1259 g_free (wvalue);
1260 return NULL;
1263 if (wcschr (wvalue, L'%') != NULL)
1265 wchar_t *tem = wvalue;
1267 len = ExpandEnvironmentStringsW (wvalue, dummy, 2);
1269 if (len > 0)
1271 wvalue = g_new (wchar_t, len);
1273 if (ExpandEnvironmentStringsW (tem, wvalue, len) != len)
1275 g_free (wvalue);
1276 wvalue = tem;
1278 else
1279 g_free (tem);
1283 value = g_utf16_to_utf8 (wvalue, -1, NULL, NULL, NULL);
1285 g_free (wname);
1286 g_free (wvalue);
1288 quark = g_quark_from_string (value);
1289 g_free (value);
1291 return g_quark_to_string (quark);
1293 #endif /* G_OS_WIN32 */
1296 /* _g_getenv_nomalloc
1297 * this function does a getenv() without doing any kind of allocation
1298 * through glib. it's suitable for chars <= 127 only (both, for the
1299 * variable name and the contents) and for contents < 1024 chars in
1300 * length. also, it aliases "" to a NULL return value.
1302 const gchar*
1303 _g_getenv_nomalloc (const gchar *variable,
1304 gchar buffer[1024])
1306 const gchar *retval = getenv (variable);
1307 if (retval && retval[0])
1309 gint l = strlen (retval);
1310 if (l < 1024)
1312 strncpy (buffer, retval, l);
1313 buffer[l] = 0;
1314 return buffer;
1317 return NULL;
1321 * g_setenv:
1322 * @variable: the environment variable to set, must not contain '='.
1323 * @value: the value for to set the variable to.
1324 * @overwrite: whether to change the variable if it already exists.
1326 * Sets an environment variable. Both the variable's name and value
1327 * should be in the GLib file name encoding. On UNIX, this means that
1328 * they can be any sequence of bytes. On Windows, they should be in
1329 * UTF-8.
1331 * Note that on some systems, when variables are overwritten, the memory
1332 * used for the previous variables and its value isn't reclaimed.
1334 * Returns: %FALSE if the environment variable couldn't be set.
1336 * Since: 2.4
1338 gboolean
1339 g_setenv (const gchar *variable,
1340 const gchar *value,
1341 gboolean overwrite)
1343 #ifndef G_OS_WIN32
1345 gint result;
1346 #ifndef HAVE_SETENV
1347 gchar *string;
1348 #endif
1350 g_return_val_if_fail (variable != NULL, FALSE);
1351 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1353 #ifdef HAVE_SETENV
1354 result = setenv (variable, value, overwrite);
1355 #else
1356 if (!overwrite && getenv (variable) != NULL)
1357 return TRUE;
1359 /* This results in a leak when you overwrite existing
1360 * settings. It would be fairly easy to fix this by keeping
1361 * our own parallel array or hash table.
1363 string = g_strconcat (variable, "=", value, NULL);
1364 result = putenv (string);
1365 #endif
1366 return result == 0;
1368 #else /* G_OS_WIN32 */
1370 gboolean retval;
1371 wchar_t *wname, *wvalue, *wassignment;
1372 gchar *tem;
1374 g_return_val_if_fail (variable != NULL, FALSE);
1375 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1376 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), FALSE);
1377 g_return_val_if_fail (g_utf8_validate (value, -1, NULL), FALSE);
1379 if (!overwrite && g_getenv (variable) != NULL)
1380 return TRUE;
1382 /* We want to (if possible) set both the environment variable copy
1383 * kept by the C runtime and the one kept by the system.
1385 * We can't use only the C runtime's putenv or _wputenv() as that
1386 * won't work for arbitrary Unicode strings in a "non-Unicode" app
1387 * (with main() and not wmain()). In a "main()" app the C runtime
1388 * initializes the C runtime's environment table by converting the
1389 * real (wide char) environment variables to system codepage, thus
1390 * breaking those that aren't representable in the system codepage.
1392 * As the C runtime's putenv() will also set the system copy, we do
1393 * the putenv() first, then call SetEnvironmentValueW ourselves.
1396 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1397 wvalue = g_utf8_to_utf16 (value, -1, NULL, NULL, NULL);
1398 tem = g_strconcat (variable, "=", value, NULL);
1399 wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1401 g_free (tem);
1402 _wputenv (wassignment);
1403 g_free (wassignment);
1405 retval = (SetEnvironmentVariableW (wname, wvalue) != 0);
1407 g_free (wname);
1408 g_free (wvalue);
1410 return retval;
1412 #endif /* G_OS_WIN32 */
1415 #ifdef HAVE__NSGETENVIRON
1416 #define environ (*_NSGetEnviron())
1417 #elif !defined(G_OS_WIN32)
1419 /* According to the Single Unix Specification, environ is not in
1420 * any system header, although unistd.h often declares it.
1422 extern char **environ;
1423 #endif
1426 * g_unsetenv:
1427 * @variable: the environment variable to remove, must not contain '='.
1429 * Removes an environment variable from the environment.
1431 * Note that on some systems, when variables are overwritten, the memory
1432 * used for the previous variables and its value isn't reclaimed.
1433 * Furthermore, this function can't be guaranteed to operate in a
1434 * threadsafe way.
1436 * Since: 2.4
1438 void
1439 g_unsetenv (const gchar *variable)
1441 #ifndef G_OS_WIN32
1443 #ifdef HAVE_UNSETENV
1444 g_return_if_fail (variable != NULL);
1445 g_return_if_fail (strchr (variable, '=') == NULL);
1447 unsetenv (variable);
1448 #else /* !HAVE_UNSETENV */
1449 int len;
1450 gchar **e, **f;
1452 g_return_if_fail (variable != NULL);
1453 g_return_if_fail (strchr (variable, '=') == NULL);
1455 len = strlen (variable);
1457 /* Mess directly with the environ array.
1458 * This seems to be the only portable way to do this.
1460 * Note that we remove *all* environment entries for
1461 * the variable name, not just the first.
1463 e = f = environ;
1464 while (*e != NULL)
1466 if (strncmp (*e, variable, len) != 0 || (*e)[len] != '=')
1468 *f = *e;
1469 f++;
1471 e++;
1473 *f = NULL;
1474 #endif /* !HAVE_UNSETENV */
1476 #else /* G_OS_WIN32 */
1478 wchar_t *wname, *wassignment;
1479 gchar *tem;
1481 g_return_if_fail (variable != NULL);
1482 g_return_if_fail (strchr (variable, '=') == NULL);
1483 g_return_if_fail (g_utf8_validate (variable, -1, NULL));
1485 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1486 tem = g_strconcat (variable, "=", NULL);
1487 wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1489 g_free (tem);
1490 _wputenv (wassignment);
1491 g_free (wassignment);
1493 SetEnvironmentVariableW (wname, NULL);
1495 g_free (wname);
1497 #endif /* G_OS_WIN32 */
1501 * g_listenv:
1503 * Gets the names of all variables set in the environment.
1505 * Returns: (array zero-terminated=1) (transfer full): a %NULL-terminated list of strings which must be freed
1506 * with g_strfreev().
1508 * Programs that want to be portable to Windows should typically use
1509 * this function and g_getenv() instead of using the environ array
1510 * from the C library directly. On Windows, the strings in the environ
1511 * array are in system codepage encoding, while in most of the typical
1512 * use cases for environment variables in GLib-using programs you want
1513 * the UTF-8 encoding that this function and g_getenv() provide.
1515 * Since: 2.8
1517 gchar **
1518 g_listenv (void)
1520 #ifndef G_OS_WIN32
1521 gchar **result, *eq;
1522 gint len, i, j;
1524 len = g_strv_length (environ);
1525 result = g_new0 (gchar *, len + 1);
1527 j = 0;
1528 for (i = 0; i < len; i++)
1530 eq = strchr (environ[i], '=');
1531 if (eq)
1532 result[j++] = g_strndup (environ[i], eq - environ[i]);
1535 result[j] = NULL;
1537 return result;
1538 #else
1539 gchar **result, *eq;
1540 gint len = 0, j;
1541 wchar_t *p, *q;
1543 p = (wchar_t *) GetEnvironmentStringsW ();
1544 if (p != NULL)
1546 q = p;
1547 while (*q)
1549 q += wcslen (q) + 1;
1550 len++;
1553 result = g_new0 (gchar *, len + 1);
1555 j = 0;
1556 q = p;
1557 while (*q)
1559 result[j] = g_utf16_to_utf8 (q, -1, NULL, NULL, NULL);
1560 if (result[j] != NULL)
1562 eq = strchr (result[j], '=');
1563 if (eq && eq > result[j])
1565 *eq = '\0';
1566 j++;
1568 else
1569 g_free (result[j]);
1571 q += wcslen (q) + 1;
1573 result[j] = NULL;
1574 FreeEnvironmentStringsW (p);
1576 return result;
1577 #endif
1581 * g_get_environ:
1583 * Gets the list of environment variables for the current process. The
1584 * list is %NULL terminated and each item in the list is of the form
1585 * 'NAME=VALUE'.
1587 * This is equivalent to direct access to the 'environ' global variable,
1588 * except portable.
1590 * The return value is freshly allocated and it should be freed with
1591 * g_strfreev() when it is no longer needed.
1593 * Returns: (array zero-terminated=1) (transfer full): the list of environment variables
1595 * Since: 2.28
1597 gchar **
1598 g_get_environ (void)
1600 #ifndef G_OS_WIN32
1601 return g_strdupv (environ);
1602 #else
1603 gunichar2 *strings;
1604 gchar **result;
1605 gint i, n;
1607 strings = GetEnvironmentStringsW ();
1608 for (n = 0; strings[n]; n += wcslen (strings + n) + 1);
1609 result = g_new (char *, n + 1);
1610 for (i = 0; strings[i]; i += wcslen (strings + i) + 1)
1611 result[i] = g_utf16_to_utf8 (strings + i, -1, NULL, NULL, NULL);
1612 FreeEnvironmentStringsW (strings);
1613 result[i] = NULL;
1615 return result;
1616 #endif
1619 G_LOCK_DEFINE_STATIC (g_utils_global);
1621 static gchar *g_tmp_dir = NULL;
1622 static gchar *g_user_name = NULL;
1623 static gchar *g_real_name = NULL;
1624 static gchar *g_home_dir = NULL;
1625 static gchar *g_host_name = NULL;
1627 #ifdef G_OS_WIN32
1628 /* System codepage versions of the above, kept at file level so that they,
1629 * too, are produced only once.
1631 static gchar *g_tmp_dir_cp = NULL;
1632 static gchar *g_user_name_cp = NULL;
1633 static gchar *g_real_name_cp = NULL;
1634 static gchar *g_home_dir_cp = NULL;
1635 #endif
1637 static gchar *g_user_data_dir = NULL;
1638 static gchar **g_system_data_dirs = NULL;
1639 static gchar *g_user_cache_dir = NULL;
1640 static gchar *g_user_config_dir = NULL;
1641 static gchar **g_system_config_dirs = NULL;
1643 static gchar **g_user_special_dirs = NULL;
1645 /* fifteen minutes of fame for everybody */
1646 #define G_USER_DIRS_EXPIRE 15 * 60
1648 #ifdef G_OS_WIN32
1650 static gchar *
1651 get_special_folder (int csidl)
1653 wchar_t path[MAX_PATH+1];
1654 HRESULT hr;
1655 LPITEMIDLIST pidl = NULL;
1656 BOOL b;
1657 gchar *retval = NULL;
1659 hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
1660 if (hr == S_OK)
1662 b = SHGetPathFromIDListW (pidl, path);
1663 if (b)
1664 retval = g_utf16_to_utf8 (path, -1, NULL, NULL, NULL);
1665 CoTaskMemFree (pidl);
1667 return retval;
1670 static char *
1671 get_windows_directory_root (void)
1673 wchar_t wwindowsdir[MAX_PATH];
1675 if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
1677 /* Usually X:\Windows, but in terminal server environments
1678 * might be an UNC path, AFAIK.
1680 char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
1681 char *p;
1683 if (windowsdir == NULL)
1684 return g_strdup ("C:\\");
1686 p = (char *) g_path_skip_root (windowsdir);
1687 if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
1688 p--;
1689 *p = '\0';
1690 return windowsdir;
1692 else
1693 return g_strdup ("C:\\");
1696 #endif
1698 /* HOLDS: g_utils_global_lock */
1699 static void
1700 g_get_any_init_do (void)
1702 gchar hostname[100];
1704 g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
1705 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1706 g_tmp_dir = g_strdup (g_getenv ("TMP"));
1707 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1708 g_tmp_dir = g_strdup (g_getenv ("TEMP"));
1710 #ifdef G_OS_WIN32
1711 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1712 g_tmp_dir = get_windows_directory_root ();
1713 #else
1714 #ifdef P_tmpdir
1715 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1717 gsize k;
1718 g_tmp_dir = g_strdup (P_tmpdir);
1719 k = strlen (g_tmp_dir);
1720 if (k > 1 && G_IS_DIR_SEPARATOR (g_tmp_dir[k - 1]))
1721 g_tmp_dir[k - 1] = '\0';
1723 #endif
1725 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1727 g_tmp_dir = g_strdup ("/tmp");
1729 #endif /* !G_OS_WIN32 */
1731 #ifdef G_OS_WIN32
1732 /* We check $HOME first for Win32, though it is a last resort for Unix
1733 * where we prefer the results of getpwuid().
1735 g_home_dir = g_strdup (g_getenv ("HOME"));
1737 /* Only believe HOME if it is an absolute path and exists */
1738 if (g_home_dir)
1740 if (!(g_path_is_absolute (g_home_dir) &&
1741 g_file_test (g_home_dir, G_FILE_TEST_IS_DIR)))
1743 g_free (g_home_dir);
1744 g_home_dir = NULL;
1748 /* In case HOME is Unix-style (it happens), convert it to
1749 * Windows style.
1751 if (g_home_dir)
1753 gchar *p;
1754 while ((p = strchr (g_home_dir, '/')) != NULL)
1755 *p = '\\';
1758 if (!g_home_dir)
1760 /* USERPROFILE is probably the closest equivalent to $HOME? */
1761 if (g_getenv ("USERPROFILE") != NULL)
1762 g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
1765 if (!g_home_dir)
1766 g_home_dir = get_special_folder (CSIDL_PROFILE);
1768 if (!g_home_dir)
1769 g_home_dir = get_windows_directory_root ();
1770 #endif /* G_OS_WIN32 */
1772 #ifdef HAVE_PWD_H
1774 struct passwd *pw = NULL;
1775 gpointer buffer = NULL;
1776 gint error;
1777 gchar *logname;
1779 # if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
1780 struct passwd pwd;
1781 # ifdef _SC_GETPW_R_SIZE_MAX
1782 /* This reurns the maximum length */
1783 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
1785 if (bufsize < 0)
1786 bufsize = 64;
1787 # else /* _SC_GETPW_R_SIZE_MAX */
1788 glong bufsize = 64;
1789 # endif /* _SC_GETPW_R_SIZE_MAX */
1791 logname = (gchar *) g_getenv ("LOGNAME");
1795 g_free (buffer);
1796 /* we allocate 6 extra bytes to work around a bug in
1797 * Mac OS < 10.3. See #156446
1799 buffer = g_malloc (bufsize + 6);
1800 errno = 0;
1802 # ifdef HAVE_POSIX_GETPWUID_R
1803 if (logname) {
1804 error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
1805 if (!pw || (pw->pw_uid != getuid ())) {
1806 /* LOGNAME is lying, fall back to looking up the uid */
1807 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1809 } else {
1810 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1812 error = error < 0 ? errno : error;
1813 # else /* HAVE_NONPOSIX_GETPWUID_R */
1814 /* HPUX 11 falls into the HAVE_POSIX_GETPWUID_R case */
1815 # if defined(_AIX) || defined(__hpux)
1816 error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1817 pw = error == 0 ? &pwd : NULL;
1818 # else /* !_AIX */
1819 if (logname) {
1820 pw = getpwnam_r (logname, &pwd, buffer, bufsize);
1821 if (!pw || (pw->pw_uid != getuid ())) {
1822 /* LOGNAME is lying, fall back to looking up the uid */
1823 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1825 } else {
1826 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1828 error = pw ? 0 : errno;
1829 # endif /* !_AIX */
1830 # endif /* HAVE_NONPOSIX_GETPWUID_R */
1832 if (!pw)
1834 /* we bail out prematurely if the user id can't be found
1835 * (should be pretty rare case actually), or if the buffer
1836 * should be sufficiently big and lookups are still not
1837 * successful.
1839 if (error == 0 || error == ENOENT)
1841 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
1842 (gulong) getuid ());
1843 break;
1845 if (bufsize > 32 * 1024)
1847 g_warning ("getpwuid_r(): failed due to: %s.",
1848 g_strerror (error));
1849 break;
1852 bufsize *= 2;
1855 while (!pw);
1856 # endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
1858 if (!pw)
1860 setpwent ();
1861 pw = getpwuid (getuid ());
1862 endpwent ();
1864 if (pw)
1866 g_user_name = g_strdup (pw->pw_name);
1868 if (pw->pw_gecos && *pw->pw_gecos != '\0')
1870 gchar **gecos_fields;
1871 gchar **name_parts;
1873 /* split the gecos field and substitute '&' */
1874 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
1875 name_parts = g_strsplit (gecos_fields[0], "&", 0);
1876 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
1877 g_real_name = g_strjoinv (pw->pw_name, name_parts);
1878 g_strfreev (gecos_fields);
1879 g_strfreev (name_parts);
1882 if (!g_home_dir)
1883 g_home_dir = g_strdup (pw->pw_dir);
1885 g_free (buffer);
1888 #else /* !HAVE_PWD_H */
1890 #ifdef G_OS_WIN32
1892 guint len = UNLEN+1;
1893 wchar_t buffer[UNLEN+1];
1895 if (GetUserNameW (buffer, (LPDWORD) &len))
1897 g_user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
1898 g_real_name = g_strdup (g_user_name);
1901 #endif /* G_OS_WIN32 */
1903 #endif /* !HAVE_PWD_H */
1905 #ifndef G_OS_WIN32
1906 if (!g_home_dir)
1907 g_home_dir = g_strdup (g_getenv ("HOME"));
1908 #endif
1910 #ifdef __EMX__
1911 /* change '\\' in %HOME% to '/' */
1912 g_strdelimit (g_home_dir, "\\",'/');
1913 #endif
1914 if (!g_user_name)
1915 g_user_name = g_strdup ("somebody");
1916 if (!g_real_name)
1917 g_real_name = g_strdup ("Unknown");
1920 #ifndef G_OS_WIN32
1921 gboolean hostname_fail = (gethostname (hostname, sizeof (hostname)) == -1);
1922 #else
1923 DWORD size = sizeof (hostname);
1924 gboolean hostname_fail = (!GetComputerName (hostname, &size));
1925 #endif
1926 g_host_name = g_strdup (hostname_fail ? "localhost" : hostname);
1929 #ifdef G_OS_WIN32
1930 g_tmp_dir_cp = g_locale_from_utf8 (g_tmp_dir, -1, NULL, NULL, NULL);
1931 g_user_name_cp = g_locale_from_utf8 (g_user_name, -1, NULL, NULL, NULL);
1932 g_real_name_cp = g_locale_from_utf8 (g_real_name, -1, NULL, NULL, NULL);
1934 if (!g_tmp_dir_cp)
1935 g_tmp_dir_cp = g_strdup ("\\");
1936 if (!g_user_name_cp)
1937 g_user_name_cp = g_strdup ("somebody");
1938 if (!g_real_name_cp)
1939 g_real_name_cp = g_strdup ("Unknown");
1941 /* home_dir might be NULL, unlike tmp_dir, user_name and
1942 * real_name.
1944 if (g_home_dir)
1945 g_home_dir_cp = g_locale_from_utf8 (g_home_dir, -1, NULL, NULL, NULL);
1946 else
1947 g_home_dir_cp = NULL;
1948 #endif /* G_OS_WIN32 */
1951 static inline void
1952 g_get_any_init (void)
1954 if (!g_tmp_dir)
1955 g_get_any_init_do ();
1958 static inline void
1959 g_get_any_init_locked (void)
1961 G_LOCK (g_utils_global);
1962 g_get_any_init ();
1963 G_UNLOCK (g_utils_global);
1968 * g_get_user_name:
1970 * Gets the user name of the current user. The encoding of the returned
1971 * string is system-defined. On UNIX, it might be the preferred file name
1972 * encoding, or something else, and there is no guarantee that it is even
1973 * consistent on a machine. On Windows, it is always UTF-8.
1975 * Returns: the user name of the current user.
1977 const gchar *
1978 g_get_user_name (void)
1980 g_get_any_init_locked ();
1981 return g_user_name;
1985 * g_get_real_name:
1987 * Gets the real name of the user. This usually comes from the user's entry
1988 * in the <filename>passwd</filename> file. The encoding of the returned
1989 * string is system-defined. (On Windows, it is, however, always UTF-8.)
1990 * If the real user name cannot be determined, the string "Unknown" is
1991 * returned.
1993 * Returns: the user's real name.
1995 const gchar *
1996 g_get_real_name (void)
1998 g_get_any_init_locked ();
1999 return g_real_name;
2003 * g_get_home_dir:
2005 * Gets the current user's home directory as defined in the
2006 * password database.
2008 * Note that in contrast to traditional UNIX tools, this function
2009 * prefers <filename>passwd</filename> entries over the <envar>HOME</envar>
2010 * environment variable.
2012 * One of the reasons for this decision is that applications in many
2013 * cases need special handling to deal with the case where
2014 * <envar>HOME</envar> is
2015 * <simplelist>
2016 * <member>Not owned by the user</member>
2017 * <member>Not writeable</member>
2018 * <member>Not even readable</member>
2019 * </simplelist>
2020 * Since applications are in general <emphasis>not</emphasis> written
2021 * to deal with these situations it was considered better to make
2022 * g_get_home_dir() not pay attention to <envar>HOME</envar> and to
2023 * return the real home directory for the user. If applications
2024 * want to pay attention to <envar>HOME</envar>, they can do:
2025 * |[
2026 * const char *homedir = g_getenv ("HOME");
2027 * if (!homedir)
2028 * homedir = g_get_home_dir (<!-- -->);
2029 * ]|
2031 * Returns: the current user's home directory
2033 const gchar *
2034 g_get_home_dir (void)
2036 g_get_any_init_locked ();
2037 return g_home_dir;
2041 * g_get_tmp_dir:
2043 * Gets the directory to use for temporary files. This is found from
2044 * inspecting the environment variables <envar>TMPDIR</envar>,
2045 * <envar>TMP</envar>, and <envar>TEMP</envar> in that order. If none
2046 * of those are defined "/tmp" is returned on UNIX and "C:\" on Windows.
2047 * The encoding of the returned string is system-defined. On Windows,
2048 * it is always UTF-8. The return value is never %NULL or the empty string.
2050 * Returns: the directory to use for temporary files.
2052 const gchar *
2053 g_get_tmp_dir (void)
2055 g_get_any_init_locked ();
2056 return g_tmp_dir;
2060 * g_get_host_name:
2062 * Return a name for the machine.
2064 * The returned name is not necessarily a fully-qualified domain name,
2065 * or even present in DNS or some other name service at all. It need
2066 * not even be unique on your local network or site, but usually it
2067 * is. Callers should not rely on the return value having any specific
2068 * properties like uniqueness for security purposes. Even if the name
2069 * of the machine is changed while an application is running, the
2070 * return value from this function does not change. The returned
2071 * string is owned by GLib and should not be modified or freed. If no
2072 * name can be determined, a default fixed string "localhost" is
2073 * returned.
2075 * Returns: the host name of the machine.
2077 * Since: 2.8
2079 const gchar *
2080 g_get_host_name (void)
2082 g_get_any_init_locked ();
2083 return g_host_name;
2086 G_LOCK_DEFINE_STATIC (g_prgname);
2087 static gchar *g_prgname = NULL;
2090 * g_get_prgname:
2092 * Gets the name of the program. This name should <emphasis>not</emphasis>
2093 * be localized, contrast with g_get_application_name().
2094 * (If you are using GDK or GTK+ the program name is set in gdk_init(),
2095 * which is called by gtk_init(). The program name is found by taking
2096 * the last component of <literal>argv[0]</literal>.)
2098 * Returns: the name of the program. The returned string belongs
2099 * to GLib and must not be modified or freed.
2101 gchar*
2102 g_get_prgname (void)
2104 gchar* retval;
2106 G_LOCK (g_prgname);
2107 #ifdef G_OS_WIN32
2108 if (g_prgname == NULL)
2110 static gboolean beenhere = FALSE;
2112 if (!beenhere)
2114 gchar *utf8_buf = NULL;
2115 wchar_t buf[MAX_PATH+1];
2117 beenhere = TRUE;
2118 if (GetModuleFileNameW (GetModuleHandle (NULL),
2119 buf, G_N_ELEMENTS (buf)) > 0)
2120 utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
2122 if (utf8_buf)
2124 g_prgname = g_path_get_basename (utf8_buf);
2125 g_free (utf8_buf);
2129 #endif
2130 retval = g_prgname;
2131 G_UNLOCK (g_prgname);
2133 return retval;
2137 * g_set_prgname:
2138 * @prgname: the name of the program.
2140 * Sets the name of the program. This name should <emphasis>not</emphasis>
2141 * be localized, contrast with g_set_application_name(). Note that for
2142 * thread-safety reasons this function can only be called once.
2144 void
2145 g_set_prgname (const gchar *prgname)
2147 G_LOCK (g_prgname);
2148 g_free (g_prgname);
2149 g_prgname = g_strdup (prgname);
2150 G_UNLOCK (g_prgname);
2153 G_LOCK_DEFINE_STATIC (g_application_name);
2154 static gchar *g_application_name = NULL;
2157 * g_get_application_name:
2159 * Gets a human-readable name for the application, as set by
2160 * g_set_application_name(). This name should be localized if
2161 * possible, and is intended for display to the user. Contrast with
2162 * g_get_prgname(), which gets a non-localized name. If
2163 * g_set_application_name() has not been called, returns the result of
2164 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
2165 * been called).
2167 * Return value: human-readable application name. may return %NULL
2169 * Since: 2.2
2171 const gchar *
2172 g_get_application_name (void)
2174 gchar* retval;
2176 G_LOCK (g_application_name);
2177 retval = g_application_name;
2178 G_UNLOCK (g_application_name);
2180 if (retval == NULL)
2181 return g_get_prgname ();
2183 return retval;
2187 * g_set_application_name:
2188 * @application_name: localized name of the application
2190 * Sets a human-readable name for the application. This name should be
2191 * localized if possible, and is intended for display to the user.
2192 * Contrast with g_set_prgname(), which sets a non-localized name.
2193 * g_set_prgname() will be called automatically by gtk_init(),
2194 * but g_set_application_name() will not.
2196 * Note that for thread safety reasons, this function can only
2197 * be called once.
2199 * The application name will be used in contexts such as error messages,
2200 * or when displaying an application's name in the task list.
2202 * Since: 2.2
2204 void
2205 g_set_application_name (const gchar *application_name)
2207 gboolean already_set = FALSE;
2209 G_LOCK (g_application_name);
2210 if (g_application_name)
2211 already_set = TRUE;
2212 else
2213 g_application_name = g_strdup (application_name);
2214 G_UNLOCK (g_application_name);
2216 if (already_set)
2217 g_warning ("g_set_application_name() called multiple times");
2221 * g_get_user_data_dir:
2223 * Returns a base directory in which to access application data such
2224 * as icons that is customized for a particular user.
2226 * On UNIX platforms this is determined using the mechanisms described in
2227 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2228 * XDG Base Directory Specification</ulink>.
2229 * In this case the directory retrieved will be XDG_DATA_HOME.
2231 * On Windows this is the folder to use for local (as opposed to
2232 * roaming) application data. See documentation for
2233 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
2234 * what g_get_user_config_dir() returns.
2236 * Return value: a string owned by GLib that must not be modified
2237 * or freed.
2238 * Since: 2.6
2240 const gchar *
2241 g_get_user_data_dir (void)
2243 gchar *data_dir;
2245 G_LOCK (g_utils_global);
2247 if (!g_user_data_dir)
2249 #ifdef G_OS_WIN32
2250 data_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
2251 #else
2252 data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
2254 if (data_dir && data_dir[0])
2255 data_dir = g_strdup (data_dir);
2256 #endif
2257 if (!data_dir || !data_dir[0])
2259 g_get_any_init ();
2261 if (g_home_dir)
2262 data_dir = g_build_filename (g_home_dir, ".local",
2263 "share", NULL);
2264 else
2265 data_dir = g_build_filename (g_tmp_dir, g_user_name, ".local",
2266 "share", NULL);
2269 g_user_data_dir = data_dir;
2271 else
2272 data_dir = g_user_data_dir;
2274 G_UNLOCK (g_utils_global);
2276 return data_dir;
2279 static void
2280 g_init_user_config_dir (void)
2282 gchar *config_dir;
2284 if (!g_user_config_dir)
2286 #ifdef G_OS_WIN32
2287 config_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
2288 #else
2289 config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
2291 if (config_dir && config_dir[0])
2292 config_dir = g_strdup (config_dir);
2293 #endif
2294 if (!config_dir || !config_dir[0])
2296 g_get_any_init ();
2298 if (g_home_dir)
2299 config_dir = g_build_filename (g_home_dir, ".config", NULL);
2300 else
2301 config_dir = g_build_filename (g_tmp_dir, g_user_name, ".config", NULL);
2304 g_user_config_dir = config_dir;
2309 * g_get_user_config_dir:
2311 * Returns a base directory in which to store user-specific application
2312 * configuration information such as user preferences and settings.
2314 * On UNIX platforms this is determined using the mechanisms described in
2315 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2316 * XDG Base Directory Specification</ulink>.
2317 * In this case the directory retrieved will be XDG_CONFIG_HOME.
2319 * On Windows this is the folder to use for local (as opposed to
2320 * roaming) application data. See documentation for
2321 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
2322 * what g_get_user_data_dir() returns.
2324 * Return value: a string owned by GLib that must not be modified
2325 * or freed.
2326 * Since: 2.6
2328 const gchar *
2329 g_get_user_config_dir (void)
2331 G_LOCK (g_utils_global);
2333 g_init_user_config_dir ();
2335 G_UNLOCK (g_utils_global);
2337 return g_user_config_dir;
2341 * g_get_user_cache_dir:
2343 * Returns a base directory in which to store non-essential, cached
2344 * data specific to particular user.
2346 * On UNIX platforms this is determined using the mechanisms described in
2347 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2348 * XDG Base Directory Specification</ulink>.
2349 * In this case the directory retrieved will be XDG_CACHE_HOME.
2351 * On Windows is the directory that serves as a common repository for
2352 * temporary Internet files. A typical path is
2353 * C:\Documents and Settings\username\Local Settings\Temporary Internet Files.
2354 * See documentation for CSIDL_INTERNET_CACHE.
2356 * Return value: a string owned by GLib that must not be modified
2357 * or freed.
2358 * Since: 2.6
2360 const gchar *
2361 g_get_user_cache_dir (void)
2363 gchar *cache_dir;
2365 G_LOCK (g_utils_global);
2367 if (!g_user_cache_dir)
2369 #ifdef G_OS_WIN32
2370 cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
2371 #else
2372 cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
2374 if (cache_dir && cache_dir[0])
2375 cache_dir = g_strdup (cache_dir);
2376 #endif
2377 if (!cache_dir || !cache_dir[0])
2379 g_get_any_init ();
2381 if (g_home_dir)
2382 cache_dir = g_build_filename (g_home_dir, ".cache", NULL);
2383 else
2384 cache_dir = g_build_filename (g_tmp_dir, g_user_name, ".cache", NULL);
2386 g_user_cache_dir = cache_dir;
2388 else
2389 cache_dir = g_user_cache_dir;
2391 G_UNLOCK (g_utils_global);
2393 return cache_dir;
2397 * g_get_user_runtime_dir:
2399 * Returns a directory that is unique to the current user on the local
2400 * system.
2402 * On UNIX platforms this is determined using the mechanisms described in
2403 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2404 * XDG Base Directory Specification</ulink>. This is the directory
2405 * specified in the <envar>XDG_RUNTIME_DIR</envar> environment variable.
2406 * In the case that this variable is not set, GLib will issue a warning
2407 * message to stderr and return the value of g_get_user_cache_dir().
2409 * On Windows this is the folder to use for local (as opposed to
2410 * roaming) application data. See documentation for
2411 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
2412 * what g_get_user_config_dir() returns.
2414 * Returns: a string owned by GLib that must not be modified or freed.
2416 * Since: 2.28
2418 const gchar *
2419 g_get_user_runtime_dir (void)
2421 #ifndef G_OS_WIN32
2422 static const gchar *runtime_dir;
2423 static gsize initialised;
2425 if (g_once_init_enter (&initialised))
2427 runtime_dir = g_strdup (getenv ("XDG_RUNTIME_DIR"));
2429 g_once_init_leave (&initialised, 1);
2432 if (runtime_dir)
2433 return runtime_dir;
2435 /* Both fallback for UNIX and the default
2436 * in Windows: use the user cache directory.
2438 #endif
2440 return g_get_user_cache_dir ();
2443 #ifdef HAVE_CARBON
2445 static gchar *
2446 find_folder (OSType type)
2448 gchar *filename = NULL;
2449 FSRef found;
2451 if (FSFindFolder (kUserDomain, type, kDontCreateFolder, &found) == noErr)
2453 CFURLRef url = CFURLCreateFromFSRef (kCFAllocatorSystemDefault, &found);
2455 if (url)
2457 CFStringRef path = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle);
2459 if (path)
2461 filename = g_strdup (CFStringGetCStringPtr (path, kCFStringEncodingUTF8));
2463 if (! filename)
2465 filename = g_new0 (gchar, CFStringGetLength (path) * 3 + 1);
2467 CFStringGetCString (path, filename,
2468 CFStringGetLength (path) * 3 + 1,
2469 kCFStringEncodingUTF8);
2472 CFRelease (path);
2475 CFRelease (url);
2479 return filename;
2482 static void
2483 load_user_special_dirs (void)
2485 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = find_folder (kDesktopFolderType);
2486 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = find_folder (kDocumentsFolderType);
2487 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = find_folder (kDesktopFolderType); /* XXX correct ? */
2488 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = find_folder (kMusicDocumentsFolderType);
2489 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = find_folder (kPictureDocumentsFolderType);
2490 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = NULL;
2491 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = NULL;
2492 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = find_folder (kMovieDocumentsFolderType);
2495 #endif /* HAVE_CARBON */
2497 #if defined(G_OS_WIN32)
2498 static void
2499 load_user_special_dirs (void)
2501 typedef HRESULT (WINAPI *t_SHGetKnownFolderPath) (const GUID *rfid,
2502 DWORD dwFlags,
2503 HANDLE hToken,
2504 PWSTR *ppszPath);
2505 t_SHGetKnownFolderPath p_SHGetKnownFolderPath;
2507 static const GUID FOLDERID_Downloads =
2508 { 0x374de290, 0x123f, 0x4565, { 0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b } };
2509 static const GUID FOLDERID_Public =
2510 { 0xDFDF76A2, 0xC82A, 0x4D63, { 0x90, 0x6A, 0x56, 0x44, 0xAC, 0x45, 0x73, 0x85 } };
2512 wchar_t *wcp;
2514 p_SHGetKnownFolderPath = (t_SHGetKnownFolderPath) GetProcAddress (GetModuleHandle ("shell32.dll"),
2515 "SHGetKnownFolderPath");
2517 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2518 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
2520 if (p_SHGetKnownFolderPath == NULL)
2522 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2524 else
2526 wcp = NULL;
2527 (*p_SHGetKnownFolderPath) (&FOLDERID_Downloads, 0, NULL, &wcp);
2528 if (wcp)
2530 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
2531 if (g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] == NULL)
2532 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2533 CoTaskMemFree (wcp);
2535 else
2536 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2539 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
2540 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
2542 if (p_SHGetKnownFolderPath == NULL)
2544 /* XXX */
2545 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2547 else
2549 wcp = NULL;
2550 (*p_SHGetKnownFolderPath) (&FOLDERID_Public, 0, NULL, &wcp);
2551 if (wcp)
2553 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
2554 if (g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] == NULL)
2555 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2556 CoTaskMemFree (wcp);
2558 else
2559 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2562 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
2563 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
2565 #endif /* G_OS_WIN32 */
2567 static void g_init_user_config_dir (void);
2569 #if defined(G_OS_UNIX) && !defined(HAVE_CARBON)
2571 /* adapted from xdg-user-dir-lookup.c
2573 * Copyright (C) 2007 Red Hat Inc.
2575 * Permission is hereby granted, free of charge, to any person
2576 * obtaining a copy of this software and associated documentation files
2577 * (the "Software"), to deal in the Software without restriction,
2578 * including without limitation the rights to use, copy, modify, merge,
2579 * publish, distribute, sublicense, and/or sell copies of the Software,
2580 * and to permit persons to whom the Software is furnished to do so,
2581 * subject to the following conditions:
2583 * The above copyright notice and this permission notice shall be
2584 * included in all copies or substantial portions of the Software.
2586 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
2587 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
2588 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
2589 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
2590 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
2591 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
2592 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2593 * SOFTWARE.
2595 static void
2596 load_user_special_dirs (void)
2598 gchar *config_file;
2599 gchar *data;
2600 gchar **lines;
2601 gint n_lines, i;
2603 g_init_user_config_dir ();
2604 config_file = g_build_filename (g_user_config_dir,
2605 "user-dirs.dirs",
2606 NULL);
2608 if (!g_file_get_contents (config_file, &data, NULL, NULL))
2610 g_free (config_file);
2611 return;
2614 lines = g_strsplit (data, "\n", -1);
2615 n_lines = g_strv_length (lines);
2616 g_free (data);
2618 for (i = 0; i < n_lines; i++)
2620 gchar *buffer = lines[i];
2621 gchar *d, *p;
2622 gint len;
2623 gboolean is_relative = FALSE;
2624 GUserDirectory directory;
2626 /* Remove newline at end */
2627 len = strlen (buffer);
2628 if (len > 0 && buffer[len - 1] == '\n')
2629 buffer[len - 1] = 0;
2631 p = buffer;
2632 while (*p == ' ' || *p == '\t')
2633 p++;
2635 if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
2637 directory = G_USER_DIRECTORY_DESKTOP;
2638 p += strlen ("XDG_DESKTOP_DIR");
2640 else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
2642 directory = G_USER_DIRECTORY_DOCUMENTS;
2643 p += strlen ("XDG_DOCUMENTS_DIR");
2645 else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
2647 directory = G_USER_DIRECTORY_DOWNLOAD;
2648 p += strlen ("XDG_DOWNLOAD_DIR");
2650 else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
2652 directory = G_USER_DIRECTORY_MUSIC;
2653 p += strlen ("XDG_MUSIC_DIR");
2655 else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
2657 directory = G_USER_DIRECTORY_PICTURES;
2658 p += strlen ("XDG_PICTURES_DIR");
2660 else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
2662 directory = G_USER_DIRECTORY_PUBLIC_SHARE;
2663 p += strlen ("XDG_PUBLICSHARE_DIR");
2665 else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
2667 directory = G_USER_DIRECTORY_TEMPLATES;
2668 p += strlen ("XDG_TEMPLATES_DIR");
2670 else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
2672 directory = G_USER_DIRECTORY_VIDEOS;
2673 p += strlen ("XDG_VIDEOS_DIR");
2675 else
2676 continue;
2678 while (*p == ' ' || *p == '\t')
2679 p++;
2681 if (*p != '=')
2682 continue;
2683 p++;
2685 while (*p == ' ' || *p == '\t')
2686 p++;
2688 if (*p != '"')
2689 continue;
2690 p++;
2692 if (strncmp (p, "$HOME", 5) == 0)
2694 p += 5;
2695 is_relative = TRUE;
2697 else if (*p != '/')
2698 continue;
2700 d = strrchr (p, '"');
2701 if (!d)
2702 continue;
2703 *d = 0;
2705 d = p;
2707 /* remove trailing slashes */
2708 len = strlen (d);
2709 if (d[len - 1] == '/')
2710 d[len - 1] = 0;
2712 if (is_relative)
2714 g_get_any_init ();
2715 g_user_special_dirs[directory] = g_build_filename (g_home_dir, d, NULL);
2717 else
2718 g_user_special_dirs[directory] = g_strdup (d);
2721 g_strfreev (lines);
2722 g_free (config_file);
2725 #endif /* G_OS_UNIX && !HAVE_CARBON */
2729 * g_reload_user_special_dirs_cache:
2731 * Resets the cache used for g_get_user_special_dir(), so
2732 * that the latest on-disk version is used. Call this only
2733 * if you just changed the data on disk yourself.
2735 * Due to threadsafety issues this may cause leaking of strings
2736 * that were previously returned from g_get_user_special_dir()
2737 * that can't be freed. We ensure to only leak the data for
2738 * the directories that actually changed value though.
2740 * Since: 2.22
2742 void
2743 g_reload_user_special_dirs_cache (void)
2745 int i;
2747 G_LOCK (g_utils_global);
2749 if (g_user_special_dirs != NULL)
2751 /* save a copy of the pointer, to check if some memory can be preserved */
2752 char **old_g_user_special_dirs = g_user_special_dirs;
2753 char *old_val;
2755 /* recreate and reload our cache */
2756 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
2757 load_user_special_dirs ();
2759 /* only leak changed directories */
2760 for (i = 0; i < G_USER_N_DIRECTORIES; i++)
2762 old_val = old_g_user_special_dirs[i];
2763 if (g_strcmp0 (old_val, g_user_special_dirs[i]) == 0)
2765 /* don't leak */
2766 g_free (g_user_special_dirs[i]);
2767 g_user_special_dirs[i] = old_val;
2769 else
2770 g_free (old_val);
2773 /* free the old array */
2774 g_free (old_g_user_special_dirs);
2777 G_UNLOCK (g_utils_global);
2781 * g_get_user_special_dir:
2782 * @directory: the logical id of special directory
2784 * Returns the full path of a special directory using its logical id.
2786 * On Unix this is done using the XDG special user directories.
2787 * For compatibility with existing practise, %G_USER_DIRECTORY_DESKTOP
2788 * falls back to <filename>$HOME/Desktop</filename> when XDG special
2789 * user directories have not been set up.
2791 * Depending on the platform, the user might be able to change the path
2792 * of the special directory without requiring the session to restart; GLib
2793 * will not reflect any change once the special directories are loaded.
2795 * Return value: the path to the specified special directory, or %NULL
2796 * if the logical id was not found. The returned string is owned by
2797 * GLib and should not be modified or freed.
2799 * Since: 2.14
2801 const gchar *
2802 g_get_user_special_dir (GUserDirectory directory)
2804 g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
2805 directory < G_USER_N_DIRECTORIES, NULL);
2807 G_LOCK (g_utils_global);
2809 if (G_UNLIKELY (g_user_special_dirs == NULL))
2811 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
2813 load_user_special_dirs ();
2815 /* Special-case desktop for historical compatibility */
2816 if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
2818 g_get_any_init ();
2820 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] =
2821 g_build_filename (g_home_dir, "Desktop", NULL);
2825 G_UNLOCK (g_utils_global);
2827 return g_user_special_dirs[directory];
2830 #ifdef G_OS_WIN32
2832 #undef g_get_system_data_dirs
2834 static HMODULE
2835 get_module_for_address (gconstpointer address)
2837 /* Holds the g_utils_global lock */
2839 static gboolean beenhere = FALSE;
2840 typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
2841 static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
2842 HMODULE hmodule = NULL;
2844 if (!address)
2845 return NULL;
2847 if (!beenhere)
2849 p_GetModuleHandleExA =
2850 (t_GetModuleHandleExA) GetProcAddress (GetModuleHandle ("kernel32.dll"),
2851 "GetModuleHandleExA");
2852 beenhere = TRUE;
2855 if (p_GetModuleHandleExA == NULL ||
2856 !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
2857 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
2858 address, &hmodule))
2860 MEMORY_BASIC_INFORMATION mbi;
2861 VirtualQuery (address, &mbi, sizeof (mbi));
2862 hmodule = (HMODULE) mbi.AllocationBase;
2865 return hmodule;
2868 static gchar *
2869 get_module_share_dir (gconstpointer address)
2871 HMODULE hmodule;
2872 gchar *filename;
2873 gchar *retval;
2875 hmodule = get_module_for_address (address);
2876 if (hmodule == NULL)
2877 return NULL;
2879 filename = g_win32_get_package_installation_directory_of_module (hmodule);
2880 retval = g_build_filename (filename, "share", NULL);
2881 g_free (filename);
2883 return retval;
2886 const gchar * const *
2887 g_win32_get_system_data_dirs_for_module (void (*address_of_function)())
2889 GArray *data_dirs;
2890 HMODULE hmodule;
2891 static GHashTable *per_module_data_dirs = NULL;
2892 gchar **retval;
2893 gchar *p;
2894 gchar *exe_root;
2896 if (address_of_function)
2898 G_LOCK (g_utils_global);
2899 hmodule = get_module_for_address (address_of_function);
2900 if (hmodule != NULL)
2902 if (per_module_data_dirs == NULL)
2903 per_module_data_dirs = g_hash_table_new (NULL, NULL);
2904 else
2906 retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
2908 if (retval != NULL)
2910 G_UNLOCK (g_utils_global);
2911 return (const gchar * const *) retval;
2917 data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
2919 /* Documents and Settings\All Users\Application Data */
2920 p = get_special_folder (CSIDL_COMMON_APPDATA);
2921 if (p)
2922 g_array_append_val (data_dirs, p);
2924 /* Documents and Settings\All Users\Documents */
2925 p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2926 if (p)
2927 g_array_append_val (data_dirs, p);
2929 /* Using the above subfolders of Documents and Settings perhaps
2930 * makes sense from a Windows perspective.
2932 * But looking at the actual use cases of this function in GTK+
2933 * and GNOME software, what we really want is the "share"
2934 * subdirectory of the installation directory for the package
2935 * our caller is a part of.
2937 * The address_of_function parameter, if non-NULL, points to a
2938 * function in the calling module. Use that to determine that
2939 * module's installation folder, and use its "share" subfolder.
2941 * Additionally, also use the "share" subfolder of the installation
2942 * locations of GLib and the .exe file being run.
2944 * To guard against none of the above being what is really wanted,
2945 * callers of this function should have Win32-specific code to look
2946 * up their installation folder themselves, and handle a subfolder
2947 * "share" of it in the same way as the folders returned from this
2948 * function.
2951 p = get_module_share_dir (address_of_function);
2952 if (p)
2953 g_array_append_val (data_dirs, p);
2955 if (glib_dll != NULL)
2957 gchar *glib_root = g_win32_get_package_installation_directory_of_module (glib_dll);
2958 p = g_build_filename (glib_root, "share", NULL);
2959 if (p)
2960 g_array_append_val (data_dirs, p);
2961 g_free (glib_root);
2964 exe_root = g_win32_get_package_installation_directory_of_module (NULL);
2965 p = g_build_filename (exe_root, "share", NULL);
2966 if (p)
2967 g_array_append_val (data_dirs, p);
2968 g_free (exe_root);
2970 retval = (gchar **) g_array_free (data_dirs, FALSE);
2972 if (address_of_function)
2974 if (hmodule != NULL)
2975 g_hash_table_insert (per_module_data_dirs, hmodule, retval);
2976 G_UNLOCK (g_utils_global);
2979 return (const gchar * const *) retval;
2982 #endif
2985 * g_get_system_data_dirs:
2987 * Returns an ordered list of base directories in which to access
2988 * system-wide application data.
2990 * On UNIX platforms this is determined using the mechanisms described in
2991 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2992 * XDG Base Directory Specification</ulink>
2993 * In this case the list of directories retrieved will be XDG_DATA_DIRS.
2995 * On Windows the first elements in the list are the Application Data
2996 * and Documents folders for All Users. (These can be determined only
2997 * on Windows 2000 or later and are not present in the list on other
2998 * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
2999 * CSIDL_COMMON_DOCUMENTS.
3001 * Then follows the "share" subfolder in the installation folder for
3002 * the package containing the DLL that calls this function, if it can
3003 * be determined.
3005 * Finally the list contains the "share" subfolder in the installation
3006 * folder for GLib, and in the installation folder for the package the
3007 * application's .exe file belongs to.
3009 * The installation folders above are determined by looking up the
3010 * folder where the module (DLL or EXE) in question is located. If the
3011 * folder's name is "bin", its parent is used, otherwise the folder
3012 * itself.
3014 * Note that on Windows the returned list can vary depending on where
3015 * this function is called.
3017 * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib that must
3018 * not be modified or freed.
3019 * Since: 2.6
3021 const gchar * const *
3022 g_get_system_data_dirs (void)
3024 gchar **data_dir_vector;
3026 G_LOCK (g_utils_global);
3028 if (!g_system_data_dirs)
3030 #ifdef G_OS_WIN32
3031 data_dir_vector = (gchar **) g_win32_get_system_data_dirs_for_module (NULL);
3032 #else
3033 gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
3035 if (!data_dirs || !data_dirs[0])
3036 data_dirs = "/usr/local/share/:/usr/share/";
3038 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
3039 #endif
3041 g_system_data_dirs = data_dir_vector;
3043 else
3044 data_dir_vector = g_system_data_dirs;
3046 G_UNLOCK (g_utils_global);
3048 return (const gchar * const *) data_dir_vector;
3052 * g_get_system_config_dirs:
3054 * Returns an ordered list of base directories in which to access
3055 * system-wide configuration information.
3057 * On UNIX platforms this is determined using the mechanisms described in
3058 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
3059 * XDG Base Directory Specification</ulink>.
3060 * In this case the list of directories retrieved will be XDG_CONFIG_DIRS.
3062 * On Windows is the directory that contains application data for all users.
3063 * A typical path is C:\Documents and Settings\All Users\Application Data.
3064 * This folder is used for application data that is not user specific.
3065 * For example, an application can store a spell-check dictionary, a database
3066 * of clip art, or a log file in the CSIDL_COMMON_APPDATA folder.
3067 * This information will not roam and is available to anyone using the computer.
3069 * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib that must
3070 * not be modified or freed.
3071 * Since: 2.6
3073 const gchar * const *
3074 g_get_system_config_dirs (void)
3076 gchar *conf_dirs, **conf_dir_vector;
3078 G_LOCK (g_utils_global);
3080 if (!g_system_config_dirs)
3082 #ifdef G_OS_WIN32
3083 conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
3084 if (conf_dirs)
3086 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
3087 g_free (conf_dirs);
3089 else
3091 /* Return empty list */
3092 conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
3094 #else
3095 conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
3097 if (!conf_dirs || !conf_dirs[0])
3098 conf_dirs = "/etc/xdg";
3100 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
3101 #endif
3103 g_system_config_dirs = conf_dir_vector;
3105 else
3106 conf_dir_vector = g_system_config_dirs;
3107 G_UNLOCK (g_utils_global);
3109 return (const gchar * const *) conf_dir_vector;
3112 #ifndef G_OS_WIN32
3114 static GHashTable *alias_table = NULL;
3116 /* read an alias file for the locales */
3117 static void
3118 read_aliases (gchar *file)
3120 FILE *fp;
3121 char buf[256];
3123 if (!alias_table)
3124 alias_table = g_hash_table_new (g_str_hash, g_str_equal);
3125 fp = fopen (file,"r");
3126 if (!fp)
3127 return;
3128 while (fgets (buf, 256, fp))
3130 char *p, *q;
3132 g_strstrip (buf);
3134 /* Line is a comment */
3135 if ((buf[0] == '#') || (buf[0] == '\0'))
3136 continue;
3138 /* Reads first column */
3139 for (p = buf, q = NULL; *p; p++) {
3140 if ((*p == '\t') || (*p == ' ') || (*p == ':')) {
3141 *p = '\0';
3142 q = p+1;
3143 while ((*q == '\t') || (*q == ' ')) {
3144 q++;
3146 break;
3149 /* The line only had one column */
3150 if (!q || *q == '\0')
3151 continue;
3153 /* Read second column */
3154 for (p = q; *p; p++) {
3155 if ((*p == '\t') || (*p == ' ')) {
3156 *p = '\0';
3157 break;
3161 /* Add to alias table if necessary */
3162 if (!g_hash_table_lookup (alias_table, buf)) {
3163 g_hash_table_insert (alias_table, g_strdup (buf), g_strdup (q));
3166 fclose (fp);
3169 #endif
3171 static char *
3172 unalias_lang (char *lang)
3174 #ifndef G_OS_WIN32
3175 char *p;
3176 int i;
3178 if (!alias_table)
3179 read_aliases ("/usr/share/locale/locale.alias");
3181 i = 0;
3182 while ((p = g_hash_table_lookup (alias_table, lang)) && (strcmp (p, lang) != 0))
3184 lang = p;
3185 if (i++ == 30)
3187 static gboolean said_before = FALSE;
3188 if (!said_before)
3189 g_warning ("Too many alias levels for a locale, "
3190 "may indicate a loop");
3191 said_before = TRUE;
3192 return lang;
3195 #endif
3196 return lang;
3199 /* Mask for components of locale spec. The ordering here is from
3200 * least significant to most significant
3202 enum
3204 COMPONENT_CODESET = 1 << 0,
3205 COMPONENT_TERRITORY = 1 << 1,
3206 COMPONENT_MODIFIER = 1 << 2
3209 /* Break an X/Open style locale specification into components
3211 static guint
3212 explode_locale (const gchar *locale,
3213 gchar **language,
3214 gchar **territory,
3215 gchar **codeset,
3216 gchar **modifier)
3218 const gchar *uscore_pos;
3219 const gchar *at_pos;
3220 const gchar *dot_pos;
3222 guint mask = 0;
3224 uscore_pos = strchr (locale, '_');
3225 dot_pos = strchr (uscore_pos ? uscore_pos : locale, '.');
3226 at_pos = strchr (dot_pos ? dot_pos : (uscore_pos ? uscore_pos : locale), '@');
3228 if (at_pos)
3230 mask |= COMPONENT_MODIFIER;
3231 *modifier = g_strdup (at_pos);
3233 else
3234 at_pos = locale + strlen (locale);
3236 if (dot_pos)
3238 mask |= COMPONENT_CODESET;
3239 *codeset = g_strndup (dot_pos, at_pos - dot_pos);
3241 else
3242 dot_pos = at_pos;
3244 if (uscore_pos)
3246 mask |= COMPONENT_TERRITORY;
3247 *territory = g_strndup (uscore_pos, dot_pos - uscore_pos);
3249 else
3250 uscore_pos = dot_pos;
3252 *language = g_strndup (locale, uscore_pos - locale);
3254 return mask;
3258 * Compute all interesting variants for a given locale name -
3259 * by stripping off different components of the value.
3261 * For simplicity, we assume that the locale is in
3262 * X/Open format: language[_territory][.codeset][@modifier]
3264 * TODO: Extend this to handle the CEN format (see the GNUlibc docs)
3265 * as well. We could just copy the code from glibc wholesale
3266 * but it is big, ugly, and complicated, so I'm reluctant
3267 * to do so when this should handle 99% of the time...
3269 static void
3270 append_locale_variants (GPtrArray *array,
3271 const gchar *locale)
3273 gchar *language = NULL;
3274 gchar *territory = NULL;
3275 gchar *codeset = NULL;
3276 gchar *modifier = NULL;
3278 guint mask;
3279 guint i, j;
3281 g_return_if_fail (locale != NULL);
3283 mask = explode_locale (locale, &language, &territory, &codeset, &modifier);
3285 /* Iterate through all possible combinations, from least attractive
3286 * to most attractive.
3288 for (j = 0; j <= mask; ++j)
3290 i = mask - j;
3292 if ((i & ~mask) == 0)
3294 gchar *val = g_strconcat (language,
3295 (i & COMPONENT_TERRITORY) ? territory : "",
3296 (i & COMPONENT_CODESET) ? codeset : "",
3297 (i & COMPONENT_MODIFIER) ? modifier : "",
3298 NULL);
3299 g_ptr_array_add (array, val);
3303 g_free (language);
3304 if (mask & COMPONENT_CODESET)
3305 g_free (codeset);
3306 if (mask & COMPONENT_TERRITORY)
3307 g_free (territory);
3308 if (mask & COMPONENT_MODIFIER)
3309 g_free (modifier);
3313 * g_get_locale_variants:
3314 * @locale: a locale identifier
3316 * Returns a list of derived variants of @locale, which can be used to
3317 * e.g. construct locale-dependent filenames or search paths. The returned
3318 * list is sorted from most desirable to least desirable.
3319 * This function handles territory, charset and extra locale modifiers.
3321 * For example, if @locale is "fr_BE", then the returned list
3322 * is "fr_BE", "fr".
3324 * If you need the list of variants for the <emphasis>current locale</emphasis>,
3325 * use g_get_language_names().
3327 * Returns: (transfer full) (array zero-terminated=1) (element-type utf8): a newly
3328 * allocated array of newly allocated strings with the locale variants. Free with
3329 * g_strfreev().
3331 * Since: 2.28
3333 gchar **
3334 g_get_locale_variants (const gchar *locale)
3336 GPtrArray *array;
3338 g_return_val_if_fail (locale != NULL, NULL);
3340 array = g_ptr_array_sized_new (8);
3341 append_locale_variants (array, locale);
3342 g_ptr_array_add (array, NULL);
3344 return (gchar **) g_ptr_array_free (array, FALSE);
3347 /* The following is (partly) taken from the gettext package.
3348 Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc. */
3350 static const gchar *
3351 guess_category_value (const gchar *category_name)
3353 const gchar *retval;
3355 /* The highest priority value is the `LANGUAGE' environment
3356 variable. This is a GNU extension. */
3357 retval = g_getenv ("LANGUAGE");
3358 if ((retval != NULL) && (retval[0] != '\0'))
3359 return retval;
3361 /* `LANGUAGE' is not set. So we have to proceed with the POSIX
3362 methods of looking to `LC_ALL', `LC_xxx', and `LANG'. On some
3363 systems this can be done by the `setlocale' function itself. */
3365 /* Setting of LC_ALL overwrites all other. */
3366 retval = g_getenv ("LC_ALL");
3367 if ((retval != NULL) && (retval[0] != '\0'))
3368 return retval;
3370 /* Next comes the name of the desired category. */
3371 retval = g_getenv (category_name);
3372 if ((retval != NULL) && (retval[0] != '\0'))
3373 return retval;
3375 /* Last possibility is the LANG environment variable. */
3376 retval = g_getenv ("LANG");
3377 if ((retval != NULL) && (retval[0] != '\0'))
3378 return retval;
3380 #ifdef G_PLATFORM_WIN32
3381 /* g_win32_getlocale() first checks for LC_ALL, LC_MESSAGES and
3382 * LANG, which we already did above. Oh well. The main point of
3383 * calling g_win32_getlocale() is to get the thread's locale as used
3384 * by Windows and the Microsoft C runtime (in the "English_United
3385 * States" format) translated into the Unixish format.
3388 char *locale = g_win32_getlocale ();
3389 retval = g_intern_string (locale);
3390 g_free (locale);
3391 return retval;
3393 #endif
3395 return NULL;
3398 typedef struct _GLanguageNamesCache GLanguageNamesCache;
3400 struct _GLanguageNamesCache {
3401 gchar *languages;
3402 gchar **language_names;
3405 static void
3406 language_names_cache_free (gpointer data)
3408 GLanguageNamesCache *cache = data;
3409 g_free (cache->languages);
3410 g_strfreev (cache->language_names);
3411 g_free (cache);
3415 * g_get_language_names:
3417 * Computes a list of applicable locale names, which can be used to
3418 * e.g. construct locale-dependent filenames or search paths. The returned
3419 * list is sorted from most desirable to least desirable and always contains
3420 * the default locale "C".
3422 * For example, if LANGUAGE=de:en_US, then the returned list is
3423 * "de", "en_US", "en", "C".
3425 * This function consults the environment variables <envar>LANGUAGE</envar>,
3426 * <envar>LC_ALL</envar>, <envar>LC_MESSAGES</envar> and <envar>LANG</envar>
3427 * to find the list of locales specified by the user.
3429 * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib
3430 * that must not be modified or freed.
3432 * Since: 2.6
3434 const gchar * const *
3435 g_get_language_names (void)
3437 static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
3438 GLanguageNamesCache *cache = g_static_private_get (&cache_private);
3439 const gchar *value;
3441 if (!cache)
3443 cache = g_new0 (GLanguageNamesCache, 1);
3444 g_static_private_set (&cache_private, cache, language_names_cache_free);
3447 value = guess_category_value ("LC_MESSAGES");
3448 if (!value)
3449 value = "C";
3451 if (!(cache->languages && strcmp (cache->languages, value) == 0))
3453 GPtrArray *array;
3454 gchar **alist, **a;
3456 g_free (cache->languages);
3457 g_strfreev (cache->language_names);
3458 cache->languages = g_strdup (value);
3460 array = g_ptr_array_sized_new (8);
3462 alist = g_strsplit (value, ":", 0);
3463 for (a = alist; *a; a++)
3464 append_locale_variants (array, unalias_lang (*a));
3465 g_strfreev (alist);
3466 g_ptr_array_add (array, g_strdup ("C"));
3467 g_ptr_array_add (array, NULL);
3469 cache->language_names = (gchar **) g_ptr_array_free (array, FALSE);
3472 return (const gchar * const *) cache->language_names;
3476 * g_direct_hash:
3477 * @v: a #gpointer key
3479 * Converts a gpointer to a hash value.
3480 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3481 * when using pointers as keys in a #GHashTable.
3483 * Returns: a hash value corresponding to the key.
3485 guint
3486 g_direct_hash (gconstpointer v)
3488 return GPOINTER_TO_UINT (v);
3492 * g_direct_equal:
3493 * @v1: a key.
3494 * @v2: a key to compare with @v1.
3496 * Compares two #gpointer arguments and returns %TRUE if they are equal.
3497 * It can be passed to g_hash_table_new() as the @key_equal_func
3498 * parameter, when using pointers as keys in a #GHashTable.
3500 * Returns: %TRUE if the two keys match.
3502 gboolean
3503 g_direct_equal (gconstpointer v1,
3504 gconstpointer v2)
3506 return v1 == v2;
3510 * g_int_equal:
3511 * @v1: a pointer to a #gint key.
3512 * @v2: a pointer to a #gint key to compare with @v1.
3514 * Compares the two #gint values being pointed to and returns
3515 * %TRUE if they are equal.
3516 * It can be passed to g_hash_table_new() as the @key_equal_func
3517 * parameter, when using pointers to integers as keys in a #GHashTable.
3519 * Returns: %TRUE if the two keys match.
3521 gboolean
3522 g_int_equal (gconstpointer v1,
3523 gconstpointer v2)
3525 return *((const gint*) v1) == *((const gint*) v2);
3529 * g_int_hash:
3530 * @v: a pointer to a #gint key
3532 * Converts a pointer to a #gint to a hash value.
3533 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3534 * when using pointers to integers values as keys in a #GHashTable.
3536 * Returns: a hash value corresponding to the key.
3538 guint
3539 g_int_hash (gconstpointer v)
3541 return *(const gint*) v;
3545 * g_int64_equal:
3546 * @v1: a pointer to a #gint64 key.
3547 * @v2: a pointer to a #gint64 key to compare with @v1.
3549 * Compares the two #gint64 values being pointed to and returns
3550 * %TRUE if they are equal.
3551 * It can be passed to g_hash_table_new() as the @key_equal_func
3552 * parameter, when using pointers to 64-bit integers as keys in a #GHashTable.
3554 * Returns: %TRUE if the two keys match.
3556 * Since: 2.22
3558 gboolean
3559 g_int64_equal (gconstpointer v1,
3560 gconstpointer v2)
3562 return *((const gint64*) v1) == *((const gint64*) v2);
3566 * g_int64_hash:
3567 * @v: a pointer to a #gint64 key
3569 * Converts a pointer to a #gint64 to a hash value.
3570 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3571 * when using pointers to 64-bit integers values as keys in a #GHashTable.
3573 * Returns: a hash value corresponding to the key.
3575 * Since: 2.22
3577 guint
3578 g_int64_hash (gconstpointer v)
3580 return (guint) *(const gint64*) v;
3584 * g_double_equal:
3585 * @v1: a pointer to a #gdouble key.
3586 * @v2: a pointer to a #gdouble key to compare with @v1.
3588 * Compares the two #gdouble values being pointed to and returns
3589 * %TRUE if they are equal.
3590 * It can be passed to g_hash_table_new() as the @key_equal_func
3591 * parameter, when using pointers to doubles as keys in a #GHashTable.
3593 * Returns: %TRUE if the two keys match.
3595 * Since: 2.22
3597 gboolean
3598 g_double_equal (gconstpointer v1,
3599 gconstpointer v2)
3601 return *((const gdouble*) v1) == *((const gdouble*) v2);
3605 * g_double_hash:
3606 * @v: a pointer to a #gdouble key
3608 * Converts a pointer to a #gdouble to a hash value.
3609 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3610 * when using pointers to doubles as keys in a #GHashTable.
3612 * Returns: a hash value corresponding to the key.
3614 * Since: 2.22
3616 guint
3617 g_double_hash (gconstpointer v)
3619 return (guint) *(const gdouble*) v;
3623 * g_nullify_pointer:
3624 * @nullify_location: the memory address of the pointer.
3626 * Set the pointer at the specified location to %NULL.
3628 void
3629 g_nullify_pointer (gpointer *nullify_location)
3631 g_return_if_fail (nullify_location != NULL);
3633 *nullify_location = NULL;
3637 * g_get_codeset:
3639 * Get the codeset for the current locale.
3641 * Return value: a newly allocated string containing the name
3642 * of the codeset. This string must be freed with g_free().
3644 gchar *
3645 g_get_codeset (void)
3647 const gchar *charset;
3649 g_get_charset (&charset);
3651 return g_strdup (charset);
3654 #ifdef G_OS_WIN32
3657 * _glib_get_locale_dir:
3659 * Return the path to the share\locale or lib\locale subfolder of the
3660 * GLib installation folder. The path is in the system codepage. We
3661 * have to use system codepage as bindtextdomain() doesn't have a
3662 * UTF-8 interface.
3664 gchar *
3665 _glib_get_locale_dir (void)
3667 gchar *install_dir = NULL, *locale_dir;
3668 gchar *retval = NULL;
3670 if (glib_dll != NULL)
3671 install_dir = g_win32_get_package_installation_directory_of_module (glib_dll);
3673 if (install_dir)
3676 * Append "/share/locale" or "/lib/locale" depending on whether
3677 * autoconfigury detected GNU gettext or not.
3679 const char *p = GLIB_LOCALE_DIR + strlen (GLIB_LOCALE_DIR);
3680 while (*--p != '/')
3682 while (*--p != '/')
3685 locale_dir = g_build_filename (install_dir, p, NULL);
3687 retval = g_win32_locale_filename_from_utf8 (locale_dir);
3689 g_free (install_dir);
3690 g_free (locale_dir);
3693 if (retval)
3694 return retval;
3695 else
3696 return g_strdup ("");
3699 #undef GLIB_LOCALE_DIR
3701 #endif /* G_OS_WIN32 */
3703 static void
3704 ensure_gettext_initialized (void)
3706 static gsize initialised;
3708 g_thread_init_glib ();
3710 if (g_once_init_enter (&initialised))
3712 #ifdef G_OS_WIN32
3713 gchar *tmp = _glib_get_locale_dir ();
3714 bindtextdomain (GETTEXT_PACKAGE, tmp);
3715 g_free (tmp);
3716 #else
3717 bindtextdomain (GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
3718 #endif
3719 # ifdef HAVE_BIND_TEXTDOMAIN_CODESET
3720 bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
3721 # endif
3722 g_once_init_leave (&initialised, TRUE);
3727 * glib_gettext:
3728 * @str: The string to be translated
3730 * Returns the translated string from the glib translations.
3731 * This is an internal function and should only be used by
3732 * the internals of glib (such as libgio).
3734 * Returns: the transation of @str to the current locale
3736 const gchar *
3737 glib_gettext (const gchar *str)
3739 ensure_gettext_initialized();
3741 return g_dgettext (GETTEXT_PACKAGE, str);
3745 * glib_pgettext:
3746 * @msgctxtid: a combined message context and message id, separated
3747 * by a \004 character
3748 * @msgidoffset: the offset of the message id in @msgctxid
3750 * This function is a variant of glib_gettext() which supports
3751 * a disambiguating message context. See g_dpgettext() for full
3752 * details.
3754 * This is an internal function and should only be used by
3755 * the internals of glib (such as libgio).
3757 * Returns: the transation of @str to the current locale
3759 const gchar *
3760 glib_pgettext(const gchar *msgctxtid,
3761 gsize msgidoffset)
3763 ensure_gettext_initialized();
3765 return g_dpgettext (GETTEXT_PACKAGE, msgctxtid, msgidoffset);
3768 #if defined (G_OS_WIN32) && !defined (_WIN64)
3770 /* Binary compatibility versions. Not for newly compiled code. */
3772 #undef g_find_program_in_path
3774 gchar*
3775 g_find_program_in_path (const gchar *program)
3777 gchar *utf8_program = g_locale_to_utf8 (program, -1, NULL, NULL, NULL);
3778 gchar *utf8_retval = g_find_program_in_path_utf8 (utf8_program);
3779 gchar *retval;
3781 g_free (utf8_program);
3782 if (utf8_retval == NULL)
3783 return NULL;
3784 retval = g_locale_from_utf8 (utf8_retval, -1, NULL, NULL, NULL);
3785 g_free (utf8_retval);
3787 return retval;
3790 #undef g_get_current_dir
3792 gchar*
3793 g_get_current_dir (void)
3795 gchar *utf8_dir = g_get_current_dir_utf8 ();
3796 gchar *dir = g_locale_from_utf8 (utf8_dir, -1, NULL, NULL, NULL);
3797 g_free (utf8_dir);
3798 return dir;
3801 #undef g_getenv
3803 const gchar *
3804 g_getenv (const gchar *variable)
3806 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3807 const gchar *utf8_value = g_getenv_utf8 (utf8_variable);
3808 gchar *value;
3809 GQuark quark;
3811 g_free (utf8_variable);
3812 if (!utf8_value)
3813 return NULL;
3814 value = g_locale_from_utf8 (utf8_value, -1, NULL, NULL, NULL);
3815 quark = g_quark_from_string (value);
3816 g_free (value);
3818 return g_quark_to_string (quark);
3821 #undef g_setenv
3823 gboolean
3824 g_setenv (const gchar *variable,
3825 const gchar *value,
3826 gboolean overwrite)
3828 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3829 gchar *utf8_value = g_locale_to_utf8 (value, -1, NULL, NULL, NULL);
3830 gboolean retval = g_setenv_utf8 (utf8_variable, utf8_value, overwrite);
3832 g_free (utf8_variable);
3833 g_free (utf8_value);
3835 return retval;
3838 #undef g_unsetenv
3840 void
3841 g_unsetenv (const gchar *variable)
3843 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3845 g_unsetenv_utf8 (utf8_variable);
3847 g_free (utf8_variable);
3850 #undef g_get_user_name
3852 const gchar *
3853 g_get_user_name (void)
3855 g_get_any_init_locked ();
3856 return g_user_name_cp;
3859 #undef g_get_real_name
3861 const gchar *
3862 g_get_real_name (void)
3864 g_get_any_init_locked ();
3865 return g_real_name_cp;
3868 #undef g_get_home_dir
3870 const gchar *
3871 g_get_home_dir (void)
3873 g_get_any_init_locked ();
3874 return g_home_dir_cp;
3877 #undef g_get_tmp_dir
3879 const gchar *
3880 g_get_tmp_dir (void)
3882 g_get_any_init_locked ();
3883 return g_tmp_dir_cp;
3886 #endif