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