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