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