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