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