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