* fix leak
[modest] / src / modest-tny-msg-view.c
1 /* modest-tny-msg-view.c */
2
3 /* insert (c)/licensing information) */
4
5 #include "modest-tny-msg-view.h"
6 #include "modest-tny-stream-gtkhtml.h"
7 #include <tny-text-buffer-stream.h>
8 #include <string.h>
9 #include <regex.h>
10 #include <ctype.h>
11 #include <glib/gi18n.h>
12
13 /* 'private'/'protected' functions */
14 static void     modest_tny_msg_view_class_init   (ModestTnyMsgViewClass *klass);
15 static void     modest_tny_msg_view_init         (ModestTnyMsgView *obj);
16 static void     modest_tny_msg_view_finalize     (GObject *obj);
17
18
19 static GSList*  get_url_matches (GString *txt);
20 static gboolean fill_gtkhtml_with_txt (GtkHTML* gtkhtml, const gchar* txt);
21
22 static gboolean on_link_clicked (GtkWidget *widget, const gchar *uri,
23                                  ModestTnyMsgView *msg_view);
24 static gboolean on_url_requested (GtkWidget *widget, const gchar *uri,
25                                   GtkHTMLStream *stream,
26                                   ModestTnyMsgView *msg_view);
27
28
29 /*
30  * we need these regexps to find URLs in plain text e-mails
31  */
32 typedef struct _UrlMatchPattern UrlMatchPattern;
33 struct _UrlMatchPattern {
34         gchar   *regex;
35         regex_t *preg;
36         gchar   *prefix;
37         
38 };
39 #define MAIL_VIEWER_URL_MATCH_PATTERNS  {\
40         { "(file|http|ftp|https)://[-A-Za-z0-9_$.+!*(),;:@%&=?/~#]+[-A-Za-z0-9_$%&=?/~#]",\
41           NULL, NULL },\
42         { "www\\.[-a-z0-9.]+[-a-z0-9](:[0-9]*)?(/[-A-Za-z0-9_$.+!*(),;:@%&=?/~#]*[^]}\\),?!;:\"]?)?",\
43           NULL, "http://" },\
44         { "ftp\\.[-a-z0-9.]+[-a-z0-9](:[0-9]*)?(/[-A-Za-z0-9_$.+!*(),;:@%&=?/~#]*[^]}\\),?!;:\"]?)?",\
45           NULL, "ftp://" },\
46         { "(voipto|callto|chatto|jabberto|xmpp):[-_a-z@0-9.\\+]+", \
47            NULL, NULL},                                             \
48         { "mailto:[-_a-z0-9.\\+]+@[-_a-z0-9.]+",                    \
49           NULL, NULL},\
50         { "[-_a-z0-9.\\+]+@[-_a-z0-9.]+",\
51           NULL, "mailto:"}\
52         }
53
54
55 /* list my signals */
56 enum {
57         /* MY_SIGNAL_1, */
58         /* MY_SIGNAL_2, */
59         LAST_SIGNAL
60 };
61
62 typedef struct _ModestTnyMsgViewPrivate ModestTnyMsgViewPrivate;
63 struct _ModestTnyMsgViewPrivate {
64         GtkWidget *gtkhtml;
65         TnyMsgIface *msg;
66 };
67 #define MODEST_TNY_MSG_VIEW_GET_PRIVATE(o)      (G_TYPE_INSTANCE_GET_PRIVATE((o), \
68                                                  MODEST_TYPE_TNY_MSG_VIEW, \
69                                                  ModestTnyMsgViewPrivate))
70 /* globals */
71 static GtkContainerClass *parent_class = NULL;
72
73 /* uncomment the following if you have defined any signals */
74 /* static guint signals[LAST_SIGNAL] = {0}; */
75
76 GType
77 modest_tny_msg_view_get_type (void)
78 {
79         static GType my_type = 0;
80         if (!my_type) {
81                 static const GTypeInfo my_info = {
82                         sizeof(ModestTnyMsgViewClass),
83                         NULL,           /* base init */
84                         NULL,           /* base finalize */
85                         (GClassInitFunc) modest_tny_msg_view_class_init,
86                         NULL,           /* class finalize */
87                         NULL,           /* class data */
88                         sizeof(ModestTnyMsgView),
89                         1,              /* n_preallocs */
90                         (GInstanceInitFunc) modest_tny_msg_view_init,
91                 };
92                 my_type = g_type_register_static (GTK_TYPE_SCROLLED_WINDOW,
93                                                   "ModestTnyMsgView",
94                                                   &my_info, 0);
95         }
96         return my_type;
97 }
98
99 static void
100 modest_tny_msg_view_class_init (ModestTnyMsgViewClass *klass)
101 {
102         GObjectClass *gobject_class;
103         gobject_class = (GObjectClass*) klass;
104
105         parent_class            = g_type_class_peek_parent (klass);
106         gobject_class->finalize = modest_tny_msg_view_finalize;
107
108         g_type_class_add_private (gobject_class, sizeof(ModestTnyMsgViewPrivate));
109 }
110
111 static void
112 modest_tny_msg_view_init (ModestTnyMsgView *obj)
113 {
114         ModestTnyMsgViewPrivate *priv;
115         
116         priv = MODEST_TNY_MSG_VIEW_GET_PRIVATE(obj);
117
118         priv->msg = NULL;
119         
120         priv->gtkhtml = gtk_html_new();
121
122         gtk_html_set_editable        (GTK_HTML(priv->gtkhtml), FALSE);
123         gtk_html_allow_selection     (GTK_HTML(priv->gtkhtml), TRUE);
124         gtk_html_set_caret_mode      (GTK_HTML(priv->gtkhtml), FALSE);
125         gtk_html_set_blocking        (GTK_HTML(priv->gtkhtml), FALSE);
126         gtk_html_set_images_blocking (GTK_HTML(priv->gtkhtml), FALSE);
127         
128         g_signal_connect (G_OBJECT(priv->gtkhtml), "link_clicked",
129                           G_CALLBACK(on_link_clicked), obj);
130         
131         g_signal_connect (G_OBJECT(priv->gtkhtml), "url_requested",
132                           G_CALLBACK(on_url_requested), obj);
133 }
134         
135
136 static void
137 modest_tny_msg_view_finalize (GObject *obj)
138 {       
139         
140 }
141
142 GtkWidget*
143 modest_tny_msg_view_new (TnyMsgIface *msg)
144 {
145         GObject *obj;
146         ModestTnyMsgView* self;
147         ModestTnyMsgViewPrivate *priv;
148         
149         obj  = G_OBJECT(g_object_new(MODEST_TYPE_TNY_MSG_VIEW, NULL));
150         self = MODEST_TNY_MSG_VIEW(obj);
151         priv = MODEST_TNY_MSG_VIEW_GET_PRIVATE (self);
152
153         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(self),
154                                        GTK_POLICY_AUTOMATIC,
155                                        GTK_POLICY_AUTOMATIC);
156
157         if (priv->gtkhtml) 
158                 gtk_container_add (GTK_CONTAINER(obj), priv->gtkhtml);  
159         
160         if (msg)
161                 modest_tny_msg_view_set_message (self, msg);
162
163         return GTK_WIDGET(self);
164 }
165
166
167
168 static gboolean
169 on_link_clicked (GtkWidget *widget, const gchar *uri,
170                                  ModestTnyMsgView *msg_view)
171 {
172         g_message ("link clicked: %s", uri); /* FIXME */
173 }
174
175
176
177 static TnyMsgMimePartIface *
178 find_cid_image (TnyMsgIface *msg, const gchar *cid)
179 {
180         TnyMsgMimePartIface *part = NULL;
181         GList *parts;
182
183         g_return_val_if_fail (msg, NULL);
184         g_return_val_if_fail (cid, NULL);
185         
186         parts  = (GList*) tny_msg_iface_get_parts (msg);
187         while (parts && !part) {
188                 const gchar *part_cid;
189                 part = TNY_MSG_MIME_PART_IFACE(parts->data);
190                 part_cid = tny_msg_mime_part_iface_get_content_id (part);
191                 if (part_cid && strcmp (cid, part_cid) == 0)
192                         return part; /* we found it! */
193                 
194                 part = NULL;
195                 parts = parts->next;
196         }
197         
198         return part;
199 }
200
201
202 static gboolean
203 on_url_requested (GtkWidget *widget, const gchar *uri,
204                   GtkHTMLStream *stream,
205                   ModestTnyMsgView *msg_view)
206 {
207         
208         ModestTnyMsgViewPrivate *priv;
209         priv = MODEST_TNY_MSG_VIEW_GET_PRIVATE (msg_view);
210
211         g_message ("url requested: %s", uri);
212         
213         if (g_str_has_prefix (uri, "cid:")) {
214                 /* +4 ==> skip "cid:" */
215                 
216                 TnyMsgMimePartIface *part = find_cid_image (priv->msg, uri + 4);
217                 if (!part) {
218                         g_message ("%s not found", uri + 4);
219                         gtk_html_stream_close (stream, GTK_HTML_STREAM_ERROR);
220                 } else {
221                         TnyStreamIface *tny_stream =
222                                 TNY_STREAM_IFACE(modest_tny_stream_gtkhtml_new(stream));
223                         tny_msg_mime_part_iface_decode_to_stream (part,tny_stream);
224                         gtk_html_stream_close (stream, GTK_HTML_STREAM_OK);
225                 }
226         }
227         return TRUE;
228 }
229
230
231
232
233 typedef struct  {
234         guint offset;
235         guint len;
236         const gchar* prefix;
237 } url_match_t;
238
239
240 static void
241 hyperlinkify_plain_text (GString *txt)
242 {
243         GSList *cursor;
244         GSList *match_list = get_url_matches (txt);
245
246         /* we will work backwards, so the offsets stay valid */
247         for (cursor = match_list; cursor; cursor = cursor->next) {
248
249                 url_match_t *match = (url_match_t*) cursor->data;
250                 gchar *url  = g_strndup (txt->str + match->offset, match->len);
251                 gchar *repl = NULL; /* replacement  */
252
253                 /* the prefix is NULL: use the one that is already there */
254                 repl = g_strdup_printf ("<a href=\"%s%s\">%s</a>",
255                                         match->prefix ? match->prefix : "", url, url);
256
257                 /* replace the old thing with our hyperlink
258                  * replacement thing */
259                 g_string_erase  (txt, match->offset, match->len);
260                 g_string_insert (txt, match->offset, repl);
261                 
262                 g_free (url);
263                 g_free (repl);
264
265                 g_free (cursor->data);  
266         }
267         
268         g_slist_free (match_list);
269 }
270
271
272
273 static gchar *
274 convert_to_html (const gchar *data)
275 {
276         int              i;
277         gboolean         first_space = TRUE;
278         GString         *html;      
279         gsize           len;
280
281         if (!data)
282                 return NULL;
283
284         len = strlen (data);
285         html = g_string_sized_new (len + 100);  /* just a  guess... */
286         
287         g_string_append_printf (html,
288                                 "<html>"
289                                 "<head>"
290                                 "<meta http-equiv=\"content-type\""
291                                 " content=\"text/html; charset=utf8\">"
292                                 "</head>"
293                                 "<body><tt>");
294         
295         /* replace with special html chars where needed*/
296         for (i = 0; i != len; ++i)  {
297                 char    kar = data[i]; 
298                 switch (kar) {
299                         
300                 case 0:  break; /* ignore embedded \0s */       
301                 case '<' : g_string_append   (html, "&lt;"); break;
302                 case '>' : g_string_append   (html, "&gt;"); break;
303                 case '&' : g_string_append   (html, "&quot;"); break;
304                 case '\n': g_string_append   (html, "<br>\n"); break;
305                 default:
306                         if (kar == ' ') {
307                                 g_string_append (html, first_space ? " " : "&nbsp;");
308                                 first_space = FALSE;
309                         } else  if (kar == '\t')
310                                 g_string_append (html, "&nbsp; &nbsp;&nbsp;");
311                         else {
312                                 int charnum = 0;
313                                 first_space = TRUE;
314                                 /* optimization trick: accumulate 'normal' chars, then copy */
315                                 do {
316                                         kar = data [++charnum + i];
317                                         
318                                 } while ((i + charnum < len) &&
319                                          (kar > '>' || (kar != '<' && kar != '>'
320                                                         && kar != '&' && kar !=  ' '
321                                                         && kar != '\n' && kar != '\t')));
322                                 g_string_append_len (html, &data[i], charnum);
323                                 i += (charnum  - 1);
324                         }
325                 }
326         }
327
328         g_string_append (html, "</tt></body></html>");
329         hyperlinkify_plain_text (html);
330
331         return g_string_free (html, FALSE);
332 }
333
334
335
336
337 static gint 
338 cmp_offsets_reverse (const url_match_t *match1, const url_match_t *match2)
339 {
340         return match2->offset - match1->offset;
341 }
342
343
344
345 /*
346  * check if the match is inside an existing match... */
347 static void
348 chk_partial_match (const url_match_t *match, int* offset)
349 {
350         if (*offset >= match->offset && *offset < match->offset + match->len)
351                 *offset = -1;
352 }
353
354 static GSList*
355 get_url_matches (GString *txt)
356 {
357         regmatch_t rm;
358         int rv, i, offset = 0;
359         GSList *match_list = NULL;
360
361         static UrlMatchPattern patterns[] = MAIL_VIEWER_URL_MATCH_PATTERNS;
362         const size_t pattern_num = sizeof(patterns)/sizeof(UrlMatchPattern);
363
364         /* initalize the regexps */
365         for (i = 0; i != pattern_num; ++i) {
366                 patterns[i].preg = g_new0 (regex_t,1);
367                 g_assert(regcomp (patterns[i].preg, patterns[i].regex,
368                                   REG_ICASE|REG_EXTENDED|REG_NEWLINE) == 0);
369         }
370         /* find all the matches */
371         for (i = 0; i != pattern_num; ++i) {
372                 offset     = 0; 
373                 while (1) {
374                         int test_offset;
375                         if ((rv = regexec (patterns[i].preg, txt->str + offset, 1, &rm, 0)) != 0) {
376                                 g_assert (rv == REG_NOMATCH); /* this should not happen */
377                                 break; /* try next regexp */ 
378                         }
379                         if (rm.rm_so == -1)
380                                 break;
381
382                         /* FIXME: optimize this */
383                         /* to avoid partial matches on something that was already found... */
384                         /* check_partial_match will put -1 in the data ptr if that is the case */
385                         test_offset = offset + rm.rm_so;
386                         g_slist_foreach (match_list, (GFunc)chk_partial_match, &test_offset);
387                         
388                         /* make a list of our matches (<offset, len, prefix> tupels)*/
389                         if (test_offset != -1) {
390                                 url_match_t *match = g_new (url_match_t,1);
391                                 match->offset = offset + rm.rm_so;
392                                 match->len    = rm.rm_eo - rm.rm_so;
393                                 match->prefix = patterns[i].prefix;
394                                 match_list = g_slist_prepend (match_list, match);
395                         }
396                         offset += rm.rm_eo;
397                 }
398         }
399
400         for (i = 0; i != pattern_num; ++i) {
401                 regfree (patterns[i].preg);
402                 g_free  (patterns[i].preg);
403         } /* don't free patterns itself -- it's static */
404         
405         /* now sort the list, so the matches are in reverse order of occurence.
406          * that way, we can do the replacements starting from the end, so we don't need
407          * to recalculate the offsets
408          */
409         match_list = g_slist_sort (match_list,
410                                    (GCompareFunc)cmp_offsets_reverse); 
411         return match_list;      
412 }
413
414 static gboolean
415 fill_gtkhtml_with_txt (GtkHTML* gtkhtml, const gchar* txt)
416 {
417         gchar *html;
418         
419         g_return_val_if_fail (gtkhtml, FALSE);
420         g_return_val_if_fail (txt, FALSE);
421
422         html = convert_to_html (txt);
423         gtk_html_load_from_string (gtkhtml, html,  strlen(html));
424         g_free (html);
425
426         return TRUE;
427 }
428
429
430
431 static TnyMsgMimePartIface *
432 find_body_part (TnyMsgIface *msg, const gchar *mime_type)
433 {
434         TnyMsgMimePartIface *part = NULL;
435         GList *parts;
436
437         g_return_val_if_fail (msg, NULL);
438         g_return_val_if_fail (mime_type, NULL);
439
440         parts  = (GList*) tny_msg_iface_get_parts (msg);
441         while (parts && !part) {
442                 part = TNY_MSG_MIME_PART_IFACE(parts->data);
443                 if (!tny_msg_mime_part_iface_content_type_is (part, mime_type))
444                         part = NULL;
445                 parts = parts->next;
446         }
447         
448         return part;
449 }
450
451 static gboolean
452 set_html_message (ModestTnyMsgView *self, TnyMsgMimePartIface *tny_body)
453 {
454         TnyStreamIface *gtkhtml_stream; 
455         ModestTnyMsgViewPrivate *priv;
456         
457         g_return_val_if_fail (self, FALSE);
458         g_return_val_if_fail (tny_body, FALSE);
459         
460         priv = MODEST_TNY_MSG_VIEW_GET_PRIVATE(self);
461
462         gtkhtml_stream =
463                 TNY_STREAM_IFACE(modest_tny_stream_gtkhtml_new
464                                  (gtk_html_begin(GTK_HTML(priv->gtkhtml))));
465         
466         tny_stream_iface_reset (gtkhtml_stream);
467         tny_msg_mime_part_iface_decode_to_stream (tny_body, gtkhtml_stream);
468         tny_stream_iface_reset (gtkhtml_stream);
469
470         g_object_unref (G_OBJECT(gtkhtml_stream));
471         
472         return TRUE;
473 }
474
475
476 /* this is a hack --> we use the tny_text_buffer_stream to
477  * get the message text, then write to gtkhtml 'by hand' */
478 static gboolean
479 set_text_message (ModestTnyMsgView *self, TnyMsgMimePartIface *tny_body)
480 {
481         GtkTextBuffer *buf;
482         GtkTextIter begin, end;
483         TnyStreamIface* txt_stream;
484         gchar *txt;
485         ModestTnyMsgViewPrivate *priv;
486                 
487         g_return_val_if_fail (self, FALSE);
488         g_return_val_if_fail (tny_body, FALSE);
489
490         priv           = MODEST_TNY_MSG_VIEW_GET_PRIVATE(self);
491         
492         buf            = gtk_text_buffer_new (NULL);
493         txt_stream     = TNY_STREAM_IFACE(tny_text_buffer_stream_new (buf));
494                 
495         tny_stream_iface_reset (txt_stream);
496         tny_msg_mime_part_iface_decode_to_stream (tny_body, txt_stream);
497         tny_stream_iface_reset (txt_stream);            
498         
499         gtk_text_buffer_get_bounds (buf, &begin, &end);
500         txt = gtk_text_buffer_get_text (buf, &begin, &end, FALSE);
501         
502         fill_gtkhtml_with_txt (GTK_HTML(priv->gtkhtml), txt);
503         
504         g_object_unref (G_OBJECT(txt_stream));
505         g_object_unref (G_OBJECT(buf));
506
507         g_free (txt);
508         return TRUE;
509 }
510
511 GtkTextBuffer *
512 modest_tny_msg_view_get_selected_text (ModestTnyMsgView *self)
513 {
514         ModestTnyMsgViewPrivate *priv;
515         gchar *sel;
516         GtkWidget *html;
517         int len;
518         GtkClipboard *clip;
519         gchar *text;
520         GtkTextBuffer *buf;
521
522         g_return_if_fail (self);
523         priv = MODEST_TNY_MSG_VIEW_GET_PRIVATE(self);
524         html = priv->gtkhtml;
525         
526         /* I'm sure there is a better way to check for selected text */
527         sel = gtk_html_get_selection_html(GTK_HTML(html), &len);
528         if (sel == NULL)
529                 return NULL;
530         g_free(sel);
531         
532         clip = gtk_widget_get_clipboard(html, GDK_SELECTION_PRIMARY);
533         text = gtk_clipboard_wait_for_text(clip);
534         if (text == NULL)
535                 return NULL;
536         
537         buf = gtk_text_buffer_new(NULL);
538         gtk_text_buffer_set_text(buf, text, -1);
539         g_free(text);
540         return buf;
541 }
542
543 void
544 modest_tny_msg_view_set_message (ModestTnyMsgView *self, TnyMsgIface *msg)
545 {
546         TnyMsgMimePartIface *body;
547         ModestTnyMsgViewPrivate *priv;
548
549         g_return_if_fail (self);
550         
551         priv = MODEST_TNY_MSG_VIEW_GET_PRIVATE(self);
552
553         priv->msg = msg;
554         
555         fill_gtkhtml_with_txt (GTK_HTML(priv->gtkhtml), "");
556
557         if (!msg) 
558                 return;
559         
560         body = find_body_part (msg, "text/html");
561         if (body) {
562                 set_html_message (self, body);
563                 return;
564         }
565         
566         body = find_body_part (msg, "text/plain");
567         if (body) {
568                 set_text_message (self, body);
569                 return;
570         }
571
572         /* hmmmmm */
573         fill_gtkhtml_with_txt (GTK_HTML(priv->gtkhtml),
574                                 _("Unsupported message type"));
575 }