3c6e9dd50ee51659101d482ab2ac44123fbb1da8
[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                 {"www.",     strcasestr, get_uri_part,   make_uri_string},
762                 {"ftp://",   strcasestr, get_uri_part,   make_uri_string},
763                 {"mailto:",  strcasestr, get_uri_part,   make_uri_string},
764                 {"@",        strcasestr, get_email_part, make_email_string}
765         };
766         const gint PARSE_ELEMS = sizeof parser / sizeof parser[0];
767
768         gint  n;
769         const gchar *walk, *bp, *ep;
770
771         struct txtpos {
772                 const gchar     *bp, *ep;       /* text position */
773                 gint             pti;           /* index in parse table */
774                 struct txtpos   *next;          /* next */
775         } head = {NULL, NULL, 0,  NULL}, *last = &head;
776
777         GtkSText *text = GTK_STEXT(textview->text);
778
779         /* parse for clickable parts, and build a list of begin and end positions  */
780         for (walk = linebuf, n = 0;;) {
781                 gint last_index = PARSE_ELEMS;
782                 gchar *scanpos = NULL;
783
784                 /* FIXME: this looks phony. scanning for anything in the parse table */
785                 for (n = 0; n < PARSE_ELEMS; n++) {
786                         gchar *tmp;
787
788                         tmp = parser[n].search(walk, parser[n].needle);
789                         if (tmp) {
790                                 if (scanpos == NULL || tmp < scanpos) {
791                                         scanpos = tmp;
792                                         last_index = n;
793                                 }
794                         }                                       
795                 }
796
797                 if (scanpos) {
798                         /* check if URI can be parsed */
799                         if (parser[last_index].parse(linebuf, scanpos, &bp, &ep)
800                             && (size_t) (ep - bp - 1) > strlen(parser[last_index].needle)) {
801                                         ADD_TXT_POS(bp, ep, last_index);
802                                         walk = ep;
803                         } else
804                                 walk = scanpos +
805                                         strlen(parser[last_index].needle);
806                 } else
807                         break;
808         }
809
810         /* colorize this line */
811         if (head.next) {
812                 const gchar *normal_text = linebuf;
813
814                 /* insert URIs */
815                 for (last = head.next; last != NULL;
816                      normal_text = last->ep, last = last->next) {
817                         RemoteURI *uri;
818
819                         uri = g_new(RemoteURI, 1);
820                         if (last->bp - normal_text > 0)
821                                 gtk_stext_insert(text, font,
822                                                 fg_color, NULL,
823                                                 normal_text,
824                                                 last->bp - normal_text);
825                         uri->uri = parser[last->pti].build_uri(last->bp,
826                                                                last->ep);
827                         uri->start = gtk_stext_get_point(text);
828                         gtk_stext_insert(text, font, uri_color,
829                                         NULL, last->bp, last->ep - last->bp);
830                         uri->end = gtk_stext_get_point(text);
831                         textview->uri_list =
832                                 g_slist_append(textview->uri_list, uri);
833                 }
834
835                 if (*normal_text)
836                         gtk_stext_insert(text, font, fg_color,
837                                         NULL, normal_text, -1);
838         } else
839                 gtk_stext_insert(text, font, fg_color, NULL, linebuf, -1);
840 }
841
842 #undef ADD_TXT_POS
843
844 /* This function writes str as a double-clickable link with the given url. */ 
845 static void textview_write_link(TextView *textview, const gchar *url,
846                                 const gchar *str, CodeConverter *conv)
847 {
848     GdkColor *link_color = NULL;
849     RemoteURI* uri;
850     GtkSText *text = GTK_STEXT(textview->text);
851     gchar buf[BUFFSIZE];
852
853     /* this part is taken from textview_write_line. Right now the only place
854      * that calls this function passes NULL for conv, but you never know. */
855     if (!conv)
856             strncpy2(buf, str, sizeof(buf));
857     else if (conv_convert(conv, buf, sizeof(buf), str) < 0) {
858             gtk_stext_insert(text, textview->msgfont,
859                             prefs_common.enable_color
860                             ? &error_color : NULL, NULL,
861                             "*** Warning: code conversion failed ***\n",
862                             -1);
863             return;
864     }
865
866     /* this part is based on the code in make_clickable_parts */
867     if (prefs_common.enable_color) {
868         link_color = &uri_color;
869     }
870     uri = g_new(RemoteURI, 1);
871     uri->uri = g_strdup(url);
872     uri->start = gtk_stext_get_point(text);
873     gtk_stext_insert(text, textview->msgfont, link_color, NULL, buf,
874                     strlen(buf));
875     uri->end = gtk_stext_get_point(text);
876     textview->uri_list = g_slist_append(textview->uri_list, uri);
877 }
878
879 static void textview_write_line(TextView *textview, const gchar *str,
880                                 CodeConverter *conv)
881 {
882         GtkSText *text = GTK_STEXT(textview->text);
883         gchar buf[BUFFSIZE];
884         GdkColor *fg_color;
885         gint quotelevel = -1;
886
887 #if 0
888         if (!conv)
889                 strncpy2(buf, str, sizeof(buf));
890         else if (conv_convert(conv, buf, sizeof(buf), str) < 0) {
891                 gtk_stext_insert(text, textview->msgfont,
892                                 prefs_common.enable_color
893                                 ? &error_color : NULL, NULL,
894                                 "*** Warning: code conversion failed ***\n",
895                                 -1);
896                 return;
897         }
898 #endif
899         if (!conv || conv_convert(conv, buf, sizeof(buf), str) < 0)
900                 strncpy2(buf, str, sizeof(buf));
901
902         strcrchomp(buf);
903         if (prefs_common.conv_mb_alnum) conv_mb_alnum(buf);
904         fg_color = NULL;
905
906         /* change color of quotation
907            >, foo>, _> ... ok, <foo>, foo bar>, foo-> ... ng
908            Up to 3 levels of quotations are detected, and each
909            level is colored using a different color. */
910         if (prefs_common.enable_color && strchr(buf, '>')) {
911                 quotelevel = get_quote_level(buf);
912
913                 /* set up the correct foreground color */
914                 if (quotelevel > 2) {
915                         /* recycle colors */
916                         if (prefs_common.recycle_quote_colors)
917                                 quotelevel %= 3;
918                         else
919                                 quotelevel = 2;
920                 }
921         }
922
923         if (quotelevel == -1)
924                 fg_color = NULL;
925         else
926                 fg_color = &quote_colors[quotelevel];
927
928         if (prefs_common.head_space && spacingfont && buf[0] != '\n')
929                 gtk_stext_insert(text, spacingfont, NULL, NULL, " ", 1);
930
931         if (prefs_common.enable_color)
932                 textview_make_clickable_parts(textview, textview->msgfont,
933                                               fg_color, &uri_color, buf);
934         else
935                 textview_make_clickable_parts(textview, textview->msgfont,
936                                               fg_color, NULL, buf);
937 }
938
939 void textview_clear(TextView *textview)
940 {
941         GtkSText *text = GTK_STEXT(textview->text);
942
943         gtk_stext_freeze(text);
944         gtk_stext_set_point(text, 0);
945         gtk_stext_forward_delete(text, gtk_stext_get_length(text));
946         gtk_stext_thaw(text);
947
948         textview_uri_list_remove_all(textview->uri_list);
949         textview->uri_list = NULL;
950 }
951
952 void textview_destroy(TextView *textview)
953 {
954         textview_uri_list_remove_all(textview->uri_list);
955         textview->uri_list = NULL;
956
957         if (!textview->scrolledwin_sb->parent)
958                 gtk_widget_destroy(textview->scrolledwin_sb);
959         if (!textview->scrolledwin_mb->parent)
960                 gtk_widget_destroy(textview->scrolledwin_mb);
961
962         if (textview->msgfont)
963                 gdk_font_unref(textview->msgfont);
964         if (textview->boldfont)
965                 gdk_font_unref(textview->boldfont);
966
967         g_free(textview);
968 }
969
970 void textview_set_all_headers(TextView *textview, gboolean all_headers)
971 {
972         textview->show_all_headers = all_headers;
973 }
974
975 void textview_set_font(TextView *textview, const gchar *codeset)
976 {
977         gboolean use_fontset = TRUE;
978
979         /* In multi-byte mode, GtkSText can't display 8bit characters
980            correctly, so it must be single-byte mode. */
981         if (MB_CUR_MAX > 1) {
982                 if (codeset) {
983                         if (!g_strncasecmp(codeset, "ISO-8859-", 9) ||
984                             !g_strcasecmp(codeset, "BALTIC"))
985                                 use_fontset = FALSE;
986                         else if (conv_get_current_charset() != C_EUC_JP &&
987                                  (!g_strncasecmp(codeset, "KOI8-", 5) ||
988                                   !g_strncasecmp(codeset, "CP", 2)    ||
989                                   !g_strncasecmp(codeset, "WINDOWS-", 8)))
990                                 use_fontset = FALSE;
991                 }
992         } else
993                 use_fontset = FALSE;
994
995         if (textview->text_is_mb && !use_fontset) {
996                 GtkWidget *parent;
997
998                 parent = textview->scrolledwin_mb->parent;
999                 gtkut_container_remove(GTK_CONTAINER(parent),
1000                                        textview->scrolledwin_mb);
1001                 gtk_container_add(GTK_CONTAINER(parent),
1002                                   textview->scrolledwin_sb);
1003
1004                 textview->text = textview->text_sb;
1005                 textview->text_is_mb = FALSE;
1006         } else if (!textview->text_is_mb && use_fontset) {
1007                 GtkWidget *parent;
1008
1009                 parent = textview->scrolledwin_sb->parent;
1010                 gtkut_container_remove(GTK_CONTAINER(parent),
1011                                        textview->scrolledwin_sb);
1012                 gtk_container_add(GTK_CONTAINER(parent),
1013                                   textview->scrolledwin_mb);
1014
1015                 textview->text = textview->text_mb;
1016                 textview->text_is_mb = TRUE;
1017         }
1018
1019         if (prefs_common.textfont) {
1020                 GdkFont *font;
1021
1022                 if (use_fontset) {
1023                         if (text_mb_font) {
1024                                 text_mb_font->ascent = text_mb_font_orig_ascent;
1025                                 text_mb_font->descent = text_mb_font_orig_descent;
1026                         }
1027                         font = gdk_fontset_load(prefs_common.textfont);
1028                         if (font && text_mb_font != font) {
1029                                 if (text_mb_font)
1030                                         gdk_font_unref(text_mb_font);
1031                                 text_mb_font = font;
1032                                 text_mb_font_orig_ascent = font->ascent;
1033                                 text_mb_font_orig_descent = font->descent;
1034                         }
1035                 } else {
1036                         if (text_sb_font) {
1037                                 text_sb_font->ascent = text_sb_font_orig_ascent;
1038                                 text_sb_font->descent = text_sb_font_orig_descent;
1039                         }
1040                         if (MB_CUR_MAX > 1) {
1041                                 FONT_LOAD(font, "-*-courier-medium-r-normal--14-*-*-*-*-*-iso8859-1");
1042                         } else {
1043                                 FONT_LOAD(font, prefs_common.textfont);
1044                         }
1045                         if (font && text_sb_font != font) {
1046                                 if (text_sb_font)
1047                                         gdk_font_unref(text_sb_font);
1048                                 text_sb_font = font;
1049                                 text_sb_font_orig_ascent = font->ascent;
1050                                 text_sb_font_orig_descent = font->descent;
1051                         }
1052                 }
1053
1054                 if (font) {
1055                         gint ascent, descent;
1056
1057                         descent = prefs_common.line_space / 2;
1058                         ascent  = prefs_common.line_space - descent;
1059                         font->ascent  += ascent;
1060                         font->descent += descent;
1061
1062                         if (textview->msgfont)
1063                                 gdk_font_unref(textview->msgfont);
1064                         textview->msgfont = font;
1065                         gdk_font_ref(font);
1066                 }
1067         }
1068
1069         if (!textview->boldfont && prefs_common.boldfont)
1070                 FONT_LOAD(textview->boldfont, prefs_common.boldfont);
1071         if (!spacingfont)
1072                 spacingfont = gdk_font_load("-*-*-medium-r-normal--6-*");
1073 }
1074
1075 enum
1076 {
1077         H_DATE          = 0,
1078         H_FROM          = 1,
1079         H_TO            = 2,
1080         H_NEWSGROUPS    = 3,
1081         H_SUBJECT       = 4,
1082         H_CC            = 5,
1083         H_REPLY_TO      = 6,
1084         H_FOLLOWUP_TO   = 7,
1085         H_X_MAILER      = 8,
1086         H_X_NEWSREADER  = 9,
1087         H_USER_AGENT    = 10,
1088         H_ORGANIZATION  = 11,
1089 };
1090
1091 void textview_set_position(TextView *textview, gint pos)
1092 {
1093         if (pos < 0) {
1094                 textview->cur_pos =
1095                         gtk_stext_get_length(GTK_STEXT(textview->text));
1096         } else {
1097                 textview->cur_pos = pos;
1098         }
1099 }
1100
1101 static GPtrArray *textview_scan_header(TextView *textview, FILE *fp)
1102 {
1103         gchar buf[BUFFSIZE];
1104         GPtrArray *headers, *sorted_headers;
1105         GSList *disphdr_list;
1106         Header *header;
1107         gint i;
1108
1109         g_return_val_if_fail(fp != NULL, NULL);
1110
1111         if (textview->show_all_headers)
1112                 return procheader_get_header_array_asis(fp);
1113
1114         if (!prefs_common.display_header) {
1115                 while (fgets(buf, sizeof(buf), fp) != NULL)
1116                         if (buf[0] == '\r' || buf[0] == '\n') break;
1117                 return NULL;
1118         }
1119
1120         headers = procheader_get_header_array_asis(fp);
1121
1122         sorted_headers = g_ptr_array_new();
1123
1124         for (disphdr_list = prefs_common.disphdr_list; disphdr_list != NULL;
1125              disphdr_list = disphdr_list->next) {
1126                 DisplayHeaderProp *dp =
1127                         (DisplayHeaderProp *)disphdr_list->data;
1128
1129                 for (i = 0; i < headers->len; i++) {
1130                         header = g_ptr_array_index(headers, i);
1131
1132                         if (procheader_headername_equal(header->name,
1133                                                         dp->name)) {
1134                                 if (dp->hidden)
1135                                         procheader_header_free(header);
1136                                 else
1137                                         g_ptr_array_add(sorted_headers, header);
1138
1139                                 g_ptr_array_remove_index(headers, i);
1140                                 i--;
1141                         }
1142                 }
1143         }
1144
1145         if (prefs_common.show_other_header) {
1146                 for (i = 0; i < headers->len; i++) {
1147                         header = g_ptr_array_index(headers, i);
1148                         g_ptr_array_add(sorted_headers, header);
1149                 }
1150         }
1151
1152         g_ptr_array_free(headers, FALSE);
1153
1154         return sorted_headers;
1155 }
1156
1157 static void textview_show_header(TextView *textview, GPtrArray *headers)
1158 {
1159         GtkSText *text = GTK_STEXT(textview->text);
1160         Header *header;
1161         gint i;
1162
1163         g_return_if_fail(headers != NULL);
1164
1165         gtk_stext_freeze(text);
1166
1167         for (i = 0; i < headers->len; i++) {
1168                 header = g_ptr_array_index(headers, i);
1169                 g_return_if_fail(header->name != NULL);
1170
1171                 gtk_stext_insert(text, textview->boldfont, NULL, NULL,
1172                                 header->name, -1);
1173                 if (header->name[strlen(header->name) - 1] != ' ')
1174                         gtk_stext_insert(text, textview->boldfont,
1175                                         NULL, NULL, " ", 1);
1176
1177                 if (procheader_headername_equal(header->name, "Subject") ||
1178                     procheader_headername_equal(header->name, "From")    ||
1179                     procheader_headername_equal(header->name, "To")      ||
1180                     procheader_headername_equal(header->name, "Cc"))
1181                         unfold_line(header->body);
1182
1183                 if (prefs_common.enable_color &&
1184                     (procheader_headername_equal(header->name, "X-Mailer") ||
1185                      procheader_headername_equal(header->name,
1186                                                  "X-Newsreader")) &&
1187                     strstr(header->body, "Sylpheed") != NULL)
1188                         gtk_stext_insert(text, NULL, &emphasis_color, NULL,
1189                                         header->body, -1);
1190                 else if (prefs_common.enable_color) {
1191                         textview_make_clickable_parts(textview,
1192                                                       NULL, NULL, &uri_color,
1193                                                       header->body);
1194                 } else {
1195                         textview_make_clickable_parts(textview,
1196                                                       NULL, NULL, NULL,
1197                                                       header->body);
1198                 }
1199                 gtk_stext_insert(text, textview->msgfont, NULL, NULL, "\n", 1);
1200         }
1201
1202         gtk_stext_insert(text, textview->msgfont, NULL, NULL, "\n", 1);
1203         gtk_stext_thaw(text);
1204         textview->body_pos = gtk_stext_get_length(text);
1205 }
1206
1207 gboolean textview_search_string(TextView *textview, const gchar *str,
1208                                 gboolean case_sens)
1209 {
1210         GtkSText *text = GTK_STEXT(textview->text);
1211         gint pos;
1212         wchar_t *wcs;
1213         gint len;
1214         gint text_len;
1215         gboolean found = FALSE;
1216
1217         g_return_val_if_fail(str != NULL, FALSE);
1218
1219         wcs = strdup_mbstowcs(str);
1220         g_return_val_if_fail(wcs != NULL, FALSE);
1221         len = wcslen(wcs);
1222         pos = textview->cur_pos;
1223         if (pos < textview->body_pos)
1224                 pos = textview->body_pos;
1225         text_len = gtk_stext_get_length(text);
1226         if (text_len - pos < len) {
1227                 g_free(wcs);
1228                 return FALSE;
1229         }
1230
1231         for (; pos < text_len; pos++) {
1232                 if (text_len - pos < len) break;
1233                 if (gtkut_stext_match_string(text, pos, wcs, len, case_sens)
1234                     == TRUE) {
1235                         gtk_editable_set_position(GTK_EDITABLE(text),
1236                                                   pos + len);
1237                         gtk_editable_select_region(GTK_EDITABLE(text),
1238                                                    pos, pos + len);
1239                         textview_set_position(textview, pos + len);
1240                         found = TRUE;
1241                         break;
1242                 }
1243                 if (text_len - pos == len) break;
1244         }
1245
1246         g_free(wcs);
1247         return found;
1248 }
1249
1250 gboolean textview_search_string_backward(TextView *textview, const gchar *str,
1251                                          gboolean case_sens)
1252 {
1253         GtkSText *text = GTK_STEXT(textview->text);
1254         gint pos;
1255         wchar_t *wcs;
1256         gint len;
1257         gint text_len;
1258         gboolean found = FALSE;
1259
1260         g_return_val_if_fail(str != NULL, FALSE);
1261
1262         wcs = strdup_mbstowcs(str);
1263         g_return_val_if_fail(wcs != NULL, FALSE);
1264         len = wcslen(wcs);
1265         pos = textview->cur_pos;
1266         text_len = gtk_stext_get_length(text);
1267         if (text_len - textview->body_pos < len) {
1268                 g_free(wcs);
1269                 return FALSE;
1270         }
1271         if (pos <= textview->body_pos || text_len - pos < len)
1272                 pos = text_len - len;
1273
1274         for (; pos >= textview->body_pos; pos--) {
1275                 if (gtkut_stext_match_string(text, pos, wcs, len, case_sens)
1276                     == TRUE) {
1277                         gtk_editable_set_position(GTK_EDITABLE(text), pos);
1278                         gtk_editable_select_region(GTK_EDITABLE(text),
1279                                                    pos, pos + len);
1280                         textview_set_position(textview, pos - 1);
1281                         found = TRUE;
1282                         break;
1283                 }
1284                 if (pos == textview->body_pos) break;
1285         }
1286
1287         g_free(wcs);
1288         return found;
1289 }
1290
1291 void textview_scroll_one_line(TextView *textview, gboolean up)
1292 {
1293         GtkSText *text = GTK_STEXT(textview->text);
1294         gfloat upper;
1295
1296         if (prefs_common.enable_smooth_scroll) {
1297                 textview_smooth_scroll_one_line(textview, up);
1298                 return;
1299         }
1300
1301         if (!up) {
1302                 upper = text->vadj->upper - text->vadj->page_size;
1303                 if (text->vadj->value < upper) {
1304                         text->vadj->value +=
1305                                 text->vadj->step_increment * 4;
1306                         text->vadj->value =
1307                                 MIN(text->vadj->value, upper);
1308                         gtk_signal_emit_by_name(GTK_OBJECT(text->vadj),
1309                                                 "value_changed");
1310                 }
1311         } else {
1312                 if (text->vadj->value > 0.0) {
1313                         text->vadj->value -=
1314                                 text->vadj->step_increment * 4;
1315                         text->vadj->value =
1316                                 MAX(text->vadj->value, 0.0);
1317                         gtk_signal_emit_by_name(GTK_OBJECT(text->vadj),
1318                                                 "value_changed");
1319                 }
1320         }
1321 }
1322
1323 gboolean textview_scroll_page(TextView *textview, gboolean up)
1324 {
1325         GtkSText *text = GTK_STEXT(textview->text);
1326         gfloat upper;
1327         gfloat page_incr;
1328
1329         if (prefs_common.enable_smooth_scroll)
1330                 return textview_smooth_scroll_page(textview, up);
1331
1332         if (prefs_common.scroll_halfpage)
1333                 page_incr = text->vadj->page_increment / 2;
1334         else
1335                 page_incr = text->vadj->page_increment;
1336
1337         if (!up) {
1338                 upper = text->vadj->upper - text->vadj->page_size;
1339                 if (text->vadj->value < upper) {
1340                         text->vadj->value += page_incr;
1341                         text->vadj->value = MIN(text->vadj->value, upper);
1342                         gtk_signal_emit_by_name(GTK_OBJECT(text->vadj),
1343                                                 "value_changed");
1344                 } else
1345                         return FALSE;
1346         } else {
1347                 if (text->vadj->value > 0.0) {
1348                         text->vadj->value -= page_incr;
1349                         text->vadj->value = MAX(text->vadj->value, 0.0);
1350                         gtk_signal_emit_by_name(GTK_OBJECT(text->vadj),
1351                                                 "value_changed");
1352                 } else
1353                         return FALSE;
1354         }
1355
1356         return TRUE;
1357 }
1358
1359 static void textview_smooth_scroll_do(TextView *textview,
1360                                       gfloat old_value, gfloat last_value,
1361                                       gint step)
1362 {
1363         GtkSText *text = GTK_STEXT(textview->text);
1364         gint change_value;
1365         gboolean up;
1366         gint i;
1367
1368         if (old_value < last_value) {
1369                 change_value = last_value - old_value;
1370                 up = FALSE;
1371         } else {
1372                 change_value = old_value - last_value;
1373                 up = TRUE;
1374         }
1375
1376         gdk_key_repeat_disable();
1377
1378         for (i = step; i <= change_value; i += step) {
1379                 text->vadj->value = old_value + (up ? -i : i);
1380                 gtk_signal_emit_by_name(GTK_OBJECT(text->vadj),
1381                                         "value_changed");
1382         }
1383
1384         text->vadj->value = last_value;
1385         gtk_signal_emit_by_name(GTK_OBJECT(text->vadj), "value_changed");
1386
1387         gdk_key_repeat_restore();
1388 }
1389
1390 static void textview_smooth_scroll_one_line(TextView *textview, gboolean up)
1391 {
1392         GtkSText *text = GTK_STEXT(textview->text);
1393         gfloat upper;
1394         gfloat old_value;
1395         gfloat last_value;
1396
1397         if (!up) {
1398                 upper = text->vadj->upper - text->vadj->page_size;
1399                 if (text->vadj->value < upper) {
1400                         old_value = text->vadj->value;
1401                         last_value = text->vadj->value +
1402                                 text->vadj->step_increment * 4;
1403                         last_value = MIN(last_value, upper);
1404
1405                         textview_smooth_scroll_do(textview, old_value,
1406                                                   last_value,
1407                                                   prefs_common.scroll_step);
1408                 }
1409         } else {
1410                 if (text->vadj->value > 0.0) {
1411                         old_value = text->vadj->value;
1412                         last_value = text->vadj->value -
1413                                 text->vadj->step_increment * 4;
1414                         last_value = MAX(last_value, 0.0);
1415
1416                         textview_smooth_scroll_do(textview, old_value,
1417                                                   last_value,
1418                                                   prefs_common.scroll_step);
1419                 }
1420         }
1421 }
1422
1423 static gboolean textview_smooth_scroll_page(TextView *textview, gboolean up)
1424 {
1425         GtkSText *text = GTK_STEXT(textview->text);
1426         gfloat upper;
1427         gfloat page_incr;
1428         gfloat old_value;
1429         gfloat last_value;
1430
1431         if (prefs_common.scroll_halfpage)
1432                 page_incr = text->vadj->page_increment / 2;
1433         else
1434                 page_incr = text->vadj->page_increment;
1435
1436         if (!up) {
1437                 upper = text->vadj->upper - text->vadj->page_size;
1438                 if (text->vadj->value < upper) {
1439                         old_value = text->vadj->value;
1440                         last_value = text->vadj->value + page_incr;
1441                         last_value = MIN(last_value, upper);
1442
1443                         textview_smooth_scroll_do(textview, old_value,
1444                                                   last_value,
1445                                                   prefs_common.scroll_step);
1446                 } else
1447                         return FALSE;
1448         } else {
1449                 if (text->vadj->value > 0.0) {
1450                         old_value = text->vadj->value;
1451                         last_value = text->vadj->value - page_incr;
1452                         last_value = MAX(last_value, 0.0);
1453
1454                         textview_smooth_scroll_do(textview, old_value,
1455                                                   last_value,
1456                                                   prefs_common.scroll_step);
1457                 } else
1458                         return FALSE;
1459         }
1460
1461         return TRUE;
1462 }
1463
1464 #define KEY_PRESS_EVENT_STOP() \
1465         if (gtk_signal_n_emissions_by_name \
1466                 (GTK_OBJECT(widget), "key_press_event") > 0) { \
1467                 gtk_signal_emit_stop_by_name(GTK_OBJECT(widget), \
1468                                              "key_press_event"); \
1469         }
1470
1471 static gint textview_key_pressed(GtkWidget *widget, GdkEventKey *event,
1472                                  TextView *textview)
1473 {
1474         SummaryView *summaryview = NULL;
1475         MessageView *messageview = textview->messageview;
1476
1477         if (!event) return FALSE;
1478         if (messageview->mainwin)
1479                 summaryview = messageview->mainwin->summaryview;
1480
1481         switch (event->keyval) {
1482         case GDK_Tab:
1483         case GDK_Home:
1484         case GDK_Left:
1485         case GDK_Up:
1486         case GDK_Right:
1487         case GDK_Down:
1488         case GDK_Page_Up:
1489         case GDK_Page_Down:
1490         case GDK_End:
1491         case GDK_Control_L:
1492         case GDK_Control_R:
1493                 break;
1494         case GDK_space:
1495                 if (summaryview)
1496                         summary_pass_key_press_event(summaryview, event);
1497                 else
1498                         textview_scroll_page(textview, FALSE);
1499                 break;
1500         case GDK_BackSpace:
1501                 textview_scroll_page(textview, TRUE);
1502                 break;
1503         case GDK_Return:
1504                 textview_scroll_one_line(textview,
1505                                          (event->state & GDK_MOD1_MASK) != 0);
1506                 break;
1507         case GDK_n:
1508         case GDK_N:
1509         case GDK_p:
1510         case GDK_P:
1511         case GDK_y:
1512         case GDK_t:
1513         case GDK_l:
1514                 if (messageview->type == MVIEW_MIME) {
1515                         KEY_PRESS_EVENT_STOP();
1516                         mimeview_pass_key_press_event(messageview->mimeview,
1517                                                       event);
1518                         break;
1519                 }
1520                 /* fall through */
1521         default:
1522                 if (summaryview)
1523                         summary_pass_key_press_event(summaryview, event);
1524                 break;
1525         }
1526
1527         return TRUE;
1528 }
1529
1530 static gint textview_button_pressed(GtkWidget *widget, GdkEventButton *event,
1531                                     TextView *textview)
1532 {
1533         if (event)
1534                 textview->last_buttonpress = event->type;
1535         return FALSE;
1536 }
1537
1538 static gint textview_button_released(GtkWidget *widget, GdkEventButton *event,
1539                                     TextView *textview)
1540 {
1541         textview->cur_pos = 
1542                 gtk_editable_get_position(GTK_EDITABLE(textview->text));
1543
1544         if (event && 
1545             ((event->button == 1 && textview->last_buttonpress == GDK_2BUTTON_PRESS)
1546              || event->button == 2 || event->button == 3)) {
1547                 GSList *cur;
1548
1549                 /* double click seems to set the cursor after the current
1550                  * word. The cursor position needs fixing, otherwise the
1551                  * last word of a clickable zone will not work */
1552                 if (event->button == 1 && textview->last_buttonpress == GDK_2BUTTON_PRESS) {
1553                         textview->cur_pos--;
1554                 }
1555
1556                 for (cur = textview->uri_list; cur != NULL; cur = cur->next) {
1557                         RemoteURI *uri = (RemoteURI *)cur->data;
1558
1559                         if (textview->cur_pos >= uri->start &&
1560                             textview->cur_pos <  uri->end) {
1561                                 if (!g_strncasecmp(uri->uri, "mailto:", 7)) {
1562                                         if (event->button == 3) {
1563                                                 gchar *fromname, *fromaddress;
1564                                                 GdkEventButton tmpev;   
1565                                                 
1566                                                 /* extract url */
1567                                                 fromaddress = g_strdup(uri->uri + 7);
1568                                                 /* Hiroyuki: please put this function in utils.c! */
1569                                                 fromname = procheader_get_fromname(fromaddress);
1570                                                 extract_address(fromaddress);
1571                                                 g_message("adding from textview %s <%s>", fromname, fromaddress);
1572                                                 /* Add to address book - Match */
1573                                                 addressbook_add_contact( fromname, fromaddress, NULL );
1574                                                 
1575                                                 g_free(fromaddress);
1576                                                 g_free(fromname);
1577                                         } else {
1578                                                 PrefsAccount *account = NULL;
1579                                                 FolderItem   *folder_item;
1580
1581                                                 if (textview->messageview && textview->messageview->mainwin 
1582                                                 &&  textview->messageview->mainwin->summaryview 
1583                                                 &&  textview->messageview->mainwin->summaryview->folder_item) {
1584                                                         folder_item = textview->messageview->mainwin->summaryview->folder_item;
1585                                                         if (folder_item->prefs && folder_item->prefs->enable_default_account)
1586                                                                 account = account_find_from_id(folder_item->prefs->default_account);
1587                                                 }
1588                                                 compose_new_with_recipient
1589                                                         (account, uri->uri + 7);
1590                                         }
1591                                 } else {
1592                                         open_uri(uri->uri,
1593                                                  prefs_common.uri_cmd);
1594                                 }
1595                         }
1596                 }
1597         }
1598         if (event)
1599                 textview->last_buttonpress = event->type;
1600         return FALSE;
1601 }
1602
1603 static void textview_uri_list_remove_all(GSList *uri_list)
1604 {
1605         GSList *cur;
1606
1607         for (cur = uri_list; cur != NULL; cur = cur->next) {
1608                 if (cur->data) {
1609                         g_free(((RemoteURI *)cur->data)->uri);
1610                         g_free(cur->data);
1611                 }
1612         }
1613
1614         g_slist_free(uri_list);
1615 }