* cosmetic
[modest] / src / modest-tny-msg-view.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 /* modest-tny-msg-view.c */
32
33 #include "modest-tny-msg-view.h"
34 #include "modest-tny-stream-gtkhtml.h"
35 #include "modest-tny-msg-actions.h"
36
37 #include <tny-text-buffer-stream.h>
38 #include <string.h>
39 #include <regex.h>
40 #include <ctype.h>
41 #include <glib/gi18n.h>
42 #include <gtkhtml/gtkhtml.h>
43 #include <gtkhtml/gtkhtml-stream.h>
44
45 /* 'private'/'protected' functions */
46 static void     modest_tny_msg_view_class_init   (ModestTnyMsgViewClass *klass);
47 static void     modest_tny_msg_view_init         (ModestTnyMsgView *obj);
48 static void     modest_tny_msg_view_finalize     (GObject *obj);
49
50
51 static GSList*  get_url_matches (GString *txt);
52 static gboolean fill_gtkhtml_with_txt (ModestTnyMsgView *self, GtkHTML* gtkhtml, const gchar* txt, TnyMsgIface *msg);
53
54 static gboolean on_link_clicked (GtkWidget *widget, const gchar *uri,
55                                  ModestTnyMsgView *msg_view);
56 static gboolean on_url_requested (GtkWidget *widget, const gchar *uri,
57                                   GtkHTMLStream *stream,
58                                   ModestTnyMsgView *msg_view);
59 static gchar *construct_virtual_filename(const gchar *filename, const gint position, const gchar *id, const gboolean active);
60 static gchar *construct_virtual_filename_from_mime_part(TnyMsgMimePartIface *msg, const gint position);
61
62 #define ATTACHMENT_ID_INLINE "attachment-inline"
63 #define ATTACHMENT_ID_LINK "attachment-link"
64 #define PREFIX_LINK_EMAIL "mailto:"
65
66 gint virtual_filename_get_pos(const gchar *filename);
67 /*
68  * we need these regexps to find URLs in plain text e-mails
69  */
70 typedef struct _UrlMatchPattern UrlMatchPattern;
71 struct _UrlMatchPattern {
72         gchar   *regex;
73         regex_t *preg;
74         gchar   *prefix;
75         
76 };
77 #define MAIL_VIEWER_URL_MATCH_PATTERNS  {\
78         { "(file|http|ftp|https)://[-A-Za-z0-9_$.+!*(),;:@%&=?/~#]+[-A-Za-z0-9_$%&=?/~#]",\
79           NULL, NULL },\
80         { "www\\.[-a-z0-9.]+[-a-z0-9](:[0-9]*)?(/[-A-Za-z0-9_$.+!*(),;:@%&=?/~#]*[^]}\\),?!;:\"]?)?",\
81           NULL, "http://" },\
82         { "ftp\\.[-a-z0-9.]+[-a-z0-9](:[0-9]*)?(/[-A-Za-z0-9_$.+!*(),;:@%&=?/~#]*[^]}\\),?!;:\"]?)?",\
83           NULL, "ftp://" },\
84         { "(voipto|callto|chatto|jabberto|xmpp):[-_a-z@0-9.\\+]+", \
85            NULL, NULL},                                             \
86         { "mailto:[-_a-z0-9.\\+]+@[-_a-z0-9.]+",                    \
87           NULL, NULL},\
88         { "[-_a-z0-9.\\+]+@[-_a-z0-9.]+",\
89           NULL, "mailto:"}\
90         }
91
92
93 /* list my signals */
94 enum {
95         MAILTO_CLICKED_SIGNAL,
96         /* MY_SIGNAL_2, */
97         LAST_SIGNAL
98 };
99
100 typedef struct _ModestTnyMsgViewPrivate ModestTnyMsgViewPrivate;
101 struct _ModestTnyMsgViewPrivate {
102         GtkWidget *gtkhtml;
103         TnyMsgIface *msg;
104         gboolean show_attachments_inline;
105 };
106 #define MODEST_TNY_MSG_VIEW_GET_PRIVATE(o)      (G_TYPE_INSTANCE_GET_PRIVATE((o), \
107                                                  MODEST_TYPE_TNY_MSG_VIEW, \
108                                                  ModestTnyMsgViewPrivate))
109 /* globals */
110 static GtkContainerClass *parent_class = NULL;
111
112 /* uncomment the following if you have defined any signals */
113 static guint signals[LAST_SIGNAL] = {0};
114
115 GType
116 modest_tny_msg_view_get_type (void)
117 {
118         static GType my_type = 0;
119         if (!my_type) {
120                 static const GTypeInfo my_info = {
121                         sizeof(ModestTnyMsgViewClass),
122                         NULL,           /* base init */
123                         NULL,           /* base finalize */
124                         (GClassInitFunc) modest_tny_msg_view_class_init,
125                         NULL,           /* class finalize */
126                         NULL,           /* class data */
127                         sizeof(ModestTnyMsgView),
128                         1,              /* n_preallocs */
129                         (GInstanceInitFunc) modest_tny_msg_view_init,
130                 };
131                 my_type = g_type_register_static (GTK_TYPE_SCROLLED_WINDOW,
132                                                   "ModestTnyMsgView",
133                                                   &my_info, 0);
134         }
135         return my_type;
136 }
137
138 static void
139 modest_tny_msg_view_class_init (ModestTnyMsgViewClass *klass)
140 {
141         GObjectClass *gobject_class;
142         gobject_class = (GObjectClass*) klass;
143
144         parent_class            = g_type_class_peek_parent (klass);
145         gobject_class->finalize = modest_tny_msg_view_finalize;
146
147         g_type_class_add_private (gobject_class, sizeof(ModestTnyMsgViewPrivate));
148         
149         signals[MAILTO_CLICKED_SIGNAL] =
150                 g_signal_new ("on_mailto_clicked",
151                               G_TYPE_FROM_CLASS (gobject_class),
152                               G_SIGNAL_RUN_FIRST,
153                               G_STRUCT_OFFSET(ModestTnyMsgViewClass, mailto_clicked),
154                               NULL, NULL,
155                               g_cclosure_marshal_VOID__STRING,
156                               G_TYPE_NONE, 1, G_TYPE_STRING/*, 1, G_TYPE_POINTER*/);
157 }
158
159 static void
160 modest_tny_msg_view_init (ModestTnyMsgView *obj)
161 {
162         ModestTnyMsgViewPrivate *priv;
163         
164         priv = MODEST_TNY_MSG_VIEW_GET_PRIVATE(obj);
165
166         priv->msg = NULL;
167         
168         priv->gtkhtml = gtk_html_new();
169         
170         priv->show_attachments_inline = FALSE;
171
172         gtk_html_set_editable        (GTK_HTML(priv->gtkhtml), FALSE);
173         gtk_html_allow_selection     (GTK_HTML(priv->gtkhtml), TRUE);
174         gtk_html_set_caret_mode      (GTK_HTML(priv->gtkhtml), FALSE);
175         gtk_html_set_blocking        (GTK_HTML(priv->gtkhtml), FALSE);
176         gtk_html_set_images_blocking (GTK_HTML(priv->gtkhtml), FALSE);
177
178         g_signal_connect (G_OBJECT(priv->gtkhtml), "link_clicked",
179                           G_CALLBACK(on_link_clicked), obj);
180         
181         g_signal_connect (G_OBJECT(priv->gtkhtml), "url_requested",
182                           G_CALLBACK(on_url_requested), obj);
183 }
184         
185
186 static void
187 modest_tny_msg_view_finalize (GObject *obj)
188 {       
189         /* TODO! */
190 }
191
192 GtkWidget*
193 modest_tny_msg_view_new (TnyMsgIface *msg, const gboolean show_attachments_inline)
194 {
195         GObject *obj;
196         ModestTnyMsgView* self;
197         ModestTnyMsgViewPrivate *priv;
198         
199         obj  = G_OBJECT(g_object_new(MODEST_TYPE_TNY_MSG_VIEW, NULL));
200         self = MODEST_TNY_MSG_VIEW(obj);
201         priv = MODEST_TNY_MSG_VIEW_GET_PRIVATE (self);
202
203         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(self),
204                                        GTK_POLICY_AUTOMATIC,
205                                        GTK_POLICY_AUTOMATIC);
206
207         if (priv->gtkhtml) 
208                 gtk_container_add (GTK_CONTAINER(obj), priv->gtkhtml);
209         
210         if (msg)
211                 modest_tny_msg_view_set_message (self, msg);
212         
213         modest_tny_msg_view_set_show_attachments_inline_flag(self, show_attachments_inline);
214
215         return GTK_WIDGET(self);
216 }
217
218
219 static gboolean
220 on_link_clicked (GtkWidget *widget, const gchar *uri,
221                                  ModestTnyMsgView *msg_view)
222 {
223         if (g_str_has_prefix(uri, PREFIX_LINK_EMAIL)) {
224                 gchar *s, *p;
225                 /* skip over "mailto:" */
226                 s = g_strdup(uri + strlen(PREFIX_LINK_EMAIL));
227                 /* strip ?subject=... and the like */
228                 for (p = s; p[0]; p++)
229                         if (p[0] == '?') {
230                                 p[0] = 0;
231                                 break;
232                         }
233                 g_signal_emit(msg_view, signals[MAILTO_CLICKED_SIGNAL], 0, s);
234                 g_free(s);
235                 return TRUE;
236         } else if (g_str_has_prefix(uri, ATTACHMENT_ID_LINK)) {
237                 /* save or open attachment */
238                 g_message ("link-to-save: %s", uri); /* FIXME */
239                 return TRUE;
240         }
241         g_message ("link clicked: %s", uri); /* FIXME */
242         return FALSE;
243         
244 }
245
246
247 static TnyMsgMimePartIface *
248 find_cid_image (TnyMsgIface *msg, const gchar *cid)
249 {
250         TnyMsgMimePartIface *part = NULL;
251         GList *parts;
252
253         g_return_val_if_fail (msg, NULL);
254         g_return_val_if_fail (cid, NULL);
255         
256         parts  = (GList*) tny_msg_iface_get_parts (msg);
257         while (parts && !part) {
258                 const gchar *part_cid;
259                 part = TNY_MSG_MIME_PART_IFACE(parts->data);
260                 part_cid = tny_msg_mime_part_iface_get_content_id (part);
261                 printf("CMP:%s:%s\n", cid, part_cid);
262                 if (part_cid && strcmp (cid, part_cid) == 0)
263                         return part; /* we found it! */
264                 
265                 part = NULL;
266                 parts = parts->next;
267         }
268         
269         return part;
270 }
271
272
273 static TnyMsgMimePartIface *
274 find_attachment_by_filename (TnyMsgIface *msg, const gchar *fn)
275 {
276         TnyMsgMimePartIface *part = NULL;
277         GList *parts;
278         gchar *dummy;
279         gint pos;
280
281         g_return_val_if_fail (msg, NULL);
282         g_return_val_if_fail (fn, NULL);
283         
284         parts  = (GList*) tny_msg_iface_get_parts (msg);
285         pos = virtual_filename_get_pos(fn);
286         
287         if ((pos < 0) || (pos >= g_list_length(parts)))
288                 return NULL;
289         
290         part = g_list_nth_data(parts, pos);
291         
292         dummy = construct_virtual_filename_from_mime_part(part, pos);
293         if (strcmp(dummy, fn) == 0) {
294                 g_free(dummy);
295                 return part;
296         } else {
297                 g_free(dummy);
298                 return NULL;
299         }
300 }
301
302
303 static gboolean
304 on_url_requested (GtkWidget *widget, const gchar *uri,
305                   GtkHTMLStream *stream,
306                   ModestTnyMsgView *msg_view)
307 {
308         
309         ModestTnyMsgViewPrivate *priv;
310         priv = MODEST_TNY_MSG_VIEW_GET_PRIVATE (msg_view);
311
312         g_message ("url requested: %s", uri);
313         
314         if (!modest_tny_msg_view_get_show_attachments_inline_flag(msg_view))
315                 return TRUE; /* debatable */
316         
317         if (g_str_has_prefix (uri, "cid:")) {
318                 /* +4 ==> skip "cid:" */
319                 
320                 TnyMsgMimePartIface *part = find_cid_image (priv->msg, uri + 4);
321                 if (!part) {
322                         g_message ("%s not found", uri + 4);
323                         gtk_html_stream_close (stream, GTK_HTML_STREAM_ERROR);
324                 } else {
325                         TnyStreamIface *tny_stream =
326                                 TNY_STREAM_IFACE(modest_tny_stream_gtkhtml_new(stream));
327                         tny_msg_mime_part_iface_decode_to_stream (part,tny_stream);
328                         gtk_html_stream_close (stream, GTK_HTML_STREAM_OK);
329                 }
330         } else if (g_str_has_prefix (uri, ATTACHMENT_ID_INLINE)) {
331                 TnyMsgMimePartIface *part;
332                 part = find_attachment_by_filename (priv->msg, uri);
333                 if (!part) {
334                         g_message ("%s not found", uri);
335                         gtk_html_stream_close (stream, GTK_HTML_STREAM_ERROR);
336                 } else {
337                         TnyStreamIface *tny_stream =
338                                 TNY_STREAM_IFACE(modest_tny_stream_gtkhtml_new(stream));
339                         tny_msg_mime_part_iface_decode_to_stream (part,tny_stream);
340                         gtk_html_stream_close (stream, GTK_HTML_STREAM_OK);
341                 }
342         }
343         return TRUE;
344 }
345
346
347 typedef struct  {
348         guint offset;
349         guint len;
350         const gchar* prefix;
351 } url_match_t;
352
353
354 static gchar *
355 secure_filename(const gchar *fn)
356 {
357         gchar *tmp, *p;
358         GString *s;
359         
360         s = g_string_new("");
361 #if 1 || DEBUG
362         tmp = g_strdup(fn);
363         for (p = tmp; p[0] ; p++ ) {
364                 p[0] &= 0x5f; /* 01011111 */
365                 p[0] |= 0x40; /* 01000000 */
366         }
367         g_string_printf(s, "0x%x:%s", g_str_hash(fn), tmp);
368         g_free(tmp);
369         return g_string_free(s, FALSE);
370 #else
371         g_string_printf(s, "0x%x", g_str_hash(fn));
372         return g_string_free(s, FALSE);
373 #endif
374 }
375         
376         
377 static gchar *
378 construct_virtual_filename(const gchar *filename,
379                            const gint position,
380                            const gchar *id,
381                            const gboolean active)
382 {
383         GString *s;
384         gchar *fn;
385         
386         if (position < 0)
387                 return g_strdup("AttachmentInvalid");
388
389         s = g_string_new("");
390         if (active)
391                 g_string_append(s, ATTACHMENT_ID_INLINE);
392         else
393                 g_string_append(s, ATTACHMENT_ID_LINK);
394         g_string_append_printf(s, ":%d:", position);
395         if (id)
396                 g_string_append(s, id);
397         g_string_append_c(s, ':');
398         
399         fn = secure_filename(filename);
400         if (fn)
401                 g_string_append(s, fn);
402         g_free(fn);
403         g_string_append_c(s, ':');
404         return g_string_free(s, FALSE);
405 }
406
407
408 static gchar *
409 construct_virtual_filename_from_mime_part(TnyMsgMimePartIface *msg, const gint position)
410 {
411         const gchar *id, *filename;
412         const gboolean active = TRUE;
413         
414         filename = tny_msg_mime_part_iface_get_filename(
415                                                                         TNY_MSG_MIME_PART_IFACE(msg));
416         if (!filename)
417                 filename = "[unknown]";
418         id = tny_msg_mime_part_iface_get_content_id(
419                                                                         TNY_MSG_MIME_PART_IFACE(msg));
420         
421         return construct_virtual_filename(filename, position, id, active);
422 }
423
424 const gchar *
425 get_next_token(const gchar *s, gint *len)
426 {
427         gchar *i1, *i2;
428         i1 = (char *) s;
429         i2 = (char *) s;
430         
431         while (i2[0]) {
432                 if (i2[0] == ':')
433                         break;
434                 i2++;
435         }
436         if (!i2[0])
437                 return NULL;
438         *len = i2 - i1;
439         return ++i2;
440 }
441
442 /* maybe I should use libregexp */
443 gint
444 virtual_filename_get_pos(const gchar *filename)
445 {
446         const gchar *i1, *i2;
447         gint len, pos;
448         GString *dummy;
449         
450         /* check prefix */
451         if ((!g_str_has_prefix(filename, ATTACHMENT_ID_INLINE ":")) &&
452             (!g_str_has_prefix(filename, ATTACHMENT_ID_LINK ":")))
453                 return -1;
454
455         i2 = filename;
456         i2 = get_next_token(i2, &len);
457         i1 = i2;
458                 
459         /* get position */
460         i2 = get_next_token(i2, &len);
461         if (i2 == NULL)
462                 return -1;
463         dummy = g_string_new_len(i1, len);
464         pos = atoi(dummy->str);
465         g_string_free(dummy, FALSE);
466         return pos;
467 }       
468
469
470 static gchar *
471 attachments_as_html(ModestTnyMsgView *self, TnyMsgIface *msg)
472 {
473         ModestTnyMsgViewPrivate *priv;
474         gboolean attachments_found = FALSE;
475         GString *appendix;
476         const GList *attachment_list, *attachment;
477         const gchar *content_type, *filename, *id;
478         gchar *virtual_filename;
479         
480         if (!msg)
481                 return g_malloc0(1);
482         
483         priv = MODEST_TNY_MSG_VIEW_GET_PRIVATE (self);
484         
485         appendix = g_string_new("");
486         g_string_printf(appendix, "<HTML><BODY>\n<hr><h5>%s:</h5>\n", _("Attachments"));
487         
488         attachment_list = tny_msg_iface_get_parts(msg);
489         attachment = attachment_list;
490         while (attachment) {
491                 filename = "";
492                 content_type = tny_msg_mime_part_iface_get_content_type(
493                                                                                 TNY_MSG_MIME_PART_IFACE(attachment->data));
494                 if (!content_type)
495                         continue;
496
497                 if ((strcmp("image/jpeg", content_type) == 0) ||
498                         (strcmp("image/gif",  content_type) == 0)) {
499                         filename = tny_msg_mime_part_iface_get_filename(
500                                 TNY_MSG_MIME_PART_IFACE(attachment->data));
501                         if (!filename)
502                                 filename = "[unknown]";
503                         else
504                                 attachments_found = TRUE;
505                         id = tny_msg_mime_part_iface_get_content_id(
506                                                                                 TNY_MSG_MIME_PART_IFACE(attachment->data));
507                         if (modest_tny_msg_view_get_show_attachments_inline_flag(self)) {
508                                 virtual_filename = construct_virtual_filename(filename,
509                                         g_list_position((GList *)attachment_list, (GList *) attachment),
510                                         id, TRUE);
511                                 g_string_append_printf(appendix, "<IMG src=\"%s\">\n<BR>", virtual_filename);
512                                 g_free(virtual_filename);
513                         }
514                         virtual_filename = construct_virtual_filename(filename,
515                                         g_list_position((GList *)attachment_list, (GList *) attachment),
516                                         id, FALSE);
517                         g_string_append_printf(appendix,
518                                 "<A href=\"%s\">%s</A>: %s<BR>\n",
519                                 virtual_filename, filename, content_type);
520                         g_free(virtual_filename);
521                 }
522                 attachment = attachment->next;
523         }
524         g_string_append(appendix, "</BODY></HTML>");
525         if (!attachments_found)
526                 g_string_assign(appendix, "");
527         return g_string_free(appendix, FALSE);
528 }
529
530 static void
531 hyperlinkify_plain_text (GString *txt)
532 {
533         GSList *cursor;
534         GSList *match_list = get_url_matches (txt);
535
536         /* we will work backwards, so the offsets stay valid */
537         for (cursor = match_list; cursor; cursor = cursor->next) {
538
539                 url_match_t *match = (url_match_t*) cursor->data;
540                 gchar *url  = g_strndup (txt->str + match->offset, match->len);
541                 gchar *repl = NULL; /* replacement  */
542
543                 /* the prefix is NULL: use the one that is already there */
544                 repl = g_strdup_printf ("<a href=\"%s%s\">%s</a>",
545                                         match->prefix ? match->prefix : "", url, url);
546
547                 /* replace the old thing with our hyperlink
548                  * replacement thing */
549                 g_string_erase  (txt, match->offset, match->len);
550                 g_string_insert (txt, match->offset, repl);
551                 
552                 g_free (url);
553                 g_free (repl);
554
555                 g_free (cursor->data);  
556         }
557         
558         g_slist_free (match_list);
559 }
560
561
562
563 static gchar *
564 convert_to_html (const gchar *data)
565 {
566         int              i;
567         gboolean         first_space = TRUE;
568         GString         *html;      
569         gsize           len;
570
571         if (!data)
572                 return NULL;
573
574         len = strlen (data);
575         html = g_string_sized_new (len + 100);  /* just a  guess... */
576         
577         g_string_append_printf (html,
578                                 "<html>"
579                                 "<head>"
580                                 "<meta http-equiv=\"content-type\""
581                                 " content=\"text/html; charset=utf8\">"
582                                 "</head>"
583                                 "<body><tt>");
584         
585         /* replace with special html chars where needed*/
586         for (i = 0; i != len; ++i)  {
587                 char    kar = data[i]; 
588                 switch (kar) {
589                         
590                 case 0:  break; /* ignore embedded \0s */       
591                 case '<' : g_string_append   (html, "&lt;"); break;
592                 case '>' : g_string_append   (html, "&gt;"); break;
593                 case '&' : g_string_append   (html, "&quot;"); break;
594                 case '\n': g_string_append   (html, "<br>\n"); break;
595                 default:
596                         if (kar == ' ') {
597                                 g_string_append (html, first_space ? " " : "&nbsp;");
598                                 first_space = FALSE;
599                         } else  if (kar == '\t')
600                                 g_string_append (html, "&nbsp; &nbsp;&nbsp;");
601                         else {
602                                 int charnum = 0;
603                                 first_space = TRUE;
604                                 /* optimization trick: accumulate 'normal' chars, then copy */
605                                 do {
606                                         kar = data [++charnum + i];
607                                         
608                                 } while ((i + charnum < len) &&
609                                          (kar > '>' || (kar != '<' && kar != '>'
610                                                         && kar != '&' && kar !=  ' '
611                                                         && kar != '\n' && kar != '\t')));
612                                 g_string_append_len (html, &data[i], charnum);
613                                 i += (charnum  - 1);
614                         }
615                 }
616         }
617         
618         g_string_append (html, "</tt></body></html>");
619         hyperlinkify_plain_text (html);
620
621         return g_string_free (html, FALSE);
622 }
623
624
625
626
627 static gint 
628 cmp_offsets_reverse (const url_match_t *match1, const url_match_t *match2)
629 {
630         return match2->offset - match1->offset;
631 }
632
633
634
635 /*
636  * check if the match is inside an existing match... */
637 static void
638 chk_partial_match (const url_match_t *match, int* offset)
639 {
640         if (*offset >= match->offset && *offset < match->offset + match->len)
641                 *offset = -1;
642 }
643
644 static GSList*
645 get_url_matches (GString *txt)
646 {
647         regmatch_t rm;
648         int rv, i, offset = 0;
649         GSList *match_list = NULL;
650
651         static UrlMatchPattern patterns[] = MAIL_VIEWER_URL_MATCH_PATTERNS;
652         const size_t pattern_num = sizeof(patterns)/sizeof(UrlMatchPattern);
653
654         /* initalize the regexps */
655         for (i = 0; i != pattern_num; ++i) {
656                 patterns[i].preg = g_new0 (regex_t,1);
657                 g_assert(regcomp (patterns[i].preg, patterns[i].regex,
658                                   REG_ICASE|REG_EXTENDED|REG_NEWLINE) == 0);
659         }
660         /* find all the matches */
661         for (i = 0; i != pattern_num; ++i) {
662                 offset     = 0; 
663                 while (1) {
664                         int test_offset;
665                         if ((rv = regexec (patterns[i].preg, txt->str + offset, 1, &rm, 0)) != 0) {
666                                 g_assert (rv == REG_NOMATCH); /* this should not happen */
667                                 break; /* try next regexp */ 
668                         }
669                         if (rm.rm_so == -1)
670                                 break;
671
672                         /* FIXME: optimize this */
673                         /* to avoid partial matches on something that was already found... */
674                         /* check_partial_match will put -1 in the data ptr if that is the case */
675                         test_offset = offset + rm.rm_so;
676                         g_slist_foreach (match_list, (GFunc)chk_partial_match, &test_offset);
677                         
678                         /* make a list of our matches (<offset, len, prefix> tupels)*/
679                         if (test_offset != -1) {
680                                 url_match_t *match = g_new (url_match_t,1);
681                                 match->offset = offset + rm.rm_so;
682                                 match->len    = rm.rm_eo - rm.rm_so;
683                                 match->prefix = patterns[i].prefix;
684                                 match_list = g_slist_prepend (match_list, match);
685                         }
686                         offset += rm.rm_eo;
687                 }
688         }
689
690         for (i = 0; i != pattern_num; ++i) {
691                 regfree (patterns[i].preg);
692                 g_free  (patterns[i].preg);
693         } /* don't free patterns itself -- it's static */
694         
695         /* now sort the list, so the matches are in reverse order of occurence.
696          * that way, we can do the replacements starting from the end, so we don't need
697          * to recalculate the offsets
698          */
699         match_list = g_slist_sort (match_list,
700                                    (GCompareFunc)cmp_offsets_reverse); 
701         return match_list;      
702 }
703
704 static gboolean
705 fill_gtkhtml_with_txt (ModestTnyMsgView *self, GtkHTML* gtkhtml, const gchar* txt, TnyMsgIface *msg)
706 {
707         GString *html;
708         gchar *html_attachments;
709         
710         g_return_val_if_fail (gtkhtml, FALSE);
711         g_return_val_if_fail (txt, FALSE);
712
713         html = g_string_new(convert_to_html (txt));
714         html_attachments = attachments_as_html(self, msg);
715         g_string_append(html, html_attachments);
716
717         gtk_html_load_from_string (gtkhtml, html->str, html->len);
718         g_string_free (html, TRUE);
719         g_free(html_attachments);
720
721         return TRUE;
722 }
723
724
725
726 static gboolean
727 set_html_message (ModestTnyMsgView *self, TnyMsgMimePartIface *tny_body, TnyMsgIface *msg)
728 {
729         gchar *html_attachments;
730         TnyStreamIface *gtkhtml_stream; 
731         ModestTnyMsgViewPrivate *priv;
732         
733         g_return_val_if_fail (self, FALSE);
734         g_return_val_if_fail (tny_body, FALSE);
735         
736         priv = MODEST_TNY_MSG_VIEW_GET_PRIVATE(self);
737
738         gtkhtml_stream =
739                 TNY_STREAM_IFACE(modest_tny_stream_gtkhtml_new
740                                  (gtk_html_begin(GTK_HTML(priv->gtkhtml))));
741         
742         tny_stream_iface_reset (gtkhtml_stream);
743         tny_msg_mime_part_iface_decode_to_stream (tny_body, gtkhtml_stream);
744         html_attachments = attachments_as_html(self, msg);
745         tny_stream_iface_write (gtkhtml_stream, html_attachments, strlen(html_attachments));
746         tny_stream_iface_reset (gtkhtml_stream);
747
748         g_object_unref (G_OBJECT(gtkhtml_stream));
749         g_free (html_attachments);
750         
751         return TRUE;
752 }
753
754
755 /* this is a hack --> we use the tny_text_buffer_stream to
756  * get the message text, then write to gtkhtml 'by hand' */
757 static gboolean
758 set_text_message (ModestTnyMsgView *self, TnyMsgMimePartIface *tny_body, TnyMsgIface *msg)
759 {
760         GtkTextBuffer *buf;
761         GtkTextIter begin, end;
762         TnyStreamIface* txt_stream;
763         gchar *txt;
764         ModestTnyMsgViewPrivate *priv;
765                 
766         g_return_val_if_fail (self, FALSE);
767         g_return_val_if_fail (tny_body, FALSE);
768
769         priv           = MODEST_TNY_MSG_VIEW_GET_PRIVATE(self);
770         
771         buf            = gtk_text_buffer_new (NULL);
772         txt_stream     = TNY_STREAM_IFACE(tny_text_buffer_stream_new (buf));
773                 
774         tny_stream_iface_reset (txt_stream);
775         tny_msg_mime_part_iface_decode_to_stream (tny_body, txt_stream);
776         tny_stream_iface_reset (txt_stream);            
777         
778         gtk_text_buffer_get_bounds (buf, &begin, &end);
779         txt = gtk_text_buffer_get_text (buf, &begin, &end, FALSE);
780         
781         fill_gtkhtml_with_txt (self, GTK_HTML(priv->gtkhtml), txt, msg);
782
783         g_object_unref (G_OBJECT(txt_stream));
784         g_object_unref (G_OBJECT(buf));
785
786         g_free (txt);
787         return TRUE;
788 }
789
790 gchar *
791 modest_tny_msg_view_get_selected_text (ModestTnyMsgView *self)
792 {
793         ModestTnyMsgViewPrivate *priv;
794         gchar *sel;
795         GtkWidget *html;
796         int len;
797         GtkClipboard *clip;
798
799         g_return_val_if_fail (self, NULL);
800         priv = MODEST_TNY_MSG_VIEW_GET_PRIVATE(self);
801         html = priv->gtkhtml;
802         
803         /* I'm sure there is a better way to check for selected text */
804         sel = gtk_html_get_selection_html(GTK_HTML(html), &len);
805         if (!sel)
806                 return NULL;
807         
808         g_free(sel);
809         
810         clip = gtk_widget_get_clipboard(html, GDK_SELECTION_PRIMARY);
811         return gtk_clipboard_wait_for_text(clip);
812 }
813
814 void
815 modest_tny_msg_view_set_message (ModestTnyMsgView *self, TnyMsgIface *msg)
816 {
817         TnyMsgMimePartIface *body;
818         ModestTnyMsgViewPrivate *priv;
819
820         g_return_if_fail (self);
821         
822         priv = MODEST_TNY_MSG_VIEW_GET_PRIVATE(self);
823
824         priv->msg = msg;
825         
826         fill_gtkhtml_with_txt (self, GTK_HTML(priv->gtkhtml), "", msg);
827         if (!msg) 
828                 return;
829         
830         body = modest_tny_msg_actions_find_body_part (msg, TRUE);
831         if (body) {
832                 if (tny_msg_mime_part_iface_content_type_is (body, "text/html"))
833                         set_html_message (self, body, msg);
834                 else
835                         set_text_message (self, body, msg);
836                 return;
837         } else {
838                 /* nothing to show */
839         }
840 }
841
842 void
843 modest_tny_msg_view_redraw (ModestTnyMsgView *self)
844 {
845         ModestTnyMsgViewPrivate *priv;
846
847         g_return_if_fail (self);
848         priv = MODEST_TNY_MSG_VIEW_GET_PRIVATE(self);
849         modest_tny_msg_view_set_message(self, priv->msg);
850 }
851
852 gboolean
853 modest_tny_msg_view_get_show_attachments_inline_flag (ModestTnyMsgView *self)
854 {
855         ModestTnyMsgViewPrivate *priv;
856
857         g_return_val_if_fail (self, FALSE);
858         priv = MODEST_TNY_MSG_VIEW_GET_PRIVATE(self);
859         return priv->show_attachments_inline;
860 }
861
862 gboolean
863 modest_tny_msg_view_set_show_attachments_inline_flag (ModestTnyMsgView *self, gboolean flag)
864 {
865         ModestTnyMsgViewPrivate *priv;
866         gboolean oldflag;
867
868         g_return_val_if_fail (self, FALSE);
869         priv = MODEST_TNY_MSG_VIEW_GET_PRIVATE(self);
870         oldflag = priv->show_attachments_inline;
871         priv->show_attachments_inline = flag;
872         if (priv->show_attachments_inline != oldflag)
873                 modest_tny_msg_view_redraw(self);
874         return priv->show_attachments_inline;
875 }