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