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