fixed bug for US-ASCII introduced by the encoding code
[claws.git] / src / textview.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2001 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/gtktext.h>
32 #include <gtk/gtksignal.h>
33 #include <stdio.h>
34 #include <ctype.h>
35 #include <string.h>
36 #include <stdlib.h>
37
38 #include "intl.h"
39 #include "main.h"
40 #include "summaryview.h"
41 #include "procheader.h"
42 #include "prefs_common.h"
43 #include "codeconv.h"
44 #include "utils.h"
45 #include "gtkutils.h"
46 #include "procmime.h"
47 #include "html.h"
48 #include "compose.h"
49 #include "addressbook.h"
50 #include "displayheader.h"
51
52 #define FONT_LOAD(font, s) \
53 { \
54         gchar *fontstr, *p; \
55  \
56         Xstrdup_a(fontstr, s, ); \
57         if ((p = strchr(fontstr, ',')) != NULL) *p = '\0'; \
58         font = gdk_font_load(fontstr); \
59 }
60
61 typedef struct _RemoteURI       RemoteURI;
62
63 struct _RemoteURI
64 {
65         gchar *uri;
66
67         guint start;
68         guint end;
69 };
70
71 static GdkColor quote_colors[3] = {
72         {(gulong)0, (gushort)0, (gushort)0, (gushort)0},
73         {(gulong)0, (gushort)0, (gushort)0, (gushort)0},
74         {(gulong)0, (gushort)0, (gushort)0, (gushort)0}
75 };
76
77 static GdkColor uri_color = {
78         (gulong)0,
79         (gushort)0,
80         (gushort)0,
81         (gushort)0
82 };
83
84 static GdkColor emphasis_color = {
85         (gulong)0,
86         (gushort)0,
87         (gushort)0,
88         (gushort)0xcfff
89 };
90
91 static GdkColor error_color = {
92         (gulong)0,
93         (gushort)0xefff,
94         (gushort)0,
95         (gushort)0
96 };
97
98 static GdkFont *spacingfont;
99
100 static void textview_show_html          (TextView       *textview,
101                                          FILE           *fp,
102                                          CodeConverter  *conv);
103 static void textview_write_line         (TextView       *textview,
104                                          const gchar    *str,
105                                          CodeConverter  *conv);
106 static GPtrArray *textview_scan_header  (TextView       *textview,
107                                          FILE           *fp);
108 static void textview_show_header        (TextView       *textview,
109                                          GPtrArray      *headers);
110
111 static void textview_key_pressed        (GtkWidget      *widget,
112                                          GdkEventKey    *event,
113                                          TextView       *textview);
114 static void textview_button_pressed     (GtkWidget      *widget,
115                                          GdkEventButton *event,
116                                          TextView       *textview);
117
118 static void textview_uri_list_remove_all(GSList         *uri_list);
119
120 static void textview_smooth_scroll_do           (TextView       *textview,
121                                                  gfloat          old_value,
122                                                  gfloat          last_value,
123                                                  gint            step);
124 static void textview_smooth_scroll_one_line     (TextView       *textview,
125                                                  gboolean        up);
126 static gboolean textview_smooth_scroll_page     (TextView       *textview,
127                                                  gboolean        up);
128
129
130 TextView *textview_create(void)
131 {
132         TextView *textview;
133         GtkWidget *vbox;
134         GtkWidget *scrolledwin_sb;
135         GtkWidget *scrolledwin_mb;
136         GtkWidget *text_sb;
137         GtkWidget *text_mb;
138
139         debug_print(_("Creating text view...\n"));
140         textview = g_new0(TextView, 1);
141
142         scrolledwin_sb = gtk_scrolled_window_new(NULL, NULL);
143         scrolledwin_mb = gtk_scrolled_window_new(NULL, NULL);
144         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledwin_sb),
145                                        GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
146         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledwin_mb),
147                                        GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
148         gtk_widget_set_usize(scrolledwin_sb, prefs_common.mainview_width, -1);
149         gtk_widget_set_usize(scrolledwin_mb, prefs_common.mainview_width, -1);
150
151         /* create GtkText widgets for single-byte and multi-byte character */
152         text_sb = gtk_text_new(NULL, NULL);
153         text_mb = gtk_text_new(NULL, NULL);
154         GTK_TEXT(text_sb)->default_tab_width = 8;
155         GTK_TEXT(text_mb)->default_tab_width = 8;
156         gtk_widget_show(text_sb);
157         gtk_widget_show(text_mb);
158         gtk_text_set_word_wrap(GTK_TEXT(text_sb), TRUE);
159         gtk_text_set_word_wrap(GTK_TEXT(text_mb), TRUE);
160         gtk_widget_ensure_style(text_sb);
161         gtk_widget_ensure_style(text_mb);
162         if (text_sb->style && text_sb->style->font->type == GDK_FONT_FONTSET) {
163                 GtkStyle *style;
164
165                 style = gtk_style_copy(text_sb->style);
166                 gdk_font_unref(style->font);
167                 FONT_LOAD(style->font, NORMAL_FONT);
168                 gtk_widget_set_style(text_sb, style);
169         }
170         if (text_mb->style && text_mb->style->font->type == GDK_FONT_FONT) {
171                 GtkStyle *style;
172
173                 style = gtk_style_copy(text_mb->style);
174                 gdk_font_unref(style->font);
175                 style->font = gdk_fontset_load(NORMAL_FONT);
176                 gtk_widget_set_style(text_mb, style);
177         }
178         gtk_widget_ref(scrolledwin_sb);
179         gtk_widget_ref(scrolledwin_mb);
180
181         gtk_container_add(GTK_CONTAINER(scrolledwin_sb), text_sb);
182         gtk_container_add(GTK_CONTAINER(scrolledwin_mb), text_mb);
183         gtk_signal_connect(GTK_OBJECT(text_sb), "key_press_event",
184                            GTK_SIGNAL_FUNC(textview_key_pressed),
185                            textview);
186         gtk_signal_connect(GTK_OBJECT(text_sb), "button_press_event",
187                            GTK_SIGNAL_FUNC(textview_button_pressed),
188                            textview);
189         gtk_signal_connect(GTK_OBJECT(text_mb), "key_press_event",
190                            GTK_SIGNAL_FUNC(textview_key_pressed),
191                            textview);
192         gtk_signal_connect(GTK_OBJECT(text_mb), "button_press_event",
193                            GTK_SIGNAL_FUNC(textview_button_pressed),
194                            textview);
195
196         gtk_widget_show(scrolledwin_sb);
197         gtk_widget_show(scrolledwin_mb);
198
199         vbox = gtk_vbox_new(FALSE, 0);
200         gtk_box_pack_start(GTK_BOX(vbox), scrolledwin_sb, TRUE, TRUE, 0);
201
202         textview->vbox           = vbox;
203         textview->scrolledwin    = scrolledwin_sb;
204         textview->scrolledwin_sb = scrolledwin_sb;
205         textview->scrolledwin_mb = scrolledwin_mb;
206         textview->text           = text_sb;
207         textview->text_sb        = text_sb;
208         textview->text_mb        = text_mb;
209         textview->text_is_mb     = FALSE;
210         textview->uri_list       = NULL;
211         textview->body_pos       = 0;
212
213         return textview;
214 }
215
216 void textview_init(TextView *textview)
217 {
218         gtkut_widget_disable_theme_engine(textview->text_sb);
219         gtkut_widget_disable_theme_engine(textview->text_mb);
220         textview_update_message_colors();
221         textview_set_font(textview, NULL);
222 }
223
224 void textview_update_message_colors(void)
225 {
226         GdkColor black = {0, 0, 0, 0};
227
228         if (prefs_common.enable_color) {
229                 /* grab the quote colors, converting from an int to a GdkColor */
230                 gtkut_convert_int_to_gdk_color(prefs_common.quote_level1_col,
231                                                &quote_colors[0]);
232                 gtkut_convert_int_to_gdk_color(prefs_common.quote_level2_col,
233                                                &quote_colors[1]);
234                 gtkut_convert_int_to_gdk_color(prefs_common.quote_level3_col,
235                                                &quote_colors[2]);
236                 gtkut_convert_int_to_gdk_color(prefs_common.uri_col,
237                                                &uri_color);
238         } else {
239                 quote_colors[0] = quote_colors[1] = quote_colors[2] = 
240                         uri_color = emphasis_color = black;
241         }
242 }
243
244 void textview_show_message(TextView *textview, MimeInfo *mimeinfo,
245                            const gchar *file)
246 {
247         FILE *fp;
248
249         if ((fp = fopen(file, "r")) == NULL) {
250                 FILE_OP_ERROR(file, "fopen");
251                 return;
252         }
253
254         textview_show_part(textview, mimeinfo, fp);
255
256         fclose(fp);
257 }
258
259 void textview_show_part(TextView *textview, MimeInfo *mimeinfo, FILE *fp)
260 {
261         GtkText *text;
262         gchar buf[BUFFSIZE];
263         const gchar *boundary = NULL;
264         gint boundary_len = 0;
265         const gchar *charset = NULL;
266         FILE *tmpfp;
267         GPtrArray *headers = NULL;
268         CodeConverter *conv;
269
270         g_return_if_fail(mimeinfo != NULL);
271         g_return_if_fail(fp != NULL);
272
273         if (mimeinfo->mime_type == MIME_MULTIPART) {
274                 if (mimeinfo->sub) {
275                         mimeinfo = mimeinfo->sub;
276                         if (fseek(fp, mimeinfo->fpos, SEEK_SET) < 0) {
277                                 perror("fseek");
278                                 return;
279                         }
280                 } else
281                         return;
282         }
283         if (mimeinfo->parent && mimeinfo->parent->boundary) {
284                 boundary = mimeinfo->parent->boundary;
285                 boundary_len = strlen(boundary);
286         }
287
288         if (!boundary && mimeinfo->mime_type == MIME_TEXT) {
289                 if (fseek(fp, mimeinfo->fpos, SEEK_SET) < 0)
290                         perror("fseek");
291                 headers = textview_scan_header(textview, fp);
292         } else {
293                 if (mimeinfo->mime_type == MIME_TEXT && mimeinfo->parent) {
294                         glong fpos;
295
296                         if ((fpos = ftell(fp)) < 0)
297                                 perror("ftell");
298                         else if (fseek(fp, mimeinfo->parent->fpos, SEEK_SET)
299                                  < 0)
300                                 perror("fseek");
301                         else {
302                                 headers = textview_scan_header(textview, fp);
303                                 if (fseek(fp, fpos, SEEK_SET) < 0)
304                                         perror("fseek");
305                         }
306                 }
307                 while (fgets(buf, sizeof(buf), fp) != NULL)
308                         if (buf[0] == '\r' || buf[0] == '\n') break;
309         }
310
311         /* display attached RFC822 single text message */
312         if (mimeinfo->parent && mimeinfo->mime_type == MIME_MESSAGE_RFC822) {
313                 if (headers) procheader_header_array_destroy(headers);
314                 if (!mimeinfo->sub || mimeinfo->sub->children) return;
315                 headers = textview_scan_header(textview, fp);
316                 mimeinfo = mimeinfo->sub;
317         } else if (!mimeinfo->parent &&
318                    mimeinfo->mime_type == MIME_MESSAGE_RFC822) {
319                 if (headers) procheader_header_array_destroy(headers);
320                 if (!mimeinfo->sub) return;
321                 headers = textview_scan_header(textview, fp);
322                 mimeinfo = mimeinfo->sub;
323         }
324
325         if (prefs_common.force_charset)
326                 charset = prefs_common.force_charset;
327         else if (mimeinfo->charset)
328                 charset = mimeinfo->charset;
329         textview_set_font(textview, charset);
330
331         conv = conv_code_converter_new(charset);
332
333         textview_clear(textview);
334         text = GTK_TEXT(textview->text);
335         gtk_text_freeze(text);
336
337         textview->body_pos = 0;
338
339         if (headers) {
340                 textview_show_header(textview, headers);
341                 procheader_header_array_destroy(headers);
342         }
343
344         tmpfp = procmime_decode_content(NULL, fp, mimeinfo);
345         if (tmpfp) {
346                 if (mimeinfo->mime_type == MIME_TEXT_HTML)
347                         textview_show_html(textview, tmpfp, conv);
348                 else
349                         while (fgets(buf, sizeof(buf), tmpfp) != NULL)
350                                 textview_write_line(textview, buf, conv);
351                 fclose(tmpfp);
352         }
353
354         conv_code_converter_destroy(conv);
355
356         gtk_text_thaw(text);
357 }
358
359 #define TEXT_INSERT(str) \
360         gtk_text_insert(text, textview->msgfont, NULL, NULL, str, -1)
361
362 void textview_show_mime_part(TextView *textview, MimeInfo *partinfo)
363 {
364         GtkText *text;
365
366         if (!partinfo) return;
367
368         textview_set_font(textview, NULL);
369         text = GTK_TEXT(textview->text);
370         textview_clear(textview);
371
372         gtk_text_freeze(text);
373
374         TEXT_INSERT(_("To save this part, pop up the context menu with "));
375         TEXT_INSERT(_("right click and select `Save as...', "));
376         TEXT_INSERT(_("or press `y' key.\n\n"));
377
378         TEXT_INSERT(_("To display this part as a text message, select "));
379         TEXT_INSERT(_("`Display as text', or press `t' key.\n\n"));
380
381         TEXT_INSERT(_("To open this part with external program, select "));
382         TEXT_INSERT(_("`Open' or `Open with...', "));
383         TEXT_INSERT(_("or double-click, or click the center button, "));
384         TEXT_INSERT(_("or press `l' key."));
385
386         gtk_text_thaw(text);
387 }
388
389 #if USE_GPGME
390 void textview_show_signature_part(TextView *textview, MimeInfo *partinfo)
391 {
392         GtkText *text;
393
394         if (!partinfo) return;
395
396         textview_set_font(textview, NULL);
397         text = GTK_TEXT(textview->text);
398         textview_clear(textview);
399
400         gtk_text_freeze(text);
401
402         if (partinfo->sigstatus_full == NULL) {
403                 TEXT_INSERT(_("This signature has not been checked yet.\n"));
404                 TEXT_INSERT(_("To check it, pop up the context menu with\n"));
405                 TEXT_INSERT(_("right click and select `Check signature'.\n"));
406         } else {
407                 TEXT_INSERT(partinfo->sigstatus_full);
408         }
409
410         gtk_text_thaw(text);
411 }
412 #endif /* USE_GPGME */
413
414 #undef TEXT_INSERT
415
416 static void textview_show_html(TextView *textview, FILE *fp,
417                                CodeConverter *conv)
418 {
419         HTMLParser *parser;
420         gchar *str;
421
422         parser = html_parser_new(fp, conv);
423         g_return_if_fail(parser != NULL);
424
425         while ((str = html_parse(parser)) != NULL) {
426                 textview_write_line(textview, str, NULL);
427         }
428         html_parser_destroy(parser);
429 }
430
431 /* get_uri_part() - retrieves a URI starting from scanpos.
432                     Returns TRUE if succesful */
433 static gboolean get_uri_part(const gchar *start, const gchar *scanpos,
434                              const gchar **bp, const gchar **ep)
435 {
436         const gchar *ep_;
437
438         g_return_val_if_fail(start != NULL, FALSE);
439         g_return_val_if_fail(scanpos != NULL, FALSE);
440         g_return_val_if_fail(bp != NULL, FALSE);
441         g_return_val_if_fail(ep != NULL, FALSE);
442
443         *bp = scanpos;
444
445         /* find end point of URI */
446         for (ep_ = scanpos; *ep_ != '\0'; ep_++) {
447                 if (!isgraph(*ep_) || !isascii(*ep_) || strchr("()<>\"", *ep_))
448                         break;
449         }
450
451         /* no punctuation at end of string */
452
453         /* FIXME: this stripping of trailing punctuations may bite with other URIs.
454          * should pass some URI type to this function and decide on that whether
455          * to perform punctuation stripping */
456
457 #define IS_REAL_PUNCT(ch) \
458         (ispunct(ch) && ((ch) != '/')) 
459
460         for (; ep_ - 1 > scanpos + 1 && IS_REAL_PUNCT(*(ep_ - 1)); ep_--)
461                 ;
462
463 #undef IS_REAL_PUNCT
464
465         *ep = ep_;
466
467         return TRUE;            
468 }
469
470 static gchar *make_uri_string(const gchar *bp, const gchar *ep)
471 {
472         return g_strndup(bp, ep - bp);
473 }
474
475 /* valid mail address characters */
476 #define IS_RFC822_CHAR(ch) \
477         (isascii(ch) && \
478          (ch) > 32   && \
479          (ch) != 127 && \
480          !isspace(ch) && \
481          !strchr("()<>\"", (ch)))
482
483 #define IS_QUOTE(ch) ((ch) == '\'' || (ch) == '"')
484
485 /* get_email_part() - retrieves an email address. Returns TRUE if succesful */
486 static gboolean get_email_part(const gchar *start, const gchar *scanpos,
487                                const gchar **bp, const gchar **ep)
488 {
489         /* more complex than the uri part because we need to scan back and forward starting from
490          * the scan position. */
491         gboolean result = FALSE;
492         const gchar *bp_ = NULL;
493         const gchar *ep_ = NULL;
494
495         /* the informative part of the email address (describing the name
496          * of the email address owner) may contain quoted parts. the
497          * closure stack stores the last encountered quotes. */
498         gchar closure_stack[128];
499         gchar *ptr = closure_stack;
500
501         g_return_val_if_fail(start != NULL, FALSE);
502         g_return_val_if_fail(scanpos != NULL, FALSE);
503         g_return_val_if_fail(bp != NULL, FALSE);
504         g_return_val_if_fail(ep != NULL, FALSE);
505
506         /* scan start of address */
507         for (bp_ = scanpos - 1; bp_ >= start && IS_RFC822_CHAR(*bp_); bp_--)
508                 ;
509
510         /* TODO: should start with an alnum? */
511         bp_++;
512         for (; bp_ < scanpos && !isalnum(*bp_); bp_++)
513                 ;
514
515         if (bp_ != scanpos) {
516                 /* scan end of address */
517                 for (ep_ = scanpos + 1; *ep_ && IS_RFC822_CHAR(*ep_); ep_++)
518                         ;
519
520                 /* TODO: really should terminate with an alnum? */
521                 for (; ep_ > scanpos  && !isalnum(*ep_); --ep_)
522                         ;
523                 ep_++;
524
525                 if (ep_ > scanpos + 1) {
526                         *ep = ep_;
527                         *bp = bp_;
528                         result = TRUE;
529                 }
530         }
531
532         if (!result) return FALSE;
533
534         /* skip if it's between quotes "'alfons@proteus.demon.nl'" <alfons@proteus.demon.nl> */
535         if (bp_ - 1 > start && IS_QUOTE(*(bp_ - 1)) && IS_QUOTE(*ep_)) 
536                 return FALSE;
537
538         /* see if this is <bracketed>; in this case we also scan for the informative part. */
539         if (bp_ - 1 <= start || *(bp_ - 1) != '<' || *ep_ != '>')
540                 return TRUE;
541
542 #define FULL_STACK()    ((size_t) (ptr - closure_stack) >= sizeof closure_stack)
543 #define IN_STACK()      (ptr > closure_stack)
544 /* has underrun check */
545 #define POP_STACK()     if(IN_STACK()) --ptr
546 /* has overrun check */
547 #define PUSH_STACK(c)   if(!FULL_STACK()) *ptr++ = (c); else return TRUE
548 /* has underrun check */
549 #define PEEK_STACK()    (IN_STACK() ? *(ptr - 1) : 0)
550
551         ep_++;
552
553         /* scan for the informative part. */
554         for (bp_ -= 2; bp_ >= start; bp_--) {
555                 /* if closure on the stack keep scanning */
556                 if (PEEK_STACK() == *bp_) {
557                         POP_STACK();
558                         continue;
559                 }
560                 if (*bp_ == '\'' || *bp_ == '"') {
561                         PUSH_STACK(*bp_);
562                         continue;
563                 }
564
565                 /* if nothing in the closure stack, do the special conditions
566                  * the following if..else expression simply checks whether 
567                  * a token is acceptable. if not acceptable, the clause
568                  * should terminate the loop with a 'break' */
569                 if (!PEEK_STACK()) {
570                         if (*bp_ == '-'
571                         && (((bp_ - 1) >= start) && isalnum(*(bp_ - 1)))
572                         && (((bp_ + 1) < ep_)    && isalnum(*(bp_ + 1)))) {
573                                 /* hyphens are allowed, but only in
574                                    between alnums */
575                         } else if (!ispunct(*bp_)) {
576                                 /* but anything not being a punctiation
577                                    is ok */
578                         } else {
579                                 break; /* anything else is rejected */
580                         }
581                 }
582         }
583
584         bp_++;
585
586 #undef PEEK_STACK
587 #undef PUSH_STACK
588 #undef POP_STACK
589 #undef IN_STACK
590 #undef FULL_STACK
591
592         /* scan forward (should start with an alnum) */
593         for (; *bp_ != '<' && isspace(*bp_) && *bp_ != '"'; bp_++)
594                 ;
595
596         *ep = ep_;
597         *bp = bp_;
598
599         return result;
600 }
601
602 #undef IS_QUOTE
603 #undef IS_RFC822_CHAR
604
605 static gchar *make_email_string(const gchar *bp, const gchar *ep)
606 {
607         /* returns a mailto: URI; mailto: is also used to detect the
608          * uri type later on in the button_pressed signal handler */
609         gchar *tmp;
610         gchar *result;
611
612         tmp = g_strndup(bp, ep - bp);
613         result = g_strconcat("mailto:", tmp, NULL);
614         g_free(tmp);
615
616         return result;
617 }
618
619 #define ADD_TXT_POS(bp_, ep_, pti_) \
620         if ((last->next = alloca(sizeof(struct txtpos))) != NULL) { \
621                 last = last->next; \
622                 last->bp = (bp_); last->ep = (ep_); last->pti = (pti_); \
623                 last->next = NULL; \
624         } else { \
625                 g_warning("alloc error scanning URIs\n"); \
626                 gtk_text_insert(text, textview->msgfont, fg_color, NULL, \
627                                 linebuf, -1); \
628                 return; \
629         }
630
631 /* textview_make_clickable_parts() - colorizes clickable parts */
632 static void textview_make_clickable_parts(TextView *textview,
633                                           GdkFont *font,
634                                           GdkColor *fg_color,
635                                           GdkColor *uri_color,
636                                           const gchar *linebuf)
637 {
638         /* parse table - in order of priority */
639         struct table {
640                 const gchar *needle; /* token */
641
642                 /* token search function */
643                 gchar    *(*search)     (const gchar *haystack,
644                                          const gchar *needle);
645                 /* part parsing function */
646                 gboolean  (*parse)      (const gchar *start,
647                                          const gchar *scanpos,
648                                          const gchar **bp_,
649                                          const gchar **ep_);
650                 /* part to URI function */
651                 gchar    *(*build_uri)  (const gchar *bp,
652                                          const gchar *ep);
653         };
654
655         static struct table parser[] = {
656                 {"http://",  strcasestr, get_uri_part,   make_uri_string},
657                 {"https://", strcasestr, get_uri_part,   make_uri_string},
658                 {"ftp://",   strcasestr, get_uri_part,   make_uri_string},
659                 {"mailto:",  strcasestr, get_uri_part,   make_uri_string},
660                 {"@",        strcasestr, get_email_part, make_email_string}
661         };
662         const gint PARSE_ELEMS = sizeof parser / sizeof parser[0];
663
664         gint  n;
665         const gchar *walk, *bp, *ep;
666
667         struct txtpos {
668                 const gchar     *bp, *ep;       /* text position */
669                 gint             pti;           /* index in parse table */
670                 struct txtpos   *next;          /* next */
671         } head = {NULL, NULL, 0,  NULL}, *last = &head;
672
673         GtkText *text = GTK_TEXT(textview->text);
674
675         /* parse for clickable parts, and build a list of begin and end positions  */
676         for (walk = linebuf, n = 0;;) {
677                 gint last_index = PARSE_ELEMS;
678                 gchar *scanpos = NULL;
679
680                 /* FIXME: this looks phony. scanning for anything in the parse table */
681                 for (n = 0; n < PARSE_ELEMS; n++) {
682                         gchar *tmp;
683
684                         tmp = parser[n].search(walk, parser[n].needle);
685                         if (tmp) {
686                                 if (scanpos == NULL || tmp < scanpos) {
687                                         scanpos = tmp;
688                                         last_index = n;
689                                 }
690                         }                                       
691                 }
692
693                 if (scanpos) {
694                         /* check if URI can be parsed */
695                         if (parser[last_index].parse(linebuf, scanpos, &bp, &ep)
696                             && (size_t) (ep - bp - 1) > strlen(parser[last_index].needle)) {
697                                         ADD_TXT_POS(bp, ep, last_index);
698                                         walk = ep;
699                         } else
700                                 walk = scanpos +
701                                         strlen(parser[last_index].needle);
702                 } else
703                         break;
704         }
705
706         /* colorize this line */
707         if (head.next) {
708                 const gchar *normal_text = linebuf;
709
710                 /* insert URIs */
711                 for (last = head.next; last != NULL;
712                      normal_text = last->ep, last = last->next) {
713                         RemoteURI *uri;
714
715                         uri = g_new(RemoteURI, 1);
716                         if (last->bp - normal_text > 0)
717                                 gtk_text_insert(text, font,
718                                                 fg_color, NULL,
719                                                 normal_text,
720                                                 last->bp - normal_text);
721                         uri->uri = parser[last->pti].build_uri(last->bp, 
722                                                                last->ep);
723                         uri->start = gtk_text_get_point(text);
724                         gtk_text_insert(text, font, uri_color,
725                                         NULL, last->bp, last->ep - last->bp);
726                         uri->end = gtk_text_get_point(text);
727                         textview->uri_list =
728                                 g_slist_append(textview->uri_list, uri);
729                 }
730
731                 if (*normal_text)
732                         gtk_text_insert(text, font, fg_color,
733                                         NULL, normal_text, -1);
734         } else
735                 gtk_text_insert(text, font, fg_color, NULL, linebuf, -1);
736 }
737
738 #undef ADD_TXT_POS
739
740 static void textview_write_line(TextView *textview, const gchar *str,
741                                 CodeConverter *conv)
742 {
743         GtkText *text = GTK_TEXT(textview->text);
744         gchar buf[BUFFSIZE];
745         size_t len;
746         GdkColor *fg_color;
747         gint quotelevel = -1;
748
749         if (!conv)
750                 strncpy2(buf, str, sizeof(buf));
751         else if (conv_convert(conv, buf, sizeof(buf), str) < 0) {
752                 gtk_text_insert(text, textview->msgfont,
753                                 prefs_common.enable_color
754                                 ? &error_color : NULL, NULL,
755                                 "*** Warning: code conversion failed ***\n",
756                                 -1);
757                 return;
758         }
759
760         len = strlen(buf);
761         if (len > 1 && buf[len - 1] == '\n' && buf[len - 2] == '\r') {
762                 buf[len - 2] = '\n';
763                 buf[len - 1] = '\0';
764         }
765         if (prefs_common.conv_mb_alnum) conv_mb_alnum(buf);
766         fg_color = NULL;
767
768         /* change color of quotation
769            >, foo>, _> ... ok, <foo>, foo bar>, foo-> ... ng
770            Up to 3 levels of quotations are detected, and each
771            level is colored using a different color. */
772         if (prefs_common.enable_color && strchr(buf, '>')) {
773                 quotelevel = get_quote_level(buf);
774
775                 /* set up the correct foreground color */
776                 if (quotelevel > 2) {
777                         /* recycle colors */
778                         if (prefs_common.recycle_quote_colors)
779                                 quotelevel %= 3;
780                         else
781                                 quotelevel = 2;
782                 }
783         }
784
785         if (quotelevel == -1)
786                 fg_color = NULL;
787         else
788                 fg_color = &quote_colors[quotelevel];
789
790         if (prefs_common.head_space && spacingfont && buf[0] != '\n')
791                 gtk_text_insert(text, spacingfont, NULL, NULL, " ", 1);
792
793         if (prefs_common.enable_color)
794                 textview_make_clickable_parts(textview, textview->msgfont,
795                                               fg_color, &uri_color, buf);
796         else
797                 textview_make_clickable_parts(textview, textview->msgfont,
798                                               fg_color, NULL, buf);
799 }
800
801 void textview_clear(TextView *textview)
802 {
803         GtkText *text = GTK_TEXT(textview->text);
804
805         gtk_text_freeze(text);
806         gtk_text_set_point(text, 0);
807         gtk_text_forward_delete(text, gtk_text_get_length(text));
808         gtk_text_thaw(text);
809
810         textview_uri_list_remove_all(textview->uri_list);
811         textview->uri_list = NULL;
812 }
813
814 void textview_destroy(TextView *textview)
815 {
816         textview_uri_list_remove_all(textview->uri_list);
817         textview->uri_list = NULL;
818
819         if (!textview->scrolledwin_sb->parent)
820                 gtk_widget_destroy(textview->scrolledwin_sb);
821         if (!textview->scrolledwin_mb->parent)
822                 gtk_widget_destroy(textview->scrolledwin_mb);
823
824         if (textview->msgfont) {
825                 textview->msgfont->ascent = textview->prev_ascent;
826                 textview->msgfont->descent = textview->prev_descent;
827                 gdk_font_unref(textview->msgfont);
828         }
829         if (textview->boldfont)
830                 gdk_font_unref(textview->boldfont);
831
832         g_free(textview);
833 }
834
835 void textview_set_font(TextView *textview, const gchar *codeset)
836 {
837         gboolean use_fontset = TRUE;
838
839         /* In multi-byte mode, GtkText can't display 8bit characters
840            correctly, so it must be single-byte mode. */
841         if (MB_CUR_MAX > 1) {
842                 if (codeset) {
843                         if (!g_strncasecmp(codeset, "ISO-8859-", 9) ||
844                             !g_strncasecmp(codeset, "KOI8-", 5)     ||
845                             !g_strncasecmp(codeset, "CP", 2)        ||
846                             !g_strncasecmp(codeset, "WINDOWS-", 8)  ||
847                             !g_strcasecmp(codeset, "BALTIC"))
848                                 use_fontset = FALSE;
849                 }
850         } else
851                 use_fontset = FALSE;
852
853         if (textview->text_is_mb && !use_fontset) {
854                 GtkWidget *parent;
855
856                 parent = textview->scrolledwin_mb->parent;
857                 gtk_editable_select_region
858                         (GTK_EDITABLE(textview->text_mb), 0, 0);
859                 gtk_container_remove(GTK_CONTAINER(parent),
860                                      textview->scrolledwin_mb);
861                 gtk_container_add(GTK_CONTAINER(parent),
862                                   textview->scrolledwin_sb);
863
864                 textview->text = textview->text_sb;
865                 textview->text_is_mb = FALSE;
866         } else if (!textview->text_is_mb && use_fontset) {
867                 GtkWidget *parent;
868
869                 parent = textview->scrolledwin_sb->parent;
870                 gtk_editable_select_region
871                         (GTK_EDITABLE(textview->text_sb), 0, 0);
872                 gtk_container_remove(GTK_CONTAINER(parent),
873                                      textview->scrolledwin_sb);
874                 gtk_container_add(GTK_CONTAINER(parent),
875                                   textview->scrolledwin_mb);
876
877                 textview->text = textview->text_mb;
878                 textview->text_is_mb = TRUE;
879         }
880
881         if (prefs_common.textfont) {
882                 if (textview->msgfont) {
883                         textview->msgfont->ascent = textview->prev_ascent;
884                         textview->msgfont->descent = textview->prev_descent;
885                         gdk_font_unref(textview->msgfont);
886                         textview->msgfont = NULL;
887                 }
888                 if (use_fontset)
889                         textview->msgfont =
890                                 gdk_fontset_load(prefs_common.textfont);
891                 else {
892                         if (MB_CUR_MAX > 1) {
893                                 FONT_LOAD(textview->msgfont,
894                                           "-*-courier-medium-r-normal--14-*-*-*-*-*-iso8859-1");
895                         } else {
896                                 FONT_LOAD(textview->msgfont,
897                                           prefs_common.textfont);
898                         }
899                 }
900
901                 if (textview->msgfont) {
902                         gint ascent, descent;
903
904                         textview->prev_ascent = textview->msgfont->ascent;
905                         textview->prev_descent = textview->msgfont->descent;
906                         descent = prefs_common.line_space / 2;
907                         ascent  = prefs_common.line_space - descent;
908                         textview->msgfont->ascent  += ascent;
909                         textview->msgfont->descent += descent;
910                 }
911         }
912
913         if (!textview->boldfont)
914                 FONT_LOAD(textview->boldfont, BOLD_FONT);
915         if (!spacingfont)
916                 spacingfont = gdk_font_load("-*-*-medium-r-normal--6-*");
917 }
918
919 enum
920 {
921         H_DATE          = 0,
922         H_FROM          = 1,
923         H_TO            = 2,
924         H_NEWSGROUPS    = 3,
925         H_SUBJECT       = 4,
926         H_CC            = 5,
927         H_REPLY_TO      = 6,
928         H_FOLLOWUP_TO   = 7,
929         H_X_MAILER      = 8,
930         H_X_NEWSREADER  = 9,
931         H_USER_AGENT    = 10,
932         H_ORGANIZATION  = 11,
933 };
934
935 static GPtrArray *textview_scan_header(TextView *textview, FILE *fp)
936 {
937         gchar buf[BUFFSIZE];
938         GPtrArray *headers, *sorted_headers;
939         GSList *disphdr_list;
940         Header *header;
941         gint i;
942
943         g_return_val_if_fail(fp != NULL, NULL);
944
945         if (!prefs_common.display_header) {
946                 while (fgets(buf, sizeof(buf), fp) != NULL)
947                         if (buf[0] == '\r' || buf[0] == '\n') break;
948                 return NULL;
949         }
950
951         headers = procheader_get_header_array_asis(fp);
952
953         sorted_headers = g_ptr_array_new();
954
955         for (disphdr_list = prefs_common.disphdr_list; disphdr_list != NULL;
956              disphdr_list = disphdr_list->next) {
957                 DisplayHeaderProp *dp =
958                         (DisplayHeaderProp *)disphdr_list->data;
959
960                 for (i = 0; i < headers->len; i++) {
961                         header = g_ptr_array_index(headers, i);
962
963                         if (procheader_headername_equal(header->name,
964                                                         dp->name)) {
965                                 if (dp->hidden)
966                                         procheader_header_free(header);
967                                 else
968                                         g_ptr_array_add(sorted_headers, header);
969
970                                 g_ptr_array_remove_index(headers, i);
971                                 i--;
972                         }
973                 }
974         }
975
976         if (prefs_common.show_other_header) {
977                 for (i = 0; i < headers->len; i++) {
978                         header = g_ptr_array_index(headers, i);
979                         g_ptr_array_add(sorted_headers, header);
980                 }
981         }
982
983         g_ptr_array_free(headers, FALSE);
984
985         return sorted_headers;
986 }
987
988 static void textview_show_header(TextView *textview, GPtrArray *headers)
989 {
990         GtkText *text = GTK_TEXT(textview->text);
991         Header *header;
992         gint i;
993
994         g_return_if_fail(headers != NULL);
995
996         gtk_text_freeze(text);
997
998         for (i = 0; i < headers->len; i++) {
999                 header = g_ptr_array_index(headers, i);
1000                 g_return_if_fail(header->name != NULL);
1001
1002                 gtk_text_insert(text, textview->boldfont, NULL, NULL,
1003                                 header->name, -1);
1004                 if (header->name[strlen(header->name) - 1] != ' ')
1005                         gtk_text_insert(text, textview->boldfont,
1006                                         NULL, NULL, " ", 1);
1007
1008                 if (procheader_headername_equal(header->name, "Subject") ||
1009                     procheader_headername_equal(header->name, "From")    ||
1010                     procheader_headername_equal(header->name, "To")      ||
1011                     procheader_headername_equal(header->name, "Cc"))
1012                         unfold_line(header->body);
1013
1014                 if (prefs_common.enable_color &&
1015                     (procheader_headername_equal(header->name, "X-Mailer") ||
1016                      procheader_headername_equal(header->name,
1017                                                  "X-Newsreader")) &&
1018                     strstr(header->body, "Sylpheed") != NULL)
1019                         gtk_text_insert(text, NULL, &emphasis_color, NULL,
1020                                         header->body, -1);
1021                 else if (prefs_common.enable_color) {
1022                         textview_make_clickable_parts(textview,
1023                                                       NULL, NULL, &uri_color,
1024                                                       header->body);
1025                 } else {
1026                         textview_make_clickable_parts(textview,
1027                                                       NULL, NULL, NULL,
1028                                                       header->body);
1029                 }
1030                 gtk_text_insert(text, textview->msgfont, NULL, NULL, "\n", 1);
1031         }
1032
1033         gtk_text_insert(text, textview->msgfont, NULL, NULL, "\n", 1);
1034         gtk_text_thaw(text);
1035         textview->body_pos = gtk_text_get_length(text);
1036 }
1037
1038 gboolean textview_search_string(TextView *textview, const gchar *str,
1039                                 gboolean case_sens)
1040 {
1041         GtkText *text = GTK_TEXT(textview->text);
1042         gint pos;
1043         wchar_t *wcs;
1044         gint len;
1045         gint text_len;
1046         gboolean found = FALSE;
1047
1048         g_return_val_if_fail(str != NULL, FALSE);
1049
1050         wcs = strdup_mbstowcs(str);
1051         g_return_val_if_fail(wcs != NULL, FALSE);
1052         len = wcslen(wcs);
1053         pos = gtk_editable_get_position(GTK_EDITABLE(text));
1054         if (pos < textview->body_pos)
1055                 pos = textview->body_pos;
1056         text_len = gtk_text_get_length(text);
1057
1058         for (; pos < text_len; pos++) {
1059                 if (text_len - pos < len) break;
1060                 if (gtkut_text_match_string(text, pos, wcs, len, case_sens)
1061                     == TRUE) {
1062                         gtk_text_freeze(text);
1063                         gtk_text_set_point(text, pos + len);
1064                         gtk_editable_set_position(GTK_EDITABLE(text), pos + len);
1065                         gtk_editable_select_region(GTK_EDITABLE(text),
1066                                                    pos, pos + len);
1067                         gtk_text_thaw(text);
1068                         found = TRUE;
1069                         break;
1070                 }
1071         }
1072
1073         g_free(wcs);
1074         return found;
1075 }
1076
1077 void textview_scroll_one_line(TextView *textview, gboolean up)
1078 {
1079         GtkText *text = GTK_TEXT(textview->text);
1080         gfloat upper;
1081
1082         if (prefs_common.enable_smooth_scroll) {
1083                 textview_smooth_scroll_one_line(textview, up);
1084                 return;
1085         }
1086
1087         if (!up) {
1088                 upper = text->vadj->upper - text->vadj->page_size;
1089                 if (text->vadj->value < upper) {
1090                         text->vadj->value +=
1091                                 text->vadj->step_increment * 4;
1092                         text->vadj->value =
1093                                 MIN(text->vadj->value, upper);
1094                         gtk_signal_emit_by_name(GTK_OBJECT(text->vadj),
1095                                                 "value_changed");
1096                 }
1097         } else {
1098                 if (text->vadj->value > 0.0) {
1099                         text->vadj->value -=
1100                                 text->vadj->step_increment * 4;
1101                         text->vadj->value =
1102                                 MAX(text->vadj->value, 0.0);
1103                         gtk_signal_emit_by_name(GTK_OBJECT(text->vadj),
1104                                                 "value_changed");
1105                 }
1106         }
1107 }
1108
1109 gboolean textview_scroll_page(TextView *textview, gboolean up)
1110 {
1111         GtkText *text = GTK_TEXT(textview->text);
1112         gfloat upper;
1113         gfloat page_incr;
1114
1115         if (prefs_common.enable_smooth_scroll)
1116                 return textview_smooth_scroll_page(textview, up);
1117
1118         if (prefs_common.scroll_halfpage)
1119                 page_incr = text->vadj->page_increment / 2;
1120         else
1121                 page_incr = text->vadj->page_increment;
1122
1123         if (!up) {
1124                 upper = text->vadj->upper - text->vadj->page_size;
1125                 if (text->vadj->value < upper) {
1126                         text->vadj->value += page_incr;
1127                         text->vadj->value = MIN(text->vadj->value, upper);
1128                         gtk_signal_emit_by_name(GTK_OBJECT(text->vadj),
1129                                                 "value_changed");
1130                 } else
1131                         return FALSE;
1132         } else {
1133                 if (text->vadj->value > 0.0) {
1134                         text->vadj->value -= page_incr;
1135                         text->vadj->value = MAX(text->vadj->value, 0.0);
1136                         gtk_signal_emit_by_name(GTK_OBJECT(text->vadj),
1137                                                 "value_changed");
1138                 } else
1139                         return FALSE;
1140         }
1141
1142         return TRUE;
1143 }
1144
1145 static void textview_smooth_scroll_do(TextView *textview,
1146                                       gfloat old_value, gfloat last_value,
1147                                       gint step)
1148 {
1149         GtkText *text = GTK_TEXT(textview->text);
1150         gint change_value;
1151         gboolean up;
1152         gint i;
1153
1154         if (old_value < last_value) {
1155                 change_value = last_value - old_value;
1156                 up = FALSE;
1157         } else {
1158                 change_value = old_value - last_value;
1159                 up = TRUE;
1160         }
1161
1162         gdk_key_repeat_disable();
1163
1164         for (i = step; i <= change_value; i += step) {
1165                 text->vadj->value = old_value + (up ? -i : i);
1166                 gtk_signal_emit_by_name(GTK_OBJECT(text->vadj),
1167                                         "value_changed");
1168         }
1169
1170         text->vadj->value = last_value;
1171         gtk_signal_emit_by_name(GTK_OBJECT(text->vadj), "value_changed");
1172
1173         gdk_key_repeat_restore();
1174 }
1175
1176 static void textview_smooth_scroll_one_line(TextView *textview, gboolean up)
1177 {
1178         GtkText *text = GTK_TEXT(textview->text);
1179         gfloat upper;
1180         gfloat old_value;
1181         gfloat last_value;
1182
1183         if (!up) {
1184                 upper = text->vadj->upper - text->vadj->page_size;
1185                 if (text->vadj->value < upper) {
1186                         old_value = text->vadj->value;
1187                         last_value = text->vadj->value +
1188                                 text->vadj->step_increment * 4;
1189                         last_value = MIN(last_value, upper);
1190
1191                         textview_smooth_scroll_do(textview, old_value,
1192                                                   last_value,
1193                                                   prefs_common.scroll_step);
1194                 }
1195         } else {
1196                 if (text->vadj->value > 0.0) {
1197                         old_value = text->vadj->value;
1198                         last_value = text->vadj->value -
1199                                 text->vadj->step_increment * 4;
1200                         last_value = MAX(last_value, 0.0);
1201
1202                         textview_smooth_scroll_do(textview, old_value,
1203                                                   last_value,
1204                                                   prefs_common.scroll_step);
1205                 }
1206         }
1207 }
1208
1209 static gboolean textview_smooth_scroll_page(TextView *textview, gboolean up)
1210 {
1211         GtkText *text = GTK_TEXT(textview->text);
1212         gfloat upper;
1213         gfloat page_incr;
1214         gfloat old_value;
1215         gfloat last_value;
1216
1217         if (prefs_common.scroll_halfpage)
1218                 page_incr = text->vadj->page_increment / 2;
1219         else
1220                 page_incr = text->vadj->page_increment;
1221
1222         if (!up) {
1223                 upper = text->vadj->upper - text->vadj->page_size;
1224                 if (text->vadj->value < upper) {
1225                         old_value = text->vadj->value;
1226                         last_value = text->vadj->value + page_incr;
1227                         last_value = MIN(last_value, upper);
1228
1229                         textview_smooth_scroll_do(textview, old_value,
1230                                                   last_value,
1231                                                   prefs_common.scroll_step);
1232                 } else
1233                         return FALSE;
1234         } else {
1235                 if (text->vadj->value > 0.0) {
1236                         old_value = text->vadj->value;
1237                         last_value = text->vadj->value - page_incr;
1238                         last_value = MAX(last_value, 0.0);
1239
1240                         textview_smooth_scroll_do(textview, old_value,
1241                                                   last_value,
1242                                                   prefs_common.scroll_step);
1243                 } else
1244                         return FALSE;
1245         }
1246
1247         return TRUE;
1248 }
1249
1250 static void textview_key_pressed(GtkWidget *widget, GdkEventKey *event,
1251                                  TextView *textview)
1252 {
1253         SummaryView *summaryview = NULL;
1254
1255         if (!event) return;
1256         if (textview->messageview->mainwin)
1257                 summaryview = textview->messageview->mainwin->summaryview;
1258
1259         switch (event->keyval) {
1260         case GDK_Tab:
1261         case GDK_Home:
1262         case GDK_Left:
1263         case GDK_Up:
1264         case GDK_Right:
1265         case GDK_Down:
1266         case GDK_Page_Up:
1267         case GDK_Page_Down:
1268         case GDK_End:
1269         case GDK_Control_L:
1270         case GDK_Control_R:
1271                 break;
1272         case GDK_space:
1273                 if (summaryview)
1274                         summary_pass_key_press_event(summaryview, event);
1275                 else
1276                         textview_scroll_page(textview, FALSE);
1277                 break;
1278         case GDK_BackSpace:
1279         case GDK_Delete:
1280                 textview_scroll_page(textview, TRUE);
1281                 break;
1282         case GDK_Return:
1283                 textview_scroll_one_line(textview,
1284                                          (event->state & GDK_MOD1_MASK) != 0);
1285                 break;
1286         default:
1287                 if (summaryview)
1288                         summary_pass_key_press_event(summaryview, event);
1289                 break;
1290         }
1291 }
1292
1293 static void textview_button_pressed(GtkWidget *widget, GdkEventButton *event,
1294                                     TextView *textview)
1295 {
1296         if (event &&
1297             ((event->button == 1 && event->type == GDK_2BUTTON_PRESS)
1298              || event->button == 2 || event->button == 3)) {
1299                 GSList *cur;
1300                 guint current_pos;
1301
1302                 current_pos = GTK_EDITABLE(textview->text)->current_pos;
1303
1304                 for (cur = textview->uri_list; cur != NULL; cur = cur->next) {
1305                         RemoteURI *uri = (RemoteURI *)cur->data;
1306
1307                         if (current_pos >= uri->start &&
1308                             current_pos <  uri->end) {
1309                                 if (!g_strncasecmp(uri->uri, "mailto:", 7)) {
1310                                         if (event->button == 3) {
1311                                                 gchar *fromname, *fromaddress;
1312                                                 /* extract url */
1313                                                 fromaddress = g_strdup(uri->uri + 7);
1314                                                 /* Hiroyuki: please put this function in utils.c! */
1315                                                 fromname = procheader_get_fromname(fromaddress);
1316                                                 extract_address(fromaddress);
1317                                                 g_message("adding from textview %s <%s>", fromname, fromaddress);
1318                                                 // Add to address book - Match
1319                                                 addressbook_add_contact( fromname, fromaddress, NULL );
1320                                                 g_free(fromaddress);
1321                                                 g_free(fromname);
1322                                         } else {
1323                                                 compose_new_with_recipient
1324                                                         (NULL, uri->uri + 7);
1325                                         }
1326                                 } else {
1327                                         open_uri(uri->uri,
1328                                                  prefs_common.uri_cmd);
1329                                 }
1330                         }
1331                 }
1332         }
1333 }
1334
1335 static void textview_uri_list_remove_all(GSList *uri_list)
1336 {
1337         GSList *cur;
1338
1339         for (cur = uri_list; cur != NULL; cur = cur->next) {
1340                 if (cur->data) {
1341                         g_free(((RemoteURI *)cur->data)->uri);
1342                         g_free(cur->data);
1343                 }
1344         }
1345
1346         g_slist_free(uri_list);
1347 }