Make _g_compute_locale_variants return a char** directly
[glib.git] / glib / gutils.c
blob3e01dae2275cdd9ef523137acd7bf766cbff579e
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 #include "config.h"
33 #ifdef HAVE_UNISTD_H
34 #include <unistd.h>
35 #endif
36 #include <stdarg.h>
37 #include <stdlib.h>
38 #include <stdio.h>
39 #include <locale.h>
40 #include <string.h>
41 #include <ctype.h> /* For tolower() */
42 #include <errno.h>
43 #include <sys/types.h>
44 #include <sys/stat.h>
45 #ifdef HAVE_PWD_H
46 #include <pwd.h>
47 #endif
48 #include <sys/types.h>
49 #ifdef HAVE_SYS_PARAM_H
50 #include <sys/param.h>
51 #endif
52 #ifdef HAVE_CRT_EXTERNS_H
53 #include <crt_externs.h> /* for _NSGetEnviron */
54 #endif
56 /* implement gutils's inline functions
58 #define G_IMPLEMENT_INLINES 1
59 #define __G_UTILS_C__
60 #include "gutils.h"
62 #include "gfileutils.h"
63 #include "ghash.h"
64 #include "gslist.h"
65 #include "gprintfint.h"
66 #include "gthread.h"
67 #include "gthreadprivate.h"
68 #include "gtestutils.h"
69 #include "gunicode.h"
70 #include "gstrfuncs.h"
71 #include "garray.h"
72 #include "glibintl.h"
74 #ifdef G_PLATFORM_WIN32
75 #include "garray.h"
76 #include "gconvert.h"
77 #include "gwin32.h"
78 #endif
80 #ifdef MAXPATHLEN
81 #define G_PATH_LENGTH MAXPATHLEN
82 #elif defined (PATH_MAX)
83 #define G_PATH_LENGTH PATH_MAX
84 #elif defined (_PC_PATH_MAX)
85 #define G_PATH_LENGTH sysconf(_PC_PATH_MAX)
86 #else
87 #define G_PATH_LENGTH 2048
88 #endif
90 #ifdef G_PLATFORM_WIN32
91 # define STRICT /* Strict typing, please */
92 # include <windows.h>
93 # undef STRICT
94 # ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
95 # define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2
96 # define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4
97 # endif
98 # include <lmcons.h> /* For UNLEN */
99 #endif /* G_PLATFORM_WIN32 */
101 #ifdef G_OS_WIN32
102 # include <direct.h>
103 # include <shlobj.h>
104 /* older SDK (e.g. msvc 5.0) does not have these*/
105 # ifndef CSIDL_MYMUSIC
106 # define CSIDL_MYMUSIC 13
107 # endif
108 # ifndef CSIDL_MYVIDEO
109 # define CSIDL_MYVIDEO 14
110 # endif
111 # ifndef CSIDL_INTERNET_CACHE
112 # define CSIDL_INTERNET_CACHE 32
113 # endif
114 # ifndef CSIDL_COMMON_APPDATA
115 # define CSIDL_COMMON_APPDATA 35
116 # endif
117 # ifndef CSIDL_MYPICTURES
118 # define CSIDL_MYPICTURES 0x27
119 # endif
120 # ifndef CSIDL_COMMON_DOCUMENTS
121 # define CSIDL_COMMON_DOCUMENTS 46
122 # endif
123 # ifndef CSIDL_PROFILE
124 # define CSIDL_PROFILE 40
125 # endif
126 # include <process.h>
127 #endif
129 #ifdef HAVE_CARBON
130 #include <CoreServices/CoreServices.h>
131 #endif
133 #ifdef HAVE_CODESET
134 #include <langinfo.h>
135 #endif
137 const guint glib_major_version = GLIB_MAJOR_VERSION;
138 const guint glib_minor_version = GLIB_MINOR_VERSION;
139 const guint glib_micro_version = GLIB_MICRO_VERSION;
140 const guint glib_interface_age = GLIB_INTERFACE_AGE;
141 const guint glib_binary_age = GLIB_BINARY_AGE;
143 #ifdef G_PLATFORM_WIN32
145 static HMODULE glib_dll = NULL;
147 #ifdef DLL_EXPORT
149 BOOL WINAPI
150 DllMain (HINSTANCE hinstDLL,
151 DWORD fdwReason,
152 LPVOID lpvReserved)
154 if (fdwReason == DLL_PROCESS_ATTACH)
155 glib_dll = hinstDLL;
157 return TRUE;
160 #endif
162 gchar *
163 _glib_get_dll_directory (void)
165 gchar *retval;
166 gchar *p;
167 wchar_t wc_fn[MAX_PATH];
169 #ifdef DLL_EXPORT
170 if (glib_dll == NULL)
171 return NULL;
172 #endif
174 /* This code is different from that in
175 * g_win32_get_package_installation_directory_of_module() in that
176 * here we return the actual folder where the GLib DLL is. We don't
177 * do the check for it being in a "bin" or "lib" subfolder and then
178 * returning the parent of that.
180 * In a statically built GLib, glib_dll will be NULL and we will
181 * thus look up the application's .exe file's location.
183 if (!GetModuleFileNameW (glib_dll, wc_fn, MAX_PATH))
184 return NULL;
186 retval = g_utf16_to_utf8 (wc_fn, -1, NULL, NULL, NULL);
188 p = strrchr (retval, G_DIR_SEPARATOR);
189 if (p == NULL)
191 /* Wtf? */
192 return NULL;
194 *p = '\0';
196 return retval;
199 #endif
202 * glib_check_version:
203 * @required_major: the required major version.
204 * @required_minor: the required minor version.
205 * @required_micro: the required micro version.
207 * Checks that the GLib library in use is compatible with the
208 * given version. Generally you would pass in the constants
209 * #GLIB_MAJOR_VERSION, #GLIB_MINOR_VERSION, #GLIB_MICRO_VERSION
210 * as the three arguments to this function; that produces
211 * a check that the library in use is compatible with
212 * the version of GLib the application or module was compiled
213 * against.
215 * Compatibility is defined by two things: first the version
216 * of the running library is newer than the version
217 * @required_major.required_minor.@required_micro. Second
218 * the running library must be binary compatible with the
219 * version @required_major.required_minor.@required_micro
220 * (same major version.)
222 * Return value: %NULL if the GLib library is compatible with the
223 * given version, or a string describing the version mismatch.
224 * The returned string is owned by GLib and must not be modified
225 * or freed.
227 * Since: 2.6
229 const gchar *
230 glib_check_version (guint required_major,
231 guint required_minor,
232 guint required_micro)
234 gint glib_effective_micro = 100 * GLIB_MINOR_VERSION + GLIB_MICRO_VERSION;
235 gint required_effective_micro = 100 * required_minor + required_micro;
237 if (required_major > GLIB_MAJOR_VERSION)
238 return "GLib version too old (major mismatch)";
239 if (required_major < GLIB_MAJOR_VERSION)
240 return "GLib version too new (major mismatch)";
241 if (required_effective_micro < glib_effective_micro - GLIB_BINARY_AGE)
242 return "GLib version too new (micro mismatch)";
243 if (required_effective_micro > glib_effective_micro)
244 return "GLib version too old (micro mismatch)";
245 return NULL;
248 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
250 * g_memmove:
251 * @dest: the destination address to copy the bytes to.
252 * @src: the source address to copy the bytes from.
253 * @len: the number of bytes to copy.
255 * Copies a block of memory @len bytes long, from @src to @dest.
256 * The source and destination areas may overlap.
258 * In order to use this function, you must include
259 * <filename>string.h</filename> yourself, because this macro will
260 * typically simply resolve to memmove() and GLib does not include
261 * <filename>string.h</filename> for you.
263 void
264 g_memmove (gpointer dest,
265 gconstpointer src,
266 gulong len)
268 gchar* destptr = dest;
269 const gchar* srcptr = src;
270 if (src + len < dest || dest + len < src)
272 bcopy (src, dest, len);
273 return;
275 else if (dest <= src)
277 while (len--)
278 *(destptr++) = *(srcptr++);
280 else
282 destptr += len;
283 srcptr += len;
284 while (len--)
285 *(--destptr) = *(--srcptr);
288 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
290 #ifdef G_OS_WIN32
291 #undef g_atexit
292 #endif
295 * g_atexit:
296 * @func: the function to call on normal program termination.
298 * Specifies a function to be called at normal program termination.
300 * Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
301 * macro that maps to a call to the atexit() function in the C
302 * library. This means that in case the code that calls g_atexit(),
303 * i.e. atexit(), is in a DLL, the function will be called when the
304 * DLL is detached from the program. This typically makes more sense
305 * than that the function is called when the GLib DLL is detached,
306 * which happened earlier when g_atexit() was a function in the GLib
307 * DLL.
309 * The behaviour of atexit() in the context of dynamically loaded
310 * modules is not formally specified and varies wildly.
312 * On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
313 * loaded module which is unloaded before the program terminates might
314 * well cause a crash at program exit.
316 * Some POSIX systems implement atexit() like Windows, and have each
317 * dynamically loaded module maintain an own atexit chain that is
318 * called when the module is unloaded.
320 * On other POSIX systems, before a dynamically loaded module is
321 * unloaded, the registered atexit functions (if any) residing in that
322 * module are called, regardless where the code that registered them
323 * resided. This is presumably the most robust approach.
325 * As can be seen from the above, for portability it's best to avoid
326 * calling g_atexit() (or atexit()) except in the main executable of a
327 * program.
329 void
330 g_atexit (GVoidFunc func)
332 gint result;
333 const gchar *error = NULL;
335 /* keep this in sync with glib.h */
337 #ifdef G_NATIVE_ATEXIT
338 result = ATEXIT (func);
339 if (result)
340 error = g_strerror (errno);
341 #elif defined (HAVE_ATEXIT)
342 # ifdef NeXT /* @#%@! NeXTStep */
343 result = !atexit ((void (*)(void)) func);
344 if (result)
345 error = g_strerror (errno);
346 # else
347 result = atexit ((void (*)(void)) func);
348 if (result)
349 error = g_strerror (errno);
350 # endif /* NeXT */
351 #elif defined (HAVE_ON_EXIT)
352 result = on_exit ((void (*)(int, void *)) func, NULL);
353 if (result)
354 error = g_strerror (errno);
355 #else
356 result = 0;
357 error = "no implementation";
358 #endif /* G_NATIVE_ATEXIT */
360 if (error)
361 g_error ("Could not register atexit() function: %s", error);
364 /* Based on execvp() from GNU Libc.
365 * Some of this code is cut-and-pasted into gspawn.c
368 static gchar*
369 my_strchrnul (const gchar *str,
370 gchar c)
372 gchar *p = (gchar*)str;
373 while (*p && (*p != c))
374 ++p;
376 return p;
379 #ifdef G_OS_WIN32
381 static gchar *inner_find_program_in_path (const gchar *program);
383 gchar*
384 g_find_program_in_path (const gchar *program)
386 const gchar *last_dot = strrchr (program, '.');
388 if (last_dot == NULL ||
389 strchr (last_dot, '\\') != NULL ||
390 strchr (last_dot, '/') != NULL)
392 const gint program_length = strlen (program);
393 gchar *pathext = g_build_path (";",
394 ".exe;.cmd;.bat;.com",
395 g_getenv ("PATHEXT"),
396 NULL);
397 gchar *p;
398 gchar *decorated_program;
399 gchar *retval;
401 p = pathext;
404 gchar *q = my_strchrnul (p, ';');
406 decorated_program = g_malloc (program_length + (q-p) + 1);
407 memcpy (decorated_program, program, program_length);
408 memcpy (decorated_program+program_length, p, q-p);
409 decorated_program [program_length + (q-p)] = '\0';
411 retval = inner_find_program_in_path (decorated_program);
412 g_free (decorated_program);
414 if (retval != NULL)
416 g_free (pathext);
417 return retval;
419 p = q;
420 } while (*p++ != '\0');
421 g_free (pathext);
422 return NULL;
424 else
425 return inner_find_program_in_path (program);
428 #endif
431 * g_find_program_in_path:
432 * @program: a program name in the GLib file name encoding
434 * Locates the first executable named @program in the user's path, in the
435 * same way that execvp() would locate it. Returns an allocated string
436 * with the absolute path name, or %NULL if the program is not found in
437 * the path. If @program is already an absolute path, returns a copy of
438 * @program if @program exists and is executable, and %NULL otherwise.
440 * On Windows, if @program does not have a file type suffix, tries
441 * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
442 * the <envar>PATHEXT</envar> environment variable.
444 * On Windows, it looks for the file in the same way as CreateProcess()
445 * would. This means first in the directory where the executing
446 * program was loaded from, then in the current directory, then in the
447 * Windows 32-bit system directory, then in the Windows directory, and
448 * finally in the directories in the <envar>PATH</envar> environment
449 * variable. If the program is found, the return value contains the
450 * full name including the type suffix.
452 * Return value: absolute path, or %NULL
454 #ifdef G_OS_WIN32
455 static gchar *
456 inner_find_program_in_path (const gchar *program)
457 #else
458 gchar*
459 g_find_program_in_path (const gchar *program)
460 #endif
462 const gchar *path, *p;
463 gchar *name, *freeme;
464 #ifdef G_OS_WIN32
465 const gchar *path_copy;
466 gchar *filename = NULL, *appdir = NULL;
467 gchar *sysdir = NULL, *windir = NULL;
468 int n;
469 wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
470 wwindir[MAXPATHLEN];
471 #endif
472 gsize len;
473 gsize pathlen;
475 g_return_val_if_fail (program != NULL, NULL);
477 /* If it is an absolute path, or a relative path including subdirectories,
478 * don't look in PATH.
480 if (g_path_is_absolute (program)
481 || strchr (program, G_DIR_SEPARATOR) != NULL
482 #ifdef G_OS_WIN32
483 || strchr (program, '/') != NULL
484 #endif
487 if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
488 !g_file_test (program, G_FILE_TEST_IS_DIR))
489 return g_strdup (program);
490 else
491 return NULL;
494 path = g_getenv ("PATH");
495 #if defined(G_OS_UNIX) || defined(G_OS_BEOS)
496 if (path == NULL)
498 /* There is no `PATH' in the environment. The default
499 * search path in GNU libc is the current directory followed by
500 * the path `confstr' returns for `_CS_PATH'.
503 /* In GLib we put . last, for security, and don't use the
504 * unportable confstr(); UNIX98 does not actually specify
505 * what to search if PATH is unset. POSIX may, dunno.
508 path = "/bin:/usr/bin:.";
510 #else
511 n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
512 if (n > 0 && n < MAXPATHLEN)
513 filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
515 n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
516 if (n > 0 && n < MAXPATHLEN)
517 sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
519 n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
520 if (n > 0 && n < MAXPATHLEN)
521 windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
523 if (filename)
525 appdir = g_path_get_dirname (filename);
526 g_free (filename);
529 path = g_strdup (path);
531 if (windir)
533 const gchar *tem = path;
534 path = g_strconcat (windir, ";", path, NULL);
535 g_free ((gchar *) tem);
536 g_free (windir);
539 if (sysdir)
541 const gchar *tem = path;
542 path = g_strconcat (sysdir, ";", path, NULL);
543 g_free ((gchar *) tem);
544 g_free (sysdir);
548 const gchar *tem = path;
549 path = g_strconcat (".;", path, NULL);
550 g_free ((gchar *) tem);
553 if (appdir)
555 const gchar *tem = path;
556 path = g_strconcat (appdir, ";", path, NULL);
557 g_free ((gchar *) tem);
558 g_free (appdir);
561 path_copy = path;
562 #endif
564 len = strlen (program) + 1;
565 pathlen = strlen (path);
566 freeme = name = g_malloc (pathlen + len + 1);
568 /* Copy the file name at the top, including '\0' */
569 memcpy (name + pathlen + 1, program, len);
570 name = name + pathlen;
571 /* And add the slash before the filename */
572 *name = G_DIR_SEPARATOR;
574 p = path;
577 char *startp;
579 path = p;
580 p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
582 if (p == path)
583 /* Two adjacent colons, or a colon at the beginning or the end
584 * of `PATH' means to search the current directory.
586 startp = name + 1;
587 else
588 startp = memcpy (name - (p - path), path, p - path);
590 if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
591 !g_file_test (startp, G_FILE_TEST_IS_DIR))
593 gchar *ret;
594 ret = g_strdup (startp);
595 g_free (freeme);
596 #ifdef G_OS_WIN32
597 g_free ((gchar *) path_copy);
598 #endif
599 return ret;
602 while (*p++ != '\0');
604 g_free (freeme);
605 #ifdef G_OS_WIN32
606 g_free ((gchar *) path_copy);
607 #endif
609 return NULL;
612 static gboolean
613 debug_key_matches (const gchar *key,
614 const gchar *token,
615 guint length)
617 for (; length; length--, key++, token++)
619 char k = (*key == '_') ? '-' : tolower (*key );
620 char t = (*token == '_') ? '-' : tolower (*token);
622 if (k != t)
623 return FALSE;
626 return *key == '\0';
630 * g_parse_debug_string:
631 * @string: a list of debug options separated by colons, spaces, or
632 * commas, or %NULL.
633 * @keys: pointer to an array of #GDebugKey which associate
634 * strings with bit flags.
635 * @nkeys: the number of #GDebugKey<!-- -->s in the array.
637 * Parses a string containing debugging options
638 * into a %guint containing bit flags. This is used
639 * within GDK and GTK+ to parse the debug options passed on the
640 * command line or through environment variables.
642 * If @string is equal to "all", all flags are set. If @string
643 * is equal to "help", all the available keys in @keys are printed
644 * out to standard error.
646 * Returns: the combined set of bit flags.
648 guint
649 g_parse_debug_string (const gchar *string,
650 const GDebugKey *keys,
651 guint nkeys)
653 guint i;
654 guint result = 0;
656 if (string == NULL)
657 return 0;
659 /* this function is used by gmem.c/gslice.c initialization code,
660 * so introducing malloc dependencies here would require adaptions
661 * of those code portions.
664 if (!g_ascii_strcasecmp (string, "all"))
666 for (i=0; i<nkeys; i++)
667 result |= keys[i].value;
669 else if (!g_ascii_strcasecmp (string, "help"))
671 /* using stdio directly for the reason stated above */
672 fprintf (stderr, "Supported debug values: ");
673 for (i=0; i<nkeys; i++)
674 fprintf (stderr, " %s", keys[i].key);
675 fprintf (stderr, "\n");
677 else
679 const gchar *p = string;
680 const gchar *q;
682 while (*p)
684 q = strpbrk (p, ":;, \t");
685 if (!q)
686 q = p + strlen(p);
688 for (i = 0; i < nkeys; i++)
689 if (debug_key_matches (keys[i].key, p, q - p))
690 result |= keys[i].value;
692 p = q;
693 if (*p)
694 p++;
698 return result;
702 * g_basename:
703 * @file_name: the name of the file.
705 * Gets the name of the file without any leading directory components.
706 * It returns a pointer into the given file name string.
708 * Return value: the name of the file without any leading directory components.
710 * Deprecated:2.2: Use g_path_get_basename() instead, but notice that
711 * g_path_get_basename() allocates new memory for the returned string, unlike
712 * this function which returns a pointer into the argument.
714 G_CONST_RETURN gchar*
715 g_basename (const gchar *file_name)
717 register gchar *base;
719 g_return_val_if_fail (file_name != NULL, NULL);
721 base = strrchr (file_name, G_DIR_SEPARATOR);
723 #ifdef G_OS_WIN32
725 gchar *q = strrchr (file_name, '/');
726 if (base == NULL || (q != NULL && q > base))
727 base = q;
729 #endif
731 if (base)
732 return base + 1;
734 #ifdef G_OS_WIN32
735 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
736 return (gchar*) file_name + 2;
737 #endif /* G_OS_WIN32 */
739 return (gchar*) file_name;
743 * g_path_get_basename:
744 * @file_name: the name of the file.
746 * Gets the last component of the filename. If @file_name ends with a
747 * directory separator it gets the component before the last slash. If
748 * @file_name consists only of directory separators (and on Windows,
749 * possibly a drive letter), a single separator is returned. If
750 * @file_name is empty, it gets ".".
752 * Return value: a newly allocated string containing the last component of
753 * the filename.
755 gchar*
756 g_path_get_basename (const gchar *file_name)
758 register gssize base;
759 register gssize last_nonslash;
760 gsize len;
761 gchar *retval;
763 g_return_val_if_fail (file_name != NULL, NULL);
765 if (file_name[0] == '\0')
766 /* empty string */
767 return g_strdup (".");
769 last_nonslash = strlen (file_name) - 1;
771 while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
772 last_nonslash--;
774 if (last_nonslash == -1)
775 /* string only containing slashes */
776 return g_strdup (G_DIR_SEPARATOR_S);
778 #ifdef G_OS_WIN32
779 if (last_nonslash == 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
780 /* string only containing slashes and a drive */
781 return g_strdup (G_DIR_SEPARATOR_S);
782 #endif /* G_OS_WIN32 */
784 base = last_nonslash;
786 while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
787 base--;
789 #ifdef G_OS_WIN32
790 if (base == -1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
791 base = 1;
792 #endif /* G_OS_WIN32 */
794 len = last_nonslash - base;
795 retval = g_malloc (len + 1);
796 memcpy (retval, file_name + base + 1, len);
797 retval [len] = '\0';
798 return retval;
802 * g_path_is_absolute:
803 * @file_name: a file name.
805 * Returns %TRUE if the given @file_name is an absolute file name.
806 * Note that this is a somewhat vague concept on Windows.
808 * On POSIX systems, an absolute file name is well-defined. It always
809 * starts from the single root directory. For example "/usr/local".
811 * On Windows, the concepts of current drive and drive-specific
812 * current directory introduce vagueness. This function interprets as
813 * an absolute file name one that either begins with a directory
814 * separator such as "\Users\tml" or begins with the root on a drive,
815 * for example "C:\Windows". The first case also includes UNC paths
816 * such as "\\myserver\docs\foo". In all cases, either slashes or
817 * backslashes are accepted.
819 * Note that a file name relative to the current drive root does not
820 * truly specify a file uniquely over time and across processes, as
821 * the current drive is a per-process value and can be changed.
823 * File names relative the current directory on some specific drive,
824 * such as "D:foo/bar", are not interpreted as absolute by this
825 * function, but they obviously are not relative to the normal current
826 * directory as returned by getcwd() or g_get_current_dir()
827 * either. Such paths should be avoided, or need to be handled using
828 * Windows-specific code.
830 * Returns: %TRUE if @file_name is absolute.
832 gboolean
833 g_path_is_absolute (const gchar *file_name)
835 g_return_val_if_fail (file_name != NULL, FALSE);
837 if (G_IS_DIR_SEPARATOR (file_name[0]))
838 return TRUE;
840 #ifdef G_OS_WIN32
841 /* Recognize drive letter on native Windows */
842 if (g_ascii_isalpha (file_name[0]) &&
843 file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
844 return TRUE;
845 #endif /* G_OS_WIN32 */
847 return FALSE;
851 * g_path_skip_root:
852 * @file_name: a file name.
854 * Returns a pointer into @file_name after the root component, i.e. after
855 * the "/" in UNIX or "C:\" under Windows. If @file_name is not an absolute
856 * path it returns %NULL.
858 * Returns: a pointer into @file_name after the root component.
860 G_CONST_RETURN gchar*
861 g_path_skip_root (const gchar *file_name)
863 g_return_val_if_fail (file_name != NULL, NULL);
865 #ifdef G_PLATFORM_WIN32
866 /* Skip \\server\share or //server/share */
867 if (G_IS_DIR_SEPARATOR (file_name[0]) &&
868 G_IS_DIR_SEPARATOR (file_name[1]) &&
869 file_name[2] &&
870 !G_IS_DIR_SEPARATOR (file_name[2]))
872 gchar *p;
874 p = strchr (file_name + 2, G_DIR_SEPARATOR);
875 #ifdef G_OS_WIN32
877 gchar *q = strchr (file_name + 2, '/');
878 if (p == NULL || (q != NULL && q < p))
879 p = q;
881 #endif
882 if (p &&
883 p > file_name + 2 &&
884 p[1])
886 file_name = p + 1;
888 while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
889 file_name++;
891 /* Possibly skip a backslash after the share name */
892 if (G_IS_DIR_SEPARATOR (file_name[0]))
893 file_name++;
895 return (gchar *)file_name;
898 #endif
900 /* Skip initial slashes */
901 if (G_IS_DIR_SEPARATOR (file_name[0]))
903 while (G_IS_DIR_SEPARATOR (file_name[0]))
904 file_name++;
905 return (gchar *)file_name;
908 #ifdef G_OS_WIN32
909 /* Skip X:\ */
910 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
911 return (gchar *)file_name + 3;
912 #endif
914 return NULL;
918 * g_path_get_dirname:
919 * @file_name: the name of the file.
921 * Gets the directory components of a file name. If the file name has no
922 * directory components "." is returned. The returned string should be
923 * freed when no longer needed.
925 * Returns: the directory components of the file.
927 gchar*
928 g_path_get_dirname (const gchar *file_name)
930 register gchar *base;
931 register gsize len;
933 g_return_val_if_fail (file_name != NULL, NULL);
935 base = strrchr (file_name, G_DIR_SEPARATOR);
936 #ifdef G_OS_WIN32
938 gchar *q = strrchr (file_name, '/');
939 if (base == NULL || (q != NULL && q > base))
940 base = q;
942 #endif
943 if (!base)
945 #ifdef G_OS_WIN32
946 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
948 gchar drive_colon_dot[4];
950 drive_colon_dot[0] = file_name[0];
951 drive_colon_dot[1] = ':';
952 drive_colon_dot[2] = '.';
953 drive_colon_dot[3] = '\0';
955 return g_strdup (drive_colon_dot);
957 #endif
958 return g_strdup (".");
961 while (base > file_name && G_IS_DIR_SEPARATOR (*base))
962 base--;
964 #ifdef G_OS_WIN32
965 /* base points to the char before the last slash.
967 * In case file_name is the root of a drive (X:\) or a child of the
968 * root of a drive (X:\foo), include the slash.
970 * In case file_name is the root share of an UNC path
971 * (\\server\share), add a slash, returning \\server\share\ .
973 * In case file_name is a direct child of a share in an UNC path
974 * (\\server\share\foo), include the slash after the share name,
975 * returning \\server\share\ .
977 if (base == file_name + 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
978 base++;
979 else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
980 G_IS_DIR_SEPARATOR (file_name[1]) &&
981 file_name[2] &&
982 !G_IS_DIR_SEPARATOR (file_name[2]) &&
983 base >= file_name + 2)
985 const gchar *p = file_name + 2;
986 while (*p && !G_IS_DIR_SEPARATOR (*p))
987 p++;
988 if (p == base + 1)
990 len = (guint) strlen (file_name) + 1;
991 base = g_new (gchar, len + 1);
992 strcpy (base, file_name);
993 base[len-1] = G_DIR_SEPARATOR;
994 base[len] = 0;
995 return base;
997 if (G_IS_DIR_SEPARATOR (*p))
999 p++;
1000 while (*p && !G_IS_DIR_SEPARATOR (*p))
1001 p++;
1002 if (p == base + 1)
1003 base++;
1006 #endif
1008 len = (guint) 1 + base - file_name;
1010 base = g_new (gchar, len + 1);
1011 g_memmove (base, file_name, len);
1012 base[len] = 0;
1014 return base;
1018 * g_get_current_dir:
1020 * Gets the current directory.
1021 * The returned string should be freed when no longer needed. The encoding
1022 * of the returned string is system defined. On Windows, it is always UTF-8.
1024 * Returns: the current directory.
1026 gchar*
1027 g_get_current_dir (void)
1029 #ifdef G_OS_WIN32
1031 gchar *dir = NULL;
1032 wchar_t dummy[2], *wdir;
1033 int len;
1035 len = GetCurrentDirectoryW (2, dummy);
1036 wdir = g_new (wchar_t, len);
1038 if (GetCurrentDirectoryW (len, wdir) == len - 1)
1039 dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
1041 g_free (wdir);
1043 if (dir == NULL)
1044 dir = g_strdup ("\\");
1046 return dir;
1048 #else
1050 gchar *buffer = NULL;
1051 gchar *dir = NULL;
1052 static gulong max_len = 0;
1054 if (max_len == 0)
1055 max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
1057 /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
1058 * and, if that wasn't bad enough, hangs in doing so.
1060 #if (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
1061 buffer = g_new (gchar, max_len + 1);
1062 *buffer = 0;
1063 dir = getwd (buffer);
1064 #else /* !sun || !HAVE_GETCWD */
1065 while (max_len < G_MAXULONG / 2)
1067 g_free (buffer);
1068 buffer = g_new (gchar, max_len + 1);
1069 *buffer = 0;
1070 dir = getcwd (buffer, max_len);
1072 if (dir || errno != ERANGE)
1073 break;
1075 max_len *= 2;
1077 #endif /* !sun || !HAVE_GETCWD */
1079 if (!dir || !*buffer)
1081 /* hm, should we g_error() out here?
1082 * this can happen if e.g. "./" has mode \0000
1084 buffer[0] = G_DIR_SEPARATOR;
1085 buffer[1] = 0;
1088 dir = g_strdup (buffer);
1089 g_free (buffer);
1091 return dir;
1092 #endif /* !Win32 */
1096 * g_getenv:
1097 * @variable: the environment variable to get, in the GLib file name encoding.
1099 * Returns the value of an environment variable. The name and value
1100 * are in the GLib file name encoding. On UNIX, this means the actual
1101 * bytes which might or might not be in some consistent character set
1102 * and encoding. On Windows, it is in UTF-8. On Windows, in case the
1103 * environment variable's value contains references to other
1104 * environment variables, they are expanded.
1106 * Return value: the value of the environment variable, or %NULL if
1107 * the environment variable is not found. The returned string may be
1108 * overwritten by the next call to g_getenv(), g_setenv() or
1109 * g_unsetenv().
1111 G_CONST_RETURN gchar*
1112 g_getenv (const gchar *variable)
1114 #ifndef G_OS_WIN32
1116 g_return_val_if_fail (variable != NULL, NULL);
1118 return getenv (variable);
1120 #else /* G_OS_WIN32 */
1122 GQuark quark;
1123 gchar *value;
1124 wchar_t dummy[2], *wname, *wvalue;
1125 int len;
1127 g_return_val_if_fail (variable != NULL, NULL);
1128 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), NULL);
1130 /* On Windows NT, it is relatively typical that environment
1131 * variables contain references to other environment variables. If
1132 * so, use ExpandEnvironmentStrings(). (In an ideal world, such
1133 * environment variables would be stored in the Registry as
1134 * REG_EXPAND_SZ type values, and would then get automatically
1135 * expanded before a program sees them. But there is broken software
1136 * that stores environment variables as REG_SZ values even if they
1137 * contain references to other environment variables.)
1140 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1142 len = GetEnvironmentVariableW (wname, dummy, 2);
1144 if (len == 0)
1146 g_free (wname);
1147 return NULL;
1149 else if (len == 1)
1150 len = 2;
1152 wvalue = g_new (wchar_t, len);
1154 if (GetEnvironmentVariableW (wname, wvalue, len) != len - 1)
1156 g_free (wname);
1157 g_free (wvalue);
1158 return NULL;
1161 if (wcschr (wvalue, L'%') != NULL)
1163 wchar_t *tem = wvalue;
1165 len = ExpandEnvironmentStringsW (wvalue, dummy, 2);
1167 if (len > 0)
1169 wvalue = g_new (wchar_t, len);
1171 if (ExpandEnvironmentStringsW (tem, wvalue, len) != len)
1173 g_free (wvalue);
1174 wvalue = tem;
1176 else
1177 g_free (tem);
1181 value = g_utf16_to_utf8 (wvalue, -1, NULL, NULL, NULL);
1183 g_free (wname);
1184 g_free (wvalue);
1186 quark = g_quark_from_string (value);
1187 g_free (value);
1189 return g_quark_to_string (quark);
1191 #endif /* G_OS_WIN32 */
1194 /* _g_getenv_nomalloc
1195 * this function does a getenv() without doing any kind of allocation
1196 * through glib. it's suitable for chars <= 127 only (both, for the
1197 * variable name and the contents) and for contents < 1024 chars in
1198 * length. also, it aliases "" to a NULL return value.
1200 const gchar*
1201 _g_getenv_nomalloc (const gchar *variable,
1202 gchar buffer[1024])
1204 const gchar *retval = getenv (variable);
1205 if (retval && retval[0])
1207 gint l = strlen (retval);
1208 if (l < 1024)
1210 strncpy (buffer, retval, l);
1211 buffer[l] = 0;
1212 return buffer;
1215 return NULL;
1219 * g_setenv:
1220 * @variable: the environment variable to set, must not contain '='.
1221 * @value: the value for to set the variable to.
1222 * @overwrite: whether to change the variable if it already exists.
1224 * Sets an environment variable. Both the variable's name and value
1225 * should be in the GLib file name encoding. On UNIX, this means that
1226 * they can be any sequence of bytes. On Windows, they should be in
1227 * UTF-8.
1229 * Note that on some systems, when variables are overwritten, the memory
1230 * used for the previous variables and its value isn't reclaimed.
1232 * Returns: %FALSE if the environment variable couldn't be set.
1234 * Since: 2.4
1236 gboolean
1237 g_setenv (const gchar *variable,
1238 const gchar *value,
1239 gboolean overwrite)
1241 #ifndef G_OS_WIN32
1243 gint result;
1244 #ifndef HAVE_SETENV
1245 gchar *string;
1246 #endif
1248 g_return_val_if_fail (variable != NULL, FALSE);
1249 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1251 #ifdef HAVE_SETENV
1252 result = setenv (variable, value, overwrite);
1253 #else
1254 if (!overwrite && getenv (variable) != NULL)
1255 return TRUE;
1257 /* This results in a leak when you overwrite existing
1258 * settings. It would be fairly easy to fix this by keeping
1259 * our own parallel array or hash table.
1261 string = g_strconcat (variable, "=", value, NULL);
1262 result = putenv (string);
1263 #endif
1264 return result == 0;
1266 #else /* G_OS_WIN32 */
1268 gboolean retval;
1269 wchar_t *wname, *wvalue, *wassignment;
1270 gchar *tem;
1272 g_return_val_if_fail (variable != NULL, FALSE);
1273 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1274 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), FALSE);
1275 g_return_val_if_fail (g_utf8_validate (value, -1, NULL), FALSE);
1277 if (!overwrite && g_getenv (variable) != NULL)
1278 return TRUE;
1280 /* We want to (if possible) set both the environment variable copy
1281 * kept by the C runtime and the one kept by the system.
1283 * We can't use only the C runtime's putenv or _wputenv() as that
1284 * won't work for arbitrary Unicode strings in a "non-Unicode" app
1285 * (with main() and not wmain()). In a "main()" app the C runtime
1286 * initializes the C runtime's environment table by converting the
1287 * real (wide char) environment variables to system codepage, thus
1288 * breaking those that aren't representable in the system codepage.
1290 * As the C runtime's putenv() will also set the system copy, we do
1291 * the putenv() first, then call SetEnvironmentValueW ourselves.
1294 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1295 wvalue = g_utf8_to_utf16 (value, -1, NULL, NULL, NULL);
1296 tem = g_strconcat (variable, "=", value, NULL);
1297 wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1299 g_free (tem);
1300 _wputenv (wassignment);
1301 g_free (wassignment);
1303 retval = (SetEnvironmentVariableW (wname, wvalue) != 0);
1305 g_free (wname);
1306 g_free (wvalue);
1308 return retval;
1310 #endif /* G_OS_WIN32 */
1313 #ifdef HAVE__NSGETENVIRON
1314 #define environ (*_NSGetEnviron())
1315 #elif !defined(G_OS_WIN32)
1317 /* According to the Single Unix Specification, environ is not in
1318 * any system header, although unistd.h often declares it.
1320 extern char **environ;
1321 #endif
1324 * g_unsetenv:
1325 * @variable: the environment variable to remove, must not contain '='.
1327 * Removes an environment variable from the environment.
1329 * Note that on some systems, when variables are overwritten, the memory
1330 * used for the previous variables and its value isn't reclaimed.
1331 * Furthermore, this function can't be guaranteed to operate in a
1332 * threadsafe way.
1334 * Since: 2.4
1336 void
1337 g_unsetenv (const gchar *variable)
1339 #ifndef G_OS_WIN32
1341 #ifdef HAVE_UNSETENV
1342 g_return_if_fail (variable != NULL);
1343 g_return_if_fail (strchr (variable, '=') == NULL);
1345 unsetenv (variable);
1346 #else /* !HAVE_UNSETENV */
1347 int len;
1348 gchar **e, **f;
1350 g_return_if_fail (variable != NULL);
1351 g_return_if_fail (strchr (variable, '=') == NULL);
1353 len = strlen (variable);
1355 /* Mess directly with the environ array.
1356 * This seems to be the only portable way to do this.
1358 * Note that we remove *all* environment entries for
1359 * the variable name, not just the first.
1361 e = f = environ;
1362 while (*e != NULL)
1364 if (strncmp (*e, variable, len) != 0 || (*e)[len] != '=')
1366 *f = *e;
1367 f++;
1369 e++;
1371 *f = NULL;
1372 #endif /* !HAVE_UNSETENV */
1374 #else /* G_OS_WIN32 */
1376 wchar_t *wname, *wassignment;
1377 gchar *tem;
1379 g_return_if_fail (variable != NULL);
1380 g_return_if_fail (strchr (variable, '=') == NULL);
1381 g_return_if_fail (g_utf8_validate (variable, -1, NULL));
1383 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1384 tem = g_strconcat (variable, "=", NULL);
1385 wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1387 g_free (tem);
1388 _wputenv (wassignment);
1389 g_free (wassignment);
1391 SetEnvironmentVariableW (wname, NULL);
1393 g_free (wname);
1395 #endif /* G_OS_WIN32 */
1399 * g_listenv:
1401 * Gets the names of all variables set in the environment.
1403 * Returns: a %NULL-terminated list of strings which must be freed
1404 * with g_strfreev().
1406 * Programs that want to be portable to Windows should typically use
1407 * this function and g_getenv() instead of using the environ array
1408 * from the C library directly. On Windows, the strings in the environ
1409 * array are in system codepage encoding, while in most of the typical
1410 * use cases for environment variables in GLib-using programs you want
1411 * the UTF-8 encoding that this function and g_getenv() provide.
1413 * Since: 2.8
1415 gchar **
1416 g_listenv (void)
1418 #ifndef G_OS_WIN32
1419 gchar **result, *eq;
1420 gint len, i, j;
1422 len = g_strv_length (environ);
1423 result = g_new0 (gchar *, len + 1);
1425 j = 0;
1426 for (i = 0; i < len; i++)
1428 eq = strchr (environ[i], '=');
1429 if (eq)
1430 result[j++] = g_strndup (environ[i], eq - environ[i]);
1433 result[j] = NULL;
1435 return result;
1436 #else
1437 gchar **result, *eq;
1438 gint len = 0, j;
1439 wchar_t *p, *q;
1441 p = (wchar_t *) GetEnvironmentStringsW ();
1442 if (p != NULL)
1444 q = p;
1445 while (*q)
1447 q += wcslen (q) + 1;
1448 len++;
1451 result = g_new0 (gchar *, len + 1);
1453 j = 0;
1454 q = p;
1455 while (*q)
1457 result[j] = g_utf16_to_utf8 (q, -1, NULL, NULL, NULL);
1458 if (result[j] != NULL)
1460 eq = strchr (result[j], '=');
1461 if (eq && eq > result[j])
1463 *eq = '\0';
1464 j++;
1466 else
1467 g_free (result[j]);
1469 q += wcslen (q) + 1;
1471 result[j] = NULL;
1472 FreeEnvironmentStringsW (p);
1474 return result;
1475 #endif
1479 * g_get_environ:
1481 * Gets the list of environment variables for the current process. The
1482 * list is %NULL terminated and each item in the list is of the form
1483 * 'NAME=VALUE'.
1485 * This is equivalent to direct access to the 'environ' global variable,
1486 * except portable.
1488 * The return value is freshly allocated and it should be freed with
1489 * g_strfreev() when it is no longer needed.
1491 * Returns: the list of environment variables
1493 * Since: 2.28
1495 gchar **
1496 g_get_environ (void)
1498 #ifndef G_OS_WIN32
1499 return g_strdupv (environ);
1500 #else
1501 gunichar2 *strings;
1502 gchar **result;
1503 gint i, n;
1505 strings = GetEnvironmentStringsW ();
1506 for (n = 0; strings[n]; n += wcslen (strings + n) + 1);
1507 result = g_new (char *, n + 1);
1508 for (i = 0; strings[i]; i += wcslen (strings + i) + 1)
1509 result[i] = g_utf16_to_utf8 (strings + i, -1, NULL, NULL, NULL);
1510 FreeEnvironmentStringsW (strings);
1511 result[i] = NULL;
1513 return result;
1514 #endif
1517 G_LOCK_DEFINE_STATIC (g_utils_global);
1519 static gchar *g_tmp_dir = NULL;
1520 static gchar *g_user_name = NULL;
1521 static gchar *g_real_name = NULL;
1522 static gchar *g_home_dir = NULL;
1523 static gchar *g_host_name = NULL;
1525 #ifdef G_OS_WIN32
1526 /* System codepage versions of the above, kept at file level so that they,
1527 * too, are produced only once.
1529 static gchar *g_tmp_dir_cp = NULL;
1530 static gchar *g_user_name_cp = NULL;
1531 static gchar *g_real_name_cp = NULL;
1532 static gchar *g_home_dir_cp = NULL;
1533 #endif
1535 static gchar *g_user_data_dir = NULL;
1536 static gchar **g_system_data_dirs = NULL;
1537 static gchar *g_user_cache_dir = NULL;
1538 static gchar *g_user_config_dir = NULL;
1539 static gchar **g_system_config_dirs = NULL;
1541 static gchar **g_user_special_dirs = NULL;
1543 /* fifteen minutes of fame for everybody */
1544 #define G_USER_DIRS_EXPIRE 15 * 60
1546 #ifdef G_OS_WIN32
1548 static gchar *
1549 get_special_folder (int csidl)
1551 wchar_t path[MAX_PATH+1];
1552 HRESULT hr;
1553 LPITEMIDLIST pidl = NULL;
1554 BOOL b;
1555 gchar *retval = NULL;
1557 hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
1558 if (hr == S_OK)
1560 b = SHGetPathFromIDListW (pidl, path);
1561 if (b)
1562 retval = g_utf16_to_utf8 (path, -1, NULL, NULL, NULL);
1563 CoTaskMemFree (pidl);
1565 return retval;
1568 static char *
1569 get_windows_directory_root (void)
1571 wchar_t wwindowsdir[MAX_PATH];
1573 if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
1575 /* Usually X:\Windows, but in terminal server environments
1576 * might be an UNC path, AFAIK.
1578 char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
1579 char *p;
1581 if (windowsdir == NULL)
1582 return g_strdup ("C:\\");
1584 p = (char *) g_path_skip_root (windowsdir);
1585 if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
1586 p--;
1587 *p = '\0';
1588 return windowsdir;
1590 else
1591 return g_strdup ("C:\\");
1594 #endif
1596 /* HOLDS: g_utils_global_lock */
1597 static void
1598 g_get_any_init_do (void)
1600 gchar hostname[100];
1602 g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
1603 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1604 g_tmp_dir = g_strdup (g_getenv ("TMP"));
1605 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1606 g_tmp_dir = g_strdup (g_getenv ("TEMP"));
1608 #ifdef G_OS_WIN32
1609 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1610 g_tmp_dir = get_windows_directory_root ();
1611 #else
1612 #ifdef P_tmpdir
1613 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1615 gsize k;
1616 g_tmp_dir = g_strdup (P_tmpdir);
1617 k = strlen (g_tmp_dir);
1618 if (k > 1 && G_IS_DIR_SEPARATOR (g_tmp_dir[k - 1]))
1619 g_tmp_dir[k - 1] = '\0';
1621 #endif
1623 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1625 g_tmp_dir = g_strdup ("/tmp");
1627 #endif /* !G_OS_WIN32 */
1629 #ifdef G_OS_WIN32
1630 /* We check $HOME first for Win32, though it is a last resort for Unix
1631 * where we prefer the results of getpwuid().
1633 g_home_dir = g_strdup (g_getenv ("HOME"));
1635 /* Only believe HOME if it is an absolute path and exists */
1636 if (g_home_dir)
1638 if (!(g_path_is_absolute (g_home_dir) &&
1639 g_file_test (g_home_dir, G_FILE_TEST_IS_DIR)))
1641 g_free (g_home_dir);
1642 g_home_dir = NULL;
1646 /* In case HOME is Unix-style (it happens), convert it to
1647 * Windows style.
1649 if (g_home_dir)
1651 gchar *p;
1652 while ((p = strchr (g_home_dir, '/')) != NULL)
1653 *p = '\\';
1656 if (!g_home_dir)
1658 /* USERPROFILE is probably the closest equivalent to $HOME? */
1659 if (g_getenv ("USERPROFILE") != NULL)
1660 g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
1663 if (!g_home_dir)
1664 g_home_dir = get_special_folder (CSIDL_PROFILE);
1666 if (!g_home_dir)
1667 g_home_dir = get_windows_directory_root ();
1668 #endif /* G_OS_WIN32 */
1670 #ifdef HAVE_PWD_H
1672 struct passwd *pw = NULL;
1673 gpointer buffer = NULL;
1674 gint error;
1675 gchar *logname;
1677 # if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
1678 struct passwd pwd;
1679 # ifdef _SC_GETPW_R_SIZE_MAX
1680 /* This reurns the maximum length */
1681 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
1683 if (bufsize < 0)
1684 bufsize = 64;
1685 # else /* _SC_GETPW_R_SIZE_MAX */
1686 glong bufsize = 64;
1687 # endif /* _SC_GETPW_R_SIZE_MAX */
1689 logname = (gchar *) g_getenv ("LOGNAME");
1693 g_free (buffer);
1694 /* we allocate 6 extra bytes to work around a bug in
1695 * Mac OS < 10.3. See #156446
1697 buffer = g_malloc (bufsize + 6);
1698 errno = 0;
1700 # ifdef HAVE_POSIX_GETPWUID_R
1701 if (logname) {
1702 error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
1703 if (!pw || (pw->pw_uid != getuid ())) {
1704 /* LOGNAME is lying, fall back to looking up the uid */
1705 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1707 } else {
1708 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1710 error = error < 0 ? errno : error;
1711 # else /* HAVE_NONPOSIX_GETPWUID_R */
1712 /* HPUX 11 falls into the HAVE_POSIX_GETPWUID_R case */
1713 # if defined(_AIX) || defined(__hpux)
1714 error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1715 pw = error == 0 ? &pwd : NULL;
1716 # else /* !_AIX */
1717 if (logname) {
1718 pw = getpwnam_r (logname, &pwd, buffer, bufsize);
1719 if (!pw || (pw->pw_uid != getuid ())) {
1720 /* LOGNAME is lying, fall back to looking up the uid */
1721 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1723 } else {
1724 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1726 error = pw ? 0 : errno;
1727 # endif /* !_AIX */
1728 # endif /* HAVE_NONPOSIX_GETPWUID_R */
1730 if (!pw)
1732 /* we bail out prematurely if the user id can't be found
1733 * (should be pretty rare case actually), or if the buffer
1734 * should be sufficiently big and lookups are still not
1735 * successfull.
1737 if (error == 0 || error == ENOENT)
1739 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
1740 (gulong) getuid ());
1741 break;
1743 if (bufsize > 32 * 1024)
1745 g_warning ("getpwuid_r(): failed due to: %s.",
1746 g_strerror (error));
1747 break;
1750 bufsize *= 2;
1753 while (!pw);
1754 # endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
1756 if (!pw)
1758 setpwent ();
1759 pw = getpwuid (getuid ());
1760 endpwent ();
1762 if (pw)
1764 g_user_name = g_strdup (pw->pw_name);
1766 if (pw->pw_gecos && *pw->pw_gecos != '\0')
1768 gchar **gecos_fields;
1769 gchar **name_parts;
1771 /* split the gecos field and substitute '&' */
1772 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
1773 name_parts = g_strsplit (gecos_fields[0], "&", 0);
1774 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
1775 g_real_name = g_strjoinv (pw->pw_name, name_parts);
1776 g_strfreev (gecos_fields);
1777 g_strfreev (name_parts);
1780 if (!g_home_dir)
1781 g_home_dir = g_strdup (pw->pw_dir);
1783 g_free (buffer);
1786 #else /* !HAVE_PWD_H */
1788 #ifdef G_OS_WIN32
1790 guint len = UNLEN+1;
1791 wchar_t buffer[UNLEN+1];
1793 if (GetUserNameW (buffer, (LPDWORD) &len))
1795 g_user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
1796 g_real_name = g_strdup (g_user_name);
1799 #endif /* G_OS_WIN32 */
1801 #endif /* !HAVE_PWD_H */
1803 #ifndef G_OS_WIN32
1804 if (!g_home_dir)
1805 g_home_dir = g_strdup (g_getenv ("HOME"));
1806 #endif
1808 #ifdef __EMX__
1809 /* change '\\' in %HOME% to '/' */
1810 g_strdelimit (g_home_dir, "\\",'/');
1811 #endif
1812 if (!g_user_name)
1813 g_user_name = g_strdup ("somebody");
1814 if (!g_real_name)
1815 g_real_name = g_strdup ("Unknown");
1818 #ifndef G_OS_WIN32
1819 gboolean hostname_fail = (gethostname (hostname, sizeof (hostname)) == -1);
1820 #else
1821 DWORD size = sizeof (hostname);
1822 gboolean hostname_fail = (!GetComputerName (hostname, &size));
1823 #endif
1824 g_host_name = g_strdup (hostname_fail ? "localhost" : hostname);
1827 #ifdef G_OS_WIN32
1828 g_tmp_dir_cp = g_locale_from_utf8 (g_tmp_dir, -1, NULL, NULL, NULL);
1829 g_user_name_cp = g_locale_from_utf8 (g_user_name, -1, NULL, NULL, NULL);
1830 g_real_name_cp = g_locale_from_utf8 (g_real_name, -1, NULL, NULL, NULL);
1832 if (!g_tmp_dir_cp)
1833 g_tmp_dir_cp = g_strdup ("\\");
1834 if (!g_user_name_cp)
1835 g_user_name_cp = g_strdup ("somebody");
1836 if (!g_real_name_cp)
1837 g_real_name_cp = g_strdup ("Unknown");
1839 /* home_dir might be NULL, unlike tmp_dir, user_name and
1840 * real_name.
1842 if (g_home_dir)
1843 g_home_dir_cp = g_locale_from_utf8 (g_home_dir, -1, NULL, NULL, NULL);
1844 else
1845 g_home_dir_cp = NULL;
1846 #endif /* G_OS_WIN32 */
1849 static inline void
1850 g_get_any_init (void)
1852 if (!g_tmp_dir)
1853 g_get_any_init_do ();
1856 static inline void
1857 g_get_any_init_locked (void)
1859 G_LOCK (g_utils_global);
1860 g_get_any_init ();
1861 G_UNLOCK (g_utils_global);
1866 * g_get_user_name:
1868 * Gets the user name of the current user. The encoding of the returned
1869 * string is system-defined. On UNIX, it might be the preferred file name
1870 * encoding, or something else, and there is no guarantee that it is even
1871 * consistent on a machine. On Windows, it is always UTF-8.
1873 * Returns: the user name of the current user.
1875 G_CONST_RETURN gchar*
1876 g_get_user_name (void)
1878 g_get_any_init_locked ();
1879 return g_user_name;
1883 * g_get_real_name:
1885 * Gets the real name of the user. This usually comes from the user's entry
1886 * in the <filename>passwd</filename> file. The encoding of the returned
1887 * string is system-defined. (On Windows, it is, however, always UTF-8.)
1888 * If the real user name cannot be determined, the string "Unknown" is
1889 * returned.
1891 * Returns: the user's real name.
1893 G_CONST_RETURN gchar*
1894 g_get_real_name (void)
1896 g_get_any_init_locked ();
1897 return g_real_name;
1901 * g_get_home_dir:
1903 * Gets the current user's home directory as defined in the
1904 * password database.
1906 * Note that in contrast to traditional UNIX tools, this function
1907 * prefers <filename>passwd</filename> entries over the <envar>HOME</envar>
1908 * environment variable.
1910 * One of the reasons for this decision is that applications in many
1911 * cases need special handling to deal with the case where
1912 * <envar>HOME</envar> is
1913 * <simplelist>
1914 * <member>Not owned by the user</member>
1915 * <member>Not writeable</member>
1916 * <member>Not even readable</member>
1917 * </simplelist>
1918 * Since applications are in general <emphasis>not</emphasis> written
1919 * to deal with these situations it was considered better to make
1920 * g_get_home_dir() not pay attention to <envar>HOME</envar> and to
1921 * return the real home directory for the user. If applications
1922 * want to pay attention to <envar>HOME</envar>, they can do:
1923 * |[
1924 * const char *homedir = g_getenv ("HOME");
1925 * if (!homedir)
1926 * homedir = g_get_home_dir (<!-- -->);
1927 * ]|
1929 * Returns: the current user's home directory
1931 G_CONST_RETURN gchar*
1932 g_get_home_dir (void)
1934 g_get_any_init_locked ();
1935 return g_home_dir;
1939 * g_get_tmp_dir:
1941 * Gets the directory to use for temporary files. This is found from
1942 * inspecting the environment variables <envar>TMPDIR</envar>,
1943 * <envar>TMP</envar>, and <envar>TEMP</envar> in that order. If none
1944 * of those are defined "/tmp" is returned on UNIX and "C:\" on Windows.
1945 * The encoding of the returned string is system-defined. On Windows,
1946 * it is always UTF-8. The return value is never %NULL or the empty string.
1948 * Returns: the directory to use for temporary files.
1950 G_CONST_RETURN gchar*
1951 g_get_tmp_dir (void)
1953 g_get_any_init_locked ();
1954 return g_tmp_dir;
1958 * g_get_host_name:
1960 * Return a name for the machine.
1962 * The returned name is not necessarily a fully-qualified domain name,
1963 * or even present in DNS or some other name service at all. It need
1964 * not even be unique on your local network or site, but usually it
1965 * is. Callers should not rely on the return value having any specific
1966 * properties like uniqueness for security purposes. Even if the name
1967 * of the machine is changed while an application is running, the
1968 * return value from this function does not change. The returned
1969 * string is owned by GLib and should not be modified or freed. If no
1970 * name can be determined, a default fixed string "localhost" is
1971 * returned.
1973 * Returns: the host name of the machine.
1975 * Since: 2.8
1977 const gchar *
1978 g_get_host_name (void)
1980 g_get_any_init_locked ();
1981 return g_host_name;
1984 G_LOCK_DEFINE_STATIC (g_prgname);
1985 static gchar *g_prgname = NULL;
1988 * g_get_prgname:
1990 * Gets the name of the program. This name should <emphasis>not</emphasis>
1991 * be localized, contrast with g_get_application_name().
1992 * (If you are using GDK or GTK+ the program name is set in gdk_init(),
1993 * which is called by gtk_init(). The program name is found by taking
1994 * the last component of <literal>argv[0]</literal>.)
1996 * Returns: the name of the program. The returned string belongs
1997 * to GLib and must not be modified or freed.
1999 gchar*
2000 g_get_prgname (void)
2002 gchar* retval;
2004 G_LOCK (g_prgname);
2005 #ifdef G_OS_WIN32
2006 if (g_prgname == NULL)
2008 static gboolean beenhere = FALSE;
2010 if (!beenhere)
2012 gchar *utf8_buf = NULL;
2013 wchar_t buf[MAX_PATH+1];
2015 beenhere = TRUE;
2016 if (GetModuleFileNameW (GetModuleHandle (NULL),
2017 buf, G_N_ELEMENTS (buf)) > 0)
2018 utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
2020 if (utf8_buf)
2022 g_prgname = g_path_get_basename (utf8_buf);
2023 g_free (utf8_buf);
2027 #endif
2028 retval = g_prgname;
2029 G_UNLOCK (g_prgname);
2031 return retval;
2035 * g_set_prgname:
2036 * @prgname: the name of the program.
2038 * Sets the name of the program. This name should <emphasis>not</emphasis>
2039 * be localized, contrast with g_set_application_name(). Note that for
2040 * thread-safety reasons this function can only be called once.
2042 void
2043 g_set_prgname (const gchar *prgname)
2045 G_LOCK (g_prgname);
2046 g_free (g_prgname);
2047 g_prgname = g_strdup (prgname);
2048 G_UNLOCK (g_prgname);
2051 G_LOCK_DEFINE_STATIC (g_application_name);
2052 static gchar *g_application_name = NULL;
2055 * g_get_application_name:
2057 * Gets a human-readable name for the application, as set by
2058 * g_set_application_name(). This name should be localized if
2059 * possible, and is intended for display to the user. Contrast with
2060 * g_get_prgname(), which gets a non-localized name. If
2061 * g_set_application_name() has not been called, returns the result of
2062 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
2063 * been called).
2065 * Return value: human-readable application name. may return %NULL
2067 * Since: 2.2
2069 G_CONST_RETURN gchar*
2070 g_get_application_name (void)
2072 gchar* retval;
2074 G_LOCK (g_application_name);
2075 retval = g_application_name;
2076 G_UNLOCK (g_application_name);
2078 if (retval == NULL)
2079 return g_get_prgname ();
2081 return retval;
2085 * g_set_application_name:
2086 * @application_name: localized name of the application
2088 * Sets a human-readable name for the application. This name should be
2089 * localized if possible, and is intended for display to the user.
2090 * Contrast with g_set_prgname(), which sets a non-localized name.
2091 * g_set_prgname() will be called automatically by gtk_init(),
2092 * but g_set_application_name() will not.
2094 * Note that for thread safety reasons, this function can only
2095 * be called once.
2097 * The application name will be used in contexts such as error messages,
2098 * or when displaying an application's name in the task list.
2100 * Since: 2.2
2102 void
2103 g_set_application_name (const gchar *application_name)
2105 gboolean already_set = FALSE;
2107 G_LOCK (g_application_name);
2108 if (g_application_name)
2109 already_set = TRUE;
2110 else
2111 g_application_name = g_strdup (application_name);
2112 G_UNLOCK (g_application_name);
2114 if (already_set)
2115 g_warning ("g_set_application_name() called multiple times");
2119 * g_get_user_data_dir:
2121 * Returns a base directory in which to access application data such
2122 * as icons that is customized for a particular user.
2124 * On UNIX platforms this is determined using the mechanisms described in
2125 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2126 * XDG Base Directory Specification</ulink>.
2127 * In this case the directory retrieved will be XDG_DATA_HOME.
2129 * On Windows this is the folder to use for local (as opposed to
2130 * roaming) application data. See documentation for
2131 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
2132 * what g_get_user_config_dir() returns.
2134 * Return value: a string owned by GLib that must not be modified
2135 * or freed.
2136 * Since: 2.6
2138 G_CONST_RETURN gchar*
2139 g_get_user_data_dir (void)
2141 gchar *data_dir;
2143 G_LOCK (g_utils_global);
2145 if (!g_user_data_dir)
2147 #ifdef G_OS_WIN32
2148 data_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
2149 #else
2150 data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
2152 if (data_dir && data_dir[0])
2153 data_dir = g_strdup (data_dir);
2154 #endif
2155 if (!data_dir || !data_dir[0])
2157 g_get_any_init ();
2159 if (g_home_dir)
2160 data_dir = g_build_filename (g_home_dir, ".local",
2161 "share", NULL);
2162 else
2163 data_dir = g_build_filename (g_tmp_dir, g_user_name, ".local",
2164 "share", NULL);
2167 g_user_data_dir = data_dir;
2169 else
2170 data_dir = g_user_data_dir;
2172 G_UNLOCK (g_utils_global);
2174 return data_dir;
2177 static void
2178 g_init_user_config_dir (void)
2180 gchar *config_dir;
2182 if (!g_user_config_dir)
2184 #ifdef G_OS_WIN32
2185 config_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
2186 #else
2187 config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
2189 if (config_dir && config_dir[0])
2190 config_dir = g_strdup (config_dir);
2191 #endif
2192 if (!config_dir || !config_dir[0])
2194 g_get_any_init ();
2196 if (g_home_dir)
2197 config_dir = g_build_filename (g_home_dir, ".config", NULL);
2198 else
2199 config_dir = g_build_filename (g_tmp_dir, g_user_name, ".config", NULL);
2202 g_user_config_dir = config_dir;
2207 * g_get_user_config_dir:
2209 * Returns a base directory in which to store user-specific application
2210 * configuration information such as user preferences and settings.
2212 * On UNIX platforms this is determined using the mechanisms described in
2213 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2214 * XDG Base Directory Specification</ulink>.
2215 * In this case the directory retrieved will be XDG_CONFIG_HOME.
2217 * On Windows this is the folder to use for local (as opposed to
2218 * roaming) application data. See documentation for
2219 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
2220 * what g_get_user_data_dir() returns.
2222 * Return value: a string owned by GLib that must not be modified
2223 * or freed.
2224 * Since: 2.6
2226 G_CONST_RETURN gchar*
2227 g_get_user_config_dir (void)
2229 G_LOCK (g_utils_global);
2231 g_init_user_config_dir ();
2233 G_UNLOCK (g_utils_global);
2235 return g_user_config_dir;
2239 * g_get_user_cache_dir:
2241 * Returns a base directory in which to store non-essential, cached
2242 * data specific to particular user.
2244 * On UNIX platforms this is determined using the mechanisms described in
2245 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2246 * XDG Base Directory Specification</ulink>.
2247 * In this case the directory retrieved will be XDG_CACHE_HOME.
2249 * On Windows is the directory that serves as a common repository for
2250 * temporary Internet files. A typical path is
2251 * C:\Documents and Settings\username\Local Settings\Temporary Internet Files.
2252 * See documentation for CSIDL_INTERNET_CACHE.
2254 * Return value: a string owned by GLib that must not be modified
2255 * or freed.
2256 * Since: 2.6
2258 G_CONST_RETURN gchar*
2259 g_get_user_cache_dir (void)
2261 gchar *cache_dir;
2263 G_LOCK (g_utils_global);
2265 if (!g_user_cache_dir)
2267 #ifdef G_OS_WIN32
2268 cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
2269 #else
2270 cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
2272 if (cache_dir && cache_dir[0])
2273 cache_dir = g_strdup (cache_dir);
2274 #endif
2275 if (!cache_dir || !cache_dir[0])
2277 g_get_any_init ();
2279 if (g_home_dir)
2280 cache_dir = g_build_filename (g_home_dir, ".cache", NULL);
2281 else
2282 cache_dir = g_build_filename (g_tmp_dir, g_user_name, ".cache", NULL);
2284 g_user_cache_dir = cache_dir;
2286 else
2287 cache_dir = g_user_cache_dir;
2289 G_UNLOCK (g_utils_global);
2291 return cache_dir;
2295 * g_get_user_runtime_dir:
2297 * Returns a directory that is unique to the current user on the local
2298 * system.
2300 * On UNIX platforms this is determined using the mechanisms described in
2301 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2302 * XDG Base Directory Specification</ulink>. This is the directory
2303 * specified in the <envar>XDG_RUNTIME_DIR</envar> environment variable.
2304 * In the case that this variable is not set, GLib will issue a warning
2305 * message to stderr and return the value of g_get_user_cache_dir().
2307 * On Windows this is the folder to use for local (as opposed to
2308 * roaming) application data. See documentation for
2309 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
2310 * what g_get_user_config_dir() returns.
2312 * Returns: a string owned by GLib that must not be modified or freed.
2314 * Since: 2.28
2316 const gchar *
2317 g_get_user_runtime_dir (void)
2319 #ifndef G_OS_WIN32
2320 static const gchar *runtime_dir;
2321 static gsize initialised;
2323 if (g_once_init_enter (&initialised))
2325 runtime_dir = g_strdup (getenv ("XDG_RUNTIME_DIR"));
2327 if (runtime_dir == NULL)
2328 g_warning ("XDG_RUNTIME_DIR variable not set. "
2329 "Falling back to XDG cache dir.");
2331 g_once_init_leave (&initialised, 1);
2334 if (runtime_dir)
2335 return runtime_dir;
2337 /* Both fallback for UNIX and the default
2338 * in Windows: use the user cache directory.
2340 #endif
2342 return g_get_user_cache_dir ();
2345 #ifdef HAVE_CARBON
2347 static gchar *
2348 find_folder (OSType type)
2350 gchar *filename = NULL;
2351 FSRef found;
2353 if (FSFindFolder (kUserDomain, type, kDontCreateFolder, &found) == noErr)
2355 CFURLRef url = CFURLCreateFromFSRef (kCFAllocatorSystemDefault, &found);
2357 if (url)
2359 CFStringRef path = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle);
2361 if (path)
2363 filename = g_strdup (CFStringGetCStringPtr (path, kCFStringEncodingUTF8));
2365 if (! filename)
2367 filename = g_new0 (gchar, CFStringGetLength (path) * 3 + 1);
2369 CFStringGetCString (path, filename,
2370 CFStringGetLength (path) * 3 + 1,
2371 kCFStringEncodingUTF8);
2374 CFRelease (path);
2377 CFRelease (url);
2381 return filename;
2384 static void
2385 load_user_special_dirs (void)
2387 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = find_folder (kDesktopFolderType);
2388 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = find_folder (kDocumentsFolderType);
2389 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = find_folder (kDesktopFolderType); /* XXX correct ? */
2390 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = find_folder (kMusicDocumentsFolderType);
2391 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = find_folder (kPictureDocumentsFolderType);
2392 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = NULL;
2393 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = NULL;
2394 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = find_folder (kMovieDocumentsFolderType);
2397 #endif /* HAVE_CARBON */
2399 #if defined(G_OS_WIN32)
2400 static void
2401 load_user_special_dirs (void)
2403 typedef HRESULT (WINAPI *t_SHGetKnownFolderPath) (const GUID *rfid,
2404 DWORD dwFlags,
2405 HANDLE hToken,
2406 PWSTR *ppszPath);
2407 t_SHGetKnownFolderPath p_SHGetKnownFolderPath;
2409 static const GUID FOLDERID_Downloads =
2410 { 0x374de290, 0x123f, 0x4565, { 0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b } };
2411 static const GUID FOLDERID_Public =
2412 { 0xDFDF76A2, 0xC82A, 0x4D63, { 0x90, 0x6A, 0x56, 0x44, 0xAC, 0x45, 0x73, 0x85 } };
2414 wchar_t *wcp;
2416 p_SHGetKnownFolderPath = (t_SHGetKnownFolderPath) GetProcAddress (GetModuleHandle ("shell32.dll"),
2417 "SHGetKnownFolderPath");
2419 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2420 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
2422 if (p_SHGetKnownFolderPath == NULL)
2424 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2426 else
2428 wcp = NULL;
2429 (*p_SHGetKnownFolderPath) (&FOLDERID_Downloads, 0, NULL, &wcp);
2430 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
2431 if (g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] == NULL)
2432 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2433 CoTaskMemFree (wcp);
2436 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
2437 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
2439 if (p_SHGetKnownFolderPath == NULL)
2441 /* XXX */
2442 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2444 else
2446 wcp = NULL;
2447 (*p_SHGetKnownFolderPath) (&FOLDERID_Public, 0, NULL, &wcp);
2448 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
2449 if (g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] == NULL)
2450 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2451 CoTaskMemFree (wcp);
2454 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
2455 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
2457 #endif /* G_OS_WIN32 */
2459 static void g_init_user_config_dir (void);
2461 #if defined(G_OS_UNIX) && !defined(HAVE_CARBON)
2463 /* adapted from xdg-user-dir-lookup.c
2465 * Copyright (C) 2007 Red Hat Inc.
2467 * Permission is hereby granted, free of charge, to any person
2468 * obtaining a copy of this software and associated documentation files
2469 * (the "Software"), to deal in the Software without restriction,
2470 * including without limitation the rights to use, copy, modify, merge,
2471 * publish, distribute, sublicense, and/or sell copies of the Software,
2472 * and to permit persons to whom the Software is furnished to do so,
2473 * subject to the following conditions:
2475 * The above copyright notice and this permission notice shall be
2476 * included in all copies or substantial portions of the Software.
2478 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
2479 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
2480 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
2481 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
2482 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
2483 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
2484 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2485 * SOFTWARE.
2487 static void
2488 load_user_special_dirs (void)
2490 gchar *config_file;
2491 gchar *data;
2492 gchar **lines;
2493 gint n_lines, i;
2495 g_init_user_config_dir ();
2496 config_file = g_build_filename (g_user_config_dir,
2497 "user-dirs.dirs",
2498 NULL);
2500 if (!g_file_get_contents (config_file, &data, NULL, NULL))
2502 g_free (config_file);
2503 return;
2506 lines = g_strsplit (data, "\n", -1);
2507 n_lines = g_strv_length (lines);
2508 g_free (data);
2510 for (i = 0; i < n_lines; i++)
2512 gchar *buffer = lines[i];
2513 gchar *d, *p;
2514 gint len;
2515 gboolean is_relative = FALSE;
2516 GUserDirectory directory;
2518 /* Remove newline at end */
2519 len = strlen (buffer);
2520 if (len > 0 && buffer[len - 1] == '\n')
2521 buffer[len - 1] = 0;
2523 p = buffer;
2524 while (*p == ' ' || *p == '\t')
2525 p++;
2527 if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
2529 directory = G_USER_DIRECTORY_DESKTOP;
2530 p += strlen ("XDG_DESKTOP_DIR");
2532 else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
2534 directory = G_USER_DIRECTORY_DOCUMENTS;
2535 p += strlen ("XDG_DOCUMENTS_DIR");
2537 else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
2539 directory = G_USER_DIRECTORY_DOWNLOAD;
2540 p += strlen ("XDG_DOWNLOAD_DIR");
2542 else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
2544 directory = G_USER_DIRECTORY_MUSIC;
2545 p += strlen ("XDG_MUSIC_DIR");
2547 else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
2549 directory = G_USER_DIRECTORY_PICTURES;
2550 p += strlen ("XDG_PICTURES_DIR");
2552 else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
2554 directory = G_USER_DIRECTORY_PUBLIC_SHARE;
2555 p += strlen ("XDG_PUBLICSHARE_DIR");
2557 else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
2559 directory = G_USER_DIRECTORY_TEMPLATES;
2560 p += strlen ("XDG_TEMPLATES_DIR");
2562 else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
2564 directory = G_USER_DIRECTORY_VIDEOS;
2565 p += strlen ("XDG_VIDEOS_DIR");
2567 else
2568 continue;
2570 while (*p == ' ' || *p == '\t')
2571 p++;
2573 if (*p != '=')
2574 continue;
2575 p++;
2577 while (*p == ' ' || *p == '\t')
2578 p++;
2580 if (*p != '"')
2581 continue;
2582 p++;
2584 if (strncmp (p, "$HOME", 5) == 0)
2586 p += 5;
2587 is_relative = TRUE;
2589 else if (*p != '/')
2590 continue;
2592 d = strrchr (p, '"');
2593 if (!d)
2594 continue;
2595 *d = 0;
2597 d = p;
2599 /* remove trailing slashes */
2600 len = strlen (d);
2601 if (d[len - 1] == '/')
2602 d[len - 1] = 0;
2604 if (is_relative)
2606 g_get_any_init ();
2607 g_user_special_dirs[directory] = g_build_filename (g_home_dir, d, NULL);
2609 else
2610 g_user_special_dirs[directory] = g_strdup (d);
2613 g_strfreev (lines);
2614 g_free (config_file);
2617 #endif /* G_OS_UNIX && !HAVE_CARBON */
2621 * g_reload_user_special_dirs_cache:
2623 * Resets the cache used for g_get_user_special_dir(), so
2624 * that the latest on-disk version is used. Call this only
2625 * if you just changed the data on disk yourself.
2627 * Due to threadsafety issues this may cause leaking of strings
2628 * that were previously returned from g_get_user_special_dir()
2629 * that can't be freed. We ensure to only leak the data for
2630 * the directories that actually changed value though.
2632 * Since: 2.22
2634 void
2635 g_reload_user_special_dirs_cache (void)
2637 int i;
2639 G_LOCK (g_utils_global);
2641 if (g_user_special_dirs != NULL)
2643 /* save a copy of the pointer, to check if some memory can be preserved */
2644 char **old_g_user_special_dirs = g_user_special_dirs;
2645 char *old_val;
2647 /* recreate and reload our cache */
2648 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
2649 load_user_special_dirs ();
2651 /* only leak changed directories */
2652 for (i = 0; i < G_USER_N_DIRECTORIES; i++)
2654 old_val = old_g_user_special_dirs[i];
2655 if (g_strcmp0 (old_val, g_user_special_dirs[i]) == 0)
2657 /* don't leak */
2658 g_free (g_user_special_dirs[i]);
2659 g_user_special_dirs[i] = old_val;
2661 else
2662 g_free (old_val);
2665 /* free the old array */
2666 g_free (old_g_user_special_dirs);
2669 G_UNLOCK (g_utils_global);
2673 * g_get_user_special_dir:
2674 * @directory: the logical id of special directory
2676 * Returns the full path of a special directory using its logical id.
2678 * On Unix this is done using the XDG special user directories.
2679 * For compatibility with existing practise, %G_USER_DIRECTORY_DESKTOP
2680 * falls back to <filename>$HOME/Desktop</filename> when XDG special
2681 * user directories have not been set up.
2683 * Depending on the platform, the user might be able to change the path
2684 * of the special directory without requiring the session to restart; GLib
2685 * will not reflect any change once the special directories are loaded.
2687 * Return value: the path to the specified special directory, or %NULL
2688 * if the logical id was not found. The returned string is owned by
2689 * GLib and should not be modified or freed.
2691 * Since: 2.14
2693 G_CONST_RETURN gchar *
2694 g_get_user_special_dir (GUserDirectory directory)
2696 g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
2697 directory < G_USER_N_DIRECTORIES, NULL);
2699 G_LOCK (g_utils_global);
2701 if (G_UNLIKELY (g_user_special_dirs == NULL))
2703 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
2705 load_user_special_dirs ();
2707 /* Special-case desktop for historical compatibility */
2708 if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
2710 g_get_any_init ();
2712 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] =
2713 g_build_filename (g_home_dir, "Desktop", NULL);
2717 G_UNLOCK (g_utils_global);
2719 return g_user_special_dirs[directory];
2722 #ifdef G_OS_WIN32
2724 #undef g_get_system_data_dirs
2726 static HMODULE
2727 get_module_for_address (gconstpointer address)
2729 /* Holds the g_utils_global lock */
2731 static gboolean beenhere = FALSE;
2732 typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
2733 static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
2734 HMODULE hmodule = NULL;
2736 if (!address)
2737 return NULL;
2739 if (!beenhere)
2741 p_GetModuleHandleExA =
2742 (t_GetModuleHandleExA) GetProcAddress (GetModuleHandle ("kernel32.dll"),
2743 "GetModuleHandleExA");
2744 beenhere = TRUE;
2747 if (p_GetModuleHandleExA == NULL ||
2748 !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
2749 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
2750 address, &hmodule))
2752 MEMORY_BASIC_INFORMATION mbi;
2753 VirtualQuery (address, &mbi, sizeof (mbi));
2754 hmodule = (HMODULE) mbi.AllocationBase;
2757 return hmodule;
2760 static gchar *
2761 get_module_share_dir (gconstpointer address)
2763 HMODULE hmodule;
2764 gchar *filename;
2765 gchar *retval;
2767 hmodule = get_module_for_address (address);
2768 if (hmodule == NULL)
2769 return NULL;
2771 filename = g_win32_get_package_installation_directory_of_module (hmodule);
2772 retval = g_build_filename (filename, "share", NULL);
2773 g_free (filename);
2775 return retval;
2778 G_CONST_RETURN gchar * G_CONST_RETURN *
2779 g_win32_get_system_data_dirs_for_module (void (*address_of_function)())
2781 GArray *data_dirs;
2782 HMODULE hmodule;
2783 static GHashTable *per_module_data_dirs = NULL;
2784 gchar **retval;
2785 gchar *p;
2786 gchar *exe_root;
2788 if (address_of_function)
2790 G_LOCK (g_utils_global);
2791 hmodule = get_module_for_address (address_of_function);
2792 if (hmodule != NULL)
2794 if (per_module_data_dirs == NULL)
2795 per_module_data_dirs = g_hash_table_new (NULL, NULL);
2796 else
2798 retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
2800 if (retval != NULL)
2802 G_UNLOCK (g_utils_global);
2803 return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2809 data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
2811 /* Documents and Settings\All Users\Application Data */
2812 p = get_special_folder (CSIDL_COMMON_APPDATA);
2813 if (p)
2814 g_array_append_val (data_dirs, p);
2816 /* Documents and Settings\All Users\Documents */
2817 p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2818 if (p)
2819 g_array_append_val (data_dirs, p);
2821 /* Using the above subfolders of Documents and Settings perhaps
2822 * makes sense from a Windows perspective.
2824 * But looking at the actual use cases of this function in GTK+
2825 * and GNOME software, what we really want is the "share"
2826 * subdirectory of the installation directory for the package
2827 * our caller is a part of.
2829 * The address_of_function parameter, if non-NULL, points to a
2830 * function in the calling module. Use that to determine that
2831 * module's installation folder, and use its "share" subfolder.
2833 * Additionally, also use the "share" subfolder of the installation
2834 * locations of GLib and the .exe file being run.
2836 * To guard against none of the above being what is really wanted,
2837 * callers of this function should have Win32-specific code to look
2838 * up their installation folder themselves, and handle a subfolder
2839 * "share" of it in the same way as the folders returned from this
2840 * function.
2843 p = get_module_share_dir (address_of_function);
2844 if (p)
2845 g_array_append_val (data_dirs, p);
2847 if (glib_dll != NULL)
2849 gchar *glib_root = g_win32_get_package_installation_directory_of_module (glib_dll);
2850 p = g_build_filename (glib_root, "share", NULL);
2851 if (p)
2852 g_array_append_val (data_dirs, p);
2853 g_free (glib_root);
2856 exe_root = g_win32_get_package_installation_directory_of_module (NULL);
2857 p = g_build_filename (exe_root, "share", NULL);
2858 if (p)
2859 g_array_append_val (data_dirs, p);
2860 g_free (exe_root);
2862 retval = (gchar **) g_array_free (data_dirs, FALSE);
2864 if (address_of_function)
2866 if (hmodule != NULL)
2867 g_hash_table_insert (per_module_data_dirs, hmodule, retval);
2868 G_UNLOCK (g_utils_global);
2871 return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2874 #endif
2877 * g_get_system_data_dirs:
2879 * Returns an ordered list of base directories in which to access
2880 * system-wide application data.
2882 * On UNIX platforms this is determined using the mechanisms described in
2883 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2884 * XDG Base Directory Specification</ulink>
2885 * In this case the list of directories retrieved will be XDG_DATA_DIRS.
2887 * On Windows the first elements in the list are the Application Data
2888 * and Documents folders for All Users. (These can be determined only
2889 * on Windows 2000 or later and are not present in the list on other
2890 * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
2891 * CSIDL_COMMON_DOCUMENTS.
2893 * Then follows the "share" subfolder in the installation folder for
2894 * the package containing the DLL that calls this function, if it can
2895 * be determined.
2897 * Finally the list contains the "share" subfolder in the installation
2898 * folder for GLib, and in the installation folder for the package the
2899 * application's .exe file belongs to.
2901 * The installation folders above are determined by looking up the
2902 * folder where the module (DLL or EXE) in question is located. If the
2903 * folder's name is "bin", its parent is used, otherwise the folder
2904 * itself.
2906 * Note that on Windows the returned list can vary depending on where
2907 * this function is called.
2909 * Return value: a %NULL-terminated array of strings owned by GLib that must
2910 * not be modified or freed.
2911 * Since: 2.6
2913 G_CONST_RETURN gchar * G_CONST_RETURN *
2914 g_get_system_data_dirs (void)
2916 gchar **data_dir_vector;
2918 G_LOCK (g_utils_global);
2920 if (!g_system_data_dirs)
2922 #ifdef G_OS_WIN32
2923 data_dir_vector = (gchar **) g_win32_get_system_data_dirs_for_module (NULL);
2924 #else
2925 gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
2927 if (!data_dirs || !data_dirs[0])
2928 data_dirs = "/usr/local/share/:/usr/share/";
2930 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2931 #endif
2933 g_system_data_dirs = data_dir_vector;
2935 else
2936 data_dir_vector = g_system_data_dirs;
2938 G_UNLOCK (g_utils_global);
2940 return (G_CONST_RETURN gchar * G_CONST_RETURN *) data_dir_vector;
2944 * g_get_system_config_dirs:
2946 * Returns an ordered list of base directories in which to access
2947 * system-wide configuration information.
2949 * On UNIX platforms this is determined using the mechanisms described in
2950 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2951 * XDG Base Directory Specification</ulink>.
2952 * In this case the list of directories retrieved will be XDG_CONFIG_DIRS.
2954 * On Windows is the directory that contains application data for all users.
2955 * A typical path is C:\Documents and Settings\All Users\Application Data.
2956 * This folder is used for application data that is not user specific.
2957 * For example, an application can store a spell-check dictionary, a database
2958 * of clip art, or a log file in the CSIDL_COMMON_APPDATA folder.
2959 * This information will not roam and is available to anyone using the computer.
2961 * Return value: a %NULL-terminated array of strings owned by GLib that must
2962 * not be modified or freed.
2963 * Since: 2.6
2965 G_CONST_RETURN gchar * G_CONST_RETURN *
2966 g_get_system_config_dirs (void)
2968 gchar *conf_dirs, **conf_dir_vector;
2970 G_LOCK (g_utils_global);
2972 if (!g_system_config_dirs)
2974 #ifdef G_OS_WIN32
2975 conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
2976 if (conf_dirs)
2978 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2979 g_free (conf_dirs);
2981 else
2983 /* Return empty list */
2984 conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2986 #else
2987 conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
2989 if (!conf_dirs || !conf_dirs[0])
2990 conf_dirs = "/etc/xdg";
2992 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2993 #endif
2995 g_system_config_dirs = conf_dir_vector;
2997 else
2998 conf_dir_vector = g_system_config_dirs;
2999 G_UNLOCK (g_utils_global);
3001 return (G_CONST_RETURN gchar * G_CONST_RETURN *) conf_dir_vector;
3004 #ifndef G_OS_WIN32
3006 static GHashTable *alias_table = NULL;
3008 /* read an alias file for the locales */
3009 static void
3010 read_aliases (gchar *file)
3012 FILE *fp;
3013 char buf[256];
3015 if (!alias_table)
3016 alias_table = g_hash_table_new (g_str_hash, g_str_equal);
3017 fp = fopen (file,"r");
3018 if (!fp)
3019 return;
3020 while (fgets (buf, 256, fp))
3022 char *p, *q;
3024 g_strstrip (buf);
3026 /* Line is a comment */
3027 if ((buf[0] == '#') || (buf[0] == '\0'))
3028 continue;
3030 /* Reads first column */
3031 for (p = buf, q = NULL; *p; p++) {
3032 if ((*p == '\t') || (*p == ' ') || (*p == ':')) {
3033 *p = '\0';
3034 q = p+1;
3035 while ((*q == '\t') || (*q == ' ')) {
3036 q++;
3038 break;
3041 /* The line only had one column */
3042 if (!q || *q == '\0')
3043 continue;
3045 /* Read second column */
3046 for (p = q; *p; p++) {
3047 if ((*p == '\t') || (*p == ' ')) {
3048 *p = '\0';
3049 break;
3053 /* Add to alias table if necessary */
3054 if (!g_hash_table_lookup (alias_table, buf)) {
3055 g_hash_table_insert (alias_table, g_strdup (buf), g_strdup (q));
3058 fclose (fp);
3061 #endif
3063 static char *
3064 unalias_lang (char *lang)
3066 #ifndef G_OS_WIN32
3067 char *p;
3068 int i;
3070 if (!alias_table)
3071 read_aliases ("/usr/share/locale/locale.alias");
3073 i = 0;
3074 while ((p = g_hash_table_lookup (alias_table, lang)) && (strcmp (p, lang) != 0))
3076 lang = p;
3077 if (i++ == 30)
3079 static gboolean said_before = FALSE;
3080 if (!said_before)
3081 g_warning ("Too many alias levels for a locale, "
3082 "may indicate a loop");
3083 said_before = TRUE;
3084 return lang;
3087 #endif
3088 return lang;
3091 /* Mask for components of locale spec. The ordering here is from
3092 * least significant to most significant
3094 enum
3096 COMPONENT_CODESET = 1 << 0,
3097 COMPONENT_TERRITORY = 1 << 1,
3098 COMPONENT_MODIFIER = 1 << 2
3101 /* Break an X/Open style locale specification into components
3103 static guint
3104 explode_locale (const gchar *locale,
3105 gchar **language,
3106 gchar **territory,
3107 gchar **codeset,
3108 gchar **modifier)
3110 const gchar *uscore_pos;
3111 const gchar *at_pos;
3112 const gchar *dot_pos;
3114 guint mask = 0;
3116 uscore_pos = strchr (locale, '_');
3117 dot_pos = strchr (uscore_pos ? uscore_pos : locale, '.');
3118 at_pos = strchr (dot_pos ? dot_pos : (uscore_pos ? uscore_pos : locale), '@');
3120 if (at_pos)
3122 mask |= COMPONENT_MODIFIER;
3123 *modifier = g_strdup (at_pos);
3125 else
3126 at_pos = locale + strlen (locale);
3128 if (dot_pos)
3130 mask |= COMPONENT_CODESET;
3131 *codeset = g_strndup (dot_pos, at_pos - dot_pos);
3133 else
3134 dot_pos = at_pos;
3136 if (uscore_pos)
3138 mask |= COMPONENT_TERRITORY;
3139 *territory = g_strndup (uscore_pos, dot_pos - uscore_pos);
3141 else
3142 uscore_pos = dot_pos;
3144 *language = g_strndup (locale, uscore_pos - locale);
3146 return mask;
3150 * Compute all interesting variants for a given locale name -
3151 * by stripping off different components of the value.
3153 * For simplicity, we assume that the locale is in
3154 * X/Open format: language[_territory][.codeset][@modifier]
3156 * TODO: Extend this to handle the CEN format (see the GNUlibc docs)
3157 * as well. We could just copy the code from glibc wholesale
3158 * but it is big, ugly, and complicated, so I'm reluctant
3159 * to do so when this should handle 99% of the time...
3161 static void
3162 append_locale_variants (GPtrArray *array,
3163 const gchar *locale)
3165 gchar *language = NULL;
3166 gchar *territory = NULL;
3167 gchar *codeset = NULL;
3168 gchar *modifier = NULL;
3170 guint mask;
3171 guint i, j;
3173 g_return_if_fail (locale != NULL);
3175 mask = explode_locale (locale, &language, &territory, &codeset, &modifier);
3177 /* Iterate through all possible combinations, from least attractive
3178 * to most attractive.
3180 for (j = 0; j <= mask; ++j)
3182 i = mask - j;
3184 if ((i & ~mask) == 0)
3186 gchar *val = g_strconcat (language,
3187 (i & COMPONENT_TERRITORY) ? territory : "",
3188 (i & COMPONENT_CODESET) ? codeset : "",
3189 (i & COMPONENT_MODIFIER) ? modifier : "",
3190 NULL);
3191 g_ptr_array_add (array, val);
3195 g_free (language);
3196 if (mask & COMPONENT_CODESET)
3197 g_free (codeset);
3198 if (mask & COMPONENT_TERRITORY)
3199 g_free (territory);
3200 if (mask & COMPONENT_MODIFIER)
3201 g_free (modifier);
3204 gchar **
3205 _g_compute_locale_variants (const gchar *locale)
3207 GPtrArray *array;
3209 g_return_val_if_fail (locale != NULL, NULL);
3211 array = g_ptr_array_sized_new (8);
3212 append_locale_variants (array, locale);
3213 g_ptr_array_add (array, NULL);
3215 return (gchar **) g_ptr_array_free (array, FALSE);
3218 /* The following is (partly) taken from the gettext package.
3219 Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc. */
3221 static const gchar *
3222 guess_category_value (const gchar *category_name)
3224 const gchar *retval;
3226 /* The highest priority value is the `LANGUAGE' environment
3227 variable. This is a GNU extension. */
3228 retval = g_getenv ("LANGUAGE");
3229 if ((retval != NULL) && (retval[0] != '\0'))
3230 return retval;
3232 /* `LANGUAGE' is not set. So we have to proceed with the POSIX
3233 methods of looking to `LC_ALL', `LC_xxx', and `LANG'. On some
3234 systems this can be done by the `setlocale' function itself. */
3236 /* Setting of LC_ALL overwrites all other. */
3237 retval = g_getenv ("LC_ALL");
3238 if ((retval != NULL) && (retval[0] != '\0'))
3239 return retval;
3241 /* Next comes the name of the desired category. */
3242 retval = g_getenv (category_name);
3243 if ((retval != NULL) && (retval[0] != '\0'))
3244 return retval;
3246 /* Last possibility is the LANG environment variable. */
3247 retval = g_getenv ("LANG");
3248 if ((retval != NULL) && (retval[0] != '\0'))
3249 return retval;
3251 #ifdef G_PLATFORM_WIN32
3252 /* g_win32_getlocale() first checks for LC_ALL, LC_MESSAGES and
3253 * LANG, which we already did above. Oh well. The main point of
3254 * calling g_win32_getlocale() is to get the thread's locale as used
3255 * by Windows and the Microsoft C runtime (in the "English_United
3256 * States" format) translated into the Unixish format.
3259 char *locale = g_win32_getlocale ();
3260 retval = g_intern_string (locale);
3261 g_free (locale);
3262 return retval;
3264 #endif
3266 return NULL;
3269 typedef struct _GLanguageNamesCache GLanguageNamesCache;
3271 struct _GLanguageNamesCache {
3272 gchar *languages;
3273 gchar **language_names;
3276 static void
3277 language_names_cache_free (gpointer data)
3279 GLanguageNamesCache *cache = data;
3280 g_free (cache->languages);
3281 g_strfreev (cache->language_names);
3282 g_free (cache);
3286 * g_get_language_names:
3288 * Computes a list of applicable locale names, which can be used to
3289 * e.g. construct locale-dependent filenames or search paths. The returned
3290 * list is sorted from most desirable to least desirable and always contains
3291 * the default locale "C".
3293 * For example, if LANGUAGE=de:en_US, then the returned list is
3294 * "de", "en_US", "en", "C".
3296 * This function consults the environment variables <envar>LANGUAGE</envar>,
3297 * <envar>LC_ALL</envar>, <envar>LC_MESSAGES</envar> and <envar>LANG</envar>
3298 * to find the list of locales specified by the user.
3300 * Return value: a %NULL-terminated array of strings owned by GLib
3301 * that must not be modified or freed.
3303 * Since: 2.6
3305 G_CONST_RETURN gchar * G_CONST_RETURN *
3306 g_get_language_names (void)
3308 static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
3309 GLanguageNamesCache *cache = g_static_private_get (&cache_private);
3310 const gchar *value;
3312 if (!cache)
3314 cache = g_new0 (GLanguageNamesCache, 1);
3315 g_static_private_set (&cache_private, cache, language_names_cache_free);
3318 value = guess_category_value ("LC_MESSAGES");
3319 if (!value)
3320 value = "C";
3322 if (!(cache->languages && strcmp (cache->languages, value) == 0))
3324 GPtrArray *array;
3325 gchar **alist, **a;
3327 g_free (cache->languages);
3328 g_strfreev (cache->language_names);
3329 cache->languages = g_strdup (value);
3331 array = g_ptr_array_sized_new (8);
3333 alist = g_strsplit (value, ":", 0);
3334 for (a = alist; *a; a++)
3335 append_locale_variants (array, unalias_lang (*a));
3336 g_strfreev (alist);
3337 g_ptr_array_add (array, g_strdup ("C"));
3338 g_ptr_array_add (array, NULL);
3340 cache->language_names = (gchar **) g_ptr_array_free (array, FALSE);
3343 return (G_CONST_RETURN gchar * G_CONST_RETURN *) cache->language_names;
3347 * g_direct_hash:
3348 * @v: a #gpointer key
3350 * Converts a gpointer to a hash value.
3351 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3352 * when using pointers as keys in a #GHashTable.
3354 * Returns: a hash value corresponding to the key.
3356 guint
3357 g_direct_hash (gconstpointer v)
3359 return GPOINTER_TO_UINT (v);
3363 * g_direct_equal:
3364 * @v1: a key.
3365 * @v2: a key to compare with @v1.
3367 * Compares two #gpointer arguments and returns %TRUE if they are equal.
3368 * It can be passed to g_hash_table_new() as the @key_equal_func
3369 * parameter, when using pointers as keys in a #GHashTable.
3371 * Returns: %TRUE if the two keys match.
3373 gboolean
3374 g_direct_equal (gconstpointer v1,
3375 gconstpointer v2)
3377 return v1 == v2;
3381 * g_int_equal:
3382 * @v1: a pointer to a #gint key.
3383 * @v2: a pointer to a #gint key to compare with @v1.
3385 * Compares the two #gint values being pointed to and returns
3386 * %TRUE if they are equal.
3387 * It can be passed to g_hash_table_new() as the @key_equal_func
3388 * parameter, when using pointers to integers as keys in a #GHashTable.
3390 * Returns: %TRUE if the two keys match.
3392 gboolean
3393 g_int_equal (gconstpointer v1,
3394 gconstpointer v2)
3396 return *((const gint*) v1) == *((const gint*) v2);
3400 * g_int_hash:
3401 * @v: a pointer to a #gint key
3403 * Converts a pointer to a #gint to a hash value.
3404 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3405 * when using pointers to integers values as keys in a #GHashTable.
3407 * Returns: a hash value corresponding to the key.
3409 guint
3410 g_int_hash (gconstpointer v)
3412 return *(const gint*) v;
3416 * g_int64_equal:
3417 * @v1: a pointer to a #gint64 key.
3418 * @v2: a pointer to a #gint64 key to compare with @v1.
3420 * Compares the two #gint64 values being pointed to and returns
3421 * %TRUE if they are equal.
3422 * It can be passed to g_hash_table_new() as the @key_equal_func
3423 * parameter, when using pointers to 64-bit integers as keys in a #GHashTable.
3425 * Returns: %TRUE if the two keys match.
3427 * Since: 2.22
3429 gboolean
3430 g_int64_equal (gconstpointer v1,
3431 gconstpointer v2)
3433 return *((const gint64*) v1) == *((const gint64*) v2);
3437 * g_int64_hash:
3438 * @v: a pointer to a #gint64 key
3440 * Converts a pointer to a #gint64 to a hash value.
3441 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3442 * when using pointers to 64-bit integers values as keys in a #GHashTable.
3444 * Returns: a hash value corresponding to the key.
3446 * Since: 2.22
3448 guint
3449 g_int64_hash (gconstpointer v)
3451 return (guint) *(const gint64*) v;
3455 * g_double_equal:
3456 * @v1: a pointer to a #gdouble key.
3457 * @v2: a pointer to a #gdouble key to compare with @v1.
3459 * Compares the two #gdouble values being pointed to and returns
3460 * %TRUE if they are equal.
3461 * It can be passed to g_hash_table_new() as the @key_equal_func
3462 * parameter, when using pointers to doubles as keys in a #GHashTable.
3464 * Returns: %TRUE if the two keys match.
3466 * Since: 2.22
3468 gboolean
3469 g_double_equal (gconstpointer v1,
3470 gconstpointer v2)
3472 return *((const gdouble*) v1) == *((const gdouble*) v2);
3476 * g_double_hash:
3477 * @v: a pointer to a #gdouble key
3479 * Converts a pointer to a #gdouble to a hash value.
3480 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3481 * when using pointers to doubles as keys in a #GHashTable.
3483 * Returns: a hash value corresponding to the key.
3485 * Since: 2.22
3487 guint
3488 g_double_hash (gconstpointer v)
3490 return (guint) *(const gdouble*) v;
3494 * g_nullify_pointer:
3495 * @nullify_location: the memory address of the pointer.
3497 * Set the pointer at the specified location to %NULL.
3499 void
3500 g_nullify_pointer (gpointer *nullify_location)
3502 g_return_if_fail (nullify_location != NULL);
3504 *nullify_location = NULL;
3508 * g_get_codeset:
3510 * Get the codeset for the current locale.
3512 * Return value: a newly allocated string containing the name
3513 * of the codeset. This string must be freed with g_free().
3515 gchar *
3516 g_get_codeset (void)
3518 const gchar *charset;
3520 g_get_charset (&charset);
3522 return g_strdup (charset);
3525 /* This is called from g_thread_init(). It's used to
3526 * initialize some static data in a threadsafe way.
3528 void
3529 _g_utils_thread_init (void)
3531 g_get_language_names ();
3534 #ifdef G_OS_WIN32
3537 * _glib_get_locale_dir:
3539 * Return the path to the share\locale or lib\locale subfolder of the
3540 * GLib installation folder. The path is in the system codepage. We
3541 * have to use system codepage as bindtextdomain() doesn't have a
3542 * UTF-8 interface.
3544 static gchar *
3545 _glib_get_locale_dir (void)
3547 gchar *install_dir = NULL, *locale_dir;
3548 gchar *retval = NULL;
3550 if (glib_dll != NULL)
3551 install_dir = g_win32_get_package_installation_directory_of_module (glib_dll);
3553 if (install_dir)
3556 * Append "/share/locale" or "/lib/locale" depending on whether
3557 * autoconfigury detected GNU gettext or not.
3559 const char *p = GLIB_LOCALE_DIR + strlen (GLIB_LOCALE_DIR);
3560 while (*--p != '/')
3562 while (*--p != '/')
3565 locale_dir = g_build_filename (install_dir, p, NULL);
3567 retval = g_win32_locale_filename_from_utf8 (locale_dir);
3569 g_free (install_dir);
3570 g_free (locale_dir);
3573 if (retval)
3574 return retval;
3575 else
3576 return g_strdup ("");
3579 #undef GLIB_LOCALE_DIR
3581 #endif /* G_OS_WIN32 */
3584 * glib_gettext:
3585 * @str: The string to be translated
3587 * Returns the translated string from the glib translations.
3588 * This is an internal function and should only be used by
3589 * the internals of glib (such as libgio).
3591 * Returns: the transation of @str to the current locale
3593 G_CONST_RETURN gchar *
3594 glib_gettext (const gchar *str)
3596 static gboolean _glib_gettext_initialized = FALSE;
3598 if (!_glib_gettext_initialized)
3600 #ifdef G_OS_WIN32
3601 gchar *tmp = _glib_get_locale_dir ();
3602 bindtextdomain (GETTEXT_PACKAGE, tmp);
3603 g_free (tmp);
3604 #else
3605 bindtextdomain (GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
3606 #endif
3607 # ifdef HAVE_BIND_TEXTDOMAIN_CODESET
3608 bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
3609 # endif
3610 _glib_gettext_initialized = TRUE;
3613 return g_dgettext (GETTEXT_PACKAGE, str);
3616 #if defined (G_OS_WIN32) && !defined (_WIN64)
3618 /* Binary compatibility versions. Not for newly compiled code. */
3620 #undef g_find_program_in_path
3622 gchar*
3623 g_find_program_in_path (const gchar *program)
3625 gchar *utf8_program = g_locale_to_utf8 (program, -1, NULL, NULL, NULL);
3626 gchar *utf8_retval = g_find_program_in_path_utf8 (utf8_program);
3627 gchar *retval;
3629 g_free (utf8_program);
3630 if (utf8_retval == NULL)
3631 return NULL;
3632 retval = g_locale_from_utf8 (utf8_retval, -1, NULL, NULL, NULL);
3633 g_free (utf8_retval);
3635 return retval;
3638 #undef g_get_current_dir
3640 gchar*
3641 g_get_current_dir (void)
3643 gchar *utf8_dir = g_get_current_dir_utf8 ();
3644 gchar *dir = g_locale_from_utf8 (utf8_dir, -1, NULL, NULL, NULL);
3645 g_free (utf8_dir);
3646 return dir;
3649 #undef g_getenv
3651 G_CONST_RETURN gchar*
3652 g_getenv (const gchar *variable)
3654 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3655 const gchar *utf8_value = g_getenv_utf8 (utf8_variable);
3656 gchar *value;
3657 GQuark quark;
3659 g_free (utf8_variable);
3660 if (!utf8_value)
3661 return NULL;
3662 value = g_locale_from_utf8 (utf8_value, -1, NULL, NULL, NULL);
3663 quark = g_quark_from_string (value);
3664 g_free (value);
3666 return g_quark_to_string (quark);
3669 #undef g_setenv
3671 gboolean
3672 g_setenv (const gchar *variable,
3673 const gchar *value,
3674 gboolean overwrite)
3676 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3677 gchar *utf8_value = g_locale_to_utf8 (value, -1, NULL, NULL, NULL);
3678 gboolean retval = g_setenv_utf8 (utf8_variable, utf8_value, overwrite);
3680 g_free (utf8_variable);
3681 g_free (utf8_value);
3683 return retval;
3686 #undef g_unsetenv
3688 void
3689 g_unsetenv (const gchar *variable)
3691 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3693 g_unsetenv_utf8 (utf8_variable);
3695 g_free (utf8_variable);
3698 #undef g_get_user_name
3700 G_CONST_RETURN gchar*
3701 g_get_user_name (void)
3703 g_get_any_init_locked ();
3704 return g_user_name_cp;
3707 #undef g_get_real_name
3709 G_CONST_RETURN gchar*
3710 g_get_real_name (void)
3712 g_get_any_init_locked ();
3713 return g_real_name_cp;
3716 #undef g_get_home_dir
3718 G_CONST_RETURN gchar*
3719 g_get_home_dir (void)
3721 g_get_any_init_locked ();
3722 return g_home_dir_cp;
3725 #undef g_get_tmp_dir
3727 G_CONST_RETURN gchar*
3728 g_get_tmp_dir (void)
3730 g_get_any_init_locked ();
3731 return g_tmp_dir_cp;
3734 #endif