.cvsignore updates
[platform/upstream/glib.git] / gutils.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1998  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
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.
8  *
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.
13  *
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.
18  */
19
20 /*
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/. 
25  */
26
27 /* 
28  * MT safe for the unix part, FIXME: make the win32 part MT safe as well.
29  */
30
31 #ifdef HAVE_CONFIG_H
32 #include <config.h>
33 #endif
34
35 #ifdef HAVE_UNISTD_H
36 #include <unistd.h>
37 #endif
38 #include <stdarg.h>
39 #include <stdlib.h>
40 #include <stdio.h>
41 #include <string.h>
42 #include <errno.h>
43 #ifdef HAVE_PWD_H
44 #include <pwd.h>
45 #endif
46 #include <sys/types.h>
47 #ifdef HAVE_SYS_PARAM_H
48 #include <sys/param.h>
49 #endif
50
51 /* implement Glib's inline functions
52  */
53 #define G_IMPLEMENT_INLINES 1
54 #define __G_UTILS_C__
55 #include "glib.h"
56
57 #ifdef  MAXPATHLEN
58 #define G_PATH_LENGTH   MAXPATHLEN
59 #elif   defined (PATH_MAX)
60 #define G_PATH_LENGTH   PATH_MAX
61 #elif   defined (_PC_PATH_MAX)
62 #define G_PATH_LENGTH   sysconf(_PC_PATH_MAX)
63 #else   
64 #define G_PATH_LENGTH   2048
65 #endif
66
67 #ifdef G_OS_WIN32
68 #  define STRICT                        /* Strict typing, please */
69 #  include <windows.h>
70 #  include <ctype.h>
71 #  include <direct.h>
72 #endif /* G_OS_WIN32 */
73
74 #ifdef HAVE_CODESET
75 #include <langinfo.h>
76 #endif
77
78 const guint glib_major_version = GLIB_MAJOR_VERSION;
79 const guint glib_minor_version = GLIB_MINOR_VERSION;
80 const guint glib_micro_version = GLIB_MICRO_VERSION;
81 const guint glib_interface_age = GLIB_INTERFACE_AGE;
82 const guint glib_binary_age = GLIB_BINARY_AGE;
83
84 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
85 void 
86 g_memmove (gpointer dest, gconstpointer src, gulong len)
87 {
88   gchar* destptr = dest;
89   const gchar* srcptr = src;
90   if (src + len < dest || dest + len < src)
91     {
92       bcopy (src, dest, len);
93       return;
94     }
95   else if (dest <= src)
96     {
97       while (len--)
98         *(destptr++) = *(srcptr++);
99     }
100   else
101     {
102       destptr += len;
103       srcptr += len;
104       while (len--)
105         *(--destptr) = *(--srcptr);
106     }
107 }
108 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
109
110 void
111 g_atexit (GVoidFunc func)
112 {
113   gint result;
114   gchar *error = NULL;
115
116   /* keep this in sync with glib.h */
117
118 #ifdef  G_NATIVE_ATEXIT
119   result = ATEXIT (func);
120   if (result)
121     error = g_strerror (errno);
122 #elif defined (HAVE_ATEXIT)
123 #  ifdef NeXT /* @#%@! NeXTStep */
124   result = !atexit ((void (*)(void)) func);
125   if (result)
126     error = g_strerror (errno);
127 #  else
128   result = atexit ((void (*)(void)) func);
129   if (result)
130     error = g_strerror (errno);
131 #  endif /* NeXT */
132 #elif defined (HAVE_ON_EXIT)
133   result = on_exit ((void (*)(int, void *)) func, NULL);
134   if (result)
135     error = g_strerror (errno);
136 #else
137   result = 0;
138   error = "no implementation";
139 #endif /* G_NATIVE_ATEXIT */
140
141   if (error)
142     g_error ("Could not register atexit() function: %s", error);
143 }
144
145 /* Based on execvp() from GNU Libc.
146  * Some of this code is cut-and-pasted into gspawn.c
147  */
148
149 static gchar*
150 my_strchrnul (const gchar *str, gchar c)
151 {
152   gchar *p = (gchar*)str;
153   while (*p && (*p != c))
154     ++p;
155
156   return p;
157 }
158
159 /**
160  * g_find_program_in_path:
161  * @program: a program name
162  * 
163  * Locates the first executable named @program in the user's path, in the
164  * same way that execvp() would locate it. Returns an allocated string
165  * with the absolute path name, or NULL if the program is not found in
166  * the path. If @program is already an absolute path, returns a copy of
167  * @program if @program exists and is executable, and NULL otherwise.
168  * 
169  * Return value: absolute path, or NULL
170  **/
171 gchar*
172 g_find_program_in_path (const gchar *program)
173 {
174   gchar *path, *p, *name, *freeme;
175   size_t len;
176   size_t pathlen;
177
178   g_return_val_if_fail (program != NULL, NULL);
179
180   if (*program == '/')
181     {
182       if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE))
183         return g_strdup (program);
184       else
185         return NULL;
186     }
187   
188   path = g_getenv ("PATH");
189   if (path == NULL)
190     {
191       /* There is no `PATH' in the environment.  The default
192        * search path in GNU libc is the current directory followed by
193        * the path `confstr' returns for `_CS_PATH'.
194        */
195       
196       /* In GLib we put . last, for security, and don't use the
197        * unportable confstr(); UNIX98 does not actually specify
198        * what to search if PATH is unset. POSIX may, dunno.
199        */
200       
201       path = "/bin:/usr/bin:.";
202     }
203   
204   len = strlen (program) + 1;
205   pathlen = strlen (path);
206   freeme = name = g_malloc (pathlen + len + 1);
207   
208   /* Copy the file name at the top, including '\0'  */
209   memcpy (name + pathlen + 1, program, len);
210   name = name + pathlen;
211   /* And add the slash before the filename  */
212   *name = '/';
213   
214   p = path;
215   do
216     {
217       char *startp;
218
219       path = p;
220       p = my_strchrnul (path, ':');
221
222       if (p == path)
223         /* Two adjacent colons, or a colon at the beginning or the end
224          * of `PATH' means to search the current directory.
225          */
226         startp = name + 1;
227       else
228         startp = memcpy (name - (p - path), path, p - path);
229
230       if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE))
231         {
232           gchar *ret;
233           ret = g_strdup (startp);
234           g_free (freeme);
235           return ret;
236         }
237     }
238   while (*p++ != '\0');
239   
240   g_free (freeme);
241
242   return NULL;
243 }
244
245 gint
246 g_snprintf (gchar       *str,
247             gulong       n,
248             gchar const *fmt,
249             ...)
250 {
251 #ifdef  HAVE_VSNPRINTF
252   va_list args;
253   gint retval;
254   
255   g_return_val_if_fail (str != NULL, 0);
256   g_return_val_if_fail (n > 0, 0);
257   g_return_val_if_fail (fmt != NULL, 0);
258
259   va_start (args, fmt);
260   retval = vsnprintf (str, n, fmt, args);
261   va_end (args);
262
263   if (retval < 0)
264     {
265       str[n-1] = '\0';
266       retval = strlen (str);
267     }
268
269   return retval;
270 #else   /* !HAVE_VSNPRINTF */
271   gchar *printed;
272   va_list args;
273   
274   g_return_val_if_fail (str != NULL, 0);
275   g_return_val_if_fail (n > 0, 0);
276   g_return_val_if_fail (fmt != NULL, 0);
277
278   va_start (args, fmt);
279   printed = g_strdup_vprintf (fmt, args);
280   va_end (args);
281   
282   strncpy (str, printed, n);
283   str[n-1] = '\0';
284
285   g_free (printed);
286   
287   return strlen (str);
288 #endif  /* !HAVE_VSNPRINTF */
289 }
290
291 gint
292 g_vsnprintf (gchar       *str,
293              gulong       n,
294              gchar const *fmt,
295              va_list      args)
296 {
297 #ifdef  HAVE_VSNPRINTF
298   gint retval;
299   
300   g_return_val_if_fail (str != NULL, 0);
301   g_return_val_if_fail (n > 0, 0);
302   g_return_val_if_fail (fmt != NULL, 0);
303
304   retval = vsnprintf (str, n, fmt, args);
305   
306   if (retval < 0)
307     {
308       str[n-1] = '\0';
309       retval = strlen (str);
310     }
311
312   return retval;
313 #else   /* !HAVE_VSNPRINTF */
314   gchar *printed;
315   
316   g_return_val_if_fail (str != NULL, 0);
317   g_return_val_if_fail (n > 0, 0);
318   g_return_val_if_fail (fmt != NULL, 0);
319
320   printed = g_strdup_vprintf (fmt, args);
321   strncpy (str, printed, n);
322   str[n-1] = '\0';
323
324   g_free (printed);
325   
326   return strlen (str);
327 #endif /* !HAVE_VSNPRINTF */
328 }
329
330 guint        
331 g_parse_debug_string  (const gchar *string, 
332                        GDebugKey   *keys, 
333                        guint        nkeys)
334 {
335   guint i;
336   guint result = 0;
337   
338   g_return_val_if_fail (string != NULL, 0);
339   
340   if (!g_strcasecmp (string, "all"))
341     {
342       for (i=0; i<nkeys; i++)
343         result |= keys[i].value;
344     }
345   else
346     {
347       gchar *str = g_strdup (string);
348       gchar *p = str;
349       gchar *q;
350       gboolean done = FALSE;
351       
352       while (*p && !done)
353         {
354           q = strchr (p, ':');
355           if (!q)
356             {
357               q = p + strlen(p);
358               done = TRUE;
359             }
360           
361           *q = 0;
362           
363           for (i=0; i<nkeys; i++)
364             if (!g_strcasecmp(keys[i].key, p))
365               result |= keys[i].value;
366           
367           p = q+1;
368         }
369       
370       g_free (str);
371     }
372   
373   return result;
374 }
375
376 gchar*
377 g_basename (const gchar    *file_name)
378 {
379   register gchar *base;
380 #if defined(G_ENABLE_DEBUG) && !defined(G_OS_WIN32)
381   static gboolean first_call = TRUE;
382
383   if (first_call)
384     {
385       g_message ("g_basename is deprecated. Use g_path_get_basename instead. "
386                  "Beware that the string returned by g_path_get_basename() has "
387                  " to be g_free()ed.");
388       first_call = FALSE;
389     }
390 #endif /* G_ENABLE_DEBUG */
391   
392   g_return_val_if_fail (file_name != NULL, NULL);
393   
394   base = strrchr (file_name, G_DIR_SEPARATOR);
395   if (base)
396     return base + 1;
397
398 #ifdef G_OS_WIN32
399   if (isalpha (file_name[0]) && file_name[1] == ':')
400     return (gchar*) file_name + 2;
401 #endif /* G_OS_WIN32 */
402   
403   return (gchar*) file_name;
404 }
405
406 gchar*
407 g_path_get_basename (const gchar   *file_name)
408 {
409   register gint base;
410   register gint last_nonslash;
411   guint len;
412   gchar *retval;
413  
414   g_return_val_if_fail (file_name != NULL, NULL);
415   
416   if (file_name[0] == '\0')
417     /* empty string */
418     return g_strdup (".");
419
420   last_nonslash = strlen (file_name) - 1;
421
422   while (last_nonslash >= 0 && file_name [last_nonslash] == G_DIR_SEPARATOR)
423     last_nonslash--;
424
425   if (last_nonslash == -1)
426     /* string only containing slashes */
427     return g_strdup (G_DIR_SEPARATOR_S);
428
429 #ifdef G_OS_WIN32
430   if (last_nonslash == 1 && isalpha (file_name[0]) && file_name[1] == ':')
431     /* string only containing slashes and a drive */
432     return g_strdup (G_DIR_SEPARATOR_S);
433 #endif /* G_OS_WIN32 */
434
435   base = last_nonslash;
436
437   while (base >=0 && file_name [base] != G_DIR_SEPARATOR)
438     base--;
439
440 #ifdef G_OS_WIN32
441   if (base == -1 && isalpha (file_name[0]) && file_name[1] == ':')
442     base = 1;
443 #endif /* G_OS_WIN32 */
444
445   len = last_nonslash - base;
446   retval = g_malloc (len + 1);
447   memcpy (retval, file_name + base + 1, len);
448   retval [len] = '\0';
449   return retval;
450 }
451
452 gboolean
453 g_path_is_absolute (const gchar *file_name)
454 {
455   g_return_val_if_fail (file_name != NULL, FALSE);
456   
457   if (file_name[0] == G_DIR_SEPARATOR)
458     return TRUE;
459
460 #ifdef G_OS_WIN32
461   if (isalpha (file_name[0]) && file_name[1] == ':' && file_name[2] == G_DIR_SEPARATOR)
462     return TRUE;
463 #endif
464
465   return FALSE;
466 }
467
468 gchar*
469 g_path_skip_root (gchar *file_name)
470 {
471   g_return_val_if_fail (file_name != NULL, NULL);
472   
473 #ifdef G_OS_WIN32
474   /* Skip \\server\share */
475   if (file_name[0] == G_DIR_SEPARATOR &&
476       file_name[1] == G_DIR_SEPARATOR &&
477       file_name[2])
478     {
479       gchar *p, *q;
480
481       if ((p = strchr (file_name + 2, G_DIR_SEPARATOR)) > file_name + 2 &&
482           p[1])
483         {
484           file_name = p + 1;
485
486           while (file_name[0] && file_name[0] != G_DIR_SEPARATOR)
487             file_name++;
488
489           /* Possibly skip a backslash after the share name */
490           if (file_name[0] == G_DIR_SEPARATOR)
491             file_name++;
492
493           return file_name;
494         }
495     }
496 #endif
497   
498   /* Skip initial slashes */
499   if (file_name[0] == G_DIR_SEPARATOR)
500     {
501       while (file_name[0] == G_DIR_SEPARATOR)
502         file_name++;
503       return file_name;
504     }
505
506 #ifdef G_OS_WIN32
507   /* Skip X:\ */
508   if (isalpha (file_name[0]) && file_name[1] == ':' && file_name[2] == G_DIR_SEPARATOR)
509     return file_name + 3;
510 #endif
511
512   return NULL;
513 }
514
515 gchar*
516 g_path_get_dirname (const gchar    *file_name)
517 {
518   register gchar *base;
519   register guint len;
520   
521   g_return_val_if_fail (file_name != NULL, NULL);
522   
523   base = strrchr (file_name, G_DIR_SEPARATOR);
524   if (!base)
525     return g_strdup (".");
526   while (base > file_name && *base == G_DIR_SEPARATOR)
527     base--;
528   len = (guint) 1 + base - file_name;
529   
530   base = g_new (gchar, len + 1);
531   g_memmove (base, file_name, len);
532   base[len] = 0;
533   
534   return base;
535 }
536
537 gchar*
538 g_dirname (const gchar     *file_name)
539 {
540 #if defined(G_ENABLE_DEBUG) && !defined(G_OS_WIN32)
541   static gboolean first_call = TRUE;
542
543   if (first_call)
544     {
545       g_message ("g_dirname() is deprecated. Use g_path_get_dirname() instead.");
546       first_call = FALSE;
547     }
548 #endif /* G_ENABLE_DEBUG */
549
550   return g_path_get_dirname (file_name);
551 }
552
553 gchar*
554 g_get_current_dir (void)
555 {
556   gchar *buffer = NULL;
557   gchar *dir = NULL;
558   static gulong max_len = 0;
559
560   if (max_len == 0) 
561     max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
562   
563   /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
564    * and, if that wasn't bad enough, hangs in doing so.
565    */
566 #if     (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
567   buffer = g_new (gchar, max_len + 1);
568   *buffer = 0;
569   dir = getwd (buffer);
570 #else   /* !sun || !HAVE_GETCWD */
571   while (max_len < G_MAXULONG / 2)
572     {
573       buffer = g_new (gchar, max_len + 1);
574       *buffer = 0;
575       dir = getcwd (buffer, max_len);
576
577       if (dir || errno != ERANGE)
578         break;
579
580       g_free (buffer);
581       max_len *= 2;
582     }
583 #endif  /* !sun || !HAVE_GETCWD */
584   
585   if (!dir || !*buffer)
586     {
587       /* hm, should we g_error() out here?
588        * this can happen if e.g. "./" has mode \0000
589        */
590       buffer[0] = G_DIR_SEPARATOR;
591       buffer[1] = 0;
592     }
593
594   dir = g_strdup (buffer);
595   g_free (buffer);
596   
597   return dir;
598 }
599
600 gchar*
601 g_getenv (const gchar *variable)
602 {
603 #ifndef G_OS_WIN32
604   g_return_val_if_fail (variable != NULL, NULL);
605
606   return getenv (variable);
607 #else
608   G_LOCK_DEFINE_STATIC (getenv);
609   struct env_struct
610   {
611     gchar *key;
612     gchar *value;
613   } *env;
614   static GArray *environs = NULL;
615   gchar *system_env;
616   guint length, i;
617   gchar dummy[2];
618
619   g_return_val_if_fail (variable != NULL, NULL);
620   
621   G_LOCK (getenv);
622
623   if (!environs)
624     environs = g_array_new (FALSE, FALSE, sizeof (struct env_struct));
625
626   /* First we try to find the envinronment variable inside the already
627    * found ones.
628    */
629
630   for (i = 0; i < environs->len; i++)
631     {
632       env = &g_array_index (environs, struct env_struct, i);
633       if (strcmp (env->key, variable) == 0)
634         {
635           g_assert (env->value);
636           G_UNLOCK (getenv);
637           return env->value;
638         }
639     }
640
641   /* If not found, we ask the system */
642
643   system_env = getenv (variable);
644   if (!system_env)
645     {
646       G_UNLOCK (getenv);
647       return NULL;
648     }
649
650   /* On Windows NT, it is relatively typical that environment variables
651    * contain references to other environment variables. Handle that by
652    * calling ExpandEnvironmentStrings.
653    */
654
655   g_array_set_size (environs, environs->len + 1);
656
657   env = &g_array_index (environs, struct env_struct, environs->len - 1);
658
659   /* First check how much space we need */
660   length = ExpandEnvironmentStrings (system_env, dummy, 2);
661
662   /* Then allocate that much, and actualy do the expansion and insert
663    * the new found pair into our buffer 
664    */
665
666   env->value = g_malloc (length);
667   env->key = g_strdup (variable);
668
669   ExpandEnvironmentStrings (system_env, env->value, length);
670
671   G_UNLOCK (getenv);
672   return env->value;
673 #endif
674 }
675
676
677 G_LOCK_DEFINE_STATIC (g_utils_global);
678
679 static  gchar   *g_tmp_dir = NULL;
680 static  gchar   *g_user_name = NULL;
681 static  gchar   *g_real_name = NULL;
682 static  gchar   *g_home_dir = NULL;
683
684 /* HOLDS: g_utils_global_lock */
685 static void
686 g_get_any_init (void)
687 {
688   if (!g_tmp_dir)
689     {
690       g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
691       if (!g_tmp_dir)
692         g_tmp_dir = g_strdup (g_getenv ("TMP"));
693       if (!g_tmp_dir)
694         g_tmp_dir = g_strdup (g_getenv ("TEMP"));
695       
696 #ifdef P_tmpdir
697       if (!g_tmp_dir)
698         {
699           int k;
700           g_tmp_dir = g_strdup (P_tmpdir);
701           k = strlen (g_tmp_dir);
702           if (g_tmp_dir[k-1] == G_DIR_SEPARATOR)
703             g_tmp_dir[k-1] = '\0';
704         }
705 #endif
706       
707       if (!g_tmp_dir)
708         {
709 #ifndef G_OS_WIN32
710           g_tmp_dir = g_strdup ("/tmp");
711 #else /* G_OS_WIN32 */
712           g_tmp_dir = g_strdup ("C:\\");
713 #endif /* G_OS_WIN32 */
714         }
715       
716       if (!g_home_dir)
717         g_home_dir = g_strdup (g_getenv ("HOME"));
718       
719 #ifdef G_OS_WIN32
720       /* In case HOME is Unix-style (it happens), convert it to
721        * Windows style.
722        */
723       if (g_home_dir)
724         {
725           gchar *p;
726           while ((p = strchr (g_home_dir, '/')) != NULL)
727             *p = '\\';
728         }
729       else
730         {
731           /* The official way to specify a home directory on NT is
732            * the HOMEDRIVE and HOMEPATH environment variables. At least
733            * it was at some time.
734            */
735           if (getenv ("HOMEDRIVE") != NULL && getenv ("HOMEPATH") != NULL)
736             {
737               gchar *homedrive, *homepath;
738               
739               homedrive = g_strdup (g_getenv ("HOMEDRIVE"));
740               homepath = g_strdup (g_getenv ("HOMEPATH"));
741               
742               g_home_dir = g_strconcat (homedrive, homepath, NULL);
743               g_free (homedrive);
744               g_free (homepath);
745             }
746         }
747 #endif /* G_OS_WIN32 */
748       
749 #ifdef HAVE_PWD_H
750       {
751         struct passwd *pw = NULL;
752         gpointer buffer = NULL;
753         
754 #  if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
755         struct passwd pwd;
756 #    ifdef _SC_GETPW_R_SIZE_MAX  
757         /* This reurns the maximum length */
758         guint bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
759 #    else /* _SC_GETPW_R_SIZE_MAX */
760         guint bufsize = 64;
761 #    endif /* _SC_GETPW_R_SIZE_MAX */
762         gint error;
763         
764         do
765           {
766             g_free (buffer);
767             buffer = g_malloc (bufsize);
768             errno = 0;
769             
770 #    ifdef HAVE_POSIX_GETPWUID_R
771             error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
772             error = error < 0 ? errno : error;
773 #    else /* HAVE_NONPOSIX_GETPWUID_R */
774 #      ifdef _AIX
775             error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
776             pw = error == 0 ? &pwd : NULL;
777 #      else /* !_AIX */
778             pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
779             error = pw ? 0 : errno;
780 #      endif /* !_AIX */            
781 #    endif /* HAVE_NONPOSIX_GETPWUID_R */
782             
783             if (!pw)
784               {
785                 /* we bail out prematurely if the user id can't be found
786                  * (should be pretty rare case actually), or if the buffer
787                  * should be sufficiently big and lookups are still not
788                  * successfull.
789                  */
790                 if (error == 0 || error == ENOENT)
791                   {
792                     g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
793                                (gulong) getuid ());
794                     break;
795                   }
796                 if (bufsize > 32 * 1024)
797                   {
798                     g_warning ("getpwuid_r(): failed due to: %s.",
799                                g_strerror (error));
800                     break;
801                   }
802                 
803                 bufsize *= 2;
804               }
805           }
806         while (!pw);
807 #  endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
808         
809         if (!pw)
810           {
811             setpwent ();
812             pw = getpwuid (getuid ());
813             endpwent ();
814           }
815         if (pw)
816           {
817             g_user_name = g_strdup (pw->pw_name);
818             g_real_name = g_strdup (pw->pw_gecos);
819             if (!g_home_dir)
820               g_home_dir = g_strdup (pw->pw_dir);
821           }
822         g_free (buffer);
823       }
824       
825 #else /* !HAVE_PWD_H */
826       
827 #  ifdef G_OS_WIN32
828       {
829         guint len = 17;
830         gchar buffer[17];
831         
832         if (GetUserName ((LPTSTR) buffer, (LPDWORD) &len))
833           {
834             g_user_name = g_strdup (buffer);
835             g_real_name = g_strdup (buffer);
836           }
837       }
838 #  endif /* G_OS_WIN32 */
839       
840 #endif /* !HAVE_PWD_H */
841       
842 #ifdef __EMX__
843       /* change '\\' in %HOME% to '/' */
844       g_strdelimit (g_home_dir, "\\",'/');
845 #endif
846       if (!g_user_name)
847         g_user_name = g_strdup ("somebody");
848       if (!g_real_name)
849         g_real_name = g_strdup ("Unknown");
850       else
851         {
852           gchar *p;
853
854           for (p = g_real_name; *p; p++)
855             if (*p == ',')
856               {
857                 *p = 0;
858                 p = g_strdup (g_real_name);
859                 g_free (g_real_name);
860                 g_real_name = p;
861                 break;
862               }
863         }
864     }
865 }
866
867 gchar*
868 g_get_user_name (void)
869 {
870   G_LOCK (g_utils_global);
871   if (!g_tmp_dir)
872     g_get_any_init ();
873   G_UNLOCK (g_utils_global);
874   
875   return g_user_name;
876 }
877
878 gchar*
879 g_get_real_name (void)
880 {
881   G_LOCK (g_utils_global);
882   if (!g_tmp_dir)
883     g_get_any_init ();
884   G_UNLOCK (g_utils_global);
885  
886   return g_real_name;
887 }
888
889 /* Return the home directory of the user. If there is a HOME
890  * environment variable, its value is returned, otherwise use some
891  * system-dependent way of finding it out. If no home directory can be
892  * deduced, return NULL.
893  */
894
895 gchar*
896 g_get_home_dir (void)
897 {
898   G_LOCK (g_utils_global);
899   if (!g_tmp_dir)
900     g_get_any_init ();
901   G_UNLOCK (g_utils_global);
902   
903   return g_home_dir;
904 }
905
906 /* Return a directory to be used to store temporary files. This is the
907  * value of the TMPDIR, TMP or TEMP environment variables (they are
908  * checked in that order). If none of those exist, use P_tmpdir from
909  * stdio.h.  If that isn't defined, return "/tmp" on POSIXly systems,
910  * and C:\ on Windows.
911  */
912
913 gchar*
914 g_get_tmp_dir (void)
915 {
916   G_LOCK (g_utils_global);
917   if (!g_tmp_dir)
918     g_get_any_init ();
919   G_UNLOCK (g_utils_global);
920   
921   return g_tmp_dir;
922 }
923
924 static gchar *g_prgname = NULL;
925
926 gchar*
927 g_get_prgname (void)
928 {
929   gchar* retval;
930
931   G_LOCK (g_utils_global);
932   retval = g_prgname;
933   G_UNLOCK (g_utils_global);
934
935   return retval;
936 }
937
938 void
939 g_set_prgname (const gchar *prgname)
940 {
941   gchar *c;
942     
943   G_LOCK (g_utils_global);
944   c = g_prgname;
945   g_prgname = g_strdup (prgname);
946   g_free (c);
947   G_UNLOCK (g_utils_global);
948 }
949
950 guint
951 g_direct_hash (gconstpointer v)
952 {
953   return GPOINTER_TO_UINT (v);
954 }
955
956 gboolean
957 g_direct_equal (gconstpointer v1,
958                 gconstpointer v2)
959 {
960   return v1 == v2;
961 }
962
963 gboolean
964 g_int_equal (gconstpointer v1,
965              gconstpointer v2)
966 {
967   return *((const gint*) v1) == *((const gint*) v2);
968 }
969
970 guint
971 g_int_hash (gconstpointer v)
972 {
973   return *(const gint*) v;
974 }
975
976 /**
977  * g_get_codeset:
978  * 
979  * Get the codeset for the current locale.
980  * 
981  * Return value: a newly allocated string containing the name
982  * of the codeset. This string must be freed with g_free().
983  **/
984 gchar *
985 g_get_codeset (void)
986 {
987 #ifdef HAVE_CODESET  
988   char *result = nl_langinfo (CODESET);
989   return g_strdup (result);
990 #else
991 #ifndef G_OS_WIN32
992   /* FIXME: Do something more intelligent based on setlocale (LC_CTYPE, NULL)
993    */
994   return g_strdup ("ISO-8859-1");
995 #else
996   return g_strdup_printf ("CP%d", GetACP ());
997 #endif
998 #endif
999 }
1000
1001 #ifdef ENABLE_NLS
1002
1003 #include <libintl.h>
1004
1005
1006 #ifdef G_OS_WIN32
1007
1008 #define GLIB_LOCALE_DIR                                         \
1009   g_win32_get_package_installation_subdirectory                 \
1010   (GETTEXT_PACKAGE, g_strdup_printf ("glib-%d.%d.dll",          \
1011                                      GLIB_MAJOR_VERSION,        \
1012                                      GLIB_MINOR_VERSION),       \
1013    "locale")
1014
1015 #endif /* G_OS_WIN32 */
1016
1017 gchar *
1018 _glib_gettext (const gchar *str)
1019 {
1020   gboolean _glib_gettext_initialized = FALSE;
1021
1022   if (!_glib_gettext_initialized)
1023     {
1024       bindtextdomain(GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
1025       _glib_gettext_initialized = TRUE;
1026     }
1027   
1028   return dgettext (GETTEXT_PACKAGE, str);
1029 }
1030
1031 #endif /* ENABLE_NLS */
1032
1033