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