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