1 #include <ctype.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <string.h>
5 #include <glib.h>
7 #include "config.h"
8 #include "support.h"
10 #ifdef HAVE_LOCALE_H
11 #include <locale.h>
12 #endif
14 #define BUFSIZE 1024
16 static const char *charset = NULL;
17 static const char *locale = NULL;
18 static gboolean noconvert = TRUE;
20 char *
21 trim(char *str)
22 {
23 char *end;
25 if( str==NULL )
26 return NULL;
28 while( IS_WHITESPACE(*str) )
29 str++;
31 end=str+strlen(str)-1;
32 while( end>str && IS_WHITESPACE(*end) )
33 {
34 *end = '\0';
35 end--;
36 }
37 return str;
38 }
40 char *
41 remove_trailing_slash(char *path)
42 {
43 int len;
45 if( path==NULL )
46 return NULL;
48 len=strlen(path);
49 if( len>1 && path[len-1] == '/' )
50 path[len-1] = '\0';
52 return path;
53 }
55 char *
56 lowerstr(char *str)
57 {
58 size_t i;
59 size_t len = strlen(str);
61 if( str==NULL )
62 return NULL;
64 i=0;
65 while(i<len && str[i])
66 {
67 str[i] = tolower(str[i]);
68 i++;
69 }
70 return str;
71 }
74 #ifndef HAVE_BASENAME
75 char *
76 basename(char *path)
77 {
78 char *end;
80 path = remove_trailing_slash(path);
81 end = path + strlen(path);
83 while( end>path && *end!='/' )
84 end--;
86 if( *end=='/' && end!=path )
87 return end+1;
89 return path;
90 }
91 #endif /* HAVE_BASENAME */
94 #ifndef HAVE_STRCASESTR
95 char *
96 strcasestr(const char *haystack, const char *needle)
97 {
98 return strstr(lowerstr(haystack), lowerstr(needle));
99 }
100 #endif /* HAVE_STRCASESTR */
103 int
104 charset_init(void)
105 {
106 #ifdef HAVE_LOCALE_H
107 /* get current locale */
108 if( (locale=setlocale(LC_CTYPE,"")) == NULL )
109 {
110 g_printerr("setlocale() - failed!\n");
111 return -1;
112 }
113 #endif
115 /* get charset */
116 noconvert = g_get_charset(&charset);
118 #ifdef DEBUG
119 g_printerr("charset: %s [%d]\n", charset, noconvert);
120 fflush(stderr);
121 #endif
123 return 0;
124 }
126 int
127 charset_close(void)
128 {
129 return 0;
130 }
132 char *
133 utf8_to_locale(char *utf8str)
134 {
135 gchar *str;
136 gsize rb, wb;
137 GError *error;
139 if( noconvert )
140 return g_strdup(utf8str);
142 rb = 0; /* bytes read */
143 wb = 0; /* bytes written */
144 error = NULL;
145 str=g_locale_from_utf8(utf8str,
146 strlen(utf8str),
147 &wb, &rb,
148 &error);
149 if( error )
150 {
151 g_printerr("utf8_to_locale(): %s\n", error->message);
152 g_error_free(error);
153 return g_strdup(utf8str);
154 }
156 return str;
157 }
159 char *
160 locale_to_utf8(char *localestr)
161 {
162 gchar *str;
163 gsize rb, wb;
164 GError *error;
166 if( noconvert )
167 return g_strdup(localestr);
169 rb = 0; /* bytes read */
170 wb = 0; /* bytes written */
171 error = NULL;
172 str=g_locale_to_utf8(localestr,
173 strlen(localestr),
174 &wb, &rb,
175 &error);
176 if( error )
177 {
178 g_printerr("locale_to_utf8: %s\n", error->message);
179 g_error_free(error);
180 return g_strdup(localestr);
181 }
183 return str;
184 }