added support to view text/enriched
[claws.git] / src / textview.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2001 Hiroyuki Yamamoto
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #include "defs.h"
25
26 #include <glib.h>
27 #include <gdk/gdk.h>
28 #include <gdk/gdkkeysyms.h>
29 #include <gtk/gtkvbox.h>
30 #include <gtk/gtkscrolledwindow.h>
31 #include <gtk/gtktext.h>
32 #include <gtk/gtksignal.h>
33 #include <stdio.h>
34 #include <ctype.h>
35 #include <string.h>
36 #include <stdlib.h>
37
38 #include "intl.h"
39 #include "main.h"
40 #include "summaryview.h"
41 #include "procheader.h"
42 #include "prefs_common.h"
43 #include "codeconv.h"
44 #include "utils.h"
45 #include "gtkutils.h"
46 #include "procmime.h"
47 #include "html.h"
48 #include "enriched.h"
49 #include "compose.h"
50 #include "addressbook.h"
51 #include "displayheader.h"
52
53 #define FONT_LOAD(font, s) \
54 { \
55         gchar *fontstr, *p; \
56  \
57         Xstrdup_a(fontstr, s, ); \
58         if ((p = strchr(fontstr, ',')) != NULL) *p = '\0'; \
59         font = gdk_font_load(fontstr); \
60 }
61
62 typedef struct _RemoteURI       RemoteURI;
63
64 struct _RemoteURI
65 {
66         gchar *uri;
67
68         guint start;
69         guint end;
70 };
71
72 static GdkColor quote_colors[3] = {
73         {(gulong)0, (gushort)0, (gushort)0, (gushort)0},
74         {(gulong)0, (gushort)0, (gushort)0, (gushort)0},
75         {(gulong)0, (gushort)0, (gushort)0, (gushort)0}
76 };
77
78 static GdkColor uri_color = {
79         (gulong)0,
80         (gushort)0,
81         (gushort)0,
82         (gushort)0
83 };
84
85 static GdkColor emphasis_color = {
86         (gulong)0,
87         (gushort)0,
88         (gushort)0,
89         (gushort)0xcfff
90 };
91
92 static GdkColor error_color = {
93         (gulong)0,
94         (gushort)0xefff,
95         (gushort)0,
96         (gushort)0
97 };
98
99 static GdkFont *spacingfont;
100
101 static void textview_show_ertf          (TextView       *textview,
102                                          FILE           *fp,
103                                          CodeConverter  *conv);
104 static void textview_show_html          (TextView       *textview,
105                                          FILE           *fp,
106                                          CodeConverter  *conv);
107 static void textview_write_line         (TextView       *textview,
108                                          const gchar    *str,
109                                          CodeConverter  *conv);
110 static void textview_write_link         (TextView       *textview,
111                                          const gchar    *url,
112                                          const gchar    *str,
113                                          CodeConverter  *conv);
114 static GPtrArray *textview_scan_header  (TextView       *textview,
115                                          FILE           *fp);
116 static void textview_show_header        (TextView       *textview,
117                                          GPtrArray      *headers);
118
119 static void textview_key_pressed        (GtkWidget      *widget,
120                                          GdkEventKey    *event,
121                                          TextView       *textview);
122 static void textview_button_pressed     (GtkWidget      *widget,
123                                          GdkEventButton *event,
124                                          TextView       *textview);
125
126 static void textview_uri_list_remove_all(GSList         *uri_list);
127
128 static void textview_smooth_scroll_do           (TextView       *textview,
129                                                  gfloat          old_value,
130                                                  gfloat          last_value,
131                                                  gint            step);
132 static void textview_smooth_scroll_one_line     (TextView       *textview,
133                                                  gboolean        up);
134 static gboolean textview_smooth_scroll_page     (TextView       *textview,
135                                                  gboolean        up);
136
137
138 TextView *textview_create(void)
139 {
140         TextView *textview;
141         GtkWidget *vbox;
142         GtkWidget *scrolledwin_sb;
143         GtkWidget *scrolledwin_mb;
144         GtkWidget *text_sb;
145         GtkWidget *text_mb;
146
147         debug_print(_("Creating text view...\n"));
148         textview = g_new0(TextView, 1);
149
150         scrolledwin_sb = gtk_scrolled_window_new(NULL, NULL);
151         scrolledwin_mb = gtk_scrolled_window_new(NULL, NULL);
152         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledwin_sb),
153                                        GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
154         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledwin_mb),
155                                        GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
156         gtk_widget_set_usize(scrolledwin_sb, prefs_common.mainview_width, -1);
157         gtk_widget_set_usize(scrolledwin_mb, prefs_common.mainview_width, -1);
158
159         /* create GtkText widgets for single-byte and multi-byte character */
160         text_sb = gtk_text_new(NULL, NULL);
161         text_mb = gtk_text_new(NULL, NULL);
162         GTK_TEXT(text_sb)->default_tab_width = 8;
163         GTK_TEXT(text_mb)->default_tab_width = 8;
164         gtk_widget_show(text_sb);
165         gtk_widget_show(text_mb);
166         gtk_text_set_word_wrap(GTK_TEXT(text_sb), TRUE);
167         gtk_text_set_word_wrap(GTK_TEXT(text_mb), TRUE);
168         gtk_widget_ensure_style(text_sb);
169         gtk_widget_ensure_style(text_mb);
170         if (text_sb->style && text_sb->style->font->type == GDK_FONT_FONTSET) {
171                 GtkStyle *style;
172
173                 style = gtk_style_copy(text_sb->style);
174                 gdk_font_unref(style->font);
175                 FONT_LOAD(style->font, NORMAL_FONT);
176                 gtk_widget_set_style(text_sb, style);
177         }
178         if (text_mb->style && text_mb->style->font->type == GDK_FONT_FONT) {
179                 GtkStyle *style;
180
181                 style = gtk_style_copy(text_mb->style);
182                 gdk_font_unref(style->font);
183                 style->font = gdk_fontset_load(NORMAL_FONT);
184                 gtk_widget_set_style(text_mb, style);
185         }
186         gtk_widget_ref(scrolledwin_sb);
187         gtk_widget_ref(scrolledwin_mb);
188
189         gtk_container_add(GTK_CONTAINER(scrolledwin_sb), text_sb);
190         gtk_container_add(GTK_CONTAINER(scrolledwin_mb), text_mb);
191         gtk_signal_connect(GTK_OBJECT(text_sb), "key_press_event",
192                            GTK_SIGNAL_FUNC(textview_key_pressed),
193                            textview);
194         gtk_signal_connect_after(GTK_OBJECT(text_sb), "button_press_event",
195                                  GTK_SIGNAL_FUNC(textview_button_pressed),
196                                  textview);
197         gtk_signal_connect(GTK_OBJECT(text_mb), "key_press_event",
198                            GTK_SIGNAL_FUNC(textview_key_pressed),
199                            textview);
200         gtk_signal_connect_after(GTK_OBJECT(text_mb), "button_press_event",
201                                  GTK_SIGNAL_FUNC(textview_button_pressed),
202                                  textview);
203
204         gtk_widget_show(scrolledwin_sb);
205         gtk_widget_show(scrolledwin_mb);
206
207         vbox = gtk_vbox_new(FALSE, 0);
208         gtk_box_pack_start(GTK_BOX(vbox), scrolledwin_sb, TRUE, TRUE, 0);
209
210         textview->vbox           = vbox;
211         textview->scrolledwin    = scrolledwin_sb;
212         textview->scrolledwin_sb = scrolledwin_sb;
213         textview->scrolledwin_mb = scrolledwin_mb;
214         textview->text           = text_sb;
215         textview->text_sb        = text_sb;
216         textview->text_mb        = text_mb;
217         textview->text_is_mb     = FALSE;
218         textview->uri_list       = NULL;
219         textview->body_pos       = 0;
220         textview->cur_pos        = 0;
221
222         return textview;
223 }
224
225 void textview_init(TextView *textview)
226 {
227         gtkut_widget_disable_theme_engine(textview->text_sb);
228         gtkut_widget_disable_theme_engine(textview->text_mb);
229         textview_update_message_colors();
230         textview_set_font(textview, NULL);
231 }
232
233 void textview_update_message_colors(void)
234 {
235         GdkColor black = {0, 0, 0, 0};
236
237         if (prefs_common.enable_color) {
238                 /* grab the quote colors, converting from an int to a GdkColor */
239                 gtkut_convert_int_to_gdk_color(prefs_common.quote_level1_col,
240                                                &quote_colors[0]);
241                 gtkut_convert_int_to_gdk_color(prefs_common.quote_level2_col,
242                                                &quote_colors[1]);
243                 gtkut_convert_int_to_gdk_color(prefs_common.quote_level3_col,
244                                                &quote_colors[2]);
245                 gtkut_convert_int_to_gdk_color(prefs_common.uri_col,
246                                                &uri_color);
247         } else {
248                 quote_colors[0] = quote_colors[1] = quote_colors[2] = 
249                         uri_color = emphasis_color = black;
250         }
251 }
252
253 void textview_show_message(TextView *textview, MimeInfo *mimeinfo,
254                            const gchar *file)
255 {
256         FILE *fp;
257
258         if ((fp = fopen(file, "r")) == NULL) {
259                 FILE_OP_ERROR(file, "fopen");
260                 return;
261         }
262
263         textview_show_part(textview, mimeinfo, fp);
264
265         fclose(fp);
266 }
267
268 void textview_show_part(TextView *textview, MimeInfo *mimeinfo, FILE *fp)
269 {
270         GtkText *text;
271         gchar buf[BUFFSIZE];
272         const gchar *boundary = NULL;
273         gint boundary_len = 0;
274         const gchar *charset = NULL;
275         FILE *tmpfp;
276         GPtrArray *headers = NULL;
277         CodeConverter *conv;
278
279         g_return_if_fail(mimeinfo != NULL);
280         g_return_if_fail(fp != NULL);
281
282         if (mimeinfo->mime_type == MIME_MULTIPART) {
283                 if (mimeinfo->sub) {
284                         mimeinfo = mimeinfo->sub;
285                         if (fseek(fp, mimeinfo->fpos, SEEK_SET) < 0) {
286                                 perror("fseek");
287                                 return;
288                         }
289                 } else
290                         return;
291         }
292         if (mimeinfo->parent && mimeinfo->parent->boundary) {
293                 boundary = mimeinfo->parent->boundary;
294                 boundary_len = strlen(boundary);
295         }
296
297         if (!boundary && (mimeinfo->mime_type == MIME_TEXT || mimeinfo->mime_type == MIME_TEXT_HTML || mimeinfo->mime_type == MIME_TEXT_ENRICHED)) {
298         
299                 if (fseek(fp, mimeinfo->fpos, SEEK_SET) < 0)
300                         perror("fseek");
301                 headers = textview_scan_header(textview, fp);
302         } else {
303                 if (mimeinfo->mime_type == MIME_TEXT && mimeinfo->parent) {
304                         glong fpos;
305                         MimeInfo *parent = mimeinfo->parent;
306
307                         while (parent->parent) {
308                                 if (parent->main &&
309                                     parent->main->mime_type ==
310                                         MIME_MESSAGE_RFC822)
311                                         break;
312                                 parent = parent->parent;
313                         }
314
315                         if ((fpos = ftell(fp)) < 0)
316                                 perror("ftell");
317                         else if (fseek(fp, parent->fpos, SEEK_SET) < 0)
318                                 perror("fseek");
319                         else {
320                                 headers = textview_scan_header(textview, fp);
321                                 if (fseek(fp, fpos, SEEK_SET) < 0)
322                                         perror("fseek");
323                         }
324                 }
325                 /* skip MIME part headers */
326                 while (fgets(buf, sizeof(buf), fp) != NULL)
327                         if (buf[0] == '\r' || buf[0] == '\n') break;
328         }
329
330         /* display attached RFC822 single text message */
331         if (mimeinfo->parent && mimeinfo->mime_type == MIME_MESSAGE_RFC822) {
332                 if (headers) procheader_header_array_destroy(headers);
333                 if (!mimeinfo->sub || mimeinfo->sub->children) return;
334                 headers = textview_scan_header(textview, fp);
335                 mimeinfo = mimeinfo->sub;
336         } else if (!mimeinfo->parent &&
337                    mimeinfo->mime_type == MIME_MESSAGE_RFC822) {
338                 if (headers) procheader_header_array_destroy(headers);
339                 if (!mimeinfo->sub) return;
340                 headers = textview_scan_header(textview, fp);
341                 mimeinfo = mimeinfo->sub;
342         }
343
344         if (prefs_common.force_charset)
345                 charset = prefs_common.force_charset;
346         else if (mimeinfo->charset)
347                 charset = mimeinfo->charset;
348         textview_set_font(textview, charset);
349
350         conv = conv_code_converter_new(charset);
351
352         textview_clear(textview);
353         text = GTK_TEXT(textview->text);
354         gtk_text_freeze(text);
355
356         textview->body_pos = 0;
357         textview->cur_pos  = 0;
358
359         if (headers) {
360                 textview_show_header(textview, headers);
361                 procheader_header_array_destroy(headers);
362         }
363
364         tmpfp = procmime_decode_content(NULL, fp, mimeinfo);
365         if (tmpfp) {
366                 if (mimeinfo->mime_type == MIME_TEXT_HTML)
367                         textview_show_html(textview, tmpfp, conv);
368                 else if (mimeinfo->mime_type == MIME_TEXT_ENRICHED)
369                         textview_show_ertf(textview, tmpfp, conv);
370                 else
371                         while (fgets(buf, sizeof(buf), tmpfp) != NULL)
372                                 textview_write_line(textview, buf, conv);
373                 fclose(tmpfp);
374         }
375
376         conv_code_converter_destroy(conv);
377
378         gtk_text_thaw(text);
379 }
380
381 #define TEXT_INSERT(str) \
382         gtk_text_insert(text, textview->msgfont, NULL, NULL, str, -1)
383
384 void textview_show_mime_part(TextView *textview, MimeInfo *partinfo)
385 {
386         GtkText *text;
387
388         if (!partinfo) return;
389
390         textview_set_font(textview, NULL);
391         text = GTK_TEXT(textview->text);
392         textview_clear(textview);
393
394         gtk_text_freeze(text);
395
396         TEXT_INSERT(_("To save this part, pop up the context menu with "));
397         TEXT_INSERT(_("right click and select `Save as...', "));
398         TEXT_INSERT(_("or press `y' key.\n\n"));
399
400         TEXT_INSERT(_("To display this part as a text message, select "));
401         TEXT_INSERT(_("`Display as text', or press `t' key.\n\n"));
402
403         TEXT_INSERT(_("To open this part with external program, select "));
404         TEXT_INSERT(_("`Open' or `Open with...', "));
405         TEXT_INSERT(_("or double-click, or click the center button, "));
406         TEXT_INSERT(_("or press `l' key."));
407
408         gtk_text_thaw(text);
409 }
410
411 #if USE_GPGME
412 void textview_show_signature_part(TextView *textview, MimeInfo *partinfo)
413 {
414         GtkText *text;
415
416         if (!partinfo) return;
417
418         textview_set_font(textview, NULL);
419         text = GTK_TEXT(textview->text);
420         textview_clear(textview);
421
422         gtk_text_freeze(text);
423
424         if (partinfo->sigstatus_full == NULL) {
425                 TEXT_INSERT(_("This signature has not been checked yet.\n"));
426                 TEXT_INSERT(_("To check it, pop up the context menu with\n"));
427                 TEXT_INSERT(_("right click and select `Check signature'.\n"));
428         } else {
429                 TEXT_INSERT(partinfo->sigstatus_full);
430         }
431
432         gtk_text_thaw(text);
433 }
434 #endif /* USE_GPGME */
435
436 #undef TEXT_INSERT
437
438 static void textview_show_html(TextView *textview, FILE *fp,
439                                CodeConverter *conv)
440 {
441         HTMLParser *parser;
442         gchar *str;
443         gchar* url = NULL;
444
445         parser = html_parser_new(fp, conv);
446         g_return_if_fail(parser != NULL);
447
448         while ((str = html_parse(parser)) != NULL) {
449                 if (parser->state == HTML_HREF) {
450                         /* first time : get and copy the URL */
451                         if (url == NULL) {
452                                 /* ALF - the sylpheed html parser returns an empty string,
453                                  * if still inside an <a>, but already parsed past HREF */
454                                 str = strtok(str, " ");
455                                 if (str) { 
456                                         url = strdup(str);
457                                         /* the URL may (or not) be followed by the
458                                          * referenced text */
459                                         str = strtok(NULL, "");
460                                 }       
461                         }
462                         if (str != NULL) {
463                                 textview_write_link(textview, url, str, NULL);
464                         }
465                 } else {
466                         if (url != NULL) {
467                                 free(url);
468                                 url = NULL;
469                         }
470                         textview_write_line(textview, str, NULL);
471                 }
472         }
473         html_parser_destroy(parser);
474 }
475
476 static void textview_show_ertf(TextView *textview, FILE *fp,
477                                CodeConverter *conv)
478 {
479         ERTFParser *parser;
480         gchar *str;
481         gchar* url = NULL;
482
483         parser = ertf_parser_new(fp, conv);
484         g_return_if_fail(parser != NULL);
485
486         while ((str = ertf_parse(parser)) != NULL) {
487                 textview_write_line(textview, str, NULL);
488         }
489         ertf_parser_destroy(parser);
490 }
491
492 /* get_uri_part() - retrieves a URI starting from scanpos.
493                     Returns TRUE if succesful */
494 static gboolean get_uri_part(const gchar *start, const gchar *scanpos,
495                              const gchar **bp, const gchar **ep)
496 {
497         const gchar *ep_;
498
499         g_return_val_if_fail(start != NULL, FALSE);
500         g_return_val_if_fail(scanpos != NULL, FALSE);
501         g_return_val_if_fail(bp != NULL, FALSE);
502         g_return_val_if_fail(ep != NULL, FALSE);
503
504         *bp = scanpos;
505
506         /* find end point of URI */
507         for (ep_ = scanpos; *ep_ != '\0'; ep_++) {
508                 if (!isgraph(*ep_) || !isascii(*ep_) || strchr("()<>\"", *ep_))
509                         break;
510         }
511
512         /* no punctuation at end of string */
513
514         /* FIXME: this stripping of trailing punctuations may bite with other URIs.
515          * should pass some URI type to this function and decide on that whether
516          * to perform punctuation stripping */
517
518 #define IS_REAL_PUNCT(ch)       (ispunct(ch) && ((ch) != '/')) 
519
520         for (; ep_ - 1 > scanpos + 1 && IS_REAL_PUNCT(*(ep_ - 1)); ep_--)
521                 ;
522
523 #undef IS_REAL_PUNCT
524
525         *ep = ep_;
526
527         return TRUE;            
528 }
529
530 static gchar *make_uri_string(const gchar *bp, const gchar *ep)
531 {
532         return g_strndup(bp, ep - bp);
533 }
534
535 /* valid mail address characters */
536 #define IS_RFC822_CHAR(ch) \
537         (isascii(ch) && \
538          (ch) > 32   && \
539          (ch) != 127 && \
540          !isspace(ch) && \
541          !strchr("()<>\"", (ch)))
542
543 /* alphabet and number within 7bit ASCII */
544 #define IS_ASCII_ALNUM(ch)      (isascii(ch) && isalnum(ch))
545 #define IS_QUOTE(ch) ((ch) == '\'' || (ch) == '"')
546
547 /* get_email_part() - retrieves an email address. Returns TRUE if succesful */
548 static gboolean get_email_part(const gchar *start, const gchar *scanpos,
549                                const gchar **bp, const gchar **ep)
550 {
551         /* more complex than the uri part because we need to scan back and forward starting from
552          * the scan position. */
553         gboolean result = FALSE;
554         const gchar *bp_ = NULL;
555         const gchar *ep_ = NULL;
556
557         /* the informative part of the email address (describing the name
558          * of the email address owner) may contain quoted parts. the
559          * closure stack stores the last encountered quotes. */
560         gchar closure_stack[128];
561         gchar *ptr = closure_stack;
562
563         g_return_val_if_fail(start != NULL, FALSE);
564         g_return_val_if_fail(scanpos != NULL, FALSE);
565         g_return_val_if_fail(bp != NULL, FALSE);
566         g_return_val_if_fail(ep != NULL, FALSE);
567
568         /* scan start of address */
569         for (bp_ = scanpos - 1; bp_ >= start && IS_RFC822_CHAR(*bp_); bp_--)
570                 ;
571
572         /* TODO: should start with an alnum? */
573         bp_++;
574         for (; bp_ < scanpos && !IS_ASCII_ALNUM(*bp_); bp_++)
575                 ;
576
577         if (bp_ != scanpos) {
578                 /* scan end of address */
579                 for (ep_ = scanpos + 1; *ep_ && IS_RFC822_CHAR(*ep_); ep_++)
580                         ;
581
582                 /* TODO: really should terminate with an alnum? */
583                 for (; ep_ > scanpos && !IS_ASCII_ALNUM(*ep_); --ep_)
584                         ;
585                 ep_++;
586
587                 if (ep_ > scanpos + 1) {
588                         *ep = ep_;
589                         *bp = bp_;
590                         result = TRUE;
591                 }
592         }
593
594         if (!result) return FALSE;
595
596         /* skip if it's between quotes "'alfons@proteus.demon.nl'" <alfons@proteus.demon.nl> */
597         if (bp_ - 1 > start && IS_QUOTE(*(bp_ - 1)) && IS_QUOTE(*ep_)) 
598                 return FALSE;
599
600         /* see if this is <bracketed>; in this case we also scan for the informative part. */
601         if (bp_ - 1 <= start || *(bp_ - 1) != '<' || *ep_ != '>')
602                 return TRUE;
603
604 #define FULL_STACK()    ((size_t) (ptr - closure_stack) >= sizeof closure_stack)
605 #define IN_STACK()      (ptr > closure_stack)
606 /* has underrun check */
607 #define POP_STACK()     if(IN_STACK()) --ptr
608 /* has overrun check */
609 #define PUSH_STACK(c)   if(!FULL_STACK()) *ptr++ = (c); else return TRUE
610 /* has underrun check */
611 #define PEEK_STACK()    (IN_STACK() ? *(ptr - 1) : 0)
612
613         ep_++;
614
615         /* scan for the informative part. */
616         for (bp_ -= 2; bp_ >= start; bp_--) {
617                 /* if closure on the stack keep scanning */
618                 if (PEEK_STACK() == *bp_) {
619                         POP_STACK();
620                         continue;
621                 }
622                 if (*bp_ == '\'' || *bp_ == '"') {
623                         PUSH_STACK(*bp_);
624                         continue;
625                 }
626
627                 /* if nothing in the closure stack, do the special conditions
628                  * the following if..else expression simply checks whether 
629                  * a token is acceptable. if not acceptable, the clause
630                  * should terminate the loop with a 'break' */
631                 if (!PEEK_STACK()) {
632                         if (*bp_ == '-'
633                         && (((bp_ - 1) >= start) && isalnum(*(bp_ - 1)))
634                         && (((bp_ + 1) < ep_)    && isalnum(*(bp_ + 1)))) {
635                                 /* hyphens are allowed, but only in
636                                    between alnums */
637                         } else if (!ispunct(*bp_)) {
638                                 /* but anything not being a punctiation
639                                    is ok */
640                         } else {
641                                 break; /* anything else is rejected */
642                         }
643                 }
644         }
645
646         bp_++;
647
648 #undef PEEK_STACK
649 #undef PUSH_STACK
650 #undef POP_STACK
651 #undef IN_STACK
652 #undef FULL_STACK
653
654         /* scan forward (should start with an alnum) */
655         for (; *bp_ != '<' && isspace(*bp_) && *bp_ != '"'; bp_++)
656                 ;
657
658         *ep = ep_;
659         *bp = bp_;
660
661         return result;
662 }
663
664 #undef IS_QUOTE
665 #undef IS_RFC822_CHAR
666
667 static gchar *make_email_string(const gchar *bp, const gchar *ep)
668 {
669         /* returns a mailto: URI; mailto: is also used to detect the
670          * uri type later on in the button_pressed signal handler */
671         gchar *tmp;
672         gchar *result;
673
674         tmp = g_strndup(bp, ep - bp);
675         result = g_strconcat("mailto:", tmp, NULL);
676         g_free(tmp);
677
678         return result;
679 }
680
681 #define ADD_TXT_POS(bp_, ep_, pti_) \
682         if ((last->next = alloca(sizeof(struct txtpos))) != NULL) { \
683                 last = last->next; \
684                 last->bp = (bp_); last->ep = (ep_); last->pti = (pti_); \
685                 last->next = NULL; \
686         } else { \
687                 g_warning("alloc error scanning URIs\n"); \
688                 gtk_text_insert(text, textview->msgfont, fg_color, NULL, \
689                                 linebuf, -1); \
690                 return; \
691         }
692
693 /* textview_make_clickable_parts() - colorizes clickable parts */
694 static void textview_make_clickable_parts(TextView *textview,
695                                           GdkFont *font,
696                                           GdkColor *fg_color,
697                                           GdkColor *uri_color,
698                                           const gchar *linebuf)
699 {
700         /* parse table - in order of priority */
701         struct table {
702                 const gchar *needle; /* token */
703
704                 /* token search function */
705                 gchar    *(*search)     (const gchar *haystack,
706                                          const gchar *needle);
707                 /* part parsing function */
708                 gboolean  (*parse)      (const gchar *start,
709                                          const gchar *scanpos,
710                                          const gchar **bp_,
711                                          const gchar **ep_);
712                 /* part to URI function */
713                 gchar    *(*build_uri)  (const gchar *bp,
714                                          const gchar *ep);
715         };
716
717         static struct table parser[] = {
718                 {"http://",  strcasestr, get_uri_part,   make_uri_string},
719                 {"https://", strcasestr, get_uri_part,   make_uri_string},
720                 {"ftp://",   strcasestr, get_uri_part,   make_uri_string},
721                 {"mailto:",  strcasestr, get_uri_part,   make_uri_string},
722                 {"@",        strcasestr, get_email_part, make_email_string}
723         };
724         const gint PARSE_ELEMS = sizeof parser / sizeof parser[0];
725
726         gint  n;
727         const gchar *walk, *bp, *ep;
728
729         struct txtpos {
730                 const gchar     *bp, *ep;       /* text position */
731                 gint             pti;           /* index in parse table */
732                 struct txtpos   *next;          /* next */
733         } head = {NULL, NULL, 0,  NULL}, *last = &head;
734
735         GtkText *text = GTK_TEXT(textview->text);
736
737         /* parse for clickable parts, and build a list of begin and end positions  */
738         for (walk = linebuf, n = 0;;) {
739                 gint last_index = PARSE_ELEMS;
740                 gchar *scanpos = NULL;
741
742                 /* FIXME: this looks phony. scanning for anything in the parse table */
743                 for (n = 0; n < PARSE_ELEMS; n++) {
744                         gchar *tmp;
745
746                         tmp = parser[n].search(walk, parser[n].needle);
747                         if (tmp) {
748                                 if (scanpos == NULL || tmp < scanpos) {
749                                         scanpos = tmp;
750                                         last_index = n;
751                                 }
752                         }                                       
753                 }
754
755                 if (scanpos) {
756                         /* check if URI can be parsed */
757                         if (parser[last_index].parse(linebuf, scanpos, &bp, &ep)
758                             && (size_t) (ep - bp - 1) > strlen(parser[last_index].needle)) {
759                                         ADD_TXT_POS(bp, ep, last_index);
760                                         walk = ep;
761                         } else
762                                 walk = scanpos +
763                                         strlen(parser[last_index].needle);
764                 } else
765                         break;
766         }
767
768         /* colorize this line */
769         if (head.next) {
770                 const gchar *normal_text = linebuf;
771
772                 /* insert URIs */
773                 for (last = head.next; last != NULL;
774                      normal_text = last->ep, last = last->next) {
775                         RemoteURI *uri;
776
777                         uri = g_new(RemoteURI, 1);
778                         if (last->bp - normal_text > 0)
779                                 gtk_text_insert(text, font,
780                                                 fg_color, NULL,
781                                                 normal_text,
782                                                 last->bp - normal_text);
783                         uri->uri = parser[last->pti].build_uri(last->bp, 
784                                                                last->ep);
785                         uri->start = gtk_text_get_point(text);
786                         gtk_text_insert(text, font, uri_color,
787                                         NULL, last->bp, last->ep - last->bp);
788                         uri->end = gtk_text_get_point(text);
789                         textview->uri_list =
790                                 g_slist_append(textview->uri_list, uri);
791                 }
792
793                 if (*normal_text)
794                         gtk_text_insert(text, font, fg_color,
795                                         NULL, normal_text, -1);
796         } else
797                 gtk_text_insert(text, font, fg_color, NULL, linebuf, -1);
798 }
799
800 #undef ADD_TXT_POS
801
802 /* This function writes str as a double-clickable link with the given url. */ 
803 static void textview_write_link(TextView *textview, const gchar *url,
804                                 const gchar *str, CodeConverter *conv)
805 {
806     GdkColor *link_color = NULL;
807     RemoteURI* uri;
808     GtkText *text = GTK_TEXT(textview->text);
809     gchar buf[BUFFSIZE];
810
811     /* this part is taken from textview_write_line. Right now the only place
812      * that calls this function passes NULL for conv, but you never know. */
813     if (!conv)
814             strncpy2(buf, str, sizeof(buf));
815     else if (conv_convert(conv, buf, sizeof(buf), str) < 0) {
816             gtk_text_insert(text, textview->msgfont,
817                             prefs_common.enable_color
818                             ? &error_color : NULL, NULL,
819                             "*** Warning: code conversion failed ***\n",
820                             -1);
821             return;
822     }
823
824     /* this part is based on the code in make_clickable_parts */
825     if (prefs_common.enable_color) {
826         link_color = &uri_color;
827     }
828     uri = g_new(RemoteURI, 1);
829     uri->uri = g_strdup(url);
830     uri->start = gtk_text_get_point(text);
831     gtk_text_insert(text, textview->msgfont, link_color, NULL, buf,
832                     strlen(buf));
833     uri->end = gtk_text_get_point(text);
834     textview->uri_list = g_slist_append(textview->uri_list, uri);
835 }
836
837 static void textview_write_line(TextView *textview, const gchar *str,
838                                 CodeConverter *conv)
839 {
840         GtkText *text = GTK_TEXT(textview->text);
841         gchar buf[BUFFSIZE];
842         GdkColor *fg_color;
843         gint quotelevel = -1;
844
845         if (!conv)
846                 strncpy2(buf, str, sizeof(buf));
847         else if (conv_convert(conv, buf, sizeof(buf), str) < 0) {
848                 gtk_text_insert(text, textview->msgfont,
849                                 prefs_common.enable_color
850                                 ? &error_color : NULL, NULL,
851                                 "*** Warning: code conversion failed ***\n",
852                                 -1);
853                 return;
854         }
855
856         strcrchomp(buf);
857         if (prefs_common.conv_mb_alnum) conv_mb_alnum(buf);
858         fg_color = NULL;
859
860         /* change color of quotation
861            >, foo>, _> ... ok, <foo>, foo bar>, foo-> ... ng
862            Up to 3 levels of quotations are detected, and each
863            level is colored using a different color. */
864         if (prefs_common.enable_color && strchr(buf, '>')) {
865                 quotelevel = get_quote_level(buf);
866
867                 /* set up the correct foreground color */
868                 if (quotelevel > 2) {
869                         /* recycle colors */
870                         if (prefs_common.recycle_quote_colors)
871                                 quotelevel %= 3;
872                         else
873                                 quotelevel = 2;
874                 }
875         }
876
877         if (quotelevel == -1)
878                 fg_color = NULL;
879         else
880                 fg_color = &quote_colors[quotelevel];
881
882         if (prefs_common.head_space && spacingfont && buf[0] != '\n')
883                 gtk_text_insert(text, spacingfont, NULL, NULL, " ", 1);
884
885         if (prefs_common.enable_color)
886                 textview_make_clickable_parts(textview, textview->msgfont,
887                                               fg_color, &uri_color, buf);
888         else
889                 textview_make_clickable_parts(textview, textview->msgfont,
890                                               fg_color, NULL, buf);
891 }
892
893 void textview_clear(TextView *textview)
894 {
895         GtkText *text = GTK_TEXT(textview->text);
896
897         gtk_text_freeze(text);
898         gtk_text_set_point(text, 0);
899         gtk_text_forward_delete(text, gtk_text_get_length(text));
900         gtk_text_thaw(text);
901
902         textview_uri_list_remove_all(textview->uri_list);
903         textview->uri_list = NULL;
904 }
905
906 void textview_destroy(TextView *textview)
907 {
908         textview_uri_list_remove_all(textview->uri_list);
909         textview->uri_list = NULL;
910
911         if (!textview->scrolledwin_sb->parent)
912                 gtk_widget_destroy(textview->scrolledwin_sb);
913         if (!textview->scrolledwin_mb->parent)
914                 gtk_widget_destroy(textview->scrolledwin_mb);
915
916         if (textview->msgfont) {
917                 textview->msgfont->ascent = textview->prev_ascent;
918                 textview->msgfont->descent = textview->prev_descent;
919                 gdk_font_unref(textview->msgfont);
920         }
921         if (textview->boldfont)
922                 gdk_font_unref(textview->boldfont);
923
924         g_free(textview);
925 }
926
927 void textview_set_font(TextView *textview, const gchar *codeset)
928 {
929         gboolean use_fontset = TRUE;
930
931         /* In multi-byte mode, GtkText can't display 8bit characters
932            correctly, so it must be single-byte mode. */
933         if (MB_CUR_MAX > 1) {
934                 if (codeset) {
935                         if (!g_strncasecmp(codeset, "ISO-8859-", 9) ||
936                             !g_strcasecmp(codeset, "BALTIC"))
937                                 use_fontset = FALSE;
938                         else if (conv_get_current_charset() != C_EUC_JP &&
939                                  (!g_strncasecmp(codeset, "KOI8-", 5) ||
940                                   !g_strncasecmp(codeset, "CP", 2)    ||
941                                   !g_strncasecmp(codeset, "WINDOWS-", 8)))
942                                 use_fontset = FALSE;
943                 }
944         } else
945                 use_fontset = FALSE;
946
947         if (textview->text_is_mb && !use_fontset) {
948                 GtkWidget *parent;
949
950                 parent = textview->scrolledwin_mb->parent;
951                 gtk_editable_select_region
952                         (GTK_EDITABLE(textview->text_mb), 0, 0);
953                 gtk_container_remove(GTK_CONTAINER(parent),
954                                      textview->scrolledwin_mb);
955                 gtk_container_add(GTK_CONTAINER(parent),
956                                   textview->scrolledwin_sb);
957
958                 textview->text = textview->text_sb;
959                 textview->text_is_mb = FALSE;
960         } else if (!textview->text_is_mb && use_fontset) {
961                 GtkWidget *parent;
962
963                 parent = textview->scrolledwin_sb->parent;
964                 gtk_editable_select_region
965                         (GTK_EDITABLE(textview->text_sb), 0, 0);
966                 gtk_container_remove(GTK_CONTAINER(parent),
967                                      textview->scrolledwin_sb);
968                 gtk_container_add(GTK_CONTAINER(parent),
969                                   textview->scrolledwin_mb);
970
971                 textview->text = textview->text_mb;
972                 textview->text_is_mb = TRUE;
973         }
974
975         if (prefs_common.textfont) {
976                 if (textview->msgfont) {
977                         textview->msgfont->ascent = textview->prev_ascent;
978                         textview->msgfont->descent = textview->prev_descent;
979                         gdk_font_unref(textview->msgfont);
980                         textview->msgfont = NULL;
981                 }
982                 if (use_fontset)
983                         textview->msgfont =
984                                 gdk_fontset_load(prefs_common.textfont);
985                 else {
986                         if (MB_CUR_MAX > 1) {
987                                 FONT_LOAD(textview->msgfont,
988                                           "-*-courier-medium-r-normal--14-*-*-*-*-*-iso8859-1");
989                         } else {
990                                 FONT_LOAD(textview->msgfont,
991                                           prefs_common.textfont);
992                         }
993                 }
994
995                 if (textview->msgfont) {
996                         gint ascent, descent;
997
998                         textview->prev_ascent = textview->msgfont->ascent;
999                         textview->prev_descent = textview->msgfont->descent;
1000                         descent = prefs_common.line_space / 2;
1001                         ascent  = prefs_common.line_space - descent;
1002                         textview->msgfont->ascent  += ascent;
1003                         textview->msgfont->descent += descent;
1004                 }
1005         }
1006
1007         if (!textview->boldfont)
1008                 FONT_LOAD(textview->boldfont, BOLD_FONT);
1009         if (!spacingfont)
1010                 spacingfont = gdk_font_load("-*-*-medium-r-normal--6-*");
1011 }
1012
1013 enum
1014 {
1015         H_DATE          = 0,
1016         H_FROM          = 1,
1017         H_TO            = 2,
1018         H_NEWSGROUPS    = 3,
1019         H_SUBJECT       = 4,
1020         H_CC            = 5,
1021         H_REPLY_TO      = 6,
1022         H_FOLLOWUP_TO   = 7,
1023         H_X_MAILER      = 8,
1024         H_X_NEWSREADER  = 9,
1025         H_USER_AGENT    = 10,
1026         H_ORGANIZATION  = 11,
1027 };
1028
1029 void textview_set_position(TextView *textview, gint pos)
1030 {
1031         if (pos < 0) {
1032                 textview->cur_pos =
1033                         gtk_text_get_length(GTK_TEXT(textview->text));
1034         } else {
1035                 textview->cur_pos = pos;
1036         }
1037 }
1038
1039 static GPtrArray *textview_scan_header(TextView *textview, FILE *fp)
1040 {
1041         gchar buf[BUFFSIZE];
1042         GPtrArray *headers, *sorted_headers;
1043         GSList *disphdr_list;
1044         Header *header;
1045         gint i;
1046
1047         g_return_val_if_fail(fp != NULL, NULL);
1048
1049         if (!prefs_common.display_header) {
1050                 while (fgets(buf, sizeof(buf), fp) != NULL)
1051                         if (buf[0] == '\r' || buf[0] == '\n') break;
1052                 return NULL;
1053         }
1054
1055         headers = procheader_get_header_array_asis(fp);
1056
1057         sorted_headers = g_ptr_array_new();
1058
1059         for (disphdr_list = prefs_common.disphdr_list; disphdr_list != NULL;
1060              disphdr_list = disphdr_list->next) {
1061                 DisplayHeaderProp *dp =
1062                         (DisplayHeaderProp *)disphdr_list->data;
1063
1064                 for (i = 0; i < headers->len; i++) {
1065                         header = g_ptr_array_index(headers, i);
1066
1067                         if (procheader_headername_equal(header->name,
1068                                                         dp->name)) {
1069                                 if (dp->hidden)
1070                                         procheader_header_free(header);
1071                                 else
1072                                         g_ptr_array_add(sorted_headers, header);
1073
1074                                 g_ptr_array_remove_index(headers, i);
1075                                 i--;
1076                         }
1077                 }
1078         }
1079
1080         if (prefs_common.show_other_header) {
1081                 for (i = 0; i < headers->len; i++) {
1082                         header = g_ptr_array_index(headers, i);
1083                         g_ptr_array_add(sorted_headers, header);
1084                 }
1085         }
1086
1087         g_ptr_array_free(headers, FALSE);
1088
1089         return sorted_headers;
1090 }
1091
1092 static void textview_show_header(TextView *textview, GPtrArray *headers)
1093 {
1094         GtkText *text = GTK_TEXT(textview->text);
1095         Header *header;
1096         gint i;
1097
1098         g_return_if_fail(headers != NULL);
1099
1100         gtk_text_freeze(text);
1101
1102         for (i = 0; i < headers->len; i++) {
1103                 header = g_ptr_array_index(headers, i);
1104                 g_return_if_fail(header->name != NULL);
1105
1106                 gtk_text_insert(text, textview->boldfont, NULL, NULL,
1107                                 header->name, -1);
1108                 if (header->name[strlen(header->name) - 1] != ' ')
1109                         gtk_text_insert(text, textview->boldfont,
1110                                         NULL, NULL, " ", 1);
1111
1112                 if (procheader_headername_equal(header->name, "Subject") ||
1113                     procheader_headername_equal(header->name, "From")    ||
1114                     procheader_headername_equal(header->name, "To")      ||
1115                     procheader_headername_equal(header->name, "Cc"))
1116                         unfold_line(header->body);
1117
1118                 if (prefs_common.enable_color &&
1119                     (procheader_headername_equal(header->name, "X-Mailer") ||
1120                      procheader_headername_equal(header->name,
1121                                                  "X-Newsreader")) &&
1122                     strstr(header->body, "Sylpheed") != NULL)
1123                         gtk_text_insert(text, NULL, &emphasis_color, NULL,
1124                                         header->body, -1);
1125                 else if (prefs_common.enable_color) {
1126                         textview_make_clickable_parts(textview,
1127                                                       NULL, NULL, &uri_color,
1128                                                       header->body);
1129                 } else {
1130                         textview_make_clickable_parts(textview,
1131                                                       NULL, NULL, NULL,
1132                                                       header->body);
1133                 }
1134                 gtk_text_insert(text, textview->msgfont, NULL, NULL, "\n", 1);
1135         }
1136
1137         gtk_text_insert(text, textview->msgfont, NULL, NULL, "\n", 1);
1138         gtk_text_thaw(text);
1139         textview->body_pos = gtk_text_get_length(text);
1140 }
1141
1142 gboolean textview_search_string(TextView *textview, const gchar *str,
1143                                 gboolean case_sens)
1144 {
1145         GtkText *text = GTK_TEXT(textview->text);
1146         gint pos;
1147         wchar_t *wcs;
1148         gint len;
1149         gint text_len;
1150         gboolean found = FALSE;
1151
1152         g_return_val_if_fail(str != NULL, FALSE);
1153
1154         wcs = strdup_mbstowcs(str);
1155         g_return_val_if_fail(wcs != NULL, FALSE);
1156         len = wcslen(wcs);
1157         pos = textview->cur_pos;
1158         if (pos < textview->body_pos)
1159                 pos = textview->body_pos;
1160         text_len = gtk_text_get_length(text);
1161         if (text_len - pos < len) {
1162                 g_free(wcs);
1163                 return FALSE;
1164         }
1165
1166         for (; pos < text_len; pos++) {
1167                 if (text_len - pos < len) break;
1168                 if (gtkut_text_match_string(text, pos, wcs, len, case_sens)
1169                     == TRUE) {
1170                         gtk_editable_set_position(GTK_EDITABLE(text),
1171                                                   pos + len);
1172                         gtk_editable_select_region(GTK_EDITABLE(text),
1173                                                    pos, pos + len);
1174                         textview_set_position(textview, pos + len);
1175                         found = TRUE;
1176                         break;
1177                 }
1178                 if (text_len - pos == len) break;
1179         }
1180
1181         g_free(wcs);
1182         return found;
1183 }
1184
1185 gboolean textview_search_string_backward(TextView *textview, const gchar *str,
1186                                          gboolean case_sens)
1187 {
1188         GtkText *text = GTK_TEXT(textview->text);
1189         gint pos;
1190         wchar_t *wcs;
1191         gint len;
1192         gint text_len;
1193         gboolean found = FALSE;
1194
1195         g_return_val_if_fail(str != NULL, FALSE);
1196
1197         wcs = strdup_mbstowcs(str);
1198         g_return_val_if_fail(wcs != NULL, FALSE);
1199         len = wcslen(wcs);
1200         pos = textview->cur_pos;
1201         text_len = gtk_text_get_length(text);
1202         if (text_len - textview->body_pos < len) {
1203                 g_free(wcs);
1204                 return FALSE;
1205         }
1206         if (pos <= textview->body_pos || text_len - pos < len)
1207                 pos = text_len - len;
1208
1209         for (; pos >= textview->body_pos; pos--) {
1210                 if (gtkut_text_match_string(text, pos, wcs, len, case_sens)
1211                     == TRUE) {
1212                         gtk_editable_set_position(GTK_EDITABLE(text), pos);
1213                         gtk_editable_select_region(GTK_EDITABLE(text),
1214                                                    pos, pos + len);
1215                         textview_set_position(textview, pos - 1);
1216                         found = TRUE;
1217                         break;
1218                 }
1219                 if (pos == textview->body_pos) break;
1220         }
1221
1222         g_free(wcs);
1223         return found;
1224 }
1225
1226 void textview_scroll_one_line(TextView *textview, gboolean up)
1227 {
1228         GtkText *text = GTK_TEXT(textview->text);
1229         gfloat upper;
1230
1231         if (prefs_common.enable_smooth_scroll) {
1232                 textview_smooth_scroll_one_line(textview, up);
1233                 return;
1234         }
1235
1236         if (!up) {
1237                 upper = text->vadj->upper - text->vadj->page_size;
1238                 if (text->vadj->value < upper) {
1239                         text->vadj->value +=
1240                                 text->vadj->step_increment * 4;
1241                         text->vadj->value =
1242                                 MIN(text->vadj->value, upper);
1243                         gtk_signal_emit_by_name(GTK_OBJECT(text->vadj),
1244                                                 "value_changed");
1245                 }
1246         } else {
1247                 if (text->vadj->value > 0.0) {
1248                         text->vadj->value -=
1249                                 text->vadj->step_increment * 4;
1250                         text->vadj->value =
1251                                 MAX(text->vadj->value, 0.0);
1252                         gtk_signal_emit_by_name(GTK_OBJECT(text->vadj),
1253                                                 "value_changed");
1254                 }
1255         }
1256 }
1257
1258 gboolean textview_scroll_page(TextView *textview, gboolean up)
1259 {
1260         GtkText *text = GTK_TEXT(textview->text);
1261         gfloat upper;
1262         gfloat page_incr;
1263
1264         if (prefs_common.enable_smooth_scroll)
1265                 return textview_smooth_scroll_page(textview, up);
1266
1267         if (prefs_common.scroll_halfpage)
1268                 page_incr = text->vadj->page_increment / 2;
1269         else
1270                 page_incr = text->vadj->page_increment;
1271
1272         if (!up) {
1273                 upper = text->vadj->upper - text->vadj->page_size;
1274                 if (text->vadj->value < upper) {
1275                         text->vadj->value += page_incr;
1276                         text->vadj->value = MIN(text->vadj->value, upper);
1277                         gtk_signal_emit_by_name(GTK_OBJECT(text->vadj),
1278                                                 "value_changed");
1279                 } else
1280                         return FALSE;
1281         } else {
1282                 if (text->vadj->value > 0.0) {
1283                         text->vadj->value -= page_incr;
1284                         text->vadj->value = MAX(text->vadj->value, 0.0);
1285                         gtk_signal_emit_by_name(GTK_OBJECT(text->vadj),
1286                                                 "value_changed");
1287                 } else
1288                         return FALSE;
1289         }
1290
1291         return TRUE;
1292 }
1293
1294 static void textview_smooth_scroll_do(TextView *textview,
1295                                       gfloat old_value, gfloat last_value,
1296                                       gint step)
1297 {
1298         GtkText *text = GTK_TEXT(textview->text);
1299         gint change_value;
1300         gboolean up;
1301         gint i;
1302
1303         if (old_value < last_value) {
1304                 change_value = last_value - old_value;
1305                 up = FALSE;
1306         } else {
1307                 change_value = old_value - last_value;
1308                 up = TRUE;
1309         }
1310
1311         gdk_key_repeat_disable();
1312
1313         for (i = step; i <= change_value; i += step) {
1314                 text->vadj->value = old_value + (up ? -i : i);
1315                 gtk_signal_emit_by_name(GTK_OBJECT(text->vadj),
1316                                         "value_changed");
1317         }
1318
1319         text->vadj->value = last_value;
1320         gtk_signal_emit_by_name(GTK_OBJECT(text->vadj), "value_changed");
1321
1322         gdk_key_repeat_restore();
1323 }
1324
1325 static void textview_smooth_scroll_one_line(TextView *textview, gboolean up)
1326 {
1327         GtkText *text = GTK_TEXT(textview->text);
1328         gfloat upper;
1329         gfloat old_value;
1330         gfloat last_value;
1331
1332         if (!up) {
1333                 upper = text->vadj->upper - text->vadj->page_size;
1334                 if (text->vadj->value < upper) {
1335                         old_value = text->vadj->value;
1336                         last_value = text->vadj->value +
1337                                 text->vadj->step_increment * 4;
1338                         last_value = MIN(last_value, upper);
1339
1340                         textview_smooth_scroll_do(textview, old_value,
1341                                                   last_value,
1342                                                   prefs_common.scroll_step);
1343                 }
1344         } else {
1345                 if (text->vadj->value > 0.0) {
1346                         old_value = text->vadj->value;
1347                         last_value = text->vadj->value -
1348                                 text->vadj->step_increment * 4;
1349                         last_value = MAX(last_value, 0.0);
1350
1351                         textview_smooth_scroll_do(textview, old_value,
1352                                                   last_value,
1353                                                   prefs_common.scroll_step);
1354                 }
1355         }
1356 }
1357
1358 static gboolean textview_smooth_scroll_page(TextView *textview, gboolean up)
1359 {
1360         GtkText *text = GTK_TEXT(textview->text);
1361         gfloat upper;
1362         gfloat page_incr;
1363         gfloat old_value;
1364         gfloat last_value;
1365
1366         if (prefs_common.scroll_halfpage)
1367                 page_incr = text->vadj->page_increment / 2;
1368         else
1369                 page_incr = text->vadj->page_increment;
1370
1371         if (!up) {
1372                 upper = text->vadj->upper - text->vadj->page_size;
1373                 if (text->vadj->value < upper) {
1374                         old_value = text->vadj->value;
1375                         last_value = text->vadj->value + page_incr;
1376                         last_value = MIN(last_value, upper);
1377
1378                         textview_smooth_scroll_do(textview, old_value,
1379                                                   last_value,
1380                                                   prefs_common.scroll_step);
1381                 } else
1382                         return FALSE;
1383         } else {
1384                 if (text->vadj->value > 0.0) {
1385                         old_value = text->vadj->value;
1386                         last_value = text->vadj->value - page_incr;
1387                         last_value = MAX(last_value, 0.0);
1388
1389                         textview_smooth_scroll_do(textview, old_value,
1390                                                   last_value,
1391                                                   prefs_common.scroll_step);
1392                 } else
1393                         return FALSE;
1394         }
1395
1396         return TRUE;
1397 }
1398
1399 static void textview_key_pressed(GtkWidget *widget, GdkEventKey *event,
1400                                  TextView *textview)
1401 {
1402         SummaryView *summaryview = NULL;
1403
1404         if (!event) return;
1405         if (textview->messageview->mainwin)
1406                 summaryview = textview->messageview->mainwin->summaryview;
1407
1408         switch (event->keyval) {
1409         case GDK_Tab:
1410         case GDK_Home:
1411         case GDK_Left:
1412         case GDK_Up:
1413         case GDK_Right:
1414         case GDK_Down:
1415         case GDK_Page_Up:
1416         case GDK_Page_Down:
1417         case GDK_End:
1418         case GDK_Control_L:
1419         case GDK_Control_R:
1420                 break;
1421         case GDK_space:
1422                 if (summaryview)
1423                         summary_pass_key_press_event(summaryview, event);
1424                 else
1425                         textview_scroll_page(textview, FALSE);
1426                 break;
1427         case GDK_BackSpace:
1428                 textview_scroll_page(textview, TRUE);
1429                 break;
1430         case GDK_Return:
1431                 textview_scroll_one_line(textview,
1432                                          (event->state & GDK_MOD1_MASK) != 0);
1433                 break;
1434         default:
1435                 if (summaryview)
1436                         summary_pass_key_press_event(summaryview, event);
1437                 break;
1438         }
1439 }
1440
1441 static void textview_button_pressed(GtkWidget *widget, GdkEventButton *event,
1442                                     TextView *textview)
1443 {
1444         textview->cur_pos = 
1445                 gtk_editable_get_position(GTK_EDITABLE(textview->text));
1446
1447         if (event &&
1448             ((event->button == 1 && event->type == GDK_2BUTTON_PRESS)
1449              || event->button == 2 || event->button == 3)) {
1450                 GSList *cur;
1451
1452                 /* double click seems to set the cursor after the current
1453                  * word. The cursor position needs fixing, otherwise the
1454                  * last word of a clickable zone will not work */
1455                 if (event->button == 1 && event->type == GDK_2BUTTON_PRESS) {
1456                         textview->cur_pos--;
1457                 }
1458
1459                 for (cur = textview->uri_list; cur != NULL; cur = cur->next) {
1460                         RemoteURI *uri = (RemoteURI *)cur->data;
1461
1462                         if (textview->cur_pos >= uri->start &&
1463                             textview->cur_pos <  uri->end) {
1464                                 if (!g_strncasecmp(uri->uri, "mailto:", 7)) {
1465                                         if (event->button == 3) {
1466                                                 gchar *fromname, *fromaddress;
1467                                                 /* extract url */
1468                                                 fromaddress = g_strdup(uri->uri + 7);
1469                                                 /* Hiroyuki: please put this function in utils.c! */
1470                                                 fromname = procheader_get_fromname(fromaddress);
1471                                                 extract_address(fromaddress);
1472                                                 g_message("adding from textview %s <%s>", fromname, fromaddress);
1473                                                 // Add to address book - Match
1474                                                 addressbook_add_contact( fromname, fromaddress, NULL );
1475                                                 g_free(fromaddress);
1476                                                 g_free(fromname);
1477                                         } else {
1478                                                 compose_new_with_recipient
1479                                                         (NULL, uri->uri + 7);
1480                                         }
1481                                 } else {
1482                                         open_uri(uri->uri,
1483                                                  prefs_common.uri_cmd);
1484                                 }
1485                         }
1486                 }
1487         }
1488 }
1489
1490 static void textview_uri_list_remove_all(GSList *uri_list)
1491 {
1492         GSList *cur;
1493
1494         for (cur = uri_list; cur != NULL; cur = cur->next) {
1495                 if (cur->data) {
1496                         g_free(((RemoteURI *)cur->data)->uri);
1497                         g_free(cur->data);
1498                 }
1499         }
1500
1501         g_slist_free(uri_list);
1502 }