fcfc9c445afdd315e65487eed5750ec4ae9b18e8
[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                 gtkut_container_remove(GTK_CONTAINER(parent),
962                                        textview->scrolledwin_mb);
963                 gtk_container_add(GTK_CONTAINER(parent),
964                                   textview->scrolledwin_sb);
965
966                 textview->text = textview->text_sb;
967                 textview->text_is_mb = FALSE;
968         } else if (!textview->text_is_mb && use_fontset) {
969                 GtkWidget *parent;
970
971                 parent = textview->scrolledwin_sb->parent;
972                 gtkut_container_remove(GTK_CONTAINER(parent),
973                                        textview->scrolledwin_sb);
974                 gtk_container_add(GTK_CONTAINER(parent),
975                                   textview->scrolledwin_mb);
976
977                 textview->text = textview->text_mb;
978                 textview->text_is_mb = TRUE;
979         }
980
981         if (prefs_common.textfont) {
982                 if (textview->msgfont) {
983                         textview->msgfont->ascent = textview->prev_ascent;
984                         textview->msgfont->descent = textview->prev_descent;
985                         gdk_font_unref(textview->msgfont);
986                         textview->msgfont = NULL;
987                 }
988                 if (use_fontset)
989                         textview->msgfont =
990                                 gdk_fontset_load(prefs_common.textfont);
991                 else {
992                         if (MB_CUR_MAX > 1) {
993                                 FONT_LOAD(textview->msgfont,
994                                           "-*-courier-medium-r-normal--14-*-*-*-*-*-iso8859-1");
995                         } else {
996                                 FONT_LOAD(textview->msgfont,
997                                           prefs_common.textfont);
998                         }
999                 }
1000
1001                 if (textview->msgfont) {
1002                         gint ascent, descent;
1003
1004                         textview->prev_ascent = textview->msgfont->ascent;
1005                         textview->prev_descent = textview->msgfont->descent;
1006                         descent = prefs_common.line_space / 2;
1007                         ascent  = prefs_common.line_space - descent;
1008                         textview->msgfont->ascent  += ascent;
1009                         textview->msgfont->descent += descent;
1010                 }
1011         }
1012
1013         if (!textview->boldfont)
1014                 FONT_LOAD(textview->boldfont, BOLD_FONT);
1015         if (!spacingfont)
1016                 spacingfont = gdk_font_load("-*-*-medium-r-normal--6-*");
1017 }
1018
1019 enum
1020 {
1021         H_DATE          = 0,
1022         H_FROM          = 1,
1023         H_TO            = 2,
1024         H_NEWSGROUPS    = 3,
1025         H_SUBJECT       = 4,
1026         H_CC            = 5,
1027         H_REPLY_TO      = 6,
1028         H_FOLLOWUP_TO   = 7,
1029         H_X_MAILER      = 8,
1030         H_X_NEWSREADER  = 9,
1031         H_USER_AGENT    = 10,
1032         H_ORGANIZATION  = 11,
1033 };
1034
1035 void textview_set_position(TextView *textview, gint pos)
1036 {
1037         if (pos < 0) {
1038                 textview->cur_pos =
1039                         gtk_text_get_length(GTK_TEXT(textview->text));
1040         } else {
1041                 textview->cur_pos = pos;
1042         }
1043 }
1044
1045 static GPtrArray *textview_scan_header(TextView *textview, FILE *fp)
1046 {
1047         gchar buf[BUFFSIZE];
1048         GPtrArray *headers, *sorted_headers;
1049         GSList *disphdr_list;
1050         Header *header;
1051         gint i;
1052
1053         g_return_val_if_fail(fp != NULL, NULL);
1054
1055         if (!prefs_common.display_header) {
1056                 while (fgets(buf, sizeof(buf), fp) != NULL)
1057                         if (buf[0] == '\r' || buf[0] == '\n') break;
1058                 return NULL;
1059         }
1060
1061         headers = procheader_get_header_array_asis(fp);
1062
1063         sorted_headers = g_ptr_array_new();
1064
1065         for (disphdr_list = prefs_common.disphdr_list; disphdr_list != NULL;
1066              disphdr_list = disphdr_list->next) {
1067                 DisplayHeaderProp *dp =
1068                         (DisplayHeaderProp *)disphdr_list->data;
1069
1070                 for (i = 0; i < headers->len; i++) {
1071                         header = g_ptr_array_index(headers, i);
1072
1073                         if (procheader_headername_equal(header->name,
1074                                                         dp->name)) {
1075                                 if (dp->hidden)
1076                                         procheader_header_free(header);
1077                                 else
1078                                         g_ptr_array_add(sorted_headers, header);
1079
1080                                 g_ptr_array_remove_index(headers, i);
1081                                 i--;
1082                         }
1083                 }
1084         }
1085
1086         if (prefs_common.show_other_header) {
1087                 for (i = 0; i < headers->len; i++) {
1088                         header = g_ptr_array_index(headers, i);
1089                         g_ptr_array_add(sorted_headers, header);
1090                 }
1091         }
1092
1093         g_ptr_array_free(headers, FALSE);
1094
1095         return sorted_headers;
1096 }
1097
1098 static void textview_show_header(TextView *textview, GPtrArray *headers)
1099 {
1100         GtkText *text = GTK_TEXT(textview->text);
1101         Header *header;
1102         gint i;
1103
1104         g_return_if_fail(headers != NULL);
1105
1106         gtk_text_freeze(text);
1107
1108         for (i = 0; i < headers->len; i++) {
1109                 header = g_ptr_array_index(headers, i);
1110                 g_return_if_fail(header->name != NULL);
1111
1112                 gtk_text_insert(text, textview->boldfont, NULL, NULL,
1113                                 header->name, -1);
1114                 if (header->name[strlen(header->name) - 1] != ' ')
1115                         gtk_text_insert(text, textview->boldfont,
1116                                         NULL, NULL, " ", 1);
1117
1118                 if (procheader_headername_equal(header->name, "Subject") ||
1119                     procheader_headername_equal(header->name, "From")    ||
1120                     procheader_headername_equal(header->name, "To")      ||
1121                     procheader_headername_equal(header->name, "Cc"))
1122                         unfold_line(header->body);
1123
1124                 if (prefs_common.enable_color &&
1125                     (procheader_headername_equal(header->name, "X-Mailer") ||
1126                      procheader_headername_equal(header->name,
1127                                                  "X-Newsreader")) &&
1128                     strstr(header->body, "Sylpheed") != NULL)
1129                         gtk_text_insert(text, NULL, &emphasis_color, NULL,
1130                                         header->body, -1);
1131                 else if (prefs_common.enable_color) {
1132                         textview_make_clickable_parts(textview,
1133                                                       NULL, NULL, &uri_color,
1134                                                       header->body);
1135                 } else {
1136                         textview_make_clickable_parts(textview,
1137                                                       NULL, NULL, NULL,
1138                                                       header->body);
1139                 }
1140                 gtk_text_insert(text, textview->msgfont, NULL, NULL, "\n", 1);
1141         }
1142
1143         gtk_text_insert(text, textview->msgfont, NULL, NULL, "\n", 1);
1144         gtk_text_thaw(text);
1145         textview->body_pos = gtk_text_get_length(text);
1146 }
1147
1148 gboolean textview_search_string(TextView *textview, const gchar *str,
1149                                 gboolean case_sens)
1150 {
1151         GtkText *text = GTK_TEXT(textview->text);
1152         gint pos;
1153         wchar_t *wcs;
1154         gint len;
1155         gint text_len;
1156         gboolean found = FALSE;
1157
1158         g_return_val_if_fail(str != NULL, FALSE);
1159
1160         wcs = strdup_mbstowcs(str);
1161         g_return_val_if_fail(wcs != NULL, FALSE);
1162         len = wcslen(wcs);
1163         pos = textview->cur_pos;
1164         if (pos < textview->body_pos)
1165                 pos = textview->body_pos;
1166         text_len = gtk_text_get_length(text);
1167         if (text_len - pos < len) {
1168                 g_free(wcs);
1169                 return FALSE;
1170         }
1171
1172         for (; pos < text_len; pos++) {
1173                 if (text_len - pos < len) break;
1174                 if (gtkut_text_match_string(GTK_TEXT(text), pos, wcs, len, case_sens)
1175                     == TRUE) {
1176                         gtk_editable_set_position(GTK_EDITABLE(text),
1177                                                   pos + len);
1178                         gtk_editable_select_region(GTK_EDITABLE(text),
1179                                                    pos, pos + len);
1180                         textview_set_position(textview, pos + len);
1181                         found = TRUE;
1182                         break;
1183                 }
1184                 if (text_len - pos == len) break;
1185         }
1186
1187         g_free(wcs);
1188         return found;
1189 }
1190
1191 gboolean textview_search_string_backward(TextView *textview, const gchar *str,
1192                                          gboolean case_sens)
1193 {
1194         GtkText *text = GTK_TEXT(textview->text);
1195         gint pos;
1196         wchar_t *wcs;
1197         gint len;
1198         gint text_len;
1199         gboolean found = FALSE;
1200
1201         g_return_val_if_fail(str != NULL, FALSE);
1202
1203         wcs = strdup_mbstowcs(str);
1204         g_return_val_if_fail(wcs != NULL, FALSE);
1205         len = wcslen(wcs);
1206         pos = textview->cur_pos;
1207         text_len = gtk_text_get_length(text);
1208         if (text_len - textview->body_pos < len) {
1209                 g_free(wcs);
1210                 return FALSE;
1211         }
1212         if (pos <= textview->body_pos || text_len - pos < len)
1213                 pos = text_len - len;
1214
1215         for (; pos >= textview->body_pos; pos--) {
1216                 if (gtkut_text_match_string(GTK_TEXT(text), pos, wcs, len, case_sens)
1217                     == TRUE) {
1218                         gtk_editable_set_position(GTK_EDITABLE(text), pos);
1219                         gtk_editable_select_region(GTK_EDITABLE(text),
1220                                                    pos, pos + len);
1221                         textview_set_position(textview, pos - 1);
1222                         found = TRUE;
1223                         break;
1224                 }
1225                 if (pos == textview->body_pos) break;
1226         }
1227
1228         g_free(wcs);
1229         return found;
1230 }
1231
1232 void textview_scroll_one_line(TextView *textview, gboolean up)
1233 {
1234         GtkText *text = GTK_TEXT(textview->text);
1235         gfloat upper;
1236
1237         if (prefs_common.enable_smooth_scroll) {
1238                 textview_smooth_scroll_one_line(textview, up);
1239                 return;
1240         }
1241
1242         if (!up) {
1243                 upper = text->vadj->upper - text->vadj->page_size;
1244                 if (text->vadj->value < upper) {
1245                         text->vadj->value +=
1246                                 text->vadj->step_increment * 4;
1247                         text->vadj->value =
1248                                 MIN(text->vadj->value, upper);
1249                         gtk_signal_emit_by_name(GTK_OBJECT(text->vadj),
1250                                                 "value_changed");
1251                 }
1252         } else {
1253                 if (text->vadj->value > 0.0) {
1254                         text->vadj->value -=
1255                                 text->vadj->step_increment * 4;
1256                         text->vadj->value =
1257                                 MAX(text->vadj->value, 0.0);
1258                         gtk_signal_emit_by_name(GTK_OBJECT(text->vadj),
1259                                                 "value_changed");
1260                 }
1261         }
1262 }
1263
1264 gboolean textview_scroll_page(TextView *textview, gboolean up)
1265 {
1266         GtkText *text = GTK_TEXT(textview->text);
1267         gfloat upper;
1268         gfloat page_incr;
1269
1270         if (prefs_common.enable_smooth_scroll)
1271                 return textview_smooth_scroll_page(textview, up);
1272
1273         if (prefs_common.scroll_halfpage)
1274                 page_incr = text->vadj->page_increment / 2;
1275         else
1276                 page_incr = text->vadj->page_increment;
1277
1278         if (!up) {
1279                 upper = text->vadj->upper - text->vadj->page_size;
1280                 if (text->vadj->value < upper) {
1281                         text->vadj->value += page_incr;
1282                         text->vadj->value = MIN(text->vadj->value, upper);
1283                         gtk_signal_emit_by_name(GTK_OBJECT(text->vadj),
1284                                                 "value_changed");
1285                 } else
1286                         return FALSE;
1287         } else {
1288                 if (text->vadj->value > 0.0) {
1289                         text->vadj->value -= page_incr;
1290                         text->vadj->value = MAX(text->vadj->value, 0.0);
1291                         gtk_signal_emit_by_name(GTK_OBJECT(text->vadj),
1292                                                 "value_changed");
1293                 } else
1294                         return FALSE;
1295         }
1296
1297         return TRUE;
1298 }
1299
1300 static void textview_smooth_scroll_do(TextView *textview,
1301                                       gfloat old_value, gfloat last_value,
1302                                       gint step)
1303 {
1304         GtkText *text = GTK_TEXT(textview->text);
1305         gint change_value;
1306         gboolean up;
1307         gint i;
1308
1309         if (old_value < last_value) {
1310                 change_value = last_value - old_value;
1311                 up = FALSE;
1312         } else {
1313                 change_value = old_value - last_value;
1314                 up = TRUE;
1315         }
1316
1317         gdk_key_repeat_disable();
1318
1319         for (i = step; i <= change_value; i += step) {
1320                 text->vadj->value = old_value + (up ? -i : i);
1321                 gtk_signal_emit_by_name(GTK_OBJECT(text->vadj),
1322                                         "value_changed");
1323         }
1324
1325         text->vadj->value = last_value;
1326         gtk_signal_emit_by_name(GTK_OBJECT(text->vadj), "value_changed");
1327
1328         gdk_key_repeat_restore();
1329 }
1330
1331 static void textview_smooth_scroll_one_line(TextView *textview, gboolean up)
1332 {
1333         GtkText *text = GTK_TEXT(textview->text);
1334         gfloat upper;
1335         gfloat old_value;
1336         gfloat last_value;
1337
1338         if (!up) {
1339                 upper = text->vadj->upper - text->vadj->page_size;
1340                 if (text->vadj->value < upper) {
1341                         old_value = text->vadj->value;
1342                         last_value = text->vadj->value +
1343                                 text->vadj->step_increment * 4;
1344                         last_value = MIN(last_value, upper);
1345
1346                         textview_smooth_scroll_do(textview, old_value,
1347                                                   last_value,
1348                                                   prefs_common.scroll_step);
1349                 }
1350         } else {
1351                 if (text->vadj->value > 0.0) {
1352                         old_value = text->vadj->value;
1353                         last_value = text->vadj->value -
1354                                 text->vadj->step_increment * 4;
1355                         last_value = MAX(last_value, 0.0);
1356
1357                         textview_smooth_scroll_do(textview, old_value,
1358                                                   last_value,
1359                                                   prefs_common.scroll_step);
1360                 }
1361         }
1362 }
1363
1364 static gboolean textview_smooth_scroll_page(TextView *textview, gboolean up)
1365 {
1366         GtkText *text = GTK_TEXT(textview->text);
1367         gfloat upper;
1368         gfloat page_incr;
1369         gfloat old_value;
1370         gfloat last_value;
1371
1372         if (prefs_common.scroll_halfpage)
1373                 page_incr = text->vadj->page_increment / 2;
1374         else
1375                 page_incr = text->vadj->page_increment;
1376
1377         if (!up) {
1378                 upper = text->vadj->upper - text->vadj->page_size;
1379                 if (text->vadj->value < upper) {
1380                         old_value = text->vadj->value;
1381                         last_value = text->vadj->value + page_incr;
1382                         last_value = MIN(last_value, upper);
1383
1384                         textview_smooth_scroll_do(textview, old_value,
1385                                                   last_value,
1386                                                   prefs_common.scroll_step);
1387                 } else
1388                         return FALSE;
1389         } else {
1390                 if (text->vadj->value > 0.0) {
1391                         old_value = text->vadj->value;
1392                         last_value = text->vadj->value - page_incr;
1393                         last_value = MAX(last_value, 0.0);
1394
1395                         textview_smooth_scroll_do(textview, old_value,
1396                                                   last_value,
1397                                                   prefs_common.scroll_step);
1398                 } else
1399                         return FALSE;
1400         }
1401
1402         return TRUE;
1403 }
1404
1405 static void textview_key_pressed(GtkWidget *widget, GdkEventKey *event,
1406                                  TextView *textview)
1407 {
1408         SummaryView *summaryview = NULL;
1409
1410         if (!event) return;
1411         if (textview->messageview->mainwin)
1412                 summaryview = textview->messageview->mainwin->summaryview;
1413
1414         switch (event->keyval) {
1415         case GDK_Tab:
1416         case GDK_Home:
1417         case GDK_Left:
1418         case GDK_Up:
1419         case GDK_Right:
1420         case GDK_Down:
1421         case GDK_Page_Up:
1422         case GDK_Page_Down:
1423         case GDK_End:
1424         case GDK_Control_L:
1425         case GDK_Control_R:
1426                 break;
1427         case GDK_space:
1428                 if (summaryview)
1429                         summary_pass_key_press_event(summaryview, event);
1430                 else
1431                         textview_scroll_page(textview, FALSE);
1432                 break;
1433         case GDK_BackSpace:
1434                 textview_scroll_page(textview, TRUE);
1435                 break;
1436         case GDK_Return:
1437                 textview_scroll_one_line(textview,
1438                                          (event->state & GDK_MOD1_MASK) != 0);
1439                 break;
1440         default:
1441                 if (summaryview)
1442                         summary_pass_key_press_event(summaryview, event);
1443                 break;
1444         }
1445 }
1446
1447 static gint textview_button_pressed(GtkWidget *widget, GdkEventButton *event,
1448                                     TextView *textview)
1449 {
1450         if (event)
1451                 textview->last_buttonpress = event->type;
1452         return FALSE;
1453 }
1454
1455 static gint textview_button_released(GtkWidget *widget, GdkEventButton *event,
1456                                     TextView *textview)
1457 {
1458         textview->cur_pos = 
1459                 gtk_editable_get_position(GTK_EDITABLE(textview->text));
1460
1461         if (event && 
1462             ((event->button == 1 && textview->last_buttonpress == GDK_2BUTTON_PRESS)
1463              || event->button == 2 || event->button == 3)) {
1464                 GSList *cur;
1465
1466                 /* double click seems to set the cursor after the current
1467                  * word. The cursor position needs fixing, otherwise the
1468                  * last word of a clickable zone will not work */
1469                 if (event->button == 1 && textview->last_buttonpress == GDK_2BUTTON_PRESS) {
1470                         textview->cur_pos--;
1471                 }
1472
1473                 for (cur = textview->uri_list; cur != NULL; cur = cur->next) {
1474                         RemoteURI *uri = (RemoteURI *)cur->data;
1475
1476                         if (textview->cur_pos >= uri->start &&
1477                             textview->cur_pos <  uri->end) {
1478                                 if (!g_strncasecmp(uri->uri, "mailto:", 7)) {
1479                                         if (event->button == 3) {
1480                                                 gchar *fromname, *fromaddress;
1481                                                 GdkEventButton tmpev;   
1482                                                 
1483                                                 /* extract url */
1484                                                 fromaddress = g_strdup(uri->uri + 7);
1485                                                 /* Hiroyuki: please put this function in utils.c! */
1486                                                 fromname = procheader_get_fromname(fromaddress);
1487                                                 extract_address(fromaddress);
1488                                                 g_message("adding from textview %s <%s>", fromname, fromaddress);
1489                                                 /* Add to address book - Match */
1490                                                 addressbook_add_contact( fromname, fromaddress, NULL );
1491                                                 
1492                                                 g_free(fromaddress);
1493                                                 g_free(fromname);
1494                                         } else {
1495                                                 compose_new_with_recipient
1496                                                         (NULL, uri->uri + 7);
1497                                         }
1498                                 } else {
1499                                         open_uri(uri->uri,
1500                                                  prefs_common.uri_cmd);
1501                                 }
1502                         }
1503                 }
1504         }
1505         if (event)
1506                 textview->last_buttonpress = event->type;
1507         return FALSE;
1508 }
1509
1510 static void textview_uri_list_remove_all(GSList *uri_list)
1511 {
1512         GSList *cur;
1513
1514         for (cur = uri_list; cur != NULL; cur = cur->next) {
1515                 if (cur->data) {
1516                         g_free(((RemoteURI *)cur->data)->uri);
1517                         g_free(cur->data);
1518                 }
1519         }
1520
1521         g_slist_free(uri_list);
1522 }