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