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