* fixed 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         }
266         g_slist_free (match_list);
267 }
268
269
270
271 static gchar *
272 convert_to_html (const gchar *data)
273 {
274         int              i;
275         gboolean         first_space = TRUE;
276         GString         *html;      
277         gsize           len;
278
279         if (!data)
280                 return NULL;
281
282         len = strlen (data);
283         html = g_string_sized_new (len + 100);  /* just a  guess... */
284         
285         g_string_append_printf (html,
286                                 "<html>"
287                                 "<head>"
288                                 "<meta http-equiv=\"content-type\""
289                                 " content=\"text/html; charset=utf8\">"
290                                 "</head>"
291                                 "<body><tt>");
292         
293         /* replace with special html chars where needed*/
294         for (i = 0; i != len; ++i)  {
295                 char    kar = data[i]; 
296                 switch (kar) {
297                         
298                 case 0:  break; /* ignore embedded \0s */       
299                 case '<' : g_string_append   (html, "&lt;"); break;
300                 case '>' : g_string_append   (html, "&gt;"); break;
301                 case '&' : g_string_append   (html, "&quot;"); break;
302                 case '\n': g_string_append   (html, "<br>\n"); break;
303                 default:
304                         if (kar == ' ') {
305                                 g_string_append (html, first_space ? " " : "&nbsp;");
306                                 first_space = FALSE;
307                         } else  if (kar == '\t')
308                                 g_string_append (html, "&nbsp; &nbsp;&nbsp;");
309                         else {
310                                 int charnum = 0;
311                                 first_space = TRUE;
312                                 /* optimization trick: accumulate 'normal' chars, then copy */
313                                 do {
314                                         kar = data [++charnum + i];
315                                         
316                                 } while ((i + charnum < len) &&
317                                          (kar > '>' || (kar != '<' && kar != '>'
318                                                         && kar != '&' && kar !=  ' '
319                                                         && kar != '\n' && kar != '\t')));
320                                 g_string_append_len (html, &data[i], charnum);
321                                 i += (charnum  - 1);
322                         }
323                 }
324         }
325
326         g_string_append (html, "</tt></body></html>");
327         hyperlinkify_plain_text (html);
328
329         return g_string_free (html, FALSE);
330 }
331
332
333
334
335 static gint 
336 cmp_offsets_reverse (const url_match_t *match1, const url_match_t *match2)
337 {
338         return match2->offset - match1->offset;
339 }
340
341
342
343 /*
344  * check if the match is inside an existing match... */
345 static void
346 chk_partial_match (const url_match_t *match, int* offset)
347 {
348         if (*offset >= match->offset && *offset < match->offset + match->len)
349                 *offset = -1;
350 }
351
352 static GSList*
353 get_url_matches (GString *txt)
354 {
355         regmatch_t rm;
356         int rv, i, offset = 0;
357         GSList *match_list = NULL;
358
359         static UrlMatchPattern patterns[] = MAIL_VIEWER_URL_MATCH_PATTERNS;
360         const size_t pattern_num = sizeof(patterns)/sizeof(UrlMatchPattern);
361
362         /* initalize the regexps */
363         for (i = 0; i != pattern_num; ++i) {
364                 patterns[i].preg = g_new0 (regex_t,1);
365                 g_assert(regcomp (patterns[i].preg, patterns[i].regex,
366                                   REG_ICASE|REG_EXTENDED|REG_NEWLINE) == 0);
367         }
368         /* find all the matches */
369         for (i = 0; i != pattern_num; ++i) {
370                 offset     = 0; 
371                 while (1) {
372                         int test_offset;
373                         if ((rv = regexec (patterns[i].preg, txt->str + offset, 1, &rm, 0)) != 0) {
374                                 g_assert (rv == REG_NOMATCH); /* this should not happen */
375                                 break; /* try next regexp */ 
376                         }
377                         if (rm.rm_so == -1)
378                                 break;
379
380                         /* FIXME: optimize this */
381                         /* to avoid partial matches on something that was already found... */
382                         /* check_partial_match will put -1 in the data ptr if that is the case */
383                         test_offset = offset + rm.rm_so;
384                         g_slist_foreach (match_list, (GFunc)chk_partial_match, &test_offset);
385                         
386                         /* make a list of our matches (<offset, len, prefix> tupels)*/
387                         if (test_offset != -1) {
388                                 url_match_t *match = g_new (url_match_t,1);
389                                 match->offset = offset + rm.rm_so;
390                                 match->len    = rm.rm_eo - rm.rm_so;
391                                 match->prefix = patterns[i].prefix;
392                                 match_list = g_slist_prepend (match_list, match);
393                         }
394                         offset += rm.rm_eo;
395                 }
396         }
397
398         for (i = 0; i != pattern_num; ++i) {
399                 regfree (patterns[i].preg);
400                 g_free  (patterns[i].preg);
401         } /* don't free patterns itself -- it's static */
402         
403         /* now sort the list, so the matches are in reverse order of occurence.
404          * that way, we can do the replacements starting from the end, so we don't need
405          * to recalculate the offsets
406          */
407         match_list = g_slist_sort (match_list,
408                                    (GCompareFunc)cmp_offsets_reverse); 
409         return match_list;      
410 }
411
412 static gboolean
413 fill_gtkhtml_with_txt (GtkHTML* gtkhtml, const gchar* txt)
414 {
415         gchar *html;
416         
417         g_return_val_if_fail (gtkhtml, FALSE);
418         g_return_val_if_fail (txt, FALSE);
419
420         html = convert_to_html (txt);
421         gtk_html_load_from_string (gtkhtml, html,  strlen(html));
422         g_free (html);
423
424         return TRUE;
425 }
426
427
428
429 static TnyMsgMimePartIface *
430 find_body_part (TnyMsgIface *msg, const gchar *mime_type)
431 {
432         TnyMsgMimePartIface *part = NULL;
433         GList *parts;
434
435         g_return_val_if_fail (msg, NULL);
436         g_return_val_if_fail (mime_type, NULL);
437
438         parts  = (GList*) tny_msg_iface_get_parts (msg);
439         while (parts && !part) {
440                 part = TNY_MSG_MIME_PART_IFACE(parts->data);
441                 if (!tny_msg_mime_part_iface_content_type_is (part, mime_type))
442                         part = NULL;
443                 parts = parts->next;
444         }
445         
446         return part;
447 }
448
449 static gboolean
450 set_html_message (ModestTnyMsgView *self, TnyMsgMimePartIface *tny_body)
451 {
452         TnyStreamIface *gtkhtml_stream; 
453         ModestTnyMsgViewPrivate *priv;
454         
455         g_return_val_if_fail (self, FALSE);
456         g_return_val_if_fail (tny_body, FALSE);
457         
458         priv = MODEST_TNY_MSG_VIEW_GET_PRIVATE(self);
459
460         gtkhtml_stream =
461                 TNY_STREAM_IFACE(modest_tny_stream_gtkhtml_new
462                                  (gtk_html_begin(GTK_HTML(priv->gtkhtml))));
463         
464         tny_stream_iface_reset (gtkhtml_stream);
465         tny_msg_mime_part_iface_decode_to_stream (tny_body, gtkhtml_stream);
466         tny_stream_iface_reset (gtkhtml_stream);
467
468         g_object_unref (G_OBJECT(gtkhtml_stream));
469         
470         return TRUE;
471 }
472
473
474 /* this is a hack --> we use the tny_text_buffer_stream to
475  * get the message text, then write to gtkhtml 'by hand' */
476 static gboolean
477 set_text_message (ModestTnyMsgView *self, TnyMsgMimePartIface *tny_body)
478 {
479         GtkTextBuffer *buf;
480         GtkTextIter begin, end;
481         TnyStreamIface* txt_stream;
482         gchar *txt;
483         ModestTnyMsgViewPrivate *priv;
484                 
485         g_return_val_if_fail (self, FALSE);
486         g_return_val_if_fail (tny_body, FALSE);
487
488         priv           = MODEST_TNY_MSG_VIEW_GET_PRIVATE(self);
489         
490         buf            = gtk_text_buffer_new (NULL);
491         txt_stream     = TNY_STREAM_IFACE(tny_text_buffer_stream_new (buf));
492                 
493         tny_stream_iface_reset (txt_stream);
494         tny_msg_mime_part_iface_decode_to_stream (tny_body, txt_stream);
495         tny_stream_iface_reset (txt_stream);            
496         
497         gtk_text_buffer_get_bounds (buf, &begin, &end);
498         txt = gtk_text_buffer_get_text (buf, &begin, &end, FALSE);
499         
500         fill_gtkhtml_with_txt (GTK_HTML(priv->gtkhtml), txt);
501         
502         g_object_unref (G_OBJECT(txt_stream));
503         g_object_unref (G_OBJECT(buf));
504
505         g_free (txt);
506         return TRUE;
507 }
508
509 GtkTextBuffer *
510 modest_tny_msg_view_get_selected_text (ModestTnyMsgView *self)
511 {
512         ModestTnyMsgViewPrivate *priv;
513         gchar *sel;
514         GtkWidget *html;
515         int len;
516         GtkClipboard *clip;
517         gchar *text;
518         GtkTextBuffer *buf;
519
520         g_return_if_fail (self);
521         priv = MODEST_TNY_MSG_VIEW_GET_PRIVATE(self);
522         html = priv->gtkhtml;
523         
524         /* I'm sure there is a better way to check for selected text */
525         sel = gtk_html_get_selection_html(GTK_HTML(html), &len);
526         if (sel == NULL)
527                 return NULL;
528         g_free(sel);
529         
530         clip = gtk_widget_get_clipboard(html, GDK_SELECTION_PRIMARY);
531         text = gtk_clipboard_wait_for_text(clip);
532         if (text == NULL)
533                 return NULL;
534         
535         buf = gtk_text_buffer_new(NULL);
536         gtk_text_buffer_set_text(buf, text, -1);
537         g_free(text);
538         return buf;
539 }
540
541 void
542 modest_tny_msg_view_set_message (ModestTnyMsgView *self, TnyMsgIface *msg)
543 {
544         TnyMsgMimePartIface *body;
545         ModestTnyMsgViewPrivate *priv;
546
547         g_return_if_fail (self);
548         
549         priv = MODEST_TNY_MSG_VIEW_GET_PRIVATE(self);
550
551         priv->msg = msg;
552         
553         fill_gtkhtml_with_txt (GTK_HTML(priv->gtkhtml), "");
554
555         if (!msg) 
556                 return;
557         
558         body = find_body_part (msg, "text/html");
559         if (body) {
560                 set_html_message (self, body);
561                 return;
562         }
563         
564         body = find_body_part (msg, "text/plain");
565         if (body) {
566                 set_text_message (self, body);
567                 return;
568         }
569
570         /* hmmmmm */
571         fill_gtkhtml_with_txt (GTK_HTML(priv->gtkhtml),
572                                 _("Unsupported message type"));
573 }