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