e11ae9111ee9bcfdeeb68055c4a2ec84fa7c1e0c
[modest] / src / widgets / modest-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 #include <tny-text-buffer-stream.h>
31 #include <string.h>
32 #include <regex.h>
33 #include <ctype.h>
34 #include <stdlib.h>
35 #include <glib/gi18n.h>
36 #include <gtkhtml/gtkhtml.h>
37 #include <gtkhtml/gtkhtml-stream.h>
38 #include <tny-list-iface.h>
39 #include <tny-list.h>
40
41 #include <modest-tny-msg-actions.h>
42 #include "modest-msg-view.h"
43 #include "modest-tny-stream-gtkhtml.h"
44
45
46 /* 'private'/'protected' functions */
47 static void     modest_msg_view_class_init   (ModestMsgViewClass *klass);
48 static void     modest_msg_view_init         (ModestMsgView *obj);
49 static void     modest_msg_view_finalize     (GObject *obj);
50
51
52 static GSList*  get_url_matches (GString *txt);
53 static gboolean on_link_clicked (GtkWidget *widget, const gchar *uri, ModestMsgView *msg_view);
54 static gboolean on_url_requested (GtkWidget *widget, const gchar *uri, GtkHTMLStream *stream,
55                                   ModestMsgView *msg_view);
56 static gboolean on_link_hover (GtkWidget *widget, const gchar *uri, ModestMsgView *msg_view);
57
58 /*
59  * we need these regexps to find URLs in plain text e-mails
60  */
61 typedef struct _UrlMatchPattern UrlMatchPattern;
62 struct _UrlMatchPattern {
63         gchar   *regex;
64         regex_t *preg;
65         gchar   *prefix;
66 };
67
68 #define ATT_PREFIX "att:"
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
86 /* list my signals */
87 enum {
88         LINK_CLICKED_SIGNAL,
89         LINK_HOVER_SIGNAL,
90         ATTACHMENT_CLICKED_SIGNAL,
91         LAST_SIGNAL
92 };
93
94 typedef struct _ModestMsgViewPrivate ModestMsgViewPrivate;
95 struct _ModestMsgViewPrivate {
96
97         GtkWidget   *gtkhtml;
98         TnyMsgIface *msg;
99
100         gulong  sig1, sig2, sig3;
101 };
102 #define MODEST_MSG_VIEW_GET_PRIVATE(o)      (G_TYPE_INSTANCE_GET_PRIVATE((o), \
103                                                  MODEST_TYPE_MSG_VIEW, \
104                                                  ModestMsgViewPrivate))
105 /* globals */
106 static GtkContainerClass *parent_class = NULL;
107
108 /* uncomment the following if you have defined any signals */
109 static guint signals[LAST_SIGNAL] = {0};
110
111 GType
112 modest_msg_view_get_type (void)
113 {
114         static GType my_type = 0;
115         if (!my_type) {
116                 static const GTypeInfo my_info = {
117                         sizeof(ModestMsgViewClass),
118                         NULL,           /* base init */
119                         NULL,           /* base finalize */
120                         (GClassInitFunc) modest_msg_view_class_init,
121                         NULL,           /* class finalize */
122                         NULL,           /* class data */
123                         sizeof(ModestMsgView),
124                         1,              /* n_preallocs */
125                         (GInstanceInitFunc) modest_msg_view_init,
126                         NULL
127                 };
128                 my_type = g_type_register_static (GTK_TYPE_SCROLLED_WINDOW,
129                                                   "ModestMsgView",
130                                                   &my_info, 0);
131         }
132         return my_type;
133 }
134
135 static void
136 modest_msg_view_class_init (ModestMsgViewClass *klass)
137 {
138         GObjectClass *gobject_class;
139         gobject_class = (GObjectClass*) klass;
140
141         parent_class            = g_type_class_peek_parent (klass);
142         gobject_class->finalize = modest_msg_view_finalize;
143
144         g_type_class_add_private (gobject_class, sizeof(ModestMsgViewPrivate));
145
146                 
147         signals[LINK_CLICKED_SIGNAL] =
148                 g_signal_new ("link_clicked",
149                               G_TYPE_FROM_CLASS (gobject_class),
150                               G_SIGNAL_RUN_FIRST,
151                               G_STRUCT_OFFSET(ModestMsgViewClass, link_clicked),
152                               NULL, NULL,
153                               g_cclosure_marshal_VOID__STRING,
154                               G_TYPE_NONE, 1, G_TYPE_STRING);
155         
156         signals[ATTACHMENT_CLICKED_SIGNAL] =
157                 g_signal_new ("attachment_clicked",
158                               G_TYPE_FROM_CLASS (gobject_class),
159                               G_SIGNAL_RUN_FIRST,
160                               G_STRUCT_OFFSET(ModestMsgViewClass, attachment_clicked),
161                               NULL, NULL,
162                               g_cclosure_marshal_VOID__POINTER,
163                               G_TYPE_NONE, 1, G_TYPE_INT);
164         
165         signals[LINK_HOVER_SIGNAL] =
166                 g_signal_new ("link_hover",
167                               G_TYPE_FROM_CLASS (gobject_class),
168                               G_SIGNAL_RUN_FIRST,
169                               G_STRUCT_OFFSET(ModestMsgViewClass, link_hover),
170                               NULL, NULL,
171                               g_cclosure_marshal_VOID__STRING,
172                               G_TYPE_NONE, 1, G_TYPE_STRING);
173 }
174
175 static void
176 modest_msg_view_init (ModestMsgView *obj)
177 {
178         ModestMsgViewPrivate *priv;
179         
180         priv = MODEST_MSG_VIEW_GET_PRIVATE(obj);
181
182         priv->msg                     = NULL;
183         priv->gtkhtml                 = gtk_html_new();
184         
185         gtk_html_set_editable        (GTK_HTML(priv->gtkhtml), FALSE);
186         gtk_html_allow_selection     (GTK_HTML(priv->gtkhtml), TRUE);
187         gtk_html_set_caret_mode      (GTK_HTML(priv->gtkhtml), FALSE);
188         gtk_html_set_blocking        (GTK_HTML(priv->gtkhtml), FALSE);
189         gtk_html_set_images_blocking (GTK_HTML(priv->gtkhtml), FALSE);
190
191         priv->sig1 = g_signal_connect (G_OBJECT(priv->gtkhtml), "link_clicked",
192                                        G_CALLBACK(on_link_clicked), obj);
193         priv->sig2 = g_signal_connect (G_OBJECT(priv->gtkhtml), "url_requested",
194                                        G_CALLBACK(on_url_requested), obj);
195         priv->sig3 = g_signal_connect (G_OBJECT(priv->gtkhtml), "on_url",
196                                        G_CALLBACK(on_link_hover), obj);
197 }
198         
199
200 static void
201 modest_msg_view_finalize (GObject *obj)
202 {       
203         ModestMsgViewPrivate *priv;
204         priv = MODEST_MSG_VIEW_GET_PRIVATE (obj);
205
206         if (priv->msg) {
207                 g_object_unref (G_OBJECT(priv->msg));
208                 priv->msg = NULL;
209         }
210         
211         /* we cannot disconnect sigs, because priv->gtkhtml is
212          * already dead */
213         
214         priv->gtkhtml = NULL;
215         
216         G_OBJECT_CLASS(parent_class)->finalize (obj);           
217 }
218
219
220 GtkWidget*
221 modest_msg_view_new (TnyMsgIface *msg)
222 {
223         GObject *obj;
224         ModestMsgView* self;
225         ModestMsgViewPrivate *priv;
226         
227         obj  = G_OBJECT(g_object_new(MODEST_TYPE_MSG_VIEW, NULL));
228         self = MODEST_MSG_VIEW(obj);
229         priv = MODEST_MSG_VIEW_GET_PRIVATE (self);
230
231         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(self),
232                                        GTK_POLICY_AUTOMATIC,
233                                        GTK_POLICY_AUTOMATIC);
234
235         if (priv->gtkhtml) 
236                 gtk_container_add (GTK_CONTAINER(obj), priv->gtkhtml);
237         
238         if (msg)
239                 modest_msg_view_set_message (self, msg);
240         
241         return GTK_WIDGET(self);
242 }
243
244
245 static gboolean
246 on_link_clicked (GtkWidget *widget, const gchar *uri, ModestMsgView *msg_view)
247 {
248         int index;
249
250         g_return_val_if_fail (msg_view, FALSE);
251         
252         /* is it an attachment? */
253         if (g_str_has_prefix(uri, ATT_PREFIX)) {
254
255                 index = atoi (uri + strlen(ATT_PREFIX));
256                 
257                 if (index == 0) {
258                         /* index is 1-based, so 0 indicates an error */
259                         g_printerr ("modest: invalid attachment id: %s\n", uri);
260                         return FALSE;
261                 }
262
263                 g_signal_emit (G_OBJECT(msg_view), signals[ATTACHMENT_CLICKED_SIGNAL],
264                                0, index);
265                 return FALSE;
266         }
267
268         g_signal_emit (G_OBJECT(msg_view), signals[LINK_CLICKED_SIGNAL],
269                        0, uri);
270
271         return FALSE;
272 }
273
274
275
276 static gboolean
277 on_link_hover (GtkWidget *widget, const gchar *uri, ModestMsgView *msg_view)
278 {
279         if (uri && g_str_has_prefix (uri, ATT_PREFIX))
280                 return FALSE;
281
282         g_signal_emit (G_OBJECT(msg_view), signals[LINK_HOVER_SIGNAL],
283                        0, uri);
284
285         return FALSE;
286 }
287
288
289
290 static TnyMimePartIface *
291 find_cid_image (TnyMsgIface *msg, const gchar *cid)
292 {
293         TnyMimePartIface *part = NULL;
294         TnyListIface *parts;
295         TnyIteratorIface *iter;
296         
297         g_return_val_if_fail (msg, NULL);
298         g_return_val_if_fail (cid, NULL);
299         
300         parts  = TNY_LIST_IFACE (tny_list_new());
301
302         tny_msg_iface_get_parts (msg, parts); 
303         iter   = tny_list_iface_create_iterator (parts);
304         
305         while (!tny_iterator_iface_is_done(iter)) {
306                 const gchar *part_cid;
307                 part = TNY_MIME_PART_IFACE(tny_iterator_iface_current(iter));
308                 part_cid = tny_mime_part_iface_get_content_id (part);
309
310                 if (part_cid && strcmp (cid, part_cid) == 0)
311                         break;
312
313                 part = NULL;
314                 tny_iterator_iface_next (iter);
315         }
316         
317         if (part)
318                 g_object_ref (G_OBJECT(part));
319
320         g_object_unref (G_OBJECT(iter));        
321         g_object_unref (G_OBJECT(parts));
322         
323         return part;
324 }
325
326
327 static gboolean
328 on_url_requested (GtkWidget *widget, const gchar *uri,
329                   GtkHTMLStream *stream,
330                   ModestMsgView *msg_view)
331 {
332         ModestMsgViewPrivate *priv;
333         priv = MODEST_MSG_VIEW_GET_PRIVATE (msg_view);
334         
335         if (g_str_has_prefix (uri, "cid:")) {
336                 /* +4 ==> skip "cid:" */
337                 TnyMimePartIface *part = find_cid_image (priv->msg, uri + 4);
338                 if (!part) {
339                         g_printerr ("modest: '%s' not found\n", uri + 4);
340                         gtk_html_stream_close (stream, GTK_HTML_STREAM_ERROR);
341                 } else {
342                         TnyStreamIface *tny_stream =
343                                 TNY_STREAM_IFACE(modest_tny_stream_gtkhtml_new(stream));
344                         tny_mime_part_iface_decode_to_stream ((TnyMimePartIface*)part,
345                                                                   tny_stream);
346                         gtk_html_stream_close (stream, GTK_HTML_STREAM_OK);
347         
348                         g_object_unref (G_OBJECT(tny_stream));
349                         g_object_unref (G_OBJECT(part));
350                 }
351         }
352
353         return TRUE;
354 }
355
356
357 typedef struct  {
358         guint offset;
359         guint len;
360         const gchar* prefix;
361 } url_match_t;
362
363
364
365 /* render the attachments as hyperlinks in html */
366 static gchar*
367 attachments_as_html (ModestMsgView *self, TnyMsgIface *msg)
368 {
369         ModestMsgViewPrivate *priv;
370         GString *appendix;
371         TnyListIface *parts;
372         TnyIteratorIface *iter;
373         gchar *html;
374         int index = 0;
375         
376         if (!msg)
377                 return NULL;
378
379         priv  = MODEST_MSG_VIEW_GET_PRIVATE (self);
380
381         parts = TNY_LIST_IFACE(tny_list_new());
382         tny_msg_iface_get_parts (msg, parts);
383         iter  = tny_list_iface_create_iterator (parts);
384         
385         appendix= g_string_new ("");
386         
387         while (!tny_iterator_iface_is_done(iter)) {
388                 TnyMimePartIface *part;
389
390                 ++index; /* attachment numbers are 1-based */
391                 
392                 part = TNY_MIME_PART_IFACE(tny_iterator_iface_current (iter));
393
394                 if (tny_mime_part_iface_is_attachment (part)) {
395
396                         const gchar *filename = tny_mime_part_iface_get_filename(part);
397                         if (!filename)
398                                 filename = _("attachment");
399
400                         g_string_append_printf (appendix, "<a href=\"%s%d\">%s</a> \n",
401                                                 ATT_PREFIX, index, filename);                    
402                 }
403                 tny_iterator_iface_next (iter);
404         }
405         g_object_unref (G_OBJECT(iter));
406         
407         if (appendix->len == 0) 
408                 return g_string_free (appendix, TRUE);
409
410         html = g_strdup_printf ("<strong>%s:</strong> %s\n<hr>",
411                                 _("Attachments"), appendix->str);                        
412         g_string_free (appendix, TRUE);
413         
414         return html;
415 }
416
417
418
419 static void
420 hyperlinkify_plain_text (GString *txt)
421 {
422         GSList *cursor;
423         GSList *match_list = get_url_matches (txt);
424
425         /* we will work backwards, so the offsets stay valid */
426         for (cursor = match_list; cursor; cursor = cursor->next) {
427
428                 url_match_t *match = (url_match_t*) cursor->data;
429                 gchar *url  = g_strndup (txt->str + match->offset, match->len);
430                 gchar *repl = NULL; /* replacement  */
431
432                 /* the prefix is NULL: use the one that is already there */
433                 repl = g_strdup_printf ("<a href=\"%s%s\">%s</a>",
434                                         match->prefix ? match->prefix : "", url, url);
435
436                 /* replace the old thing with our hyperlink
437                  * replacement thing */
438                 g_string_erase  (txt, match->offset, match->len);
439                 g_string_insert (txt, match->offset, repl);
440                 
441                 g_free (url);
442                 g_free (repl);
443
444                 g_free (cursor->data);  
445         }
446         
447         g_slist_free (match_list);
448 }
449
450
451
452 static gchar *
453 convert_to_html (const gchar *data)
454 {
455         guint            i;
456         gboolean         first_space = TRUE;
457         GString         *html;      
458         gsize           len;
459
460         if (!data)
461                 return NULL;
462
463         len = strlen (data);
464         html = g_string_sized_new (len + 100);  /* just a  guess... */
465         
466         g_string_append_printf (html,
467                                 "<html>"
468                                 "<head>"
469                                 "<meta http-equiv=\"content-type\""
470                                 " content=\"text/html; charset=utf8\">"
471                                 "</head>"
472                                 "<body><tt>");
473         
474         /* replace with special html chars where needed*/
475         for (i = 0; i != len; ++i)  {
476                 char    kar = data[i]; 
477                 switch (kar) {
478                         
479                 case 0:  break; /* ignore embedded \0s */       
480                 case '<' : g_string_append   (html, "&lt;"); break;
481                 case '>' : g_string_append   (html, "&gt;"); break;
482                 case '&' : g_string_append   (html, "&quot;"); break;
483                 case '\n': g_string_append   (html, "<br>\n"); break;
484                 default:
485                         if (kar == ' ') {
486                                 g_string_append (html, first_space ? " " : "&nbsp;");
487                                 first_space = FALSE;
488                         } else  if (kar == '\t')
489                                 g_string_append (html, "&nbsp; &nbsp;&nbsp;");
490                         else {
491                                 int charnum = 0;
492                                 first_space = TRUE;
493                                 /* optimization trick: accumulate 'normal' chars, then copy */
494                                 do {
495                                         kar = data [++charnum + i];
496                                         
497                                 } while ((i + charnum < len) &&
498                                          (kar > '>' || (kar != '<' && kar != '>'
499                                                         && kar != '&' && kar !=  ' '
500                                                         && kar != '\n' && kar != '\t')));
501                                 g_string_append_len (html, &data[i], charnum);
502                                 i += (charnum  - 1);
503                         }
504                 }
505         }
506         
507         g_string_append (html, "</tt></body></html>");
508         hyperlinkify_plain_text (html);
509
510         return g_string_free (html, FALSE);
511 }
512
513
514
515
516 static gint 
517 cmp_offsets_reverse (const url_match_t *match1, const url_match_t *match2)
518 {
519         return match2->offset - match1->offset;
520 }
521
522
523
524 /*
525  * check if the match is inside an existing match... */
526 static void
527 chk_partial_match (const url_match_t *match, guint* offset)
528 {
529         if (*offset >= match->offset && *offset < match->offset + match->len)
530                 *offset = -1;
531 }
532
533 static GSList*
534 get_url_matches (GString *txt)
535 {
536         regmatch_t rm;
537         guint rv, i, offset = 0;
538         GSList *match_list = NULL;
539
540         static UrlMatchPattern patterns[] = MAIL_VIEWER_URL_MATCH_PATTERNS;
541         const size_t pattern_num = sizeof(patterns)/sizeof(UrlMatchPattern);
542
543         /* initalize the regexps */
544         for (i = 0; i != pattern_num; ++i) {
545                 patterns[i].preg = g_new0 (regex_t,1);
546                 g_assert(regcomp (patterns[i].preg, patterns[i].regex,
547                                   REG_ICASE|REG_EXTENDED|REG_NEWLINE) == 0);
548         }
549         /* find all the matches */
550         for (i = 0; i != pattern_num; ++i) {
551                 offset     = 0; 
552                 while (1) {
553                         int test_offset;
554                         if ((rv = regexec (patterns[i].preg, txt->str + offset, 1, &rm, 0)) != 0) {
555                                 g_assert (rv == REG_NOMATCH); /* this should not happen */
556                                 break; /* try next regexp */ 
557                         }
558                         if (rm.rm_so == -1)
559                                 break;
560
561                         /* FIXME: optimize this */
562                         /* to avoid partial matches on something that was already found... */
563                         /* check_partial_match will put -1 in the data ptr if that is the case */
564                         test_offset = offset + rm.rm_so;
565                         g_slist_foreach (match_list, (GFunc)chk_partial_match, &test_offset);
566                         
567                         /* make a list of our matches (<offset, len, prefix> tupels)*/
568                         if (test_offset != -1) {
569                                 url_match_t *match = g_new (url_match_t,1);
570                                 match->offset = offset + rm.rm_so;
571                                 match->len    = rm.rm_eo - rm.rm_so;
572                                 match->prefix = patterns[i].prefix;
573                                 match_list = g_slist_prepend (match_list, match);
574                         }
575                         offset += rm.rm_eo;
576                 }
577         }
578
579         for (i = 0; i != pattern_num; ++i) {
580                 regfree (patterns[i].preg);
581                 g_free  (patterns[i].preg);
582         } /* don't free patterns itself -- it's static */
583         
584         /* now sort the list, so the matches are in reverse order of occurence.
585          * that way, we can do the replacements starting from the end, so we don't need
586          * to recalculate the offsets
587          */
588         match_list = g_slist_sort (match_list,
589                                    (GCompareFunc)cmp_offsets_reverse); 
590         return match_list;      
591 }
592
593
594
595 static gboolean
596 set_html_message (ModestMsgView *self, TnyMimePartIface *tny_body, TnyMsgIface *msg)
597 {
598         gchar *html_attachments;
599         TnyStreamIface *gtkhtml_stream; 
600         ModestMsgViewPrivate *priv;
601         
602         g_return_val_if_fail (self, FALSE);
603         g_return_val_if_fail (tny_body, FALSE);
604         
605         priv = MODEST_MSG_VIEW_GET_PRIVATE(self);
606
607         gtkhtml_stream =
608                 TNY_STREAM_IFACE(modest_tny_stream_gtkhtml_new
609                                  (gtk_html_begin(GTK_HTML(priv->gtkhtml))));
610         
611         tny_stream_iface_reset (gtkhtml_stream);
612         
613         html_attachments = attachments_as_html(self, msg);
614         if (html_attachments) {
615                 tny_stream_iface_write (gtkhtml_stream, html_attachments,
616                                         strlen(html_attachments));
617                 tny_stream_iface_reset (gtkhtml_stream);
618                 g_free (html_attachments);
619         }
620
621         // FIXME: tinymail
622         tny_mime_part_iface_decode_to_stream ((TnyMimePartIface*)tny_body,
623                                                   gtkhtml_stream);
624
625         g_object_unref (G_OBJECT(gtkhtml_stream));
626         
627         return TRUE;
628 }
629
630
631 /* this is a hack --> we use the tny_text_buffer_stream to
632  * get the message text, then write to gtkhtml 'by hand' */
633 static gboolean
634 set_text_message (ModestMsgView *self, TnyMimePartIface *tny_body, TnyMsgIface *msg)
635 {
636         GtkTextBuffer *buf;
637         GtkTextIter begin, end;
638         TnyStreamIface* txt_stream, *gtkhtml_stream;
639         gchar *txt, *html_attachments;
640         ModestMsgViewPrivate *priv;
641                 
642         g_return_val_if_fail (self, FALSE);
643         g_return_val_if_fail (tny_body, FALSE);
644
645         priv           = MODEST_MSG_VIEW_GET_PRIVATE(self);
646         
647         buf            = gtk_text_buffer_new (NULL);
648         txt_stream     = TNY_STREAM_IFACE(tny_text_buffer_stream_new (buf));
649                 
650         tny_stream_iface_reset (txt_stream);
651         
652         gtkhtml_stream =
653                 TNY_STREAM_IFACE(modest_tny_stream_gtkhtml_new
654                                  (gtk_html_begin(GTK_HTML(priv->gtkhtml))));
655
656         html_attachments = attachments_as_html(self, msg);
657         if (html_attachments) {
658                 tny_stream_iface_write (gtkhtml_stream, html_attachments,
659                                         strlen(html_attachments));
660                 tny_stream_iface_reset (gtkhtml_stream);
661                 g_free (html_attachments);
662         }
663
664         // FIXME: tinymail
665         tny_mime_part_iface_decode_to_stream ((TnyMimePartIface*)tny_body,
666                                                   txt_stream);
667         tny_stream_iface_reset (txt_stream);            
668         
669         gtk_text_buffer_get_bounds (buf, &begin, &end);
670         txt = gtk_text_buffer_get_text (buf, &begin, &end, FALSE);
671         if (txt) {
672                 gchar *html = convert_to_html (txt);
673                 tny_stream_iface_write (gtkhtml_stream, html, strlen(html));
674                 tny_stream_iface_reset (gtkhtml_stream);
675                 g_free (txt);
676                 g_free (html);
677         }
678         
679         g_object_unref (G_OBJECT(gtkhtml_stream));
680         g_object_unref (G_OBJECT(txt_stream));
681         g_object_unref (G_OBJECT(buf));
682
683         return TRUE;
684 }
685
686
687 static gboolean
688 set_empty_message (ModestMsgView *self)
689 {
690         ModestMsgViewPrivate *priv;
691         
692         g_return_val_if_fail (self, FALSE);
693         priv           = MODEST_MSG_VIEW_GET_PRIVATE(self);
694
695         gtk_html_load_from_string (GTK_HTML(priv->gtkhtml),
696                                    "", 1);
697         
698         return TRUE;
699 }
700
701
702 gchar *
703 modest_msg_view_get_selected_text (ModestMsgView *self)
704 {
705         ModestMsgViewPrivate *priv;
706         gchar *sel;
707         GtkWidget *html;
708         int len;
709         GtkClipboard *clip;
710
711         g_return_val_if_fail (self, NULL);
712         priv = MODEST_MSG_VIEW_GET_PRIVATE(self);
713         html = priv->gtkhtml;
714         
715         /* I'm sure there is a better way to check for selected text */
716         sel = gtk_html_get_selection_html(GTK_HTML(html), &len);
717         if (!sel)
718                 return NULL;
719         
720         g_free(sel);
721         
722         clip = gtk_widget_get_clipboard(html, GDK_SELECTION_PRIMARY);
723         return gtk_clipboard_wait_for_text(clip);
724 }
725
726
727 void
728 modest_msg_view_set_message (ModestMsgView *self, TnyMsgIface *msg)
729 {
730         TnyMimePartIface *body;
731         ModestMsgViewPrivate *priv;
732
733         g_return_if_fail (self);
734         
735         priv = MODEST_MSG_VIEW_GET_PRIVATE(self);
736
737
738         if (msg != priv->msg) {
739                 if (priv->msg)
740                         g_object_unref (G_OBJECT(priv->msg));
741                 if (msg)
742                         g_object_ref   (G_OBJECT(msg));
743                 priv->msg = msg;
744         }
745         
746         if (!msg) {
747                 set_empty_message (self);
748                 return;
749         }
750                 
751         body = modest_tny_msg_actions_find_body_part (msg, TRUE);
752         if (body) {
753                 if (tny_mime_part_iface_content_type_is (body, "text/html"))
754                         set_html_message (self, body, msg);
755                 else
756                         set_text_message (self, body, msg);
757                 return;
758         } else 
759                 set_empty_message (self);
760 }