3014b977a3de8fe6a2a9b53f8d30adaeada67df9
[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         html_parser_destroy(parser);
653 }
654
655 static void textview_show_ertf(TextView *textview, FILE *fp,
656                                CodeConverter *conv)
657 {
658         ERTFParser *parser;
659         gchar *str;
660
661         parser = ertf_parser_new(fp, conv);
662         g_return_if_fail(parser != NULL);
663
664         while ((str = ertf_parse(parser)) != NULL) {
665                 textview_write_line(textview, str, NULL);
666         }
667         ertf_parser_destroy(parser);
668 }
669
670 /* get_uri_part() - retrieves a URI starting from scanpos.
671                     Returns TRUE if succesful */
672 static gboolean get_uri_part(const gchar *start, const gchar *scanpos,
673                              const gchar **bp, const gchar **ep)
674 {
675         const gchar *ep_;
676
677         g_return_val_if_fail(start != NULL, FALSE);
678         g_return_val_if_fail(scanpos != NULL, FALSE);
679         g_return_val_if_fail(bp != NULL, FALSE);
680         g_return_val_if_fail(ep != NULL, FALSE);
681
682         *bp = scanpos;
683
684         /* find end point of URI */
685         for (ep_ = scanpos; *ep_ != '\0'; ep_++) {
686                 if (!isgraph(*ep_) || !isascii(*ep_) || strchr("()<>\"", *ep_))
687                         break;
688         }
689
690         /* no punctuation at end of string */
691
692         /* FIXME: this stripping of trailing punctuations may bite with other URIs.
693          * should pass some URI type to this function and decide on that whether
694          * to perform punctuation stripping */
695
696 #define IS_REAL_PUNCT(ch)       (ispunct(ch) && ((ch) != '/')) 
697
698         for (; ep_ - 1 > scanpos + 1 && IS_REAL_PUNCT(*(ep_ - 1)); ep_--)
699                 ;
700
701 #undef IS_REAL_PUNCT
702
703         *ep = ep_;
704
705         return TRUE;            
706 }
707
708 static gchar *make_uri_string(const gchar *bp, const gchar *ep)
709 {
710         return g_strndup(bp, ep - bp);
711 }
712
713 /* valid mail address characters */
714 #define IS_RFC822_CHAR(ch) \
715         (isascii(ch) && \
716          (ch) > 32   && \
717          (ch) != 127 && \
718          !isspace(ch) && \
719          !strchr("(),;<>\"", (ch)))
720
721 /* alphabet and number within 7bit ASCII */
722 #define IS_ASCII_ALNUM(ch)      (isascii(ch) && isalnum(ch))
723 #define IS_QUOTE(ch) ((ch) == '\'' || (ch) == '"')
724
725 /* get_email_part() - retrieves an email address. Returns TRUE if succesful */
726 static gboolean get_email_part(const gchar *start, const gchar *scanpos,
727                                const gchar **bp, const gchar **ep)
728 {
729         /* more complex than the uri part because we need to scan back and forward starting from
730          * the scan position. */
731         gboolean result = FALSE;
732         const gchar *bp_ = NULL;
733         const gchar *ep_ = NULL;
734
735         /* the informative part of the email address (describing the name
736          * of the email address owner) may contain quoted parts. the
737          * closure stack stores the last encountered quotes. */
738         gchar closure_stack[128];
739         gchar *ptr = closure_stack;
740
741         g_return_val_if_fail(start != NULL, FALSE);
742         g_return_val_if_fail(scanpos != NULL, FALSE);
743         g_return_val_if_fail(bp != NULL, FALSE);
744         g_return_val_if_fail(ep != NULL, FALSE);
745
746         /* scan start of address */
747         for (bp_ = scanpos - 1; bp_ >= start && IS_RFC822_CHAR(*bp_); bp_--)
748                 ;
749
750         /* TODO: should start with an alnum? */
751         bp_++;
752         for (; bp_ < scanpos && !IS_ASCII_ALNUM(*bp_); bp_++)
753                 ;
754
755         if (bp_ != scanpos) {
756                 /* scan end of address */
757                 for (ep_ = scanpos + 1; *ep_ && IS_RFC822_CHAR(*ep_); ep_++)
758                         ;
759
760                 /* TODO: really should terminate with an alnum? */
761                 for (; ep_ > scanpos && !IS_ASCII_ALNUM(*ep_); --ep_)
762                         ;
763                 ep_++;
764
765                 if (ep_ > scanpos + 1) {
766                         *ep = ep_;
767                         *bp = bp_;
768                         result = TRUE;
769                 }
770         }
771
772         if (!result) return FALSE;
773
774         /* skip if it's between quotes "'alfons@proteus.demon.nl'" <alfons@proteus.demon.nl> */
775         if (bp_ - 1 > start && IS_QUOTE(*(bp_ - 1)) && IS_QUOTE(*ep_)) 
776                 return FALSE;
777
778         /* see if this is <bracketed>; in this case we also scan for the informative part. */
779         if (bp_ - 1 <= start || *(bp_ - 1) != '<' || *ep_ != '>')
780                 return TRUE;
781
782 #define FULL_STACK()    ((size_t) (ptr - closure_stack) >= sizeof closure_stack)
783 #define IN_STACK()      (ptr > closure_stack)
784 /* has underrun check */
785 #define POP_STACK()     if(IN_STACK()) --ptr
786 /* has overrun check */
787 #define PUSH_STACK(c)   if(!FULL_STACK()) *ptr++ = (c); else return TRUE
788 /* has underrun check */
789 #define PEEK_STACK()    (IN_STACK() ? *(ptr - 1) : 0)
790
791         ep_++;
792
793         /* scan for the informative part. */
794         for (bp_ -= 2; bp_ >= start; bp_--) {
795                 /* if closure on the stack keep scanning */
796                 if (PEEK_STACK() == *bp_) {
797                         POP_STACK();
798                         continue;
799                 }
800                 if (*bp_ == '\'' || *bp_ == '"') {
801                         PUSH_STACK(*bp_);
802                         continue;
803                 }
804
805                 /* if nothing in the closure stack, do the special conditions
806                  * the following if..else expression simply checks whether 
807                  * a token is acceptable. if not acceptable, the clause
808                  * should terminate the loop with a 'break' */
809                 if (!PEEK_STACK()) {
810                         if (*bp_ == '-'
811                         && (((bp_ - 1) >= start) && isalnum(*(bp_ - 1)))
812                         && (((bp_ + 1) < ep_)    && isalnum(*(bp_ + 1)))) {
813                                 /* hyphens are allowed, but only in
814                                    between alnums */
815                         } else if (!ispunct(*bp_)) {
816                                 /* but anything not being a punctiation
817                                    is ok */
818                         } else {
819                                 break; /* anything else is rejected */
820                         }
821                 }
822         }
823
824         bp_++;
825
826 #undef PEEK_STACK
827 #undef PUSH_STACK
828 #undef POP_STACK
829 #undef IN_STACK
830 #undef FULL_STACK
831
832         /* scan forward (should start with an alnum) */
833         for (; *bp_ != '<' && isspace(*bp_) && *bp_ != '"'; bp_++)
834                 ;
835
836         *ep = ep_;
837         *bp = bp_;
838
839         return result;
840 }
841
842 #undef IS_QUOTE
843 #undef IS_RFC822_CHAR
844
845 static gchar *make_email_string(const gchar *bp, const gchar *ep)
846 {
847         /* returns a mailto: URI; mailto: is also used to detect the
848          * uri type later on in the button_pressed signal handler */
849         gchar *tmp;
850         gchar *result;
851
852         tmp = g_strndup(bp, ep - bp);
853         result = g_strconcat("mailto:", tmp, NULL);
854         g_free(tmp);
855
856         return result;
857 }
858
859 #define ADD_TXT_POS(bp_, ep_, pti_) \
860         if ((last->next = alloca(sizeof(struct txtpos))) != NULL) { \
861                 last = last->next; \
862                 last->bp = (bp_); last->ep = (ep_); last->pti = (pti_); \
863                 last->next = NULL; \
864         } else { \
865                 g_warning("alloc error scanning URIs\n"); \
866                 gtk_stext_insert(text, textview->msgfont, fg_color, NULL, \
867                                 linebuf, -1); \
868                 return; \
869         }
870
871 /* textview_make_clickable_parts() - colorizes clickable parts */
872 static void textview_make_clickable_parts(TextView *textview,
873                                           GdkFont *font,
874                                           GdkColor *fg_color,
875                                           GdkColor *uri_color,
876                                           const gchar *linebuf)
877 {
878         /* parse table - in order of priority */
879         struct table {
880                 const gchar *needle; /* token */
881
882                 /* token search function */
883                 gchar    *(*search)     (const gchar *haystack,
884                                          const gchar *needle);
885                 /* part parsing function */
886                 gboolean  (*parse)      (const gchar *start,
887                                          const gchar *scanpos,
888                                          const gchar **bp_,
889                                          const gchar **ep_);
890                 /* part to URI function */
891                 gchar    *(*build_uri)  (const gchar *bp,
892                                          const gchar *ep);
893         };
894
895         static struct table parser[] = {
896                 {"http://",  strcasestr, get_uri_part,   make_uri_string},
897                 {"https://", strcasestr, get_uri_part,   make_uri_string},
898                 {"www.",     strcasestr, get_uri_part,   make_uri_string},
899                 {"ftp://",   strcasestr, get_uri_part,   make_uri_string},
900                 {"mailto:",  strcasestr, get_uri_part,   make_uri_string},
901                 {"@",        strcasestr, get_email_part, make_email_string}
902         };
903         const gint PARSE_ELEMS = sizeof parser / sizeof parser[0];
904
905         gint  n;
906         const gchar *walk, *bp, *ep;
907
908         struct txtpos {
909                 const gchar     *bp, *ep;       /* text position */
910                 gint             pti;           /* index in parse table */
911                 struct txtpos   *next;          /* next */
912         } head = {NULL, NULL, 0,  NULL}, *last = &head;
913
914         GtkSText *text = GTK_STEXT(textview->text);
915
916         /* parse for clickable parts, and build a list of begin and end positions  */
917         for (walk = linebuf, n = 0;;) {
918                 gint last_index = PARSE_ELEMS;
919                 gchar *scanpos = NULL;
920
921                 /* FIXME: this looks phony. scanning for anything in the parse table */
922                 for (n = 0; n < PARSE_ELEMS; n++) {
923                         gchar *tmp;
924
925                         tmp = parser[n].search(walk, parser[n].needle);
926                         if (tmp) {
927                                 if (scanpos == NULL || tmp < scanpos) {
928                                         scanpos = tmp;
929                                         last_index = n;
930                                 }
931                         }                                       
932                 }
933
934                 if (scanpos) {
935                         /* check if URI can be parsed */
936                         if (parser[last_index].parse(linebuf, scanpos, &bp, &ep)
937                             && (size_t) (ep - bp - 1) > strlen(parser[last_index].needle)) {
938                                         ADD_TXT_POS(bp, ep, last_index);
939                                         walk = ep;
940                         } else
941                                 walk = scanpos +
942                                         strlen(parser[last_index].needle);
943                 } else
944                         break;
945         }
946
947         /* colorize this line */
948         if (head.next) {
949                 const gchar *normal_text = linebuf;
950
951                 /* insert URIs */
952                 for (last = head.next; last != NULL;
953                      normal_text = last->ep, last = last->next) {
954                         RemoteURI *uri;
955
956                         uri = g_new(RemoteURI, 1);
957                         if (last->bp - normal_text > 0)
958                                 gtk_stext_insert(text, font,
959                                                 fg_color, NULL,
960                                                 normal_text,
961                                                 last->bp - normal_text);
962                         uri->uri = parser[last->pti].build_uri(last->bp,
963                                                                last->ep);
964                         uri->start = gtk_stext_get_point(text);
965                         gtk_stext_insert(text, font, uri_color,
966                                         NULL, last->bp, last->ep - last->bp);
967                         uri->end = gtk_stext_get_point(text);
968                         textview->uri_list =
969                                 g_slist_append(textview->uri_list, uri);
970                 }
971
972                 if (*normal_text)
973                         gtk_stext_insert(text, font, fg_color,
974                                         NULL, normal_text, -1);
975         } else
976                 gtk_stext_insert(text, font, fg_color, NULL, linebuf, -1);
977 }
978
979 #undef ADD_TXT_POS
980
981 /* This function writes str as a double-clickable link with the given url. */ 
982 static void textview_write_link(TextView *textview, const gchar *url,
983                                 const gchar *str, CodeConverter *conv)
984 {
985     GdkColor *link_color = NULL;
986     RemoteURI* uri;
987     GtkSText *text = GTK_STEXT(textview->text);
988     gchar buf[BUFFSIZE];
989
990     /* this part is taken from textview_write_line. Right now the only place
991      * that calls this function passes NULL for conv, but you never know. */
992 #if 0
993     if (!conv)
994             strncpy2(buf, str, sizeof(buf));
995     else if (conv_convert(conv, buf, sizeof(buf), str) < 0) {
996             gtk_stext_insert(text, textview->msgfont,
997                             prefs_common.enable_color
998                             ? &error_color : NULL, NULL,
999                             "*** Warning: code conversion failed ***\n",
1000                             -1);
1001             return;
1002     }
1003 #endif
1004
1005     if (!conv || conv_convert(conv, buf, sizeof(buf), str) < 0)
1006         strncpy2(buf, str, sizeof(buf));
1007
1008     strcrchomp(buf);
1009     gtk_stext_insert(text, textview->msgfont, NULL, NULL, " ", 1);
1010  
1011     /* this part is based on the code in make_clickable_parts */
1012     if (prefs_common.enable_color) {
1013         link_color = &uri_color;
1014     }
1015     uri = g_new(RemoteURI, 1);
1016     uri->uri = g_strdup(url);
1017     uri->start = gtk_stext_get_point(text);
1018     gtk_stext_insert(text, textview->msgfont, link_color, NULL, str,
1019                     strlen(str));
1020     uri->end = gtk_stext_get_point(text);
1021     textview->uri_list = g_slist_append(textview->uri_list, uri);
1022 }
1023
1024 static void textview_write_line(TextView *textview, const gchar *str,
1025                                 CodeConverter *conv)
1026 {
1027         GtkSText *text = GTK_STEXT(textview->text);
1028         gchar buf[BUFFSIZE];
1029         GdkColor *fg_color;
1030         gint quotelevel = -1;
1031
1032 #if 0
1033         if (!conv)
1034                 strncpy2(buf, str, sizeof(buf));
1035         else if (conv_convert(conv, buf, sizeof(buf), str) < 0) {
1036                 gtk_stext_insert(text, textview->msgfont,
1037                                 prefs_common.enable_color
1038                                 ? &error_color : NULL, NULL,
1039                                 "*** Warning: code conversion failed ***\n",
1040                                 -1);
1041                 return;
1042         }
1043 #endif
1044         if (!conv || conv_convert(conv, buf, sizeof(buf), str) < 0)
1045                 strncpy2(buf, str, sizeof(buf));
1046
1047         strcrchomp(buf);
1048         if (prefs_common.conv_mb_alnum) conv_mb_alnum(buf);
1049         fg_color = NULL;
1050
1051         /* change color of quotation
1052            >, foo>, _> ... ok, <foo>, foo bar>, foo-> ... ng
1053            Up to 3 levels of quotations are detected, and each
1054            level is colored using a different color. */
1055         if (prefs_common.enable_color 
1056             && line_has_quote_char(buf, prefs_common.quote_chars)) {
1057                 quotelevel = get_quote_level(buf, prefs_common.quote_chars);
1058
1059                 /* set up the correct foreground color */
1060                 if (quotelevel > 2) {
1061                         /* recycle colors */
1062                         if (prefs_common.recycle_quote_colors)
1063                                 quotelevel %= 3;
1064                         else
1065                                 quotelevel = 2;
1066                 }
1067         }
1068
1069         if (quotelevel == -1)
1070                 fg_color = NULL;
1071         else
1072                 fg_color = &quote_colors[quotelevel];
1073
1074         if (prefs_common.head_space && spacingfont && buf[0] != '\n')
1075                 gtk_stext_insert(text, spacingfont, NULL, NULL, " ", 1);
1076
1077         if (prefs_common.enable_color)
1078                 textview_make_clickable_parts(textview, textview->msgfont,
1079                                               fg_color, &uri_color, buf);
1080         else
1081                 textview_make_clickable_parts(textview, textview->msgfont,
1082                                               fg_color, NULL, buf);
1083 }
1084
1085 void textview_clear(TextView *textview)
1086 {
1087         GtkSText *text = GTK_STEXT(textview->text);
1088
1089         gtk_stext_freeze(text);
1090         gtk_stext_set_point(text, 0);
1091         gtk_stext_forward_delete(text, gtk_stext_get_length(text));
1092         gtk_stext_thaw(text);
1093
1094         textview_uri_list_remove_all(textview->uri_list);
1095         textview->uri_list = NULL;
1096
1097         textview->body_pos = 0;
1098         textview->cur_pos  = 0;
1099 }
1100
1101 void textview_destroy(TextView *textview)
1102 {
1103         textview_uri_list_remove_all(textview->uri_list);
1104         textview->uri_list = NULL;
1105
1106         if (!textview->scrolledwin_sb->parent)
1107                 gtk_widget_destroy(textview->scrolledwin_sb);
1108         if (!textview->scrolledwin_mb->parent)
1109                 gtk_widget_destroy(textview->scrolledwin_mb);
1110
1111         if (textview->msgfont)
1112                 gdk_font_unref(textview->msgfont);
1113         if (textview->boldfont)
1114                 gdk_font_unref(textview->boldfont);
1115
1116         g_free(textview);
1117 }
1118
1119 void textview_set_all_headers(TextView *textview, gboolean all_headers)
1120 {
1121         textview->show_all_headers = all_headers;
1122 }
1123
1124 void textview_set_font(TextView *textview, const gchar *codeset)
1125 {
1126         gboolean use_fontset = TRUE;
1127
1128         /* In multi-byte mode, GtkSText can't display 8bit characters
1129            correctly, so it must be single-byte mode. */
1130         if (MB_CUR_MAX > 1) {
1131                 if (codeset) {
1132                         if (!g_strncasecmp(codeset, "ISO-8859-", 9) ||
1133                             !g_strcasecmp(codeset, "BALTIC"))
1134                                 use_fontset = FALSE;
1135                         else if (conv_get_current_charset() != C_EUC_JP &&
1136                                  (!g_strncasecmp(codeset, "KOI8-", 5) ||
1137                                   !g_strncasecmp(codeset, "CP", 2)    ||
1138                                   !g_strncasecmp(codeset, "WINDOWS-", 8)))
1139                                 use_fontset = FALSE;
1140                 }
1141         } else
1142                 use_fontset = FALSE;
1143
1144         if (textview->text_is_mb && !use_fontset) {
1145                 GtkWidget *parent;
1146
1147                 parent = textview->scrolledwin_mb->parent;
1148                 gtkut_container_remove(GTK_CONTAINER(parent),
1149                                        textview->scrolledwin_mb);
1150                 gtk_container_add(GTK_CONTAINER(parent),
1151                                   textview->scrolledwin_sb);
1152
1153                 textview->text = textview->text_sb;
1154                 textview->text_is_mb = FALSE;
1155         } else if (!textview->text_is_mb && use_fontset) {
1156                 GtkWidget *parent;
1157
1158                 parent = textview->scrolledwin_sb->parent;
1159                 gtkut_container_remove(GTK_CONTAINER(parent),
1160                                        textview->scrolledwin_sb);
1161                 gtk_container_add(GTK_CONTAINER(parent),
1162                                   textview->scrolledwin_mb);
1163
1164                 textview->text = textview->text_mb;
1165                 textview->text_is_mb = TRUE;
1166         }
1167
1168         if (prefs_common.textfont) {
1169                 GdkFont *font;
1170
1171                 if (use_fontset) {
1172                         if (text_mb_font) {
1173                                 text_mb_font->ascent = text_mb_font_orig_ascent;
1174                                 text_mb_font->descent = text_mb_font_orig_descent;
1175                         }
1176                         font = gdk_fontset_load(prefs_common.textfont);
1177                         if (font && text_mb_font != font) {
1178                                 if (text_mb_font)
1179                                         gdk_font_unref(text_mb_font);
1180                                 text_mb_font = font;
1181                                 text_mb_font_orig_ascent = font->ascent;
1182                                 text_mb_font_orig_descent = font->descent;
1183                         }
1184                 } else {
1185                         if (text_sb_font) {
1186                                 text_sb_font->ascent = text_sb_font_orig_ascent;
1187                                 text_sb_font->descent = text_sb_font_orig_descent;
1188                         }
1189                         if (MB_CUR_MAX > 1) {
1190                                 FONT_LOAD(font, "-*-courier-medium-r-normal--14-*-*-*-*-*-iso8859-1");
1191                         } else {
1192                                 FONT_LOAD(font, prefs_common.textfont);
1193                         }
1194                         if (font && text_sb_font != font) {
1195                                 if (text_sb_font)
1196                                         gdk_font_unref(text_sb_font);
1197                                 text_sb_font = font;
1198                                 text_sb_font_orig_ascent = font->ascent;
1199                                 text_sb_font_orig_descent = font->descent;
1200                         }
1201                 }
1202
1203                 if (font) {
1204                         gint ascent, descent;
1205
1206                         descent = prefs_common.line_space / 2;
1207                         ascent  = prefs_common.line_space - descent;
1208                         font->ascent  += ascent;
1209                         font->descent += descent;
1210
1211                         if (textview->msgfont)
1212                                 gdk_font_unref(textview->msgfont);
1213                         textview->msgfont = font;
1214                         gdk_font_ref(font);
1215                 }
1216         }
1217
1218         if (!textview->boldfont && prefs_common.boldfont)
1219                 FONT_LOAD(textview->boldfont, prefs_common.boldfont);
1220         if (!spacingfont)
1221                 spacingfont = gdk_font_load("-*-*-medium-r-normal--6-*");
1222 }
1223
1224 enum
1225 {
1226         H_DATE          = 0,
1227         H_FROM          = 1,
1228         H_TO            = 2,
1229         H_NEWSGROUPS    = 3,
1230         H_SUBJECT       = 4,
1231         H_CC            = 5,
1232         H_REPLY_TO      = 6,
1233         H_FOLLOWUP_TO   = 7,
1234         H_X_MAILER      = 8,
1235         H_X_NEWSREADER  = 9,
1236         H_USER_AGENT    = 10,
1237         H_ORGANIZATION  = 11,
1238 };
1239
1240 void textview_set_position(TextView *textview, gint pos)
1241 {
1242         if (pos < 0) {
1243                 textview->cur_pos =
1244                         gtk_stext_get_length(GTK_STEXT(textview->text));
1245         } else {
1246                 textview->cur_pos = pos;
1247         }
1248 }
1249
1250 static GPtrArray *textview_scan_header(TextView *textview, FILE *fp)
1251 {
1252         gchar buf[BUFFSIZE];
1253         GPtrArray *headers, *sorted_headers;
1254         GSList *disphdr_list;
1255         Header *header;
1256         gint i;
1257
1258         g_return_val_if_fail(fp != NULL, NULL);
1259
1260         if (textview->show_all_headers)
1261                 return procheader_get_header_array_asis(fp);
1262
1263         if (!prefs_common.display_header) {
1264                 while (fgets(buf, sizeof(buf), fp) != NULL)
1265                         if (buf[0] == '\r' || buf[0] == '\n') break;
1266                 return NULL;
1267         }
1268
1269         headers = procheader_get_header_array_asis(fp);
1270
1271         sorted_headers = g_ptr_array_new();
1272
1273         for (disphdr_list = prefs_common.disphdr_list; disphdr_list != NULL;
1274              disphdr_list = disphdr_list->next) {
1275                 DisplayHeaderProp *dp =
1276                         (DisplayHeaderProp *)disphdr_list->data;
1277
1278                 for (i = 0; i < headers->len; i++) {
1279                         header = g_ptr_array_index(headers, i);
1280
1281                         if (procheader_headername_equal(header->name,
1282                                                         dp->name)) {
1283                                 if (dp->hidden)
1284                                         procheader_header_free(header);
1285                                 else
1286                                         g_ptr_array_add(sorted_headers, header);
1287
1288                                 g_ptr_array_remove_index(headers, i);
1289                                 i--;
1290                         }
1291                 }
1292         }
1293
1294         if (prefs_common.show_other_header) {
1295                 for (i = 0; i < headers->len; i++) {
1296                         header = g_ptr_array_index(headers, i);
1297                         g_ptr_array_add(sorted_headers, header);
1298                 }
1299         }
1300
1301         g_ptr_array_free(headers, FALSE);
1302
1303         return sorted_headers;
1304 }
1305
1306 static void textview_show_header(TextView *textview, GPtrArray *headers)
1307 {
1308         GtkSText *text = GTK_STEXT(textview->text);
1309         Header *header;
1310         gint i;
1311
1312         g_return_if_fail(headers != NULL);
1313
1314         gtk_stext_freeze(text);
1315
1316         for (i = 0; i < headers->len; i++) {
1317                 header = g_ptr_array_index(headers, i);
1318                 g_return_if_fail(header->name != NULL);
1319
1320                 gtk_stext_insert(text, textview->boldfont, NULL, NULL,
1321                                 header->name, -1);
1322                 if (header->name[strlen(header->name) - 1] != ' ')
1323                         gtk_stext_insert(text, textview->boldfont,
1324                                         NULL, NULL, " ", 1);
1325
1326                 if (procheader_headername_equal(header->name, "Subject") ||
1327                     procheader_headername_equal(header->name, "From")    ||
1328                     procheader_headername_equal(header->name, "To")      ||
1329                     procheader_headername_equal(header->name, "Cc"))
1330                         unfold_line(header->body);
1331
1332                 if (prefs_common.enable_color &&
1333                     (procheader_headername_equal(header->name, "X-Mailer") ||
1334                      procheader_headername_equal(header->name,
1335                                                  "X-Newsreader")) &&
1336                     strstr(header->body, "Sylpheed") != NULL)
1337                         gtk_stext_insert(text, NULL, &emphasis_color, NULL,
1338                                         header->body, -1);
1339                 else if (prefs_common.enable_color) {
1340                         textview_make_clickable_parts(textview,
1341                                                       NULL, NULL, &uri_color,
1342                                                       header->body);
1343                 } else {
1344                         textview_make_clickable_parts(textview,
1345                                                       NULL, NULL, NULL,
1346                                                       header->body);
1347                 }
1348                 gtk_stext_insert(text, textview->msgfont, NULL, NULL, "\n", 1);
1349         }
1350
1351         gtk_stext_thaw(text);
1352 }
1353
1354 gboolean textview_search_string(TextView *textview, const gchar *str,
1355                                 gboolean case_sens)
1356 {
1357         GtkSText *text = GTK_STEXT(textview->text);
1358         gint pos;
1359         wchar_t *wcs;
1360         gint len;
1361         gint text_len;
1362         gboolean found = FALSE;
1363
1364         g_return_val_if_fail(str != NULL, FALSE);
1365
1366         wcs = strdup_mbstowcs(str);
1367         g_return_val_if_fail(wcs != NULL, FALSE);
1368         len = wcslen(wcs);
1369         pos = textview->cur_pos;
1370         if (pos < textview->body_pos)
1371                 pos = textview->body_pos;
1372         text_len = gtk_stext_get_length(text);
1373         if (text_len - pos < len) {
1374                 g_free(wcs);
1375                 return FALSE;
1376         }
1377
1378         for (; pos < text_len; pos++) {
1379                 if (text_len - pos < len) break;
1380                 if (gtkut_stext_match_string(text, pos, wcs, len, case_sens)
1381                     == TRUE) {
1382                         gtk_widget_hide(GTK_WIDGET(textview->scrolledwin));
1383                         gtk_editable_set_position(GTK_EDITABLE(text),
1384                                                   pos + len);
1385                         gtk_editable_select_region(GTK_EDITABLE(text),
1386                                                    pos, pos + len);
1387                         gtk_widget_show(GTK_WIDGET(textview->scrolledwin));
1388                         textview_set_position(textview, pos + len);
1389                         found = TRUE;
1390                         break;
1391                 }
1392                 if (text_len - pos == len) break;
1393         }
1394         g_free(wcs);
1395         return found;
1396 }
1397
1398 gboolean textview_search_string_backward(TextView *textview, const gchar *str,
1399                                          gboolean case_sens)
1400 {
1401         GtkSText *text = GTK_STEXT(textview->text);
1402         gint pos;
1403         wchar_t *wcs;
1404         gint len;
1405         gint text_len;
1406         gboolean found = FALSE;
1407
1408         g_return_val_if_fail(str != NULL, FALSE);
1409
1410         wcs = strdup_mbstowcs(str);
1411         g_return_val_if_fail(wcs != NULL, FALSE);
1412         len = wcslen(wcs);
1413         pos = textview->cur_pos;
1414         text_len = gtk_stext_get_length(text);
1415         if (text_len - textview->body_pos < len) {
1416                 g_free(wcs);
1417                 return FALSE;
1418         }
1419         if (pos <= textview->body_pos || text_len - pos < len)
1420                 pos = text_len - len;
1421
1422         for (; pos >= textview->body_pos; pos--) {
1423                 if (gtkut_stext_match_string(text, pos, wcs, len, case_sens)
1424                     == TRUE) {
1425                         gtk_editable_set_position(GTK_EDITABLE(text), pos);
1426                         gtk_editable_select_region(GTK_EDITABLE(text),
1427                                                    pos, pos + len);
1428                         textview_set_position(textview, pos - 1);
1429                         found = TRUE;
1430                         break;
1431                 }
1432                 if (pos == textview->body_pos) break;
1433         }
1434
1435         g_free(wcs);
1436         return found;
1437 }
1438
1439 void textview_scroll_one_line(TextView *textview, gboolean up)
1440 {
1441         GtkSText *text = GTK_STEXT(textview->text);
1442         gfloat upper;
1443
1444         if (prefs_common.enable_smooth_scroll) {
1445                 textview_smooth_scroll_one_line(textview, up);
1446                 return;
1447         }
1448
1449         if (!up) {
1450                 upper = text->vadj->upper - text->vadj->page_size;
1451                 if (text->vadj->value < upper) {
1452                         text->vadj->value +=
1453                                 text->vadj->step_increment * 4;
1454                         text->vadj->value =
1455                                 MIN(text->vadj->value, upper);
1456                         gtk_signal_emit_by_name(GTK_OBJECT(text->vadj),
1457                                                 "value_changed");
1458                 }
1459         } else {
1460                 if (text->vadj->value > 0.0) {
1461                         text->vadj->value -=
1462                                 text->vadj->step_increment * 4;
1463                         text->vadj->value =
1464                                 MAX(text->vadj->value, 0.0);
1465                         gtk_signal_emit_by_name(GTK_OBJECT(text->vadj),
1466                                                 "value_changed");
1467                 }
1468         }
1469 }
1470
1471 gboolean textview_scroll_page(TextView *textview, gboolean up)
1472 {
1473         GtkSText *text = GTK_STEXT(textview->text);
1474         gfloat upper;
1475         gfloat page_incr;
1476
1477         if (prefs_common.enable_smooth_scroll)
1478                 return textview_smooth_scroll_page(textview, up);
1479
1480         if (prefs_common.scroll_halfpage)
1481                 page_incr = text->vadj->page_increment / 2;
1482         else
1483                 page_incr = text->vadj->page_increment;
1484
1485         if (!up) {
1486                 upper = text->vadj->upper - text->vadj->page_size;
1487                 if (text->vadj->value < upper) {
1488                         text->vadj->value += page_incr;
1489                         text->vadj->value = MIN(text->vadj->value, upper);
1490                         gtk_signal_emit_by_name(GTK_OBJECT(text->vadj),
1491                                                 "value_changed");
1492                 } else
1493                         return FALSE;
1494         } else {
1495                 if (text->vadj->value > 0.0) {
1496                         text->vadj->value -= page_incr;
1497                         text->vadj->value = MAX(text->vadj->value, 0.0);
1498                         gtk_signal_emit_by_name(GTK_OBJECT(text->vadj),
1499                                                 "value_changed");
1500                 } else
1501                         return FALSE;
1502         }
1503
1504         return TRUE;
1505 }
1506
1507 static void textview_smooth_scroll_do(TextView *textview,
1508                                       gfloat old_value, gfloat last_value,
1509                                       gint step)
1510 {
1511         GtkSText *text = GTK_STEXT(textview->text);
1512         gint change_value;
1513         gboolean up;
1514         gint i;
1515
1516         if (old_value < last_value) {
1517                 change_value = last_value - old_value;
1518                 up = FALSE;
1519         } else {
1520                 change_value = old_value - last_value;
1521                 up = TRUE;
1522         }
1523
1524         gdk_key_repeat_disable();
1525
1526         for (i = step; i <= change_value; i += step) {
1527                 text->vadj->value = old_value + (up ? -i : i);
1528                 gtk_signal_emit_by_name(GTK_OBJECT(text->vadj),
1529                                         "value_changed");
1530         }
1531
1532         text->vadj->value = last_value;
1533         gtk_signal_emit_by_name(GTK_OBJECT(text->vadj), "value_changed");
1534
1535         gdk_key_repeat_restore();
1536 }
1537
1538 static void textview_smooth_scroll_one_line(TextView *textview, gboolean up)
1539 {
1540         GtkSText *text = GTK_STEXT(textview->text);
1541         gfloat upper;
1542         gfloat old_value;
1543         gfloat last_value;
1544
1545         if (!up) {
1546                 upper = text->vadj->upper - text->vadj->page_size;
1547                 if (text->vadj->value < upper) {
1548                         old_value = text->vadj->value;
1549                         last_value = text->vadj->value +
1550                                 text->vadj->step_increment * 4;
1551                         last_value = MIN(last_value, upper);
1552
1553                         textview_smooth_scroll_do(textview, old_value,
1554                                                   last_value,
1555                                                   prefs_common.scroll_step);
1556                 }
1557         } else {
1558                 if (text->vadj->value > 0.0) {
1559                         old_value = text->vadj->value;
1560                         last_value = text->vadj->value -
1561                                 text->vadj->step_increment * 4;
1562                         last_value = MAX(last_value, 0.0);
1563
1564                         textview_smooth_scroll_do(textview, old_value,
1565                                                   last_value,
1566                                                   prefs_common.scroll_step);
1567                 }
1568         }
1569 }
1570
1571 static gboolean textview_smooth_scroll_page(TextView *textview, gboolean up)
1572 {
1573         GtkSText *text = GTK_STEXT(textview->text);
1574         gfloat upper;
1575         gfloat page_incr;
1576         gfloat old_value;
1577         gfloat last_value;
1578
1579         if (prefs_common.scroll_halfpage)
1580                 page_incr = text->vadj->page_increment / 2;
1581         else
1582                 page_incr = text->vadj->page_increment;
1583
1584         if (!up) {
1585                 upper = text->vadj->upper - text->vadj->page_size;
1586                 if (text->vadj->value < upper) {
1587                         old_value = text->vadj->value;
1588                         last_value = text->vadj->value + page_incr;
1589                         last_value = MIN(last_value, upper);
1590
1591                         textview_smooth_scroll_do(textview, old_value,
1592                                                   last_value,
1593                                                   prefs_common.scroll_step);
1594                 } else
1595                         return FALSE;
1596         } else {
1597                 if (text->vadj->value > 0.0) {
1598                         old_value = text->vadj->value;
1599                         last_value = text->vadj->value - page_incr;
1600                         last_value = MAX(last_value, 0.0);
1601
1602                         textview_smooth_scroll_do(textview, old_value,
1603                                                   last_value,
1604                                                   prefs_common.scroll_step);
1605                 } else
1606                         return FALSE;
1607         }
1608
1609         return TRUE;
1610 }
1611
1612 #define KEY_PRESS_EVENT_STOP() \
1613         if (gtk_signal_n_emissions_by_name \
1614                 (GTK_OBJECT(widget), "key_press_event") > 0) { \
1615                 gtk_signal_emit_stop_by_name(GTK_OBJECT(widget), \
1616                                              "key_press_event"); \
1617         }
1618
1619 static gint textview_key_pressed(GtkWidget *widget, GdkEventKey *event,
1620                                  TextView *textview)
1621 {
1622         SummaryView *summaryview = NULL;
1623         MessageView *messageview = textview->messageview;
1624
1625         if (!event) return FALSE;
1626         if (messageview->mainwin)
1627                 summaryview = messageview->mainwin->summaryview;
1628
1629         switch (event->keyval) {
1630         case GDK_Tab:
1631         case GDK_Home:
1632         case GDK_Left:
1633         case GDK_Up:
1634         case GDK_Right:
1635         case GDK_Down:
1636         case GDK_Page_Up:
1637         case GDK_Page_Down:
1638         case GDK_End:
1639         case GDK_Control_L:
1640         case GDK_Control_R:
1641                 break;
1642         case GDK_space:
1643                 if (summaryview)
1644                         summary_pass_key_press_event(summaryview, event);
1645                 else
1646                         textview_scroll_page(textview, FALSE);
1647                 break;
1648         case GDK_BackSpace:
1649                 textview_scroll_page(textview, TRUE);
1650                 break;
1651         case GDK_Return:
1652                 textview_scroll_one_line(textview,
1653                                          (event->state & GDK_MOD1_MASK) != 0);
1654                 break;
1655         case GDK_n:
1656         case GDK_N:
1657         case GDK_p:
1658         case GDK_P:
1659         case GDK_y:
1660         case GDK_t:
1661         case GDK_l:
1662                 if (messageview->type == MVIEW_MIME &&
1663                     textview == messageview->mimeview->textview) {
1664                         KEY_PRESS_EVENT_STOP();
1665                         mimeview_pass_key_press_event(messageview->mimeview,
1666                                                       event);
1667                         break;
1668                 }
1669                 /* fall through */
1670         default:
1671                 if (summaryview &&
1672                     event->window != messageview->mainwin->window->window) {
1673                         GdkEventKey tmpev = *event;
1674
1675                         tmpev.window = messageview->mainwin->window->window;
1676                         KEY_PRESS_EVENT_STOP();
1677                         gtk_widget_event(messageview->mainwin->window,
1678                                          (GdkEvent *)&tmpev);
1679                 }
1680                 break;
1681         }
1682
1683         return TRUE;
1684 }
1685
1686 static gint show_url_timeout_cb(gpointer data)
1687 {
1688         TextView *textview = (TextView *)data;
1689         
1690         if (textview->messageview->mainwin)
1691                 if (textview->show_url_msgid)
1692                         gtk_statusbar_remove(GTK_STATUSBAR(
1693                                 textview->messageview->mainwin->statusbar),
1694                                 textview->messageview->mainwin->folderview_cid,
1695                                 textview->show_url_msgid);
1696                 return FALSE;
1697 }
1698
1699 static gint textview_button_pressed(GtkWidget *widget, GdkEventButton *event,
1700                                     TextView *textview)
1701 {
1702         if (event)
1703                 textview->last_buttonpress = event->type;
1704         return FALSE;
1705 }
1706
1707 static gint textview_button_released(GtkWidget *widget, GdkEventButton *event,
1708                                     TextView *textview)
1709 {
1710         textview->cur_pos = 
1711                 gtk_editable_get_position(GTK_EDITABLE(textview->text));
1712
1713         if (event && 
1714             ((event->button == 1)
1715              || event->button == 2 || event->button == 3)) {
1716                 GSList *cur;
1717
1718                 /* double click seems to set the cursor after the current
1719                  * word. The cursor position needs fixing, otherwise the
1720                  * last word of a clickable zone will not work */
1721                 if (event->button == 1 && textview->last_buttonpress == GDK_2BUTTON_PRESS) {
1722                         textview->cur_pos--;
1723                 }
1724
1725                 for (cur = textview->uri_list; cur != NULL; cur = cur->next) {
1726                         RemoteURI *uri = (RemoteURI *)cur->data;
1727
1728                         if (textview->cur_pos >= uri->start &&
1729                             textview->cur_pos <  uri->end) {
1730                                 /* single click: display url in statusbar */
1731                                 if (event->button == 1 && textview->last_buttonpress != GDK_2BUTTON_PRESS) {
1732                                         if (textview->messageview->mainwin) {
1733                                                 if (textview->show_url_msgid) {
1734                                                         gtk_timeout_remove(textview->show_url_timeout_tag);
1735                                                         gtk_statusbar_remove(GTK_STATUSBAR(
1736                                                                 textview->messageview->mainwin->statusbar),
1737                                                                 textview->messageview->mainwin->folderview_cid,
1738                                                                 textview->show_url_msgid);
1739                                                         textview->show_url_msgid = 0;
1740                                                 }
1741                                                 textview->show_url_msgid = gtk_statusbar_push(
1742                                                                 GTK_STATUSBAR(textview->messageview->mainwin->statusbar),
1743                                                                 textview->messageview->mainwin->folderview_cid,
1744                                                                 uri->uri);
1745                                                 textview->show_url_timeout_tag = gtk_timeout_add( 4000, show_url_timeout_cb, textview );
1746                                                 gtkut_widget_wait_for_draw(textview->messageview->mainwin->hbox_stat);
1747                                         }
1748                                 } else
1749                                 if (!g_strncasecmp(uri->uri, "mailto:", 7)) {
1750                                         if (event->button == 3) {
1751                                                 gchar *fromname, *fromaddress;
1752                                                 
1753                                                 /* extract url */
1754                                                 fromaddress = g_strdup(uri->uri + 7);
1755                                                 /* Hiroyuki: please put this function in utils.c! */
1756                                                 fromname = procheader_get_fromname(fromaddress);
1757                                                 extract_address(fromaddress);
1758                                                 g_message("adding from textview %s <%s>", fromname, fromaddress);
1759                                                 /* Add to address book - Match */
1760                                                 addressbook_add_contact( fromname, fromaddress, NULL );
1761                                                 
1762                                                 g_free(fromaddress);
1763                                                 g_free(fromname);
1764                                         } else {
1765                                                 PrefsAccount *account = NULL;
1766                                                 FolderItem   *folder_item;
1767
1768                                                 if (textview->messageview && textview->messageview->mainwin 
1769                                                 &&  textview->messageview->mainwin->summaryview 
1770                                                 &&  textview->messageview->mainwin->summaryview->folder_item) {
1771                                                         folder_item = textview->messageview->mainwin->summaryview->folder_item;
1772                                                         if (folder_item->prefs && folder_item->prefs->enable_default_account)
1773                                                                 account = account_find_from_id(folder_item->prefs->default_account);
1774                                                 }
1775                                                 compose_new_with_recipient
1776                                                         (account, uri->uri + 7);
1777                                         }
1778                                 } else {
1779                                         open_uri(uri->uri,
1780                                                  prefs_common.uri_cmd);
1781                                 }
1782                         }
1783                 }
1784         }
1785         if (event)
1786                 textview->last_buttonpress = event->type;
1787         return FALSE;
1788 }
1789
1790 static void textview_uri_list_remove_all(GSList *uri_list)
1791 {
1792         GSList *cur;
1793
1794         for (cur = uri_list; cur != NULL; cur = cur->next) {
1795                 if (cur->data) {
1796                         g_free(((RemoteURI *)cur->data)->uri);
1797                         g_free(cur->data);
1798                 }
1799         }
1800
1801         g_slist_free(uri_list);
1802 }