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