* replace the _pango functions with modest_text_utils_convert_to_pango,
[modest] / src / modest-text-utils.c
1 /* Copyright (c) 2006, Nokia Corporation
2  * All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are
6  * met:
7  *
8  * * Redistributions of source code must retain the above copyright
9  *   notice, this list of conditions and the following disclaimer.
10  * * Redistributions in binary form must reproduce the above copyright
11  *   notice, this list of conditions and the following disclaimer in the
12  *   documentation and/or other materials provided with the distribution.
13  * * Neither the name of the Nokia Corporation nor the names of its
14  *   contributors may be used to endorse or promote products derived from
15  *   this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
18  * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
19  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
20  * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
21  * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
24  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
25  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
26  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29
30
31 #include <glib.h>
32 #include <string.h>
33 #include <stdlib.h>
34 #include <glib/gi18n.h>
35 #include <regex.h>
36 #include <modest-tny-platform-factory.h>
37 #include <modest-text-utils.h>
38 #include <modest-runtime.h>
39
40
41 #ifdef HAVE_CONFIG_H
42 #include <config.h>
43 #endif /*HAVE_CONFIG_H */
44
45 /* defines */
46 #define FORWARD_STRING _("-----Forwarded Message-----")
47 #define FROM_STRING _("From:")
48 #define SENT_STRING _("Sent:")
49 #define TO_STRING _("To:")
50 #define SUBJECT_STRING _("Subject:")
51 #define EMPTY_STRING ""
52
53 /*
54  * we need these regexps to find URLs in plain text e-mails
55  */
56 typedef struct _url_match_pattern_t url_match_pattern_t;
57 struct _url_match_pattern_t {
58         gchar   *regex;
59         regex_t *preg;
60         gchar   *prefix;
61 };
62
63 typedef struct _url_match_t url_match_t;
64 struct _url_match_t {
65         guint offset;
66         guint len;
67         const gchar* prefix;
68 };
69
70 #define MAIL_VIEWER_URL_MATCH_PATTERNS  {                               \
71         { "(file|rtsp|http|ftp|https)://[-A-Za-z0-9_$.+!*(),;:@%&=?/~#]+[-A-Za-z0-9_$%&=?/~#]",\
72           NULL, NULL },\
73         { "www\\.[-a-z0-9.]+[-a-z0-9](:[0-9]*)?(/[-A-Za-z0-9_$.+!*(),;:@%&=?/~#]*[^]}\\),?!;:\"]?)?",\
74           NULL, "http://" },\
75         { "ftp\\.[-a-z0-9.]+[-a-z0-9](:[0-9]*)?(/[-A-Za-z0-9_$.+!*(),;:@%&=?/~#]*[^]}\\),?!;:\"]?)?",\
76           NULL, "ftp://" },\
77         { "(voipto|callto|chatto|jabberto|xmpp):[-_a-z@0-9.\\+]+", \
78            NULL, NULL},                                             \
79         { "mailto:[-_a-z0-9.\\+]+@[-_a-z0-9.]+",                    \
80           NULL, NULL},\
81         { "[-_a-z0-9.\\+]+@[-_a-z0-9.]+",\
82           NULL, "mailto:"}\
83         }
84
85 /* private */
86 static gchar*   cite                    (const time_t sent_date, const gchar *from);
87 static void     hyperlinkify_plain_text (GString *txt);
88 static gint     cmp_offsets_reverse     (const url_match_t *match1, const url_match_t *match2);
89 static void     chk_partial_match       (const url_match_t *match, guint* offset);
90 static GSList*  get_url_matches         (GString *txt);
91
92 static GString* get_next_line           (const char *b, const gsize blen, const gchar * iter);
93 static int      get_indent_level        (const char *l);
94 static void     unquote_line            (GString * l);
95 static void     append_quoted           (GString * buf, const int indent, const GString * str, 
96                                          const int cutpoint);
97 static int      get_breakpoint_utf8     (const gchar * s, const gint indent, const gint limit);
98 static int      get_breakpoint_ascii    (const gchar * s, const gint indent, const gint limit);
99 static int      get_breakpoint          (const gchar * s, const gint indent, const gint limit);
100
101 static gchar*   modest_text_utils_quote_plain_text (const gchar *text, 
102                                                     const gchar *cite, 
103                                                     int limit);
104
105 static gchar*   modest_text_utils_quote_html       (const gchar *text, 
106                                                     const gchar *cite, 
107                                                     int limit);
108
109
110 /* ******************************************************************* */
111 /* ************************* PUBLIC FUNCTIONS ************************ */
112 /* ******************************************************************* */
113
114 gchar *
115 modest_text_utils_quote (const gchar *text, 
116                          const gchar *content_type,
117                          const gchar *from,
118                          const time_t sent_date, 
119                          int limit)
120 {
121         gchar *retval, *cited;
122
123         g_return_val_if_fail (text, NULL);
124         g_return_val_if_fail (content_type, NULL);
125
126         cited = cite (sent_date, from);
127         
128         if (content_type && strcmp (content_type, "text/html") == 0)
129                 /* TODO: extract the <body> of the HTML and pass it to
130                    the function */
131                 retval = modest_text_utils_quote_html (text, cited, limit);
132         else
133                 retval = modest_text_utils_quote_plain_text (text, cited, limit);
134         
135         g_free (cited);
136
137         return retval;
138 }
139
140
141 gchar *
142 modest_text_utils_cite (const gchar *text,
143                         const gchar *content_type,
144                         const gchar *from,
145                         time_t sent_date)
146 {
147         gchar *tmp, *retval;
148
149         g_return_val_if_fail (text, NULL);
150         g_return_val_if_fail (content_type, NULL);
151
152         tmp = cite (sent_date, from);
153         retval = g_strdup_printf ("%s%s\n", tmp, text);
154         g_free (tmp);
155
156         return retval;
157 }
158
159 gchar * 
160 modest_text_utils_inline (const gchar *text,
161                           const gchar *content_type,
162                           const gchar *from,
163                           time_t sent_date,
164                           const gchar *to,
165                           const gchar *subject)
166 {
167         gchar sent_str[101];
168         const gchar *plain_format = "%s\n%s %s\n%s %s\n%s %s\n%s %s\n\n%s";
169         const gchar *html_format = \
170                 "%s<br>\n<table width=\"100%\" border=\"0\" cellspacing=\"2\" cellpadding=\"2\">\n" \
171                 "<tr><td>%s</td><td>%s</td></tr>\n" \
172                 "<tr><td>%s</td><td>%s</td></tr>\n" \
173                 "<tr><td>%s</td><td>%s</td></tr>\n" \
174                 "<tr><td>%s</td><td>%s</td></tr>\n" \
175                 "<br><br>%s";
176         const gchar *format;
177
178         g_return_val_if_fail (text, NULL);
179         g_return_val_if_fail (content_type, NULL);
180         g_return_val_if_fail (text, NULL);
181         
182         modest_text_utils_strftime (sent_str, 100, "%c", sent_date);
183
184         if (!strcmp (content_type, "text/html"))
185                 /* TODO: extract the <body> of the HTML and pass it to
186                    the function */
187                 format = html_format;
188         else
189                 format = plain_format;
190
191         return g_strdup_printf (format, 
192                                 FORWARD_STRING,
193                                 FROM_STRING, (from) ? from : EMPTY_STRING,
194                                 SENT_STRING, sent_str,
195                                 TO_STRING, (to) ? to : EMPTY_STRING,
196                                 SUBJECT_STRING, (subject) ? subject : EMPTY_STRING,
197                                 text);
198 }
199
200 /* just to prevent warnings:
201  * warning: `%x' yields only last 2 digits of year in some locales
202  */
203 gsize
204 modest_text_utils_strftime(char *s, gsize max, const char *fmt, time_t timet)
205 {
206         struct tm tm;
207
208         /* does not work on old maemo glib: 
209          *   g_date_set_time_t (&date, timet);
210          */
211         localtime_r (&timet, &tm);
212
213         return strftime(s, max, fmt, &tm);
214 }
215
216 gchar *
217 modest_text_utils_derived_subject (const gchar *subject, const gchar *prefix)
218 {
219         gchar *tmp;
220
221         g_return_val_if_fail (prefix, NULL);
222         
223         if (!subject)
224                 return g_strdup (prefix);
225
226         tmp = g_strchug (g_strdup (subject));
227
228         if (!strncmp (tmp, prefix, strlen (prefix))) {
229                 return tmp;
230         } else {
231                 g_free (tmp);
232                 return g_strdup_printf ("%s %s", prefix, subject);
233         }
234 }
235
236 gchar*
237 modest_text_utils_remove_address (const gchar *address_list, const gchar *address)
238 {
239         gchar *dup, *token, *ptr, *result;
240         GString *filtered_emails;
241
242         g_return_val_if_fail (address_list, NULL);
243
244         if (!address)
245                 return g_strdup (address_list);
246         
247         /* search for substring */
248         if (!strstr ((const char *) address_list, (const char *) address))
249                 return g_strdup (address_list);
250
251         dup = g_strdup (address_list);
252         filtered_emails = g_string_new (NULL);
253         
254         token = strtok_r (dup, ",", &ptr);
255
256         while (token != NULL) {
257                 /* Add to list if not found */
258                 if (!strstr ((const char *) token, (const char *) address)) {
259                         if (filtered_emails->len == 0)
260                                 g_string_append_printf (filtered_emails, "%s", g_strstrip (token));
261                         else
262                                 g_string_append_printf (filtered_emails, ",%s", g_strstrip (token));
263                 }
264                 token = strtok_r (NULL, ",", &ptr);
265         }
266         result = filtered_emails->str;
267
268         /* Clean */
269         g_free (dup);
270         g_string_free (filtered_emails, FALSE);
271
272         return result;
273 }
274
275
276 static gchar*
277 modest_text_utils_convert_to_html_or_pango (const gchar *data, gboolean pango)
278 {
279         guint            i;
280         gboolean         first_space = TRUE;
281         GString         *html;      
282         gsize           len;
283
284         if (!data)
285                 return NULL;
286
287         len = strlen (data);
288         html = g_string_sized_new (1.5 * len);  /* just a  guess... */
289
290         if (!pango)
291                 g_string_append_printf (html,
292                                         "<html>"
293                                         "<head>"
294                                         "<meta http-equiv=\"content-type\""
295                                         " content=\"text/html; charset=utf8\">"
296                                         "</head>"
297                                         "<body><tt>");
298         
299         /* replace with special html chars where needed*/
300         for (i = 0; i != len; ++i)  {
301                 char    kar = data[i]; 
302                 switch (kar) {
303                         
304                 case 0:  break; /* ignore embedded \0s */       
305                 case '<'  : g_string_append   (html, "&lt;");   break;
306                 case '>'  : g_string_append   (html, "&gt;");   break;
307                 case '&'  : g_string_append   (html, "&amp;");  break;
308                 case '\'' : g_string_append   (html, "&apos;"); break;
309                 case '\n' : g_string_append   (html, "<br>\n");  break;
310                 default:
311                         if (!pango && (kar==' '||kar=='\t')) {
312                                 if (kar == ' ') {
313                                         g_string_append (html, first_space ? " " : "&nbsp;");
314                                         first_space = FALSE;
315                                 } else /* kart == '\t' */
316                                         g_string_append (html, "&nbsp; &nbsp;&nbsp;");
317                         } else {
318                                 int charnum = 0;
319                                 first_space = TRUE;
320                                 /* optimization trick: accumulate 'normal' chars, then copy */
321                                 do {
322                                         kar = data [++charnum + i];
323                                         
324                                 } while ((i + charnum < len) &&
325                                          (kar > '>' || (kar != '<' && kar != '>'
326                                                         && kar != '&' && kar !=  ' '
327                                                         && kar != '\n' && kar != '\t')));
328                                 g_string_append_len (html, &data[i], charnum);
329                                 i += (charnum  - 1);
330                         }
331                 }
332         }
333
334         if (!pango) {
335                 g_string_append (html, "</tt></body></html>");
336                 hyperlinkify_plain_text (html);
337         }
338
339         return g_string_free (html, FALSE);
340 }
341
342
343 gchar*
344 modest_text_utils_convert_to_html (const gchar *data)
345 {
346         return modest_text_utils_convert_to_html_or_pango (data, FALSE);
347 }
348
349
350 gchar*
351 modest_text_utils_convert_to_pango (const gchar *data)
352 {
353         /* FIXME:
354          * in many cases, it might not be needed to do anything, so
355          * we can simply scan the str for the special characters and
356          * if there are none, just return g_strdup (data).
357          *
358          * we could even get rid of the strdup there, and notify
359          * the caller that the string did not change -- however,
360          * that would complicate matters a bit on the caller side
361          */
362         return modest_text_utils_convert_to_html_or_pango (data, TRUE);
363 }
364
365
366         
367 GSList *
368 modest_text_utils_split_addresses_list (const gchar *addresses)
369 {
370         gchar *current, *start, *last_blank;
371         GSList *result = NULL;
372
373         start = (gchar *) addresses;
374         current = start;
375         last_blank = start;
376
377         while (*current != '\0') {
378                 if ((start == current)&&((*current == ' ')||(*current == ','))) {
379                         start++;
380                         last_blank = current;
381                 } else if (*current == ',') {
382                         gchar *new_address = NULL;
383                         new_address = g_strndup (start, current - last_blank);
384                         result = g_slist_prepend (result, new_address);
385                         start = current + 1;
386                         last_blank = start;
387                 } else if (*current == '\"') {
388                         if (current == start) {
389                                 current++;
390                                 start++;
391                         }
392                         while ((*current != '\"')&&(*current != '\0'))
393                                 current++;
394                 }
395                                 
396                 current++;
397         }
398
399         if (start != current) {
400                 gchar *new_address = NULL;
401                 new_address = g_strndup (start, current - last_blank);
402                 result = g_slist_prepend (result, new_address);
403         }
404
405         result = g_slist_reverse (result);
406         return result;
407
408 }
409
410 void
411 modest_text_utils_address_range_at_position (const gchar *recipients_list,
412                                              gint position,
413                                              gint *start,
414                                              gint *end)
415 {
416         gchar *current = NULL;
417         gint range_start = 0;
418         gint range_end = 0;
419         gint index;
420         gboolean is_quoted = FALSE;
421
422         index = 0;
423         for (current = (gchar *) recipients_list; *current != '\0'; current = g_utf8_find_next_char (current, NULL)) {
424                 gunichar c = g_utf8_get_char (current);
425
426                 if ((c == ',') && (!is_quoted)) {
427                         if (index < position) {
428                                 range_start = index + 1;
429                         } else {
430                                 break;
431                         }
432                 } else if (c == '\"') {
433                         is_quoted = !is_quoted;
434                 } else if ((c == ' ') &&(range_start == index)) {
435                         range_start ++;
436                 }
437                 index ++;
438                 range_end = index;
439         }
440
441         if (start)
442                 *start = range_start;
443         if (end)
444                 *end = range_end;
445 }
446
447
448 /* ******************************************************************* */
449 /* ************************* UTILIY FUNCTIONS ************************ */
450 /* ******************************************************************* */
451
452 static GString *
453 get_next_line (const gchar * b, const gsize blen, const gchar * iter)
454 {
455         GString *gs;
456         const gchar *i0;
457         
458         if (iter > b + blen)
459                 return g_string_new("");
460         
461         i0 = iter;
462         while (iter[0]) {
463                 if (iter[0] == '\n')
464                         break;
465                 iter++;
466         }
467         gs = g_string_new_len (i0, iter - i0);
468         return gs;
469 }
470 static int
471 get_indent_level (const char *l)
472 {
473         int indent = 0;
474
475         while (l[0]) {
476                 if (l[0] == '>') {
477                         indent++;
478                         if (l[1] == ' ') {
479                                 l++;
480                         }
481                 } else {
482                         break;
483                 }
484                 l++;
485
486         }
487
488         /*      if we hit the signature marker "-- ", we return -(indent + 1). This
489          *      stops reformatting.
490          */
491         if (strcmp (l, "-- ") == 0) {
492                 return -1 - indent;
493         } else {
494                 return indent;
495         }
496 }
497
498 static void
499 unquote_line (GString * l)
500 {
501         gchar *p;
502
503         p = l->str;
504         while (p[0]) {
505                 if (p[0] == '>') {
506                         if (p[1] == ' ') {
507                                 p++;
508                         }
509                 } else {
510                         break;
511                 }
512                 p++;
513         }
514         g_string_erase (l, 0, p - l->str);
515 }
516
517 static void
518 append_quoted (GString * buf, int indent, const GString * str,
519                const int cutpoint)
520 {
521         int i;
522
523         indent = indent < 0 ? abs (indent) - 1 : indent;
524         for (i = 0; i <= indent; i++) {
525                 g_string_append (buf, "> ");
526         }
527         if (cutpoint > 0) {
528                 g_string_append_len (buf, str->str, cutpoint);
529         } else {
530                 g_string_append (buf, str->str);
531         }
532         g_string_append (buf, "\n");
533 }
534
535 static int
536 get_breakpoint_utf8 (const gchar * s, gint indent, const gint limit)
537 {
538         gint index = 0;
539         const gchar *pos, *last;
540         gunichar *uni;
541
542         indent = indent < 0 ? abs (indent) - 1 : indent;
543
544         last = NULL;
545         pos = s;
546         uni = g_utf8_to_ucs4_fast (s, -1, NULL);
547         while (pos[0]) {
548                 if ((index + 2 * indent > limit) && last) {
549                         g_free (uni);
550                         return last - s;
551                 }
552                 if (g_unichar_isspace (uni[index])) {
553                         last = pos;
554                 }
555                 pos = g_utf8_next_char (pos);
556                 index++;
557         }
558         g_free (uni);
559         return strlen (s);
560 }
561
562 static int
563 get_breakpoint_ascii (const gchar * s, const gint indent, const gint limit)
564 {
565         gint i, last;
566
567         last = strlen (s);
568         if (last + 2 * indent < limit)
569                 return last;
570
571         for (i = strlen (s); i > 0; i--) {
572                 if (s[i] == ' ') {
573                         if (i + 2 * indent <= limit) {
574                                 return i;
575                         } else {
576                                 last = i;
577                         }
578                 }
579         }
580         return last;
581 }
582
583 static int
584 get_breakpoint (const gchar * s, const gint indent, const gint limit)
585 {
586
587         if (g_utf8_validate (s, -1, NULL)) {
588                 return get_breakpoint_utf8 (s, indent, limit);
589         } else {                /* assume ASCII */
590                 //g_warning("invalid UTF-8 in msg");
591                 return get_breakpoint_ascii (s, indent, limit);
592         }
593 }
594
595 static gchar *
596 cite (const time_t sent_date, const gchar *from)
597 {
598         gchar sent_str[101];
599
600         /* format sent_date */
601         modest_text_utils_strftime (sent_str, 100, "%c", sent_date);
602         return g_strdup_printf (N_("On %s, %s wrote:\n"), 
603                                 sent_str, 
604                                 (from) ? from : EMPTY_STRING);
605 }
606
607
608 static gchar *
609 modest_text_utils_quote_plain_text (const gchar *text, 
610                                     const gchar *cite, 
611                                     int limit)
612 {
613         const gchar *iter;
614         gint indent, breakpoint, rem_indent = 0;
615         GString *q, *l, *remaining;
616         gsize len;
617
618         /* remaining will store the rest of the line if we have to break it */
619         q = g_string_new (cite);
620         remaining = g_string_new ("");
621
622         iter = text;
623         len = strlen(text);
624         do {
625                 l = get_next_line (text, len, iter);
626                 iter = iter + l->len + 1;
627                 indent = get_indent_level (l->str);
628                 unquote_line (l);
629
630                 if (remaining->len) {
631                         if (l->len && indent == rem_indent) {
632                                 g_string_prepend (l, " ");
633                                 g_string_prepend (l, remaining->str);
634                         } else {
635                                 do {
636                                         breakpoint =
637                                                 get_breakpoint (remaining->str,
638                                                                 rem_indent,
639                                                                 limit);
640                                         append_quoted (q, rem_indent,
641                                                        remaining, breakpoint);
642                                         g_string_erase (remaining, 0,
643                                                         breakpoint);
644                                         if (remaining->str[0] == ' ') {
645                                                 g_string_erase (remaining, 0,
646                                                                 1);
647                                         }
648                                 } while (remaining->len);
649                         }
650                 }
651                 g_string_free (remaining, TRUE);
652                 breakpoint = get_breakpoint (l->str, indent, limit);
653                 remaining = g_string_new (l->str + breakpoint);
654                 if (remaining->str[0] == ' ') {
655                         g_string_erase (remaining, 0, 1);
656                 }
657                 rem_indent = indent;
658                 append_quoted (q, indent, l, breakpoint);
659                 g_string_free (l, TRUE);
660         } while ((iter < text + len) || (remaining->str[0]));
661
662         return g_string_free (q, FALSE);
663 }
664
665 static gchar*
666 modest_text_utils_quote_html (const gchar *text, 
667                               const gchar *cite, 
668                               int limit)
669 {
670         const gchar *format = \
671                 "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n" \
672                 "<html>\n" \
673                 "<body>\n" \
674                 "%s" \
675                 "<blockquote type=\"cite\">\n%s\n</blockquote>\n" \
676                 "</body>\n" \
677                 "</html>\n";
678
679         return g_strdup_printf (format, cite, text);
680 }
681
682 static gint 
683 cmp_offsets_reverse (const url_match_t *match1, const url_match_t *match2)
684 {
685         return match2->offset - match1->offset;
686 }
687
688
689
690 /*
691  * check if the match is inside an existing match... */
692 static void
693 chk_partial_match (const url_match_t *match, guint* offset)
694 {
695         if (*offset >= match->offset && *offset < match->offset + match->len)
696                 *offset = -1;
697 }
698
699 static GSList*
700 get_url_matches (GString *txt)
701 {
702         regmatch_t rm;
703         guint rv, i, offset = 0;
704         GSList *match_list = NULL;
705
706         static url_match_pattern_t patterns[] = MAIL_VIEWER_URL_MATCH_PATTERNS;
707         const size_t pattern_num = sizeof(patterns)/sizeof(url_match_pattern_t);
708
709         /* initalize the regexps */
710         for (i = 0; i != pattern_num; ++i) {
711                 patterns[i].preg = g_slice_new0 (regex_t);
712
713                 /* this should not happen */
714                 g_return_val_if_fail (regcomp (patterns[i].preg, patterns[i].regex,
715                                                REG_ICASE|REG_EXTENDED|REG_NEWLINE) == 0, NULL);
716         }
717         /* find all the matches */
718         for (i = 0; i != pattern_num; ++i) {
719                 offset     = 0; 
720                 while (1) {
721                         int test_offset;
722                         if ((rv = regexec (patterns[i].preg, txt->str + offset, 1, &rm, 0)) != 0) {
723                                 g_return_val_if_fail (rv == REG_NOMATCH, NULL); /* this should not happen */
724                                 break; /* try next regexp */ 
725                         }
726                         if (rm.rm_so == -1)
727                                 break;
728
729                         /* FIXME: optimize this */
730                         /* to avoid partial matches on something that was already found... */
731                         /* check_partial_match will put -1 in the data ptr if that is the case */
732                         test_offset = offset + rm.rm_so;
733                         g_slist_foreach (match_list, (GFunc)chk_partial_match, &test_offset);
734                         
735                         /* make a list of our matches (<offset, len, prefix> tupels)*/
736                         if (test_offset != -1) {
737                                 url_match_t *match = g_slice_new (url_match_t);
738                                 match->offset = offset + rm.rm_so;
739                                 match->len    = rm.rm_eo - rm.rm_so;
740                                 match->prefix = patterns[i].prefix;
741                                 match_list = g_slist_prepend (match_list, match);
742                         }
743                         offset += rm.rm_eo;
744                 }
745         }
746
747         for (i = 0; i != pattern_num; ++i) {
748                 regfree (patterns[i].preg);
749                 g_slice_free  (regex_t, patterns[i].preg);
750         } /* don't free patterns itself -- it's static */
751         
752         /* now sort the list, so the matches are in reverse order of occurence.
753          * that way, we can do the replacements starting from the end, so we don't need
754          * to recalculate the offsets
755          */
756         match_list = g_slist_sort (match_list,
757                                    (GCompareFunc)cmp_offsets_reverse); 
758         return match_list;      
759 }
760
761
762
763 static void
764 hyperlinkify_plain_text (GString *txt)
765 {
766         GSList *cursor;
767         GSList *match_list = get_url_matches (txt);
768
769         /* we will work backwards, so the offsets stay valid */
770         for (cursor = match_list; cursor; cursor = cursor->next) {
771
772                 url_match_t *match = (url_match_t*) cursor->data;
773                 gchar *url  = g_strndup (txt->str + match->offset, match->len);
774                 gchar *repl = NULL; /* replacement  */
775
776                 /* the prefix is NULL: use the one that is already there */
777                 repl = g_strdup_printf ("<a href=\"%s%s\">%s</a>",
778                                         match->prefix ? match->prefix : EMPTY_STRING, 
779                                         url, url);
780
781                 /* replace the old thing with our hyperlink
782                  * replacement thing */
783                 g_string_erase  (txt, match->offset, match->len);
784                 g_string_insert (txt, match->offset, repl);
785                 
786                 g_free (url);
787                 g_free (repl);
788
789                 g_slice_free (url_match_t, match);      
790         }
791         
792         g_slist_free (match_list);
793 }
794
795
796
797 gchar*
798 modest_text_utils_get_display_address (gchar *address)
799 {
800         gchar *cursor;
801         
802         if (!address)
803                 return NULL;
804
805         g_return_val_if_fail (g_utf8_validate (address, -1, NULL), NULL);
806
807         g_strchug (address); /* remove leading whitespace */
808
809         /*  <email@address> from display name */
810         cursor = g_strstr_len (address, strlen(address), "<");
811         if (cursor == address) /* there's nothing else? leave it */
812                 return address;
813         if (cursor) 
814                 cursor[0]='\0';
815
816         /* remove (bla bla) from display name */
817         cursor = g_strstr_len (address, strlen(address), "(");
818         if (cursor == address) /* there's nothing else? leave it */
819                 return address;
820         if (cursor) 
821                 cursor[0]='\0';
822
823         g_strchomp (address); /* remove trailing whitespace */
824
825         return address;
826 }
827
828
829
830 gint 
831 modest_text_utils_get_subject_prefix_len (const gchar *sub)
832 {
833         gint i;
834         static const gchar* prefix[] = {
835                 "Re:", "RE:", "Fwd:", "FWD:", "FW:", NULL
836         };
837                 
838         if (!sub || (sub[0] != 'R' && sub[0] != 'F')) /* optimization */
839                 return 0;
840
841         i = 0;
842         
843         while (prefix[i]) {
844                 if (g_str_has_prefix(sub, prefix[i])) {
845                         int prefix_len = strlen(prefix[i]); 
846                         if (sub[prefix_len] == ' ')
847                                 ++prefix_len; /* ignore space after prefix as well */
848                         return prefix_len; 
849                 }
850                 ++i;
851         }
852         return 0;
853 }
854
855
856 gint
857 modest_text_utils_utf8_strcmp (const gchar* s1, const gchar *s2, gboolean insensitive)
858 {
859         gint result = 0;
860         gchar *n1, *n2;
861
862         /* work even when s1 and/or s2 == NULL */
863         if (G_UNLIKELY(s1 == s2))
864                 return 0;
865
866         /* if it's not case sensitive */
867         if (!insensitive)
868                 return strcmp (s1 ? s1 : "", s2 ? s2 : "");
869         
870         n1 = g_utf8_collate_key (s1 ? s1 : "", -1);
871         n2 = g_utf8_collate_key (s2 ? s2 : "", -1);
872         
873         result = strcmp (n1, n2);
874
875         g_free (n1);
876         g_free (n2);
877         
878         return result;
879 }
880
881
882 gchar*
883 modest_text_utils_get_display_date (time_t date)
884 {
885         time_t now;
886         const guint BUF_SIZE = 64; 
887         gchar date_buf[BUF_SIZE];  
888         gchar now_buf [BUF_SIZE];  
889         
890         now = time (NULL);
891
892         modest_text_utils_strftime (date_buf, BUF_SIZE, "%d/%m/%Y", date);
893         modest_text_utils_strftime (now_buf,  BUF_SIZE, "%d/%m/%Y",  now); /* today */
894         
895         /* if this is today, get the time instead of the date */
896         if (strcmp (date_buf, now_buf) == 0)
897                 modest_text_utils_strftime (date_buf, BUF_SIZE, "%H:%M %P", date);
898         
899         return g_strdup(date_buf);
900 }
901
902 gboolean 
903 modest_text_utils_validate_email_address (const gchar *email_address)
904 {
905         int count = 0;
906         const gchar *c = NULL, *domain = NULL;
907         static gchar *rfc822_specials = "()<>@,;:\\\"[]";
908
909         /* first we validate the name portion (name@domain) */
910         for (c = email_address;  *c;  c++) {
911                 if (*c == '\"' && 
912                     (c == email_address || 
913                      *(c - 1) == '.' || 
914                      *(c - 1) == '\"')) {
915                         while (*++c) {
916                                 if (*c == '\"') 
917                                         break;
918                                 if (*c == '\\' && (*++c == ' ')) 
919                                         continue;
920                                 if (*c <= ' ' || *c >= 127) 
921                                         return FALSE;
922                         }
923                         if (!*c++) 
924                                 return FALSE;
925                         if (*c == '@') 
926                                 break;
927                         if (*c != '.') 
928                                 return FALSE;
929                         continue;
930                 }
931                 if (*c == '@') 
932                         break;
933                 if (*c <= ' ' || *c >= 127) 
934                         return FALSE;
935                 if (strchr(rfc822_specials, *c)) 
936                         return FALSE;
937         }
938         if (c == email_address || *(c - 1) == '.') 
939                 return FALSE;
940
941         /* next we validate the domain portion (name@domain) */
942         if (!*(domain = ++c)) 
943                 return FALSE;
944         do {
945                 if (*c == '.') {
946                         if (c == domain || *(c - 1) == '.') 
947                                 return FALSE;
948                         count++;
949                 }
950                 if (*c <= ' ' || *c >= 127) 
951                         return FALSE;
952                 if (strchr(rfc822_specials, *c)) 
953                         return FALSE;
954         } while (*++c);
955
956         return (count >= 1) ? TRUE : FALSE;
957 }
958
959
960
961
962 gchar *
963 modest_text_utils_get_display_size (guint size)
964 {
965         const guint KB=1024;
966         const guint MB=1024 * KB;
967         const guint GB=1024 * MB;
968         const guint TB=1024 * GB;
969
970         if (size < KB)
971                 return g_strdup_printf (_("%0.1f Kb"), (double)size / KB);
972         else if (size < MB)
973                 return g_strdup_printf (_("%d Kb"), size / KB);
974         else if (size < GB)
975                 return g_strdup_printf (_("%d Mb"), size / MB);
976         else if (size < TB)
977                 return g_strdup_printf (_("%d Gb"), size/ GB);
978         else
979                 return g_strdup_printf (_("Very big"));
980 }