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