2 * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3 * Copyright (C) 1999-2005 Hiroyuki Yamamoto & The Sylpheed-Claws Team
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
27 #include <glib/gi18n.h>
33 #if (HAVE_WCTYPE_H && HAVE_WCHAR_H)
41 #include <sys/types.h>
46 #include <sys/utsname.h>
50 #include "../codeconv.h"
54 static gboolean debug_mode = FALSE;
56 static void hash_free_strings_func(gpointer key, gpointer value, gpointer data);
58 void list_free_strings(GList *list)
60 list = g_list_first(list);
62 while (list != NULL) {
68 void slist_free_strings(GSList *list)
70 while (list != NULL) {
76 GSList *slist_concat_unique (GSList *first, GSList *second)
84 } else if (second == NULL)
87 for (tmp = second; tmp != NULL; tmp = g_slist_next(tmp)) {
88 if (g_slist_find(ret, tmp->data) == NULL)
89 ret = g_slist_prepend(ret, tmp->data);
94 static void hash_free_strings_func(gpointer key, gpointer value, gpointer data)
99 void hash_free_strings(GHashTable *table)
101 g_hash_table_foreach(table, hash_free_strings_func, NULL);
104 static void hash_free_value_mem_func(gpointer key, gpointer value,
110 void hash_free_value_mem(GHashTable *table)
112 g_hash_table_foreach(table, hash_free_value_mem_func, NULL);
115 gint str_case_equal(gconstpointer v, gconstpointer v2)
117 return g_ascii_strcasecmp((const gchar *)v, (const gchar *)v2) == 0;
120 guint str_case_hash(gconstpointer key)
122 const gchar *p = key;
127 for (p += 1; *p != '\0'; p++)
128 h = (h << 5) - h + tolower(*p);
134 void ptr_array_free_strings(GPtrArray *array)
139 g_return_if_fail(array != NULL);
141 for (i = 0; i < array->len; i++) {
142 str = g_ptr_array_index(array, i);
147 gboolean str_find(const gchar *haystack, const gchar *needle)
149 return strstr(haystack, needle) != NULL ? TRUE : FALSE;
152 gboolean str_case_find(const gchar *haystack, const gchar *needle)
154 return strcasestr(haystack, needle) != NULL ? TRUE : FALSE;
157 gboolean str_find_equal(const gchar *haystack, const gchar *needle)
159 return strcmp(haystack, needle) == 0;
162 gboolean str_case_find_equal(const gchar *haystack, const gchar *needle)
164 return g_ascii_strcasecmp(haystack, needle) == 0;
167 gint to_number(const gchar *nstr)
169 register const gchar *p;
171 if (*nstr == '\0') return -1;
173 for (p = nstr; *p != '\0'; p++)
174 if (!g_ascii_isdigit(*p)) return -1;
179 /* convert integer into string,
180 nstr must be not lower than 11 characters length */
181 gchar *itos_buf(gchar *nstr, gint n)
183 g_snprintf(nstr, 11, "%d", n);
187 /* convert integer into string */
190 static gchar nstr[11];
192 return itos_buf(nstr, n);
195 gchar *to_human_readable(off_t size)
197 static gchar str[10];
200 g_snprintf(str, sizeof(str), _("%dB"), (gint)size);
201 else if (size >> 10 < 1024)
202 g_snprintf(str, sizeof(str), _("%.1fKB"), (gfloat)size / (1 << 10));
203 else if (size >> 20 < 1024)
204 g_snprintf(str, sizeof(str), _("%.2fMB"), (gfloat)size / (1 << 20));
206 g_snprintf(str, sizeof(str), _("%.2fGB"), (gfloat)size / (1 << 30));
211 /* strcmp with NULL-checking */
212 gint strcmp2(const gchar *s1, const gchar *s2)
214 if (s1 == NULL || s2 == NULL)
217 return strcmp(s1, s2);
219 /* strstr with NULL-checking */
220 gchar *strstr2(const gchar *s1, const gchar *s2)
222 if (s1 == NULL || s2 == NULL)
225 return strstr(s1, s2);
228 gint path_cmp(const gchar *s1, const gchar *s2)
232 if (s1 == NULL || s2 == NULL) return -1;
233 if (*s1 == '\0' || *s2 == '\0') return -1;
238 if (s1[len1 - 1] == G_DIR_SEPARATOR) len1--;
239 if (s2[len2 - 1] == G_DIR_SEPARATOR) len2--;
241 return strncmp(s1, s2, MAX(len1, len2));
244 /* remove trailing return code */
245 gchar *strretchomp(gchar *str)
249 if (!*str) return str;
251 for (s = str + strlen(str) - 1;
252 s >= str && (*s == '\n' || *s == '\r');
259 /* remove trailing character */
260 gchar *strtailchomp(gchar *str, gchar tail_char)
264 if (!*str) return str;
265 if (tail_char == '\0') return str;
267 for (s = str + strlen(str) - 1; s >= str && *s == tail_char; s--)
273 /* remove CR (carriage return) */
274 gchar *strcrchomp(gchar *str)
278 if (!*str) return str;
280 s = str + strlen(str) - 1;
281 if (*s == '\n' && s > str && *(s - 1) == '\r') {
289 /* Similar to `strstr' but this function ignores the case of both strings. */
290 gchar *strcasestr(const gchar *haystack, const gchar *needle)
292 register size_t haystack_len, needle_len;
294 haystack_len = strlen(haystack);
295 needle_len = strlen(needle);
297 if (haystack_len < needle_len || needle_len == 0)
300 while (haystack_len >= needle_len) {
301 if (!g_ascii_strncasecmp(haystack, needle, needle_len))
302 return (gchar *)haystack;
312 gpointer my_memmem(gconstpointer haystack, size_t haystacklen,
313 gconstpointer needle, size_t needlelen)
315 const gchar *haystack_ = (const gchar *)haystack;
316 const gchar *needle_ = (const gchar *)needle;
317 const gchar *haystack_cur = (const gchar *)haystack;
320 return memchr(haystack_, *needle_, haystacklen);
322 while ((haystack_cur = memchr(haystack_cur, *needle_, haystacklen))
324 if (haystacklen - (haystack_cur - haystack_) < needlelen)
326 if (memcmp(haystack_cur + 1, needle_ + 1, needlelen - 1) == 0)
327 return (gpointer)haystack_cur;
335 /* Copy no more than N characters of SRC to DEST, with NULL terminating. */
336 gchar *strncpy2(gchar *dest, const gchar *src, size_t n)
338 register const gchar *s = src;
339 register gchar *d = dest;
349 int iswalnum(wint_t wc)
351 return g_ascii_isalnum((int)wc);
356 int iswspace(wint_t wc)
358 return g_ascii_isspace((int)wc);
363 wint_t towlower(wint_t wc)
365 if (wc >= L'A' && wc <= L'Z')
366 return wc + L'a' - L'A';
373 size_t wcslen(const wchar_t *s)
385 /* Copy SRC to DEST. */
386 wchar_t *wcscpy(wchar_t *dest, const wchar_t *src)
394 } while (c != L'\0');
401 /* Copy no more than N wide-characters of SRC to DEST. */
402 wchar_t *wcsncpy (wchar_t *dest, const wchar_t *src, size_t n)
412 } while (c != L'\0');
423 /* Duplicate S, returning an identical malloc'd string. */
424 wchar_t *wcsdup(const wchar_t *s)
429 new_str = g_new(wchar_t, wcslen(s) + 1);
437 /* Duplicate no more than N wide-characters of S,
438 returning an identical malloc'd string. */
439 wchar_t *wcsndup(const wchar_t *s, size_t n)
444 new_str = g_new(wchar_t, n + 1);
445 wcsncpy(new_str, s, n);
446 new_str[n] = (wchar_t)0;
453 wchar_t *strdup_mbstowcs(const gchar *s)
458 new_str = g_new(wchar_t, strlen(s) + 1);
459 if (mbstowcs(new_str, s, strlen(s) + 1) < 0) {
463 new_str = g_realloc(new_str,
464 sizeof(wchar_t) * (wcslen(new_str) + 1));
471 gchar *strdup_wcstombs(const wchar_t *s)
477 len = wcslen(s) * MB_CUR_MAX + 1;
478 new_str = g_new(gchar, len);
479 if (wcstombs(new_str, s, len) < 0) {
483 new_str = g_realloc(new_str, strlen(new_str) + 1);
490 /* Compare S1 and S2, ignoring case. */
491 gint wcsncasecmp(const wchar_t *s1, const wchar_t *s2, size_t n)
497 c1 = towlower(*s1++);
498 c2 = towlower(*s2++);
501 else if (c1 == 0 && c2 == 0)
508 /* Find the first occurrence of NEEDLE in HAYSTACK, ignoring case. */
509 wchar_t *wcscasestr(const wchar_t *haystack, const wchar_t *needle)
511 register size_t haystack_len, needle_len;
513 haystack_len = wcslen(haystack);
514 needle_len = wcslen(needle);
516 if (haystack_len < needle_len || needle_len == 0)
519 while (haystack_len >= needle_len) {
520 if (!wcsncasecmp(haystack, needle, needle_len))
521 return (wchar_t *)haystack;
531 gint get_mbs_len(const gchar *s)
541 mb_len = g_utf8_skip[*(guchar *)p];
553 /* Examine if next block is non-ASCII string */
554 gboolean is_next_nonascii(const gchar *s)
558 /* skip head space */
559 for (p = s; *p != '\0' && g_ascii_isspace(*p); p++)
561 for (; *p != '\0' && !g_ascii_isspace(*p); p++) {
562 if (*(guchar *)p > 127 || *(guchar *)p < 32)
569 gint get_next_word_len(const gchar *s)
573 for (; *s != '\0' && !g_ascii_isspace(*s); s++, len++)
579 /* compare subjects */
580 gint subject_compare(const gchar *s1, const gchar *s2)
584 if (!s1 || !s2) return -1;
585 if (!*s1 || !*s2) return -1;
587 Xstrdup_a(str1, s1, return -1);
588 Xstrdup_a(str2, s2, return -1);
590 trim_subject_for_compare(str1);
591 trim_subject_for_compare(str2);
593 if (!*str1 || !*str2) return -1;
595 return strcmp(str1, str2);
598 gint subject_compare_for_sort(const gchar *s1, const gchar *s2)
602 if (!s1 || !s2) return -1;
604 Xstrdup_a(str1, s1, return -1);
605 Xstrdup_a(str2, s2, return -1);
607 trim_subject_for_sort(str1);
608 trim_subject_for_sort(str2);
610 return g_utf8_collate(str1, str2);
613 void trim_subject_for_compare(gchar *str)
617 eliminate_parenthesis(str, '[', ']');
618 eliminate_parenthesis(str, '(', ')');
621 srcp = str + subject_get_prefix_length(str);
623 memmove(str, srcp, strlen(srcp) + 1);
626 void trim_subject_for_sort(gchar *str)
632 srcp = str + subject_get_prefix_length(str);
634 memmove(str, srcp, strlen(srcp) + 1);
637 void trim_subject(gchar *str)
639 register gchar *srcp;
645 srcp = str + subject_get_prefix_length(str);
650 } else if (*srcp == '(') {
662 else if (*srcp == cl)
669 while (g_ascii_isspace(*srcp)) srcp++;
670 memmove(str, srcp, strlen(srcp) + 1);
673 void eliminate_parenthesis(gchar *str, gchar op, gchar cl)
675 register gchar *srcp, *destp;
680 while ((destp = strchr(destp, op))) {
686 else if (*srcp == cl)
692 while (g_ascii_isspace(*srcp)) srcp++;
693 memmove(destp, srcp, strlen(srcp) + 1);
697 void extract_parenthesis(gchar *str, gchar op, gchar cl)
699 register gchar *srcp, *destp;
704 while ((srcp = strchr(destp, op))) {
707 memmove(destp, srcp + 1, strlen(srcp));
712 else if (*destp == cl)
724 void extract_parenthesis_with_skip_quote(gchar *str, gchar quote_chr,
727 register gchar *srcp, *destp;
729 gboolean in_quote = FALSE;
733 while ((srcp = strchr_with_skip_quote(destp, quote_chr, op))) {
736 memmove(destp, srcp + 1, strlen(srcp));
739 if (*destp == op && !in_quote)
741 else if (*destp == cl && !in_quote)
743 else if (*destp == quote_chr)
755 void eliminate_quote(gchar *str, gchar quote_chr)
757 register gchar *srcp, *destp;
761 while ((destp = strchr(destp, quote_chr))) {
762 if ((srcp = strchr(destp + 1, quote_chr))) {
764 while (g_ascii_isspace(*srcp)) srcp++;
765 memmove(destp, srcp, strlen(srcp) + 1);
773 void extract_quote(gchar *str, gchar quote_chr)
777 if ((str = strchr(str, quote_chr))) {
779 while ((p = strchr(p + 1, quote_chr)) && (p[-1] == '\\')) {
780 memmove(p - 1, p, strlen(p) + 1);
785 memmove(str, str + 1, p - str);
790 void eliminate_address_comment(gchar *str)
792 register gchar *srcp, *destp;
797 while ((destp = strchr(destp, '"'))) {
798 if ((srcp = strchr(destp + 1, '"'))) {
803 while (g_ascii_isspace(*srcp)) srcp++;
804 memmove(destp, srcp, strlen(srcp) + 1);
814 while ((destp = strchr_with_skip_quote(destp, '"', '('))) {
820 else if (*srcp == ')')
826 while (g_ascii_isspace(*srcp)) srcp++;
827 memmove(destp, srcp, strlen(srcp) + 1);
831 gchar *strchr_with_skip_quote(const gchar *str, gint quote_chr, gint c)
833 gboolean in_quote = FALSE;
836 if (*str == c && !in_quote)
838 if (*str == quote_chr)
846 gchar *strrchr_with_skip_quote(const gchar *str, gint quote_chr, gint c)
848 gboolean in_quote = FALSE;
851 p = str + strlen(str) - 1;
853 if (*p == c && !in_quote)
863 void extract_address(gchar *str)
865 eliminate_address_comment(str);
866 if (strchr_with_skip_quote(str, '"', '<'))
867 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
871 void extract_list_id_str(gchar *str)
873 if (strchr_with_skip_quote(str, '"', '<'))
874 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
878 static GSList *address_list_append_real(GSList *addr_list, const gchar *str, gboolean removecomments)
883 if (!str) return addr_list;
885 Xstrdup_a(work, str, return addr_list);
888 eliminate_address_comment(work);
891 while (workp && *workp) {
894 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
900 if (removecomments && strchr_with_skip_quote(workp, '"', '<'))
901 extract_parenthesis_with_skip_quote
902 (workp, '"', '<', '>');
906 addr_list = g_slist_append(addr_list, g_strdup(workp));
914 GSList *address_list_append(GSList *addr_list, const gchar *str)
916 return address_list_append_real(addr_list, str, TRUE);
919 GSList *address_list_append_with_comments(GSList *addr_list, const gchar *str)
921 return address_list_append_real(addr_list, str, FALSE);
924 GSList *references_list_prepend(GSList *msgid_list, const gchar *str)
928 if (!str) return msgid_list;
931 while (strp && *strp) {
932 const gchar *start, *end;
935 if ((start = strchr(strp, '<')) != NULL) {
936 end = strchr(start + 1, '>');
941 msgid = g_strndup(start + 1, end - start - 1);
944 msgid_list = g_slist_prepend(msgid_list, msgid);
954 GSList *references_list_append(GSList *msgid_list, const gchar *str)
958 list = references_list_prepend(NULL, str);
959 list = g_slist_reverse(list);
960 msgid_list = g_slist_concat(msgid_list, list);
965 GSList *newsgroup_list_append(GSList *group_list, const gchar *str)
970 if (!str) return group_list;
972 Xstrdup_a(work, str, return group_list);
976 while (workp && *workp) {
979 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
987 group_list = g_slist_append(group_list,
996 GList *add_history(GList *list, const gchar *str)
1000 g_return_val_if_fail(str != NULL, list);
1002 old = g_list_find_custom(list, (gpointer)str, (GCompareFunc)strcmp2);
1005 list = g_list_remove(list, old->data);
1006 } else if (g_list_length(list) >= MAX_HISTORY_SIZE) {
1009 last = g_list_last(list);
1012 g_list_remove(list, last->data);
1016 list = g_list_prepend(list, g_strdup(str));
1021 void remove_return(gchar *str)
1023 register gchar *p = str;
1026 if (*p == '\n' || *p == '\r')
1027 memmove(p, p + 1, strlen(p));
1033 void remove_space(gchar *str)
1035 register gchar *p = str;
1040 while (g_ascii_isspace(*(p + spc)))
1043 memmove(p, p + spc, strlen(p + spc) + 1);
1049 void unfold_line(gchar *str)
1051 register gchar *p = str;
1055 if (*p == '\n' || *p == '\r') {
1058 while (g_ascii_isspace(*(p + spc)))
1061 memmove(p, p + spc, strlen(p + spc) + 1);
1067 void subst_char(gchar *str, gchar orig, gchar subst)
1069 register gchar *p = str;
1078 void subst_chars(gchar *str, gchar *orig, gchar subst)
1080 register gchar *p = str;
1083 if (strchr(orig, *p) != NULL)
1089 void subst_for_filename(gchar *str)
1093 subst_chars(str, "\t\r\n\\/*", '_');
1096 void subst_for_shellsafe_filename(gchar *str)
1100 subst_for_filename(str);
1101 subst_chars(str, " \"'|&;()<>'!{}[]",'_');
1104 gboolean is_header_line(const gchar *str)
1106 if (str[0] == ':') return FALSE;
1108 while (*str != '\0' && *str != ' ') {
1117 gboolean is_ascii_str(const gchar *str)
1119 const guchar *p = (const guchar *)str;
1121 while (*p != '\0') {
1122 if (*p != '\t' && *p != ' ' &&
1123 *p != '\r' && *p != '\n' &&
1124 (*p < 32 || *p >= 127))
1132 gint get_quote_level(const gchar *str, const gchar *quote_chars)
1134 const gchar *first_pos;
1135 const gchar *last_pos;
1136 const gchar *p = str;
1137 gint quote_level = -1;
1139 /* speed up line processing by only searching to the last '>' */
1140 if ((first_pos = line_has_quote_char(str, quote_chars)) != NULL) {
1141 /* skip a line if it contains a '<' before the initial '>' */
1142 if (memchr(str, '<', first_pos - str) != NULL)
1144 last_pos = line_has_quote_char_last(first_pos, quote_chars);
1148 while (p <= last_pos) {
1149 while (p < last_pos) {
1150 if (g_ascii_isspace(*p))
1156 if (strchr(quote_chars, *p))
1158 else if (*p != '-' && !g_ascii_isspace(*p) && p <= last_pos) {
1159 /* any characters are allowed except '-' and space */
1161 && !strchr(quote_chars, *p)
1162 && !g_ascii_isspace(*p)
1165 if (strchr(quote_chars, *p))
1177 gint check_line_length(const gchar *str, gint max_chars, gint *line)
1179 const gchar *p = str, *q;
1180 gint cur_line = 0, len;
1182 while ((q = strchr(p, '\n')) != NULL) {
1184 if (len > max_chars) {
1194 if (len > max_chars) {
1203 const gchar * line_has_quote_char(const gchar * str, const gchar *quote_chars)
1205 gchar * position = NULL;
1206 gchar * tmp_pos = NULL;
1209 if (quote_chars == NULL)
1212 for (i = 0; i < strlen(quote_chars); i++) {
1213 tmp_pos = strchr (str, quote_chars[i]);
1215 || (tmp_pos != NULL && position >= tmp_pos) )
1221 const gchar * line_has_quote_char_last(const gchar * str, const gchar *quote_chars)
1223 gchar * position = NULL;
1224 gchar * tmp_pos = NULL;
1227 if (quote_chars == NULL)
1230 for (i = 0; i < strlen(quote_chars); i++) {
1231 tmp_pos = strrchr (str, quote_chars[i]);
1233 || (tmp_pos != NULL && position <= tmp_pos) )
1239 gchar *strstr_with_skip_quote(const gchar *haystack, const gchar *needle)
1241 register guint haystack_len, needle_len;
1242 gboolean in_squote = FALSE, in_dquote = FALSE;
1244 haystack_len = strlen(haystack);
1245 needle_len = strlen(needle);
1247 if (haystack_len < needle_len || needle_len == 0)
1250 while (haystack_len >= needle_len) {
1251 if (!in_squote && !in_dquote &&
1252 !strncmp(haystack, needle, needle_len))
1253 return (gchar *)haystack;
1255 /* 'foo"bar"' -> foo"bar"
1256 "foo'bar'" -> foo'bar' */
1257 if (*haystack == '\'') {
1260 else if (!in_dquote)
1262 } else if (*haystack == '\"') {
1265 else if (!in_squote)
1276 gchar *strchr_parenthesis_close(const gchar *str, gchar op, gchar cl)
1279 gchar quote_chr = '"';
1281 gboolean in_quote = FALSE;
1285 if ((p = strchr_with_skip_quote(p, quote_chr, op))) {
1289 if (*p == op && !in_quote)
1291 else if (*p == cl && !in_quote)
1293 else if (*p == quote_chr)
1306 gchar **strsplit_parenthesis(const gchar *str, gchar op, gchar cl,
1309 GSList *string_list = NULL, *slist;
1311 const gchar *s_op, *s_cl;
1314 g_return_val_if_fail(str != NULL, NULL);
1317 max_tokens = G_MAXINT;
1319 s_op = strchr_with_skip_quote(str, '"', op);
1320 if (!s_op) return NULL;
1322 s_cl = strchr_parenthesis_close(str, op, cl);
1330 new_string = g_new(gchar, len + 1);
1331 strncpy(new_string, str, len);
1332 new_string[len] = 0;
1333 string_list = g_slist_prepend(string_list, new_string);
1337 while (*str && g_ascii_isspace(*str)) str++;
1339 string_list = g_slist_prepend(string_list,
1342 s_op = strchr_with_skip_quote(str, '"', op);
1343 if (!--max_tokens || !s_op) break;
1347 s_cl = strchr_parenthesis_close(str, op, cl);
1348 } while (--max_tokens && s_cl);
1351 str_array = g_new(gchar*, n);
1355 str_array[i--] = NULL;
1356 for (slist = string_list; slist; slist = slist->next)
1357 str_array[i--] = slist->data;
1359 g_slist_free(string_list);
1364 gchar **strsplit_with_quote(const gchar *str, const gchar *delim,
1367 GSList *string_list = NULL, *slist;
1368 gchar **str_array, *s, *new_str;
1369 guint i, n = 1, len;
1371 g_return_val_if_fail(str != NULL, NULL);
1372 g_return_val_if_fail(delim != NULL, NULL);
1375 max_tokens = G_MAXINT;
1377 s = strstr_with_skip_quote(str, delim);
1379 guint delimiter_len = strlen(delim);
1383 new_str = g_strndup(str, len);
1385 if (new_str[0] == '\'' || new_str[0] == '\"') {
1386 if (new_str[len - 1] == new_str[0]) {
1387 new_str[len - 1] = '\0';
1388 memmove(new_str, new_str + 1, len - 1);
1391 string_list = g_slist_prepend(string_list, new_str);
1393 str = s + delimiter_len;
1394 s = strstr_with_skip_quote(str, delim);
1395 } while (--max_tokens && s);
1399 new_str = g_strdup(str);
1400 if (new_str[0] == '\'' || new_str[0] == '\"') {
1402 if (new_str[len - 1] == new_str[0]) {
1403 new_str[len - 1] = '\0';
1404 memmove(new_str, new_str + 1, len - 1);
1407 string_list = g_slist_prepend(string_list, new_str);
1411 str_array = g_new(gchar*, n);
1415 str_array[i--] = NULL;
1416 for (slist = string_list; slist; slist = slist->next)
1417 str_array[i--] = slist->data;
1419 g_slist_free(string_list);
1424 gchar *get_abbrev_newsgroup_name(const gchar *group, gint len)
1426 gchar *abbrev_group;
1428 const gchar *p = group;
1431 g_return_val_if_fail(group != NULL, NULL);
1433 last = group + strlen(group);
1434 abbrev_group = ap = g_malloc(strlen(group) + 1);
1439 if ((ap - abbrev_group) + (last - p) > len && strchr(p, '.')) {
1441 while (*p != '.') p++;
1444 return abbrev_group;
1449 return abbrev_group;
1452 gchar *trim_string(const gchar *str, gint len)
1454 const gchar *p = str;
1459 if (!str) return NULL;
1460 if (strlen(str) <= len)
1461 return g_strdup(str);
1462 if (g_utf8_validate(str, -1, NULL) == FALSE)
1463 return g_strdup(str);
1465 while (*p != '\0') {
1466 mb_len = g_utf8_skip[*(guchar *)p];
1469 else if (new_len + mb_len > len)
1476 Xstrndup_a(new_str, str, new_len, return g_strdup(str));
1477 return g_strconcat(new_str, "...", NULL);
1480 GList *uri_list_extract_filenames(const gchar *uri_list)
1482 GList *result = NULL;
1484 gchar *escaped_utf8uri;
1490 while (g_ascii_isspace(*p)) p++;
1491 if (!strncmp(p, "file:", 5)) {
1494 while (*q && *q != '\n' && *q != '\r') q++;
1497 gchar *file, *locale_file = NULL;
1499 while (q > p && g_ascii_isspace(*q))
1501 Xalloca(escaped_utf8uri, q - p + 2,
1503 Xalloca(file, q - p + 2,
1506 strncpy(escaped_utf8uri, p, q - p + 1);
1507 escaped_utf8uri[q - p + 1] = '\0';
1508 decode_uri(file, escaped_utf8uri);
1510 * g_filename_from_uri() rejects escaped/locale encoded uri
1511 * string which come from Nautilus.
1513 if (g_utf8_validate(file, -1, NULL))
1515 = conv_codeset_strdup(
1518 conv_get_locale_charset_str());
1520 locale_file = g_strdup(file + 5);
1521 result = g_list_append(result, locale_file);
1525 p = strchr(p, '\n');
1532 /* Converts two-digit hexadecimal to decimal. Used for unescaping escaped
1535 static gint axtoi(const gchar *hexstr)
1537 gint hi, lo, result;
1540 if ('0' <= hi && hi <= '9') {
1543 if ('a' <= hi && hi <= 'f') {
1546 if ('A' <= hi && hi <= 'F') {
1551 if ('0' <= lo && lo <= '9') {
1554 if ('a' <= lo && lo <= 'f') {
1557 if ('A' <= lo && lo <= 'F') {
1560 result = lo + (16 * hi);
1564 gboolean is_uri_string(const gchar *str)
1566 return (g_ascii_strncasecmp(str, "http://", 7) == 0 ||
1567 g_ascii_strncasecmp(str, "https://", 8) == 0 ||
1568 g_ascii_strncasecmp(str, "ftp://", 6) == 0 ||
1569 g_ascii_strncasecmp(str, "www.", 4) == 0);
1572 gchar *get_uri_path(const gchar *uri)
1574 if (g_ascii_strncasecmp(uri, "http://", 7) == 0)
1575 return (gchar *)(uri + 7);
1576 else if (g_ascii_strncasecmp(uri, "https://", 8) == 0)
1577 return (gchar *)(uri + 8);
1578 else if (g_ascii_strncasecmp(uri, "ftp://", 6) == 0)
1579 return (gchar *)(uri + 6);
1581 return (gchar *)uri;
1584 gint get_uri_len(const gchar *str)
1588 if (is_uri_string(str)) {
1589 for (p = str; *p != '\0'; p++) {
1590 if (!g_ascii_isgraph(*p) || strchr("()<>\"", *p))
1599 /* Decodes URL-Encoded strings (i.e. strings in which spaces are replaced by
1600 * plusses, and escape characters are used)
1602 void decode_uri(gchar *decoded_uri, const gchar *encoded_uri)
1604 gchar *dec = decoded_uri;
1605 const gchar *enc = encoded_uri;
1610 if (isxdigit((guchar)enc[0]) &&
1611 isxdigit((guchar)enc[1])) {
1629 gint scan_mailto_url(const gchar *mailto, gchar **to, gchar **cc, gchar **bcc,
1630 gchar **subject, gchar **body)
1635 Xstrdup_a(tmp_mailto, mailto, return -1);
1637 if (!strncmp(tmp_mailto, "mailto:", 7))
1640 p = strchr(tmp_mailto, '?');
1647 *to = g_strdup(tmp_mailto);
1650 gchar *field, *value;
1667 if (*value == '\0') continue;
1669 if (cc && !*cc && !g_ascii_strcasecmp(field, "cc")) {
1670 *cc = g_strdup(value);
1671 } else if (bcc && !*bcc && !g_ascii_strcasecmp(field, "bcc")) {
1672 *bcc = g_strdup(value);
1673 } else if (subject && !*subject &&
1674 !g_ascii_strcasecmp(field, "subject")) {
1675 *subject = g_malloc(strlen(value) + 1);
1676 decode_uri(*subject, value);
1677 } else if (body && !*body && !g_ascii_strcasecmp(field, "body")) {
1678 *body = g_malloc(strlen(value) + 1);
1679 decode_uri(*body, value);
1687 * We need this wrapper around g_get_home_dir(), so that
1688 * we can fix some Windoze things here. Should be done in glibc of course
1689 * but as long as we are not able to do our own extensions to glibc, we do
1692 const gchar *get_home_dir(void)
1694 #if HAVE_DOSISH_SYSTEM
1695 static gchar *home_dir;
1698 home_dir = read_w32_registry_string(NULL,
1699 "Software\\Sylpheed", "HomeDir" );
1700 if (!home_dir || !*home_dir) {
1701 if (getenv ("HOMEDRIVE") && getenv("HOMEPATH")) {
1702 const char *s = g_get_home_dir();
1704 home_dir = g_strdup (s);
1706 if (!home_dir || !*home_dir)
1707 home_dir = g_strdup ("c:\\sylpheed");
1709 debug_print("initialized home_dir to '%s'\n", home_dir);
1712 #else /* standard glib */
1713 return g_get_home_dir();
1717 const gchar *get_rc_dir(void)
1719 static gchar *rc_dir = NULL;
1722 rc_dir = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
1728 const gchar *get_news_cache_dir(void)
1730 static gchar *news_cache_dir = NULL;
1732 if (!news_cache_dir)
1733 news_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1734 NEWS_CACHE_DIR, NULL);
1736 return news_cache_dir;
1739 const gchar *get_imap_cache_dir(void)
1741 static gchar *imap_cache_dir = NULL;
1743 if (!imap_cache_dir)
1744 imap_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1745 IMAP_CACHE_DIR, NULL);
1747 return imap_cache_dir;
1750 const gchar *get_mbox_cache_dir(void)
1752 static gchar *mbox_cache_dir = NULL;
1754 if (!mbox_cache_dir)
1755 mbox_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1756 MBOX_CACHE_DIR, NULL);
1758 return mbox_cache_dir;
1761 const gchar *get_mime_tmp_dir(void)
1763 static gchar *mime_tmp_dir = NULL;
1766 mime_tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1767 MIME_TMP_DIR, NULL);
1769 return mime_tmp_dir;
1772 const gchar *get_template_dir(void)
1774 static gchar *template_dir = NULL;
1777 template_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1778 TEMPLATE_DIR, NULL);
1780 return template_dir;
1783 const gchar *get_header_cache_dir(void)
1785 static gchar *header_dir = NULL;
1788 header_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1789 HEADER_CACHE_DIR, NULL);
1794 const gchar *get_tmp_dir(void)
1796 static gchar *tmp_dir = NULL;
1799 tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1805 gchar *get_tmp_file(void)
1808 static guint32 id = 0;
1810 tmp_file = g_strdup_printf("%s%ctmpfile.%08x",
1811 get_tmp_dir(), G_DIR_SEPARATOR, id++);
1816 const gchar *get_domain_name(void)
1818 static gchar *domain_name = NULL;
1824 if (uname(&uts) < 0) {
1825 perror("gethostname");
1826 domain_name = "unknown";
1828 if ((hp = my_gethostbyname(uts.nodename)) == NULL) {
1829 perror("gethostbyname");
1830 domain_name = g_strdup(uts.nodename);
1832 domain_name = g_strdup(hp->h_name);
1836 debug_print("domain name = %s\n", domain_name);
1842 off_t get_file_size(const gchar *file)
1846 if (stat(file, &s) < 0) {
1847 FILE_OP_ERROR(file, "stat");
1854 off_t get_file_size_as_crlf(const gchar *file)
1858 gchar buf[BUFFSIZE];
1860 if ((fp = fopen(file, "rb")) == NULL) {
1861 FILE_OP_ERROR(file, "fopen");
1865 while (fgets(buf, sizeof(buf), fp) != NULL) {
1867 size += strlen(buf) + 2;
1871 FILE_OP_ERROR(file, "fgets");
1880 off_t get_left_file_size(FILE *fp)
1886 if ((pos = ftell(fp)) < 0) {
1890 if (fseek(fp, 0L, SEEK_END) < 0) {
1894 if ((end = ftell(fp)) < 0) {
1899 if (fseek(fp, pos, SEEK_SET) < 0) {
1907 gboolean file_exist(const gchar *file, gboolean allow_fifo)
1914 if (stat(file, &s) < 0) {
1915 if (ENOENT != errno) FILE_OP_ERROR(file, "stat");
1919 if (S_ISREG(s.st_mode) || (allow_fifo && S_ISFIFO(s.st_mode)))
1925 gboolean is_dir_exist(const gchar *dir)
1930 return g_file_test(dir, G_FILE_TEST_IS_DIR);
1933 gboolean is_file_entry_exist(const gchar *file)
1938 return g_file_test(file, G_FILE_TEST_EXISTS);
1941 gboolean dirent_is_regular_file(struct dirent *d)
1943 #ifdef HAVE_DIRENT_D_TYPE
1944 if (d->d_type == DT_REG)
1946 else if (d->d_type != DT_UNKNOWN)
1950 return g_file_test(d->d_name, G_FILE_TEST_IS_REGULAR);
1953 gboolean dirent_is_directory(struct dirent *d)
1955 #ifdef HAVE_DIRENT_D_TYPE
1956 if (d->d_type == DT_DIR)
1958 else if (d->d_type != DT_UNKNOWN)
1962 return g_file_test(d->d_name, G_FILE_TEST_IS_DIR);
1965 gint change_dir(const gchar *dir)
1967 gchar *prevdir = NULL;
1970 prevdir = g_get_current_dir();
1972 if (chdir(dir) < 0) {
1973 FILE_OP_ERROR(dir, "chdir");
1974 if (debug_mode) g_free(prevdir);
1976 } else if (debug_mode) {
1979 cwd = g_get_current_dir();
1980 if (strcmp(prevdir, cwd) != 0)
1981 g_print("current dir: %s\n", cwd);
1989 gint make_dir(const gchar *dir)
1991 if (mkdir(dir, S_IRWXU) < 0) {
1992 FILE_OP_ERROR(dir, "mkdir");
1995 if (chmod(dir, S_IRWXU) < 0)
1996 FILE_OP_ERROR(dir, "chmod");
2001 gint make_dir_hier(const gchar *dir)
2006 for (p = dir; (p = strchr(p, G_DIR_SEPARATOR)) != NULL; p++) {
2007 parent_dir = g_strndup(dir, p - dir);
2008 if (*parent_dir != '\0') {
2009 if (!is_dir_exist(parent_dir)) {
2010 if (make_dir(parent_dir) < 0) {
2019 if (!is_dir_exist(dir)) {
2020 if (make_dir(dir) < 0)
2027 gint remove_all_files(const gchar *dir)
2033 prev_dir = g_get_current_dir();
2035 if (chdir(dir) < 0) {
2036 FILE_OP_ERROR(dir, "chdir");
2041 if ((dp = opendir(".")) == NULL) {
2042 FILE_OP_ERROR(dir, "opendir");
2047 while ((d = readdir(dp)) != NULL) {
2048 if (!strcmp(d->d_name, ".") ||
2049 !strcmp(d->d_name, ".."))
2052 if (unlink(d->d_name) < 0)
2053 FILE_OP_ERROR(d->d_name, "unlink");
2058 if (chdir(prev_dir) < 0) {
2059 FILE_OP_ERROR(prev_dir, "chdir");
2069 gint remove_numbered_files(const gchar *dir, guint first, guint last)
2076 prev_dir = g_get_current_dir();
2078 if (chdir(dir) < 0) {
2079 FILE_OP_ERROR(dir, "chdir");
2084 if ((dp = opendir(".")) == NULL) {
2085 FILE_OP_ERROR(dir, "opendir");
2090 while ((d = readdir(dp)) != NULL) {
2091 file_no = to_number(d->d_name);
2092 if (file_no > 0 && first <= file_no && file_no <= last) {
2093 if (is_dir_exist(d->d_name))
2095 if (unlink(d->d_name) < 0)
2096 FILE_OP_ERROR(d->d_name, "unlink");
2102 if (chdir(prev_dir) < 0) {
2103 FILE_OP_ERROR(prev_dir, "chdir");
2113 gint remove_numbered_files_not_in_list(const gchar *dir, GSList *numberlist)
2120 prev_dir = g_get_current_dir();
2122 if (chdir(dir) < 0) {
2123 FILE_OP_ERROR(dir, "chdir");
2128 if ((dp = opendir(".")) == NULL) {
2129 FILE_OP_ERROR(dir, "opendir");
2134 while ((d = readdir(dp)) != NULL) {
2135 file_no = to_number(d->d_name);
2136 if (file_no > 0 && (g_slist_find(numberlist, GINT_TO_POINTER(file_no)) == NULL)) {
2137 debug_print("removing unwanted file %d from %s\n", file_no, dir);
2138 if (is_dir_exist(d->d_name))
2140 if (unlink(d->d_name) < 0)
2141 FILE_OP_ERROR(d->d_name, "unlink");
2147 if (chdir(prev_dir) < 0) {
2148 FILE_OP_ERROR(prev_dir, "chdir");
2158 gint remove_all_numbered_files(const gchar *dir)
2160 return remove_numbered_files(dir, 0, UINT_MAX);
2163 gint remove_expired_files(const gchar *dir, guint hours)
2170 time_t mtime, now, expire_time;
2172 prev_dir = g_get_current_dir();
2174 if (chdir(dir) < 0) {
2175 FILE_OP_ERROR(dir, "chdir");
2180 if ((dp = opendir(".")) == NULL) {
2181 FILE_OP_ERROR(dir, "opendir");
2187 expire_time = hours * 60 * 60;
2189 while ((d = readdir(dp)) != NULL) {
2190 file_no = to_number(d->d_name);
2192 if (stat(d->d_name, &s) < 0) {
2193 FILE_OP_ERROR(d->d_name, "stat");
2196 if (S_ISDIR(s.st_mode))
2198 mtime = MAX(s.st_mtime, s.st_atime);
2199 if (now - mtime > expire_time) {
2200 if (unlink(d->d_name) < 0)
2201 FILE_OP_ERROR(d->d_name, "unlink");
2208 if (chdir(prev_dir) < 0) {
2209 FILE_OP_ERROR(prev_dir, "chdir");
2219 gint remove_dir_recursive(const gchar *dir)
2226 /* g_print("dir = %s\n", dir); */
2228 if (stat(dir, &s) < 0) {
2229 FILE_OP_ERROR(dir, "stat");
2230 if (ENOENT == errno) return 0;
2234 if (!S_ISDIR(s.st_mode)) {
2235 if (unlink(dir) < 0) {
2236 FILE_OP_ERROR(dir, "unlink");
2243 prev_dir = g_get_current_dir();
2244 /* g_print("prev_dir = %s\n", prev_dir); */
2246 if (!path_cmp(prev_dir, dir)) {
2248 if (chdir("..") < 0) {
2249 FILE_OP_ERROR(dir, "chdir");
2252 prev_dir = g_get_current_dir();
2255 if (chdir(dir) < 0) {
2256 FILE_OP_ERROR(dir, "chdir");
2261 if ((dp = opendir(".")) == NULL) {
2262 FILE_OP_ERROR(dir, "opendir");
2268 /* remove all files in the directory */
2269 while ((d = readdir(dp)) != NULL) {
2270 if (!strcmp(d->d_name, ".") ||
2271 !strcmp(d->d_name, ".."))
2274 /* g_print("removing %s\n", d->d_name); */
2276 if (dirent_is_directory(d)) {
2277 if (remove_dir_recursive(d->d_name) < 0) {
2278 g_warning("can't remove directory\n");
2282 if (unlink(d->d_name) < 0)
2283 FILE_OP_ERROR(d->d_name, "unlink");
2289 if (chdir(prev_dir) < 0) {
2290 FILE_OP_ERROR(prev_dir, "chdir");
2297 if (rmdir(dir) < 0) {
2298 FILE_OP_ERROR(dir, "rmdir");
2306 /* this seems to be slower than the stdio version... */
2307 gint copy_file(const gchar *src, const gchar *dest)
2309 gint src_fd, dest_fd;
2313 gchar *dest_bak = NULL;
2315 if ((src_fd = open(src, O_RDONLY)) < 0) {
2316 FILE_OP_ERROR(src, "open");
2320 if (is_file_exist(dest)) {
2321 dest_bak = g_strconcat(dest, ".bak", NULL);
2322 if (rename(dest, dest_bak) < 0) {
2323 FILE_OP_ERROR(dest, "rename");
2330 if ((dest_fd = open(dest, O_RDWR|O_CREAT, S_IRUSR|S_IWUSR)) < 0) {
2331 FILE_OP_ERROR(dest, "open");
2334 if (rename(dest_bak, dest) < 0)
2335 FILE_OP_ERROR(dest_bak, "rename");
2341 while ((n_read = read(src_fd, buf, sizeof(buf))) > 0) {
2346 n_write = write(dest_fd, bufp, len);
2348 g_warning("writing to %s failed.\n", dest);
2353 if (rename(dest_bak, dest) < 0)
2354 FILE_OP_ERROR(dest_bak, "rename");
2367 if (n_read < 0 || get_file_size(src) != get_file_size(dest)) {
2368 g_warning("File copy from %s to %s failed.\n", src, dest);
2371 if (rename(dest_bak, dest) < 0)
2372 FILE_OP_ERROR(dest_bak, "rename");
2385 * Append src file body to the tail of dest file.
2386 * Now keep_backup has no effects.
2388 gint append_file(const gchar *src, const gchar *dest, gboolean keep_backup)
2390 FILE *src_fp, *dest_fp;
2394 gboolean err = FALSE;
2396 if ((src_fp = fopen(src, "rb")) == NULL) {
2397 FILE_OP_ERROR(src, "fopen");
2401 if ((dest_fp = fopen(dest, "ab")) == NULL) {
2402 FILE_OP_ERROR(dest, "fopen");
2407 if (change_file_mode_rw(dest_fp, dest) < 0) {
2408 FILE_OP_ERROR(dest, "chmod");
2409 g_warning("can't change file mode\n");
2412 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
2413 if (n_read < sizeof(buf) && ferror(src_fp))
2415 if (fwrite(buf, 1, n_read, dest_fp) < n_read) {
2416 g_warning("writing to %s failed.\n", dest);
2424 if (ferror(src_fp)) {
2425 FILE_OP_ERROR(src, "fread");
2429 if (fclose(dest_fp) == EOF) {
2430 FILE_OP_ERROR(dest, "fclose");
2442 gint copy_file(const gchar *src, const gchar *dest, gboolean keep_backup)
2444 FILE *src_fp, *dest_fp;
2447 gchar *dest_bak = NULL;
2448 gboolean err = FALSE;
2450 if ((src_fp = fopen(src, "rb")) == NULL) {
2451 FILE_OP_ERROR(src, "fopen");
2454 if (is_file_exist(dest)) {
2455 dest_bak = g_strconcat(dest, ".bak", NULL);
2456 if (rename(dest, dest_bak) < 0) {
2457 FILE_OP_ERROR(dest, "rename");
2464 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2465 FILE_OP_ERROR(dest, "fopen");
2468 if (rename(dest_bak, dest) < 0)
2469 FILE_OP_ERROR(dest_bak, "rename");
2475 if (change_file_mode_rw(dest_fp, dest) < 0) {
2476 FILE_OP_ERROR(dest, "chmod");
2477 g_warning("can't change file mode\n");
2480 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
2481 if (n_read < sizeof(buf) && ferror(src_fp))
2483 if (fwrite(buf, 1, n_read, dest_fp) < n_read) {
2484 g_warning("writing to %s failed.\n", dest);
2489 if (rename(dest_bak, dest) < 0)
2490 FILE_OP_ERROR(dest_bak, "rename");
2497 if (ferror(src_fp)) {
2498 FILE_OP_ERROR(src, "fread");
2502 if (fclose(dest_fp) == EOF) {
2503 FILE_OP_ERROR(dest, "fclose");
2510 if (rename(dest_bak, dest) < 0)
2511 FILE_OP_ERROR(dest_bak, "rename");
2517 if (keep_backup == FALSE && dest_bak)
2525 gint move_file(const gchar *src, const gchar *dest, gboolean overwrite)
2527 if (overwrite == FALSE && is_file_exist(dest)) {
2528 g_warning("move_file(): file %s already exists.", dest);
2532 if (rename(src, dest) == 0) return 0;
2534 if (EXDEV != errno) {
2535 FILE_OP_ERROR(src, "rename");
2539 if (copy_file(src, dest, FALSE) < 0) return -1;
2546 gint copy_file_part_to_fp(FILE *fp, off_t offset, size_t length, FILE *dest_fp)
2549 gint bytes_left, to_read;
2552 if (fseek(fp, offset, SEEK_SET) < 0) {
2557 bytes_left = length;
2558 to_read = MIN(bytes_left, sizeof(buf));
2560 while ((n_read = fread(buf, sizeof(gchar), to_read, fp)) > 0) {
2561 if (n_read < to_read && ferror(fp))
2563 if (fwrite(buf, 1, n_read, dest_fp) < n_read) {
2566 bytes_left -= n_read;
2567 if (bytes_left == 0)
2569 to_read = MIN(bytes_left, sizeof(buf));
2580 gint copy_file_part(FILE *fp, off_t offset, size_t length, const gchar *dest)
2583 gboolean err = FALSE;
2585 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2586 FILE_OP_ERROR(dest, "fopen");
2590 if (change_file_mode_rw(dest_fp, dest) < 0) {
2591 FILE_OP_ERROR(dest, "chmod");
2592 g_warning("can't change file mode\n");
2595 if (copy_file_part_to_fp(fp, offset, length, dest_fp) < 0)
2598 if (!err && fclose(dest_fp) == EOF) {
2599 FILE_OP_ERROR(dest, "fclose");
2604 g_warning("writing to %s failed.\n", dest);
2612 /* convert line endings into CRLF. If the last line doesn't end with
2613 * linebreak, add it.
2615 gchar *canonicalize_str(const gchar *str)
2621 for (p = str; *p != '\0'; ++p) {
2628 if (p == str || *(p - 1) != '\n')
2631 out = outp = g_malloc(new_len + 1);
2632 for (p = str; *p != '\0'; ++p) {
2639 if (p == str || *(p - 1) != '\n') {
2648 gint canonicalize_file(const gchar *src, const gchar *dest)
2650 FILE *src_fp, *dest_fp;
2651 gchar buf[BUFFSIZE];
2653 gboolean err = FALSE;
2654 gboolean last_linebreak = FALSE;
2656 if ((src_fp = fopen(src, "rb")) == NULL) {
2657 FILE_OP_ERROR(src, "fopen");
2661 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2662 FILE_OP_ERROR(dest, "fopen");
2667 if (change_file_mode_rw(dest_fp, dest) < 0) {
2668 FILE_OP_ERROR(dest, "chmod");
2669 g_warning("can't change file mode\n");
2672 while (fgets(buf, sizeof(buf), src_fp) != NULL) {
2676 if (len == 0) break;
2677 last_linebreak = FALSE;
2679 if (buf[len - 1] != '\n') {
2680 last_linebreak = TRUE;
2681 r = fputs(buf, dest_fp);
2682 } else if (len > 1 && buf[len - 1] == '\n' && buf[len - 2] == '\r') {
2683 r = fputs(buf, dest_fp);
2686 r = fwrite(buf, 1, len - 1, dest_fp);
2691 r = fputs("\r\n", dest_fp);
2695 g_warning("writing to %s failed.\n", dest);
2703 if (last_linebreak == TRUE) {
2704 if (fputs("\r\n", dest_fp) == EOF)
2708 if (ferror(src_fp)) {
2709 FILE_OP_ERROR(src, "fgets");
2713 if (fclose(dest_fp) == EOF) {
2714 FILE_OP_ERROR(dest, "fclose");
2726 gint canonicalize_file_replace(const gchar *file)
2730 tmp_file = get_tmp_file();
2732 if (canonicalize_file(file, tmp_file) < 0) {
2737 if (move_file(tmp_file, file, TRUE) < 0) {
2738 g_warning("can't replace %s .\n", file);
2748 gint uncanonicalize_file(const gchar *src, const gchar *dest)
2750 FILE *src_fp, *dest_fp;
2751 gchar buf[BUFFSIZE];
2752 gboolean err = FALSE;
2754 if ((src_fp = fopen(src, "rb")) == NULL) {
2755 FILE_OP_ERROR(src, "fopen");
2759 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2760 FILE_OP_ERROR(dest, "fopen");
2765 if (change_file_mode_rw(dest_fp, dest) < 0) {
2766 FILE_OP_ERROR(dest, "chmod");
2767 g_warning("can't change file mode\n");
2770 while (fgets(buf, sizeof(buf), src_fp) != NULL) {
2772 if (fputs(buf, dest_fp) == EOF) {
2773 g_warning("writing to %s failed.\n", dest);
2781 if (ferror(src_fp)) {
2782 FILE_OP_ERROR(src, "fgets");
2786 if (fclose(dest_fp) == EOF) {
2787 FILE_OP_ERROR(dest, "fclose");
2799 gint uncanonicalize_file_replace(const gchar *file)
2803 tmp_file = get_tmp_file();
2805 if (uncanonicalize_file(file, tmp_file) < 0) {
2810 if (move_file(tmp_file, file, TRUE) < 0) {
2811 g_warning("can't replace %s .\n", file);
2821 gchar *normalize_newlines(const gchar *str)
2823 const gchar *p = str;
2826 out = outp = g_malloc(strlen(str) + 1);
2827 for (p = str; *p != '\0'; ++p) {
2829 if (*(p + 1) != '\n')
2840 gchar *get_outgoing_rfc2822_str(FILE *fp)
2842 gchar buf[BUFFSIZE];
2846 str = g_string_new(NULL);
2848 /* output header part */
2849 while (fgets(buf, sizeof(buf), fp) != NULL) {
2851 if (!g_ascii_strncasecmp(buf, "Bcc:", 4)) {
2858 else if (next != ' ' && next != '\t') {
2862 if (fgets(buf, sizeof(buf), fp) == NULL)
2866 g_string_append(str, buf);
2867 g_string_append(str, "\r\n");
2873 /* output body part */
2874 while (fgets(buf, sizeof(buf), fp) != NULL) {
2877 g_string_append_c(str, '.');
2878 g_string_append(str, buf);
2879 g_string_append(str, "\r\n");
2883 g_string_free(str, FALSE);
2889 * Create a new boundary in a way that it is very unlikely that this
2890 * will occur in the following text. It would be easy to ensure
2891 * uniqueness if everything is either quoted-printable or base64
2892 * encoded (note that conversion is allowed), but because MIME bodies
2893 * may be nested, it may happen that the same boundary has already
2894 * been used. We avoid scanning the message for conflicts and hope the
2897 * boundary := 0*69<bchars> bcharsnospace
2898 * bchars := bcharsnospace / " "
2899 * bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" /
2900 * "+" / "_" / "," / "-" / "." /
2901 * "/" / ":" / "=" / "?"
2903 * some special characters removed because of buggy MTAs
2906 gchar *generate_mime_boundary(const gchar *prefix)
2908 static gchar tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2909 "abcdefghijklmnopqrstuvwxyz"
2918 /* We make the boundary depend on the pid, so that all running
2919 * processes generate different values even when they have been
2920 * started within the same second and srandom(time(NULL)) has been
2921 * used. I can't see whether this is really an advantage but it
2922 * doesn't do any harm.
2924 for (i = 0; i < sizeof(buf_uniq) - 1; i++)
2925 buf_uniq[i] = tbl[(rand() ^ pid) % (sizeof(tbl) - 1)];
2928 get_rfc822_date(buf_date, sizeof(buf_date));
2929 subst_char(buf_date, ' ', '_');
2930 subst_char(buf_date, ',', '_');
2931 subst_char(buf_date, ':', '_');
2933 return g_strdup_printf("%s_%s_%s", prefix ? prefix : "Multipart",
2934 buf_date, buf_uniq);
2937 gint change_file_mode_rw(FILE *fp, const gchar *file)
2940 return fchmod(fileno(fp), S_IRUSR|S_IWUSR);
2942 return chmod(file, S_IRUSR|S_IWUSR);
2946 FILE *my_tmpfile(void)
2949 const gchar suffix[] = ".XXXXXX";
2950 const gchar *tmpdir;
2952 const gchar *progname;
2958 tmpdir = get_tmp_dir();
2959 tmplen = strlen(tmpdir);
2960 progname = g_get_prgname();
2961 if (progname == NULL)
2962 progname = "sylpheed-claws";
2963 proglen = strlen(progname);
2964 Xalloca(fname, tmplen + 1 + proglen + sizeof(suffix),
2967 memcpy(fname, tmpdir, tmplen);
2968 fname[tmplen] = G_DIR_SEPARATOR;
2969 memcpy(fname + tmplen + 1, progname, proglen);
2970 memcpy(fname + tmplen + 1 + proglen, suffix, sizeof(suffix));
2972 fd = mkstemp(fname);
2978 fp = fdopen(fd, "w+b");
2983 #endif /* HAVE_MKSTEMP */
2988 FILE *get_tmpfile_in_dir(const gchar *dir, gchar **filename)
2992 *filename = g_strdup_printf("%s%csylpheed.XXXXXX", dir, G_DIR_SEPARATOR);
2993 fd = mkstemp(*filename);
2995 return fdopen(fd, "w+");
2998 FILE *str_open_as_stream(const gchar *str)
3003 g_return_val_if_fail(str != NULL, NULL);
3007 FILE_OP_ERROR("str_open_as_stream", "my_tmpfile");
3012 if (len == 0) return fp;
3014 if (fwrite(str, 1, len, fp) != len) {
3015 FILE_OP_ERROR("str_open_as_stream", "fwrite");
3024 gint str_write_to_file(const gchar *str, const gchar *file)
3029 g_return_val_if_fail(str != NULL, -1);
3030 g_return_val_if_fail(file != NULL, -1);
3032 if ((fp = fopen(file, "wb")) == NULL) {
3033 FILE_OP_ERROR(file, "fopen");
3043 if (fwrite(str, 1, len, fp) != len) {
3044 FILE_OP_ERROR(file, "fwrite");
3050 if (fclose(fp) == EOF) {
3051 FILE_OP_ERROR(file, "fclose");
3059 gchar *file_read_to_str(const gchar *file)
3064 g_return_val_if_fail(file != NULL, NULL);
3066 if ((fp = fopen(file, "rb")) == NULL) {
3067 FILE_OP_ERROR(file, "fopen");
3071 str = file_read_stream_to_str(fp);
3078 gchar *file_read_stream_to_str(FILE *fp)
3085 g_return_val_if_fail(fp != NULL, NULL);
3087 array = g_byte_array_new();
3089 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
3090 if (n_read < sizeof(buf) && ferror(fp))
3092 g_byte_array_append(array, buf, n_read);
3096 FILE_OP_ERROR("file stream", "fread");
3097 g_byte_array_free(array, TRUE);
3102 g_byte_array_append(array, buf, 1);
3103 str = (gchar *)array->data;
3104 g_byte_array_free(array, FALSE);
3106 if (!g_utf8_validate(str, -1, NULL)) {
3107 const gchar *src_codeset, *dest_codeset;
3109 src_codeset = conv_get_locale_charset_str();
3110 dest_codeset = CS_UTF_8;
3111 tmp = conv_codeset_strdup(str, src_codeset, dest_codeset);
3119 gint execute_async(gchar *const argv[])
3124 if ((pid = fork()) < 0) {
3129 if (pid == 0) { /* child process */
3132 if ((gch_pid = fork()) < 0) {
3137 if (gch_pid == 0) { /* grandchild process */
3138 execvp(argv[0], argv);
3147 waitpid(pid, &status, 0);
3149 if (WIFEXITED(status))
3150 return WEXITSTATUS(status);
3155 gint execute_sync(gchar *const argv[])
3160 if ((pid = fork()) < 0) {
3165 if (pid == 0) { /* child process */
3166 execvp(argv[0], argv);
3172 waitpid(pid, &status, 0);
3174 if (WIFEXITED(status))
3175 return WEXITSTATUS(status);
3180 gint execute_command_line(const gchar *cmdline, gboolean async)
3185 debug_print("executing: %s\n", cmdline);
3187 argv = strsplit_with_quote(cmdline, " ", 0);
3190 ret = execute_async(argv);
3192 ret = execute_sync(argv);
3199 gchar *get_command_output(const gchar *cmdline)
3201 gchar *child_stdout;
3204 g_return_val_if_fail(cmdline != NULL, NULL);
3206 if (g_spawn_command_line_sync(cmdline, &child_stdout, NULL, &status,
3208 g_warning("Can't execute command: %s\n", cmdline);
3212 return child_stdout;
3215 static gint is_unchanged_uri_char(char c)
3227 void encode_uri(gchar *encoded_uri, gint bufsize, const gchar *uri)
3233 for(i = 0; i < strlen(uri) ; i++) {
3234 if (is_unchanged_uri_char(uri[i])) {
3235 if (k + 2 >= bufsize)
3237 encoded_uri[k++] = uri[i];
3240 char * hexa = "0123456789ABCDEF";
3242 if (k + 4 >= bufsize)
3244 encoded_uri[k++] = '%';
3245 encoded_uri[k++] = hexa[uri[i] / 16];
3246 encoded_uri[k++] = hexa[uri[i] % 16];
3252 gint open_uri(const gchar *uri, const gchar *cmdline)
3254 gchar buf[BUFFSIZE];
3256 gchar encoded_uri[BUFFSIZE];
3258 g_return_val_if_fail(uri != NULL, -1);
3260 /* an option to choose whether to use encode_uri or not ? */
3261 encode_uri(encoded_uri, BUFFSIZE, uri);
3264 (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
3265 !strchr(p + 2, '%'))
3266 g_snprintf(buf, sizeof(buf), cmdline, encoded_uri);
3269 g_warning("Open URI command line is invalid "
3270 "(there must be only one '%%s'): %s",
3272 g_snprintf(buf, sizeof(buf), DEFAULT_BROWSER_CMD, encoded_uri);
3275 execute_command_line(buf, TRUE);
3280 time_t remote_tzoffset_sec(const gchar *zone)
3282 static gchar ustzstr[] = "PSTPDTMSTMDTCSTCDTESTEDT";
3288 time_t remoteoffset;
3290 strncpy(zone3, zone, 3);
3294 if (sscanf(zone, "%c%d", &c, &offset) == 2 &&
3295 (c == '+' || c == '-')) {
3296 remoteoffset = ((offset / 100) * 60 + (offset % 100)) * 60;
3298 remoteoffset = -remoteoffset;
3299 } else if (!strncmp(zone, "UT" , 2) ||
3300 !strncmp(zone, "GMT", 2)) {
3302 } else if (strlen(zone3) == 3) {
3303 for (p = ustzstr; *p != '\0'; p += 3) {
3304 if (!g_ascii_strncasecmp(p, zone3, 3)) {
3305 iustz = ((gint)(p - ustzstr) / 3 + 1) / 2 - 8;
3306 remoteoffset = iustz * 3600;
3312 } else if (strlen(zone3) == 1) {
3314 case 'Z': remoteoffset = 0; break;
3315 case 'A': remoteoffset = -1; break;
3316 case 'B': remoteoffset = -2; break;
3317 case 'C': remoteoffset = -3; break;
3318 case 'D': remoteoffset = -4; break;
3319 case 'E': remoteoffset = -5; break;
3320 case 'F': remoteoffset = -6; break;
3321 case 'G': remoteoffset = -7; break;
3322 case 'H': remoteoffset = -8; break;
3323 case 'I': remoteoffset = -9; break;
3324 case 'K': remoteoffset = -10; break; /* J is not used */
3325 case 'L': remoteoffset = -11; break;
3326 case 'M': remoteoffset = -12; break;
3327 case 'N': remoteoffset = 1; break;
3328 case 'O': remoteoffset = 2; break;
3329 case 'P': remoteoffset = 3; break;
3330 case 'Q': remoteoffset = 4; break;
3331 case 'R': remoteoffset = 5; break;
3332 case 'S': remoteoffset = 6; break;
3333 case 'T': remoteoffset = 7; break;
3334 case 'U': remoteoffset = 8; break;
3335 case 'V': remoteoffset = 9; break;
3336 case 'W': remoteoffset = 10; break;
3337 case 'X': remoteoffset = 11; break;
3338 case 'Y': remoteoffset = 12; break;
3339 default: remoteoffset = 0; break;
3341 remoteoffset = remoteoffset * 3600;
3345 return remoteoffset;
3348 time_t tzoffset_sec(time_t *now)
3354 lt = localtime(now);
3356 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
3358 if (lt->tm_year < gmt.tm_year)
3360 else if (lt->tm_year > gmt.tm_year)
3362 else if (lt->tm_yday < gmt.tm_yday)
3364 else if (lt->tm_yday > gmt.tm_yday)
3367 if (off >= 24 * 60) /* should be impossible */
3368 off = 23 * 60 + 59; /* if not, insert silly value */
3369 if (off <= -24 * 60)
3370 off = -(23 * 60 + 59);
3375 /* calculate timezone offset */
3376 gchar *tzoffset(time_t *now)
3378 static gchar offset_string[6];
3384 lt = localtime(now);
3386 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
3388 if (lt->tm_year < gmt.tm_year)
3390 else if (lt->tm_year > gmt.tm_year)
3392 else if (lt->tm_yday < gmt.tm_yday)
3394 else if (lt->tm_yday > gmt.tm_yday)
3402 if (off >= 24 * 60) /* should be impossible */
3403 off = 23 * 60 + 59; /* if not, insert silly value */
3405 sprintf(offset_string, "%c%02d%02d", sign, off / 60, off % 60);
3407 return offset_string;
3410 void get_rfc822_date(gchar *buf, gint len)
3414 gchar day[4], mon[4];
3415 gint dd, hh, mm, ss, yyyy;
3420 sscanf(asctime(lt), "%3s %3s %d %d:%d:%d %d\n",
3421 day, mon, &dd, &hh, &mm, &ss, &yyyy);
3422 g_snprintf(buf, len, "%s, %d %s %d %02d:%02d:%02d %s",
3423 day, dd, mon, yyyy, hh, mm, ss, tzoffset(&t));
3426 /* just a wrapper to suppress the warning of gcc about %c */
3427 size_t my_strftime(gchar *s, size_t max, const gchar *format,
3428 const struct tm *tm)
3430 return strftime(s, max, format, tm);
3433 void debug_set_mode(gboolean mode)
3438 gboolean debug_get_mode(void)
3443 void debug_print_real(const gchar *format, ...)
3446 gchar buf[BUFFSIZE];
3448 if (!debug_mode) return;
3450 va_start(args, format);
3451 g_vsnprintf(buf, sizeof(buf), format, args);
3457 void * subject_table_lookup(GHashTable *subject_table, gchar * subject)
3459 if (subject == NULL)
3462 subject += subject_get_prefix_length(subject);
3464 return g_hash_table_lookup(subject_table, subject);
3467 void subject_table_insert(GHashTable *subject_table, gchar * subject,
3470 if (subject == NULL || *subject == 0)
3472 subject += subject_get_prefix_length(subject);
3473 g_hash_table_insert(subject_table, subject, data);
3476 void subject_table_remove(GHashTable *subject_table, gchar * subject)
3478 if (subject == NULL)
3481 subject += subject_get_prefix_length(subject);
3482 g_hash_table_remove(subject_table, subject);
3486 *\brief Check if a string is prefixed with known (combinations)
3487 * of prefixes. The function assumes that each prefix
3488 * is terminated by zero or exactly _one_ space.
3490 *\param str String to check for a prefixes
3492 *\return int Number of chars in the prefix that should be skipped
3493 * for a "clean" subject line. If no prefix was found, 0
3496 int subject_get_prefix_length(const gchar *subject)
3498 /*!< Array with allowable reply prefixes regexps. */
3499 static const gchar * const prefixes[] = {
3500 "Re\\:", /* "Re:" */
3501 "Re\\[[1-9][0-9]*\\]\\:", /* "Re[XXX]:" (non-conforming news mail clients) */
3502 "Antw\\:", /* "Antw:" (Dutch / German Outlook) */
3503 "Aw\\:", /* "Aw:" (German) */
3504 "Antwort\\:", /* "Antwort:" (German Lotus Notes) */
3505 "Res\\:", /* "Res:" (Brazilian Outlook) */
3506 "Fw\\:", /* "Fw:" Forward */
3507 "Enc\\:", /* "Enc:" Forward (Brazilian Outlook) */
3508 "Odp\\:", /* "Odp:" Re (Polish Outlook) */
3509 "Rif\\:" /* "Rif:" (Italian Outlook) */
3512 const int PREFIXES = sizeof prefixes / sizeof prefixes[0];
3515 static regex_t regex;
3516 static gboolean init_;
3518 if (!subject) return 0;
3519 if (!*subject) return 0;
3522 GString *s = g_string_new("");
3524 for (n = 0; n < PREFIXES; n++)
3525 /* Terminate each prefix regexpression by a
3526 * "\ ?" (zero or ONE space), and OR them */
3527 g_string_append_printf(s, "(%s\\ ?)%s",
3532 g_string_prepend(s, "(");
3533 g_string_append(s, ")+"); /* match at least once */
3534 g_string_prepend(s, "^\\ *"); /* from beginning of line */
3537 /* We now have something like "^\ *((PREFIX1\ ?)|(PREFIX2\ ?))+"
3538 * TODO: Should this be "^\ *(((PREFIX1)|(PREFIX2))\ ?)+" ??? */
3539 if (regcomp(®ex, s->str, REG_EXTENDED | REG_ICASE)) {
3540 debug_print("Error compiling regexp %s\n", s->str);
3541 g_string_free(s, TRUE);
3545 g_string_free(s, TRUE);
3549 if (!regexec(®ex, subject, 1, &pos, 0) && pos.rm_so != -1)
3555 guint g_stricase_hash(gconstpointer gptr)
3557 guint hash_result = 0;
3560 for (str = gptr; str && *str; str++) {
3561 if (isupper((guchar)*str)) hash_result += (*str + ' ');
3562 else hash_result += *str;
3568 gint g_stricase_equal(gconstpointer gptr1, gconstpointer gptr2)
3570 const char *str1 = gptr1;
3571 const char *str2 = gptr2;
3573 return !g_utf8_collate(str1, str2);
3576 gint g_int_compare(gconstpointer a, gconstpointer b)
3578 return GPOINTER_TO_INT(a) - GPOINTER_TO_INT(b);
3581 gchar *generate_msgid(gchar *buf, gint len)
3590 addr = g_strconcat("@", get_domain_name(), NULL);
3592 g_snprintf(buf, len, "%04d%02d%02d%02d%02d%02d.%08x%s",
3593 lt->tm_year + 1900, lt->tm_mon + 1,
3594 lt->tm_mday, lt->tm_hour,
3595 lt->tm_min, lt->tm_sec,
3596 (guint) rand(), addr);
3603 quote_cmd_argument()
3605 return a quoted string safely usable in argument of a command.
3607 code is extracted and adapted from etPan! project -- DINH V. Hoà .
3610 gint quote_cmd_argument(gchar * result, guint size,
3620 for(p = path ; * p != '\0' ; p ++) {
3622 if (isalnum((guchar)*p) || (* p == '/')) {
3623 if (remaining > 0) {
3629 result[size - 1] = '\0';
3634 if (remaining >= 2) {
3642 result[size - 1] = '\0';
3647 if (remaining > 0) {
3651 result[size - 1] = '\0';
3665 static void g_node_map_recursive(GNode *node, gpointer data)
3667 GNodeMapData *mapdata = (GNodeMapData *) data;
3669 GNodeMapData newmapdata;
3672 newdata = mapdata->func(node->data, mapdata->data);
3673 if (newdata != NULL) {
3674 newnode = g_node_new(newdata);
3675 g_node_append(mapdata->parent, newnode);
3677 newmapdata.parent = newnode;
3678 newmapdata.func = mapdata->func;
3679 newmapdata.data = mapdata->data;
3681 g_node_children_foreach(node, G_TRAVERSE_ALL, g_node_map_recursive, &newmapdata);
3685 GNode *g_node_map(GNode *node, GNodeMapFunc func, gpointer data)
3688 GNodeMapData mapdata;
3690 g_return_val_if_fail(node != NULL, NULL);
3691 g_return_val_if_fail(func != NULL, NULL);
3693 root = g_node_new(func(node->data, data));
3695 mapdata.parent = root;
3696 mapdata.func = func;
3697 mapdata.data = data;
3699 g_node_children_foreach(node, G_TRAVERSE_ALL, g_node_map_recursive, &mapdata);
3704 #define HEX_TO_INT(val, hex) \
3708 if ('0' <= c && c <= '9') { \
3710 } else if ('a' <= c && c <= 'f') { \
3711 val = c - 'a' + 10; \
3712 } else if ('A' <= c && c <= 'F') { \
3713 val = c - 'A' + 10; \
3719 gboolean get_hex_value(guchar *out, gchar c1, gchar c2)
3726 if (hi == -1 || lo == -1)
3729 *out = (hi << 4) + lo;
3733 #define INT_TO_HEX(hex, val) \
3736 hex = '0' + (val); \
3738 hex = 'A' + (val) - 10; \
3741 void get_hex_str(gchar *out, guchar ch)
3745 INT_TO_HEX(hex, ch >> 4);
3747 INT_TO_HEX(hex, ch & 0x0f);
3753 #define G_PRINT_REF 1 == 1 ? (void) 0 : (void)
3755 #define G_PRINT_REF g_print
3759 *\brief Register ref counted pointer. It is based on GBoxed, so should
3760 * work with anything that uses the GType system. The semantics
3761 * are similar to a C++ auto pointer, with the exception that
3762 * C doesn't have automatic closure (calling destructors) when
3763 * exiting a block scope.
3764 * Use the \ref G_TYPE_AUTO_POINTER macro instead of calling this
3765 * function directly.
3767 *\return GType A GType type.
3769 GType g_auto_pointer_register(void)
3771 static GType auto_pointer_type;
3772 if (!auto_pointer_type)
3774 g_boxed_type_register_static
3775 ("G_TYPE_AUTO_POINTER",
3776 (GBoxedCopyFunc) g_auto_pointer_copy,
3777 (GBoxedFreeFunc) g_auto_pointer_free);
3778 return auto_pointer_type;
3782 *\brief Structure with g_new() allocated pointer guarded by the
3785 typedef struct AutoPointerRef {
3786 void (*free) (gpointer);
3792 *\brief The auto pointer opaque structure that references the
3793 * pointer guard block.
3795 typedef struct AutoPointer {
3796 AutoPointerRef *ref;
3797 gpointer ptr; /*!< access to protected pointer */
3801 *\brief Creates an auto pointer for a g_new()ed pointer. Example:
3805 * ... tell gtk_list_store it should use a G_TYPE_AUTO_POINTER
3806 * ... when assigning, copying and freeing storage elements
3808 * gtk_list_store_new(N_S_COLUMNS,
3809 * G_TYPE_AUTO_POINTER,
3813 * Template *precious_data = g_new0(Template, 1);
3814 * g_pointer protect = g_auto_pointer_new(precious_data);
3816 * gtk_list_store_set(container, &iter,
3820 * ... the gtk_list_store has copied the pointer and
3821 * ... incremented its reference count, we should free
3822 * ... the auto pointer (in C++ a destructor would do
3823 * ... this for us when leaving block scope)
3825 * g_auto_pointer_free(protect);
3827 * ... gtk_list_store_set() now manages the data. When
3828 * ... *explicitly* requesting a pointer from the list
3829 * ... store, don't forget you get a copy that should be
3830 * ... freed with g_auto_pointer_free() eventually.
3834 *\param pointer Pointer to be guarded.
3836 *\return GAuto * Pointer that should be used in containers with
3839 GAuto *g_auto_pointer_new(gpointer p)
3841 AutoPointerRef *ref;
3847 ref = g_new0(AutoPointerRef, 1);
3848 ptr = g_new0(AutoPointer, 1);
3858 G_PRINT_REF ("XXXX ALLOC(%lx)\n", p);
3864 *\brief Allocate an autopointer using the passed \a free function to
3865 * free the guarded pointer
3867 GAuto *g_auto_pointer_new_with_free(gpointer p, GFreeFunc free_)
3874 aptr = g_auto_pointer_new(p);
3875 aptr->ref->free = free_;
3879 gpointer g_auto_pointer_get_ptr(GAuto *auto_ptr)
3881 if (auto_ptr == NULL)
3883 return ((AutoPointer *) auto_ptr)->ptr;
3887 *\brief Copies an auto pointer by. It's mostly not necessary
3888 * to call this function directly, unless you copy/assign
3889 * the guarded pointer.
3891 *\param auto_ptr Auto pointer returned by previous call to
3892 * g_auto_pointer_new_XXX()
3894 *\return gpointer An auto pointer
3896 GAuto *g_auto_pointer_copy(GAuto *auto_ptr)
3899 AutoPointerRef *ref;
3902 if (auto_ptr == NULL)
3907 newp = g_new0(AutoPointer, 1);
3910 newp->ptr = ref->pointer;
3914 G_PRINT_REF ("XXXX COPY(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);
3920 *\brief Free an auto pointer
3922 void g_auto_pointer_free(GAuto *auto_ptr)
3925 AutoPointerRef *ref;
3927 if (auto_ptr == NULL)
3933 if (--(ref->cnt) == 0) {
3935 G_PRINT_REF ("XXXX FREE(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);
3937 ref->free(ref->pointer);
3942 G_PRINT_REF ("XXXX DEREF(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);
3947 void replace_returns(gchar *str)
3952 while (strstr(str, "\n")) {
3953 *strstr(str, "\n") = ' ';
3955 while (strstr(str, "\r")) {
3956 *strstr(str, "\r") = ' ';