2006-07-27 [colin] 2.3.1cvs86
[claws.git] / src / textview.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2006 Hiroyuki Yamamoto and the Sylpheed-Claws team
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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 <glib/gi18n.h>
28 #include <gdk/gdk.h>
29 #include <gdk/gdkkeysyms.h>
30 #include <gtk/gtkvbox.h>
31 #include <gtk/gtkscrolledwindow.h>
32 #include <gtk/gtksignal.h>
33 #include <stdio.h>
34 #include <ctype.h>
35 #include <string.h>
36 #include <stdlib.h>
37 #include <errno.h>
38 #include <sys/wait.h>
39 #if HAVE_LIBCOMPFACE
40 #  include <compface.h>
41 #endif
42
43 #if HAVE_LIBCOMPFACE
44 #define XPM_XFACE_HEIGHT        (HEIGHT + 3)  /* 3 = 1 header + 2 colors */
45 #endif
46
47 #include "main.h"
48 #include "summaryview.h"
49 #include "procheader.h"
50 #include "prefs_common.h"
51 #include "codeconv.h"
52 #include "utils.h"
53 #include "gtkutils.h"
54 #include "procmime.h"
55 #include "html.h"
56 #include "enriched.h"
57 #include "compose.h"
58 #include "addressbook.h"
59 #include "displayheader.h"
60 #include "account.h"
61 #include "mimeview.h"
62 #include "alertpanel.h"
63 #include "menu.h"
64 #include "image_viewer.h"
65 #include "filesel.h"
66 #include "base64.h"
67
68 struct _RemoteURI
69 {
70         gchar *uri;
71
72         gchar *filename;
73
74         gpointer data;
75
76         guint start;
77         guint end;
78 };
79
80 static GdkColor quote_colors[3] = {
81         {(gulong)0, (gushort)0, (gushort)0, (gushort)0},
82         {(gulong)0, (gushort)0, (gushort)0, (gushort)0},
83         {(gulong)0, (gushort)0, (gushort)0, (gushort)0}
84 };
85
86 static GdkColor quote_bgcolors[3] = {
87         {(gulong)0, (gushort)0, (gushort)0, (gushort)0},
88         {(gulong)0, (gushort)0, (gushort)0, (gushort)0},
89         {(gulong)0, (gushort)0, (gushort)0, (gushort)0}
90 };
91 static GdkColor signature_color = {
92         (gulong)0,
93         (gushort)0x7fff,
94         (gushort)0x7fff,
95         (gushort)0x7fff
96 };
97         
98 static GdkColor uri_color = {
99         (gulong)0,
100         (gushort)0,
101         (gushort)0,
102         (gushort)0
103 };
104
105 static GdkColor emphasis_color = {
106         (gulong)0,
107         (gushort)0,
108         (gushort)0,
109         (gushort)0xcfff
110 };
111
112 static GdkCursor *hand_cursor = NULL;
113 static GdkCursor *text_cursor = NULL;
114 static GdkCursor *watch_cursor= NULL;
115
116 #define TEXTVIEW_STATUSBAR_PUSH(textview, str)                              \
117 {       if (textview->messageview->statusbar)                               \
118         gtk_statusbar_push(GTK_STATUSBAR(textview->messageview->statusbar), \
119                            textview->messageview->statusbar_cid, str);      \
120 }
121
122 #define TEXTVIEW_STATUSBAR_POP(textview)                                   \
123 {       if (textview->messageview->statusbar)                              \
124         gtk_statusbar_pop(GTK_STATUSBAR(textview->messageview->statusbar), \
125                           textview->messageview->statusbar_cid);           \
126 }
127
128 static void textview_show_ertf          (TextView       *textview,
129                                          FILE           *fp,
130                                          CodeConverter  *conv);
131 static void textview_add_part           (TextView       *textview,
132                                          MimeInfo       *mimeinfo);
133 static void textview_add_parts          (TextView       *textview,
134                                          MimeInfo       *mimeinfo);
135 static void textview_write_body         (TextView       *textview,
136                                          MimeInfo       *mimeinfo);
137 static void textview_show_html          (TextView       *textview,
138                                          FILE           *fp,
139                                          CodeConverter  *conv);
140
141 static void textview_write_line         (TextView       *textview,
142                                          const gchar    *str,
143                                          CodeConverter  *conv);
144 static void textview_write_link         (TextView       *textview,
145                                          const gchar    *str,
146                                          const gchar    *uri,
147                                          CodeConverter  *conv);
148
149 static GPtrArray *textview_scan_header  (TextView       *textview,
150                                          FILE           *fp);
151 static void textview_show_header        (TextView       *textview,
152                                          GPtrArray      *headers);
153
154 static gint textview_key_pressed                (GtkWidget      *widget,
155                                                  GdkEventKey    *event,
156                                                  TextView       *textview);
157 static gboolean textview_motion_notify          (GtkWidget      *widget,
158                                                  GdkEventMotion *motion,
159                                                  TextView       *textview);
160 static gboolean textview_leave_notify           (GtkWidget        *widget,
161                                                  GdkEventCrossing *event,
162                                                  TextView         *textview);
163 static gboolean textview_visibility_notify      (GtkWidget      *widget,
164                                                  GdkEventVisibility *event,
165                                                  TextView       *textview);
166 static void textview_uri_update                 (TextView       *textview,
167                                                  gint           x,
168                                                  gint           y);
169 static gboolean textview_get_uri_range          (TextView       *textview,
170                                                  GtkTextIter    *iter,
171                                                  GtkTextTag     *tag,
172                                                  GtkTextIter    *start_iter,
173                                                  GtkTextIter    *end_iter);
174 static RemoteURI *textview_get_uri_from_range   (TextView       *textview,
175                                                  GtkTextIter    *iter,
176                                                  GtkTextTag     *tag,
177                                                  GtkTextIter    *start_iter,
178                                                  GtkTextIter    *end_iter);
179 static RemoteURI *textview_get_uri              (TextView       *textview,
180                                                  GtkTextIter    *iter,
181                                                  GtkTextTag     *tag);
182 static gboolean textview_uri_button_pressed     (GtkTextTag     *tag,
183                                                  GObject        *obj,
184                                                  GdkEvent       *event,
185                                                  GtkTextIter    *iter,
186                                                  TextView       *textview);
187
188 static void textview_smooth_scroll_do           (TextView       *textview,
189                                                  gfloat          old_value,
190                                                  gfloat          last_value,
191                                                  gint            step);
192 static void textview_smooth_scroll_one_line     (TextView       *textview,
193                                                  gboolean        up);
194 static gboolean textview_smooth_scroll_page     (TextView       *textview,
195                                                  gboolean        up);
196
197 static gboolean textview_uri_security_check     (TextView       *textview,
198                                                  RemoteURI      *uri);
199 static void textview_uri_list_remove_all        (GSList         *uri_list);
200
201 static void open_uri_cb                         (TextView       *textview,
202                                                  guint           action,
203                                                  void           *data);
204 static void copy_uri_cb                         (TextView       *textview,
205                                                  guint           action,
206                                                  void           *data);
207 static void add_uri_to_addrbook_cb              (TextView       *textview, 
208                                                  guint           action, 
209                                                  void           *data);
210 static void mail_to_uri_cb                      (TextView       *textview, 
211                                                  guint           action, 
212                                                  void           *data);
213 static void copy_mail_to_uri_cb                 (TextView       *textview,
214                                                  guint           action,
215                                                  void           *data);
216 static void save_file_cb                        (TextView       *textview,
217                                                  guint           action,
218                                                  void           *data);
219 static void open_image_cb                       (TextView       *textview,
220                                                  guint           action,
221                                                  void           *data);
222 static void textview_show_icon(TextView *textview, const gchar *stock_id);
223
224 static GtkItemFactoryEntry textview_link_popup_entries[] = 
225 {
226         {N_("/_Open with Web browser"), NULL, open_uri_cb, 0, NULL},
227         {N_("/Copy this _link"),        NULL, copy_uri_cb, 0, NULL},
228 };
229
230 static GtkItemFactoryEntry textview_mail_popup_entries[] = 
231 {
232         {N_("/Compose _new message"),   NULL, mail_to_uri_cb, 0, NULL},
233         {N_("/Add to _address book"),   NULL, add_uri_to_addrbook_cb, 0, NULL},
234         {N_("/Copy this add_ress"),     NULL, copy_mail_to_uri_cb, 0, NULL},
235 };
236
237 static GtkItemFactoryEntry textview_file_popup_entries[] = 
238 {
239         {N_("/_Open image"),            NULL, open_image_cb, 0, NULL},
240         {N_("/_Save image..."),         NULL, save_file_cb, 0, NULL},
241 };
242
243 static void scrolled_cb (GtkAdjustment *adj, TextView *textview)
244 {
245 #ifndef WIDTH
246 #  define WIDTH 48
247 #  define HEIGHT 48
248 #endif
249         if (textview->image) {
250                 gint x, y, x1;
251                 x1 = textview->text->allocation.width - WIDTH - 5;
252                 gtk_text_view_buffer_to_window_coords(
253                         GTK_TEXT_VIEW(textview->text),
254                         GTK_TEXT_WINDOW_TEXT, x1, 5, &x, &y);
255                 gtk_text_view_move_child(GTK_TEXT_VIEW(textview->text), 
256                         textview->image, x1, y);
257         }
258 }
259
260 static void textview_size_allocate_cb   (GtkWidget      *widget,
261                                          GtkAllocation  *allocation,
262                                          gpointer        data)
263 {
264         scrolled_cb(NULL, (TextView *)data);
265 }
266
267 TextView *textview_create(void)
268 {
269         TextView *textview;
270         GtkWidget *vbox;
271         GtkWidget *scrolledwin;
272         GtkWidget *text;
273         GtkTextBuffer *buffer;
274         GtkClipboard *clipboard;
275         GtkItemFactory *link_popupfactory, *mail_popupfactory, *file_popupfactory;
276         GtkWidget *link_popupmenu, *mail_popupmenu, *file_popupmenu;
277         GtkAdjustment *adj;
278         gint n_entries;
279
280         debug_print("Creating text view...\n");
281         textview = g_new0(TextView, 1);
282
283         scrolledwin = gtk_scrolled_window_new(NULL, NULL);
284         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledwin),
285                                        GTK_POLICY_AUTOMATIC,
286                                        GTK_POLICY_AUTOMATIC);
287         gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scrolledwin),
288                                             GTK_SHADOW_IN);
289         gtk_widget_set_size_request
290                 (scrolledwin, prefs_common.mainview_width, -1);
291
292         /* create GtkSText widgets for single-byte and multi-byte character */
293         text = gtk_text_view_new();
294         gtk_widget_add_events(text, GDK_LEAVE_NOTIFY_MASK);
295         gtk_widget_show(text);
296         gtk_text_view_set_editable(GTK_TEXT_VIEW(text), FALSE);
297         gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(text), GTK_WRAP_WORD_CHAR);
298         gtk_text_view_set_cursor_visible(GTK_TEXT_VIEW(text), FALSE);
299         gtk_text_view_set_left_margin(GTK_TEXT_VIEW(text), 6);
300         gtk_text_view_set_right_margin(GTK_TEXT_VIEW(text), 6);
301
302         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
303         clipboard = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
304         gtk_text_buffer_add_selection_clipboard(buffer, clipboard);
305
306         gtk_widget_ensure_style(text);
307
308         gtk_widget_ref(scrolledwin);
309
310         gtk_container_add(GTK_CONTAINER(scrolledwin), text);
311
312         g_signal_connect(G_OBJECT(text), "key-press-event",
313                          G_CALLBACK(textview_key_pressed), textview);
314         g_signal_connect(G_OBJECT(text), "motion-notify-event",
315                          G_CALLBACK(textview_motion_notify), textview);
316         g_signal_connect(G_OBJECT(text), "leave-notify-event",
317                          G_CALLBACK(textview_leave_notify), textview);
318         g_signal_connect(G_OBJECT(text), "visibility-notify-event",
319                          G_CALLBACK(textview_visibility_notify), textview);
320         adj = gtk_scrolled_window_get_vadjustment(
321                 GTK_SCROLLED_WINDOW(scrolledwin));
322         g_signal_connect(G_OBJECT(adj), "value-changed",
323                          G_CALLBACK(scrolled_cb), textview);
324         g_signal_connect(G_OBJECT(text), "size_allocate",
325                          G_CALLBACK(textview_size_allocate_cb),
326                          textview);
327
328
329         gtk_widget_show(scrolledwin);
330
331         vbox = gtk_vbox_new(FALSE, 0);
332         gtk_box_pack_start(GTK_BOX(vbox), scrolledwin, TRUE, TRUE, 0);
333
334         gtk_widget_show(vbox);
335
336         n_entries = sizeof(textview_link_popup_entries) /
337                 sizeof(textview_link_popup_entries[0]);
338         link_popupmenu = menu_create_items(textview_link_popup_entries, n_entries,
339                                       "<UriPopupMenu>", &link_popupfactory,
340                                       textview);
341
342         n_entries = sizeof(textview_mail_popup_entries) /
343                 sizeof(textview_mail_popup_entries[0]);
344         mail_popupmenu = menu_create_items(textview_mail_popup_entries, n_entries,
345                                       "<UriPopupMenu>", &mail_popupfactory,
346                                       textview);
347
348         n_entries = sizeof(textview_file_popup_entries) /
349                 sizeof(textview_file_popup_entries[0]);
350         file_popupmenu = menu_create_items(textview_file_popup_entries, n_entries,
351                                       "<FilePopupMenu>", &file_popupfactory,
352                                       textview);
353
354         textview->vbox               = vbox;
355         textview->scrolledwin        = scrolledwin;
356         textview->text               = text;
357         textview->uri_list           = NULL;
358         textview->body_pos           = 0;
359         textview->show_all_headers   = FALSE;
360         textview->last_buttonpress   = GDK_NOTHING;
361         textview->link_popup_menu    = link_popupmenu;
362         textview->link_popup_factory = link_popupfactory;
363         textview->mail_popup_menu    = mail_popupmenu;
364         textview->mail_popup_factory = mail_popupfactory;
365         textview->file_popup_menu    = file_popupmenu;
366         textview->file_popup_factory = file_popupfactory;
367         textview->image              = NULL;
368         return textview;
369 }
370
371 static void textview_create_tags(GtkTextView *text, TextView *textview)
372 {
373         GtkTextBuffer *buffer;
374         GtkTextTag *tag;
375         static PangoFontDescription *font_desc, *bold_font_desc;
376         
377         if (!font_desc)
378                 font_desc = pango_font_description_from_string
379                         (NORMAL_FONT);
380
381         if (!bold_font_desc) {
382                 bold_font_desc = pango_font_description_from_string
383                         (NORMAL_FONT);
384                 pango_font_description_set_weight
385                         (bold_font_desc, PANGO_WEIGHT_BOLD);
386         }
387
388         buffer = gtk_text_view_get_buffer(text);
389
390         gtk_text_buffer_create_tag(buffer, "header",
391                                    "pixels-above-lines", 0,
392                                    "pixels-above-lines-set", TRUE,
393                                    "pixels-below-lines", 0,
394                                    "pixels-below-lines-set", TRUE,
395                                    "font-desc", font_desc,
396                                    "left-margin", 3,
397                                    "left-margin-set", TRUE,
398                                    NULL);
399         gtk_text_buffer_create_tag(buffer, "header_title",
400                                    "font-desc", bold_font_desc,
401                                    NULL);
402         if (prefs_common.enable_bgcolor) {
403                 gtk_text_buffer_create_tag(buffer, "quote0",
404                                 "foreground-gdk", &quote_colors[0],
405                                 "paragraph-background-gdk", &quote_bgcolors[0],
406                                 NULL);
407                 gtk_text_buffer_create_tag(buffer, "quote1",
408                                 "foreground-gdk", &quote_colors[1],
409                                 "paragraph-background-gdk", &quote_bgcolors[1],
410                                 NULL);
411                 gtk_text_buffer_create_tag(buffer, "quote2",
412                                 "foreground-gdk", &quote_colors[2],
413                                 "paragraph-background-gdk", &quote_bgcolors[2],
414                                 NULL);
415         } else {
416                 gtk_text_buffer_create_tag(buffer, "quote0",
417                                 "foreground-gdk", &quote_colors[0],
418                                 NULL);
419                 gtk_text_buffer_create_tag(buffer, "quote1",
420                                 "foreground-gdk", &quote_colors[1],
421                                 NULL);
422                 gtk_text_buffer_create_tag(buffer, "quote2",
423                                 "foreground-gdk", &quote_colors[2],
424                                 NULL);
425         }
426         gtk_text_buffer_create_tag(buffer, "emphasis",
427                         "foreground-gdk", &emphasis_color,
428                         NULL);
429         gtk_text_buffer_create_tag(buffer, "signature",
430                         "foreground-gdk", &signature_color,
431                         NULL);
432         tag = gtk_text_buffer_create_tag(buffer, "link",
433                         "foreground-gdk", &uri_color,
434                         NULL);
435         gtk_text_buffer_create_tag(buffer, "link-hover",
436                         "foreground-gdk", &uri_color,
437                         "underline", PANGO_UNDERLINE_SINGLE,
438                         NULL);
439         g_signal_connect(G_OBJECT(tag), "event",
440                          G_CALLBACK(textview_uri_button_pressed), textview);
441  }
442
443 void textview_init(TextView *textview)
444 {
445         if (!hand_cursor)
446                 hand_cursor = gdk_cursor_new(GDK_HAND2);
447         if (!text_cursor)
448                 text_cursor = gdk_cursor_new(GDK_XTERM);
449         if (!watch_cursor)
450                 watch_cursor = gdk_cursor_new(GDK_WATCH);
451
452         textview_reflect_prefs(textview);
453         textview_set_all_headers(textview, FALSE);
454         textview_set_font(textview, NULL);
455         textview_create_tags(GTK_TEXT_VIEW(textview->text), textview);
456 }
457
458 #if GTK_CHECK_VERSION(2, 8, 0)
459  #define CHANGE_TAG_COLOR(tagname, colorfg, colorbg) { \
460         tag = gtk_text_tag_table_lookup(tags, tagname); \
461         if (tag) \
462                 g_object_set(G_OBJECT(tag), "foreground-gdk", colorfg, "paragraph-background-gdk", colorbg, NULL); \
463  }
464 #else
465  #define CHANGE_TAG_COLOR(tagname, colorfg, colorbg) { \
466         tag = gtk_text_tag_table_lookup(tags, tagname); \
467         if (tag) \
468                 g_object_set(G_OBJECT(tag), "foreground-gdk", colorfg, NULL); \
469  }
470 #endif
471
472 static void textview_update_message_colors(TextView *textview)
473 {
474         GdkColor black = {0, 0, 0, 0};
475         GdkColor colored_emphasis = {0, 0, 0, 0xcfff};
476         GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview->text));
477
478         GtkTextTagTable *tags = gtk_text_buffer_get_tag_table(buffer);
479         GtkTextTag *tag = NULL;
480
481         quote_bgcolors[0] = quote_bgcolors[1] = quote_bgcolors[2] = black;
482         quote_colors[0] = quote_colors[1] = quote_colors[2] = 
483                 uri_color = emphasis_color = signature_color = black;
484
485         if (prefs_common.enable_color) {
486                 /* grab the quote colors, converting from an int to a GdkColor */
487                 gtkut_convert_int_to_gdk_color(prefs_common.quote_level1_col,
488                                                &quote_colors[0]);
489                 gtkut_convert_int_to_gdk_color(prefs_common.quote_level2_col,
490                                                &quote_colors[1]);
491                 gtkut_convert_int_to_gdk_color(prefs_common.quote_level3_col,
492                                                &quote_colors[2]);
493                 gtkut_convert_int_to_gdk_color(prefs_common.uri_col,
494                                                &uri_color);
495                 gtkut_convert_int_to_gdk_color(prefs_common.signature_col,
496                                                &signature_color);
497                 emphasis_color = colored_emphasis;
498         }
499         if (prefs_common.enable_color && prefs_common.enable_bgcolor) {
500                 gtkut_convert_int_to_gdk_color(prefs_common.quote_level1_bgcol,
501                                                    &quote_bgcolors[0]);
502                 gtkut_convert_int_to_gdk_color(prefs_common.quote_level2_bgcol,
503                                                    &quote_bgcolors[1]);
504                 gtkut_convert_int_to_gdk_color(prefs_common.quote_level3_bgcol,
505                                                    &quote_bgcolors[2]);
506                 CHANGE_TAG_COLOR("quote0", &quote_colors[0], &quote_bgcolors[0]);
507                 CHANGE_TAG_COLOR("quote1", &quote_colors[1], &quote_bgcolors[1]);
508                 CHANGE_TAG_COLOR("quote2", &quote_colors[2], &quote_bgcolors[2]);
509         } else {
510                 CHANGE_TAG_COLOR("quote0", &quote_colors[0], NULL);
511                 CHANGE_TAG_COLOR("quote1", &quote_colors[1], NULL);
512                 CHANGE_TAG_COLOR("quote2", &quote_colors[2], NULL);
513         }
514
515         CHANGE_TAG_COLOR("emphasis", &emphasis_color, NULL);
516         CHANGE_TAG_COLOR("signature", &signature_color, NULL);
517         CHANGE_TAG_COLOR("link", &uri_color, NULL);
518         CHANGE_TAG_COLOR("link-hover", &uri_color, NULL);
519 }
520 #undef CHANGE_TAG_COLOR
521
522 void textview_reflect_prefs(TextView *textview)
523 {
524         textview_set_font(textview, NULL);
525         textview_update_message_colors(textview);
526         gtk_text_view_set_cursor_visible(GTK_TEXT_VIEW(textview->text),
527                                          prefs_common.textview_cursor_visible);
528 }
529
530 void textview_show_message(TextView *textview, MimeInfo *mimeinfo,
531                            const gchar *file)
532 {
533         textview_clear(textview);
534
535         textview_add_parts(textview, mimeinfo);
536
537         textview_set_position(textview, 0);
538 }
539
540 void textview_show_part(TextView *textview, MimeInfo *mimeinfo, FILE *fp)
541 {
542         g_return_if_fail(mimeinfo != NULL);
543         g_return_if_fail(fp != NULL);
544
545         if ((mimeinfo->type == MIMETYPE_MULTIPART) ||
546             ((mimeinfo->type == MIMETYPE_MESSAGE) && !g_ascii_strcasecmp(mimeinfo->subtype, "rfc822"))) {
547                 textview_clear(textview);
548                 textview_add_parts(textview, mimeinfo);
549                 return;
550         }
551
552         if (fseek(fp, mimeinfo->offset, SEEK_SET) < 0)
553                 perror("fseek");
554
555         textview_clear(textview);
556
557         if (mimeinfo->type == MIMETYPE_MULTIPART)
558                 textview_add_parts(textview, mimeinfo);
559         else
560                 textview_write_body(textview, mimeinfo);
561 }
562
563 #define TEXT_INSERT(str) \
564         gtk_text_buffer_insert_with_tags_by_name \
565                                 (buffer, &iter, str, -1,\
566                                  "header", NULL)
567
568 #define TEXT_INSERT_LINK(str, fname, udata) {                           \
569         RemoteURI *uri;                                                 \
570         uri = g_new(RemoteURI, 1);                                      \
571         uri->uri = g_strdup("");                                        \
572         uri->start = gtk_text_iter_get_offset(&iter);                   \
573         gtk_text_buffer_insert_with_tags_by_name                        \
574                                 (buffer, &iter, str, -1,                \
575                                  "link", "header_title", "header",      \
576                                  NULL);                                 \
577         uri->end = gtk_text_iter_get_offset(&iter);                     \
578         uri->filename = fname?g_strdup(fname):NULL;                     \
579         uri->data = udata;                                              \
580         textview->uri_list =                                            \
581                 g_slist_append(textview->uri_list, uri);                \
582 }
583
584 static void textview_add_part(TextView *textview, MimeInfo *mimeinfo)
585 {
586         GtkTextView *text;
587         GtkTextBuffer *buffer;
588         GtkTextIter iter, start_iter;
589         gchar buf[BUFFSIZE];
590         GPtrArray *headers = NULL;
591         const gchar *name;
592         gchar *content_type;
593         gint charcount;
594
595         g_return_if_fail(mimeinfo != NULL);
596         text = GTK_TEXT_VIEW(textview->text);
597         buffer = gtk_text_view_get_buffer(text);
598         charcount = gtk_text_buffer_get_char_count(buffer);
599         gtk_text_buffer_get_end_iter(buffer, &iter);
600
601         if (mimeinfo->type == MIMETYPE_MULTIPART) return;
602
603         if ((mimeinfo->type == MIMETYPE_MESSAGE) && !g_ascii_strcasecmp(mimeinfo->subtype, "rfc822")) {
604                 FILE *fp;
605
606                 fp = g_fopen(mimeinfo->data.filename, "rb");
607                 fseek(fp, mimeinfo->offset, SEEK_SET);
608                 headers = textview_scan_header(textview, fp);
609                 if (headers) {
610                         if (charcount > 0)
611                                 gtk_text_buffer_insert(buffer, &iter, "\n", 1);
612                         textview_show_header(textview, headers);
613                         procheader_header_array_destroy(headers);
614                 }
615                 fclose(fp);
616                 return;
617         }
618
619         name = procmime_mimeinfo_get_parameter(mimeinfo, "filename");
620         content_type = procmime_get_content_type_str(mimeinfo->type,
621                                                      mimeinfo->subtype);
622         if (name == NULL)
623                 name = procmime_mimeinfo_get_parameter(mimeinfo, "name");
624         if (name != NULL)
625                 g_snprintf(buf, sizeof(buf), _("[%s  %s (%d bytes)]"),
626                            name, content_type, mimeinfo->length);
627         else
628                 g_snprintf(buf, sizeof(buf), _("[%s (%d bytes)]"),
629                            content_type, mimeinfo->length);
630
631         g_free(content_type);                      
632
633         if (mimeinfo->disposition == DISPOSITIONTYPE_ATTACHMENT
634         || (mimeinfo->disposition == DISPOSITIONTYPE_INLINE && 
635             mimeinfo->type != MIMETYPE_TEXT)) {
636                 gtk_text_buffer_insert(buffer, &iter, "\n", 1);
637                 TEXT_INSERT_LINK(buf, "sc://select_attachment", mimeinfo);
638                 gtk_text_buffer_insert(buffer, &iter, " \n", -1);
639                 if (mimeinfo->type == MIMETYPE_IMAGE  &&
640                     prefs_common.inline_img ) {
641                         GdkPixbuf *pixbuf;
642                         GError *error = NULL;
643                         gchar *filename;
644                         RemoteURI *uri;
645                         gchar *uri_str;
646
647                         filename = procmime_get_tmp_file_name(mimeinfo);
648                         if (procmime_get_part(filename, mimeinfo) < 0) {
649                                 g_warning("Can't get the image file.");
650                                 g_free(filename);
651                                 return;
652                         }
653
654                         pixbuf = gdk_pixbuf_new_from_file(filename, &error);
655                         if (error != NULL) {
656                                 g_warning("%s\n", error->message);
657                                 g_error_free(error);
658                         }
659                         if (!pixbuf) {
660                                 g_warning("Can't load the image.");
661                                 g_free(filename);
662                                 return;
663                         }
664
665                         if (prefs_common.resize_img) {
666                                 int new_width, new_height;
667                                 GdkPixbuf *scaled;
668                                 image_viewer_get_resized_size(gdk_pixbuf_get_width(pixbuf),
669                                                  gdk_pixbuf_get_height(pixbuf),
670                                                  textview->scrolledwin->allocation.width - 100, 
671                                                  gdk_pixbuf_get_height(pixbuf),
672                                                  &new_width, &new_height);
673                                 scaled = gdk_pixbuf_scale_simple
674                                         (pixbuf, new_width, new_height, GDK_INTERP_BILINEAR);
675
676                                 g_object_unref(pixbuf);
677                                 pixbuf = scaled;
678                         }
679
680                         uri_str = g_filename_to_uri(filename, NULL, NULL);
681                         if (uri_str) {
682                                 uri = g_new(RemoteURI, 1);
683                                 uri->uri = uri_str;
684                                 uri->start = gtk_text_iter_get_offset(&iter);
685                                 
686                                 gtk_text_buffer_insert_pixbuf(buffer, &iter, pixbuf);
687                                 
688                                 uri->end = uri->start + 1;
689                                 uri->filename = procmime_get_part_file_name(mimeinfo);
690                                 textview->uri_list =
691                                         g_slist_append(textview->uri_list, uri);
692                                 
693                                 gtk_text_buffer_insert(buffer, &iter, " ", 1);
694                                 gtk_text_buffer_get_iter_at_offset(buffer, &start_iter, uri->start);    
695                                 gtk_text_buffer_apply_tag_by_name(buffer, "link", 
696                                                 &start_iter, &iter);
697                         } else {
698                                 gtk_text_buffer_insert_pixbuf(buffer, &iter, pixbuf);
699                                 gtk_text_buffer_insert(buffer, &iter, " ", 1);
700                         }
701
702                         g_object_unref(pixbuf);
703                         g_free(filename);
704                 }
705         } else if (mimeinfo->type == MIMETYPE_TEXT) {
706                 if (prefs_common.display_header && (charcount > 0))
707                         gtk_text_buffer_insert(buffer, &iter, "\n", 1);
708
709                 textview_write_body(textview, mimeinfo);
710         }
711 }
712
713 static void recursive_add_parts(TextView *textview, GNode *node)
714 {
715         GNode * iter;
716         MimeInfo *mimeinfo;
717         
718         mimeinfo = (MimeInfo *) node->data;
719         
720         textview_add_part(textview, mimeinfo);
721         
722         if ((mimeinfo->type != MIMETYPE_MULTIPART) &&
723             (mimeinfo->type != MIMETYPE_MESSAGE))
724                 return;
725         
726         if (g_ascii_strcasecmp(mimeinfo->subtype, "alternative") == 0) {
727                 GNode * prefered_body;
728                 int prefered_score;
729                 
730                 /*
731                   text/plain : score 3
732                   text/ *    : score 2
733                   other      : score 1
734                 */
735                 prefered_body = NULL;
736                 prefered_score = 0;
737                 
738                 for (iter = g_node_first_child(node) ; iter != NULL ;
739                      iter = g_node_next_sibling(iter)) {
740                         int score;
741                         MimeInfo * submime;
742                         
743                         score = 1;
744                         submime = (MimeInfo *) iter->data;
745                         if (submime->type == MIMETYPE_TEXT)
746                                 score = 2;
747                         
748                         if (submime->subtype != NULL) {
749                                 if (g_ascii_strcasecmp(submime->subtype, "plain") == 0)
750                                         score = 3;
751                         }
752                         
753                         if (score > prefered_score) {
754                                 prefered_score = score;
755                                 prefered_body = iter;
756                         }
757                 }
758                 
759                 if (prefered_body != NULL) {
760                         recursive_add_parts(textview, prefered_body);
761                 }
762         }
763         else {
764                 for (iter = g_node_first_child(node) ; iter != NULL ;
765                      iter = g_node_next_sibling(iter)) {
766                         recursive_add_parts(textview, iter);
767                 }
768         }
769 }
770
771 static void textview_add_parts(TextView *textview, MimeInfo *mimeinfo)
772 {
773         g_return_if_fail(mimeinfo != NULL);
774         
775         recursive_add_parts(textview, mimeinfo->node);
776 }
777
778 void textview_show_error(TextView *textview)
779 {
780         GtkTextView *text;
781         GtkTextBuffer *buffer;
782         GtkTextIter iter;
783
784         textview_set_font(textview, NULL);
785         textview_clear(textview);
786
787         text = GTK_TEXT_VIEW(textview->text);
788         buffer = gtk_text_view_get_buffer(text);
789         gtk_text_buffer_get_start_iter(buffer, &iter);
790
791         TEXT_INSERT(_("\n"
792                       "  This message can't be displayed.\n"
793                       "  This is probably due to a network error.\n"
794                       "\n"
795                       "  Use "));
796         TEXT_INSERT_LINK(_("'View Log'"), "sc://view_log", NULL);
797         TEXT_INSERT(_(" in the Tools menu for more information."));
798         textview_show_icon(textview, GTK_STOCK_DIALOG_ERROR);
799
800 }
801
802 void textview_show_mime_part(TextView *textview, MimeInfo *partinfo)
803 {
804         GtkTextView *text;
805         GtkTextBuffer *buffer;
806         GtkTextIter iter;
807
808         if (!partinfo) return;
809
810         textview_set_font(textview, NULL);
811         textview_clear(textview);
812
813         text = GTK_TEXT_VIEW(textview->text);
814         buffer = gtk_text_view_get_buffer(text);
815         gtk_text_buffer_get_start_iter(buffer, &iter);
816
817         TEXT_INSERT("\n");
818         TEXT_INSERT(_("  The following can be performed on this part by\n"));
819         TEXT_INSERT(_("  right-clicking the icon or list item:\n"));
820
821         TEXT_INSERT(_("     - To save, select "));
822         TEXT_INSERT_LINK(_("'Save as...'"), "sc://save_as", NULL);
823         TEXT_INSERT(_(" (Shortcut key: 'y')\n"));
824         TEXT_INSERT(_("     - To display as text, select "));
825         TEXT_INSERT_LINK(_("'Display as text'"), "sc://display_as_text", NULL);
826         TEXT_INSERT(_(" (Shortcut key: 't')\n"));
827         TEXT_INSERT(_("     - To open with an external program, select "));
828         TEXT_INSERT_LINK(_("'Open'"), "sc://open", NULL);
829         TEXT_INSERT(_(" (Shortcut key: 'l')\n"));
830         TEXT_INSERT(_("       (alternately double-click, or click the middle "));
831         TEXT_INSERT(_("mouse button)\n"));
832         TEXT_INSERT(_("     - Or use "));
833         TEXT_INSERT_LINK(_("'Open with...'"), "sc://open_with", NULL);
834         TEXT_INSERT(_(" (Shortcut key: 'o')\n"));
835         textview_show_icon(textview, GTK_STOCK_DIALOG_INFO);
836 }
837
838 #undef TEXT_INSERT
839 #undef TEXT_INSERT_LINK
840
841 static void textview_write_body(TextView *textview, MimeInfo *mimeinfo)
842 {
843         FILE *tmpfp;
844         gchar buf[BUFFSIZE];
845         CodeConverter *conv;
846         const gchar *charset, *p, *cmd;
847         
848         if (textview->messageview->forced_charset)
849                 charset = textview->messageview->forced_charset;
850         else
851                 charset = procmime_mimeinfo_get_parameter(mimeinfo, "charset");
852
853         textview_set_font(textview, charset);
854
855         conv = conv_code_converter_new(charset);
856
857         procmime_force_encoding(textview->messageview->forced_encoding);
858         
859         textview->is_in_signature = FALSE;
860
861         procmime_decode_content(mimeinfo);
862
863         if (!g_ascii_strcasecmp(mimeinfo->subtype, "html") &&
864             prefs_common.render_html) {
865                 gchar *filename;
866                 
867                 filename = procmime_get_tmp_file_name(mimeinfo);
868                 if (procmime_get_part(filename, mimeinfo) == 0) {
869                         tmpfp = g_fopen(filename, "rb");
870                         textview_show_html(textview, tmpfp, conv);
871                         fclose(tmpfp);
872                         g_unlink(filename);
873                 }
874                 g_free(filename);
875         } else if (!g_ascii_strcasecmp(mimeinfo->subtype, "enriched")) {
876                 gchar *filename;
877                 
878                 filename = procmime_get_tmp_file_name(mimeinfo);
879                 if (procmime_get_part(filename, mimeinfo) == 0) {
880                         tmpfp = g_fopen(filename, "rb");
881                         textview_show_ertf(textview, tmpfp, conv);
882                         fclose(tmpfp);
883                         g_unlink(filename);
884                 }
885                 g_free(filename);
886         } else if ( g_ascii_strcasecmp(mimeinfo->subtype, "plain") &&
887                    (cmd = prefs_common.mime_textviewer) && *cmd &&
888                    (p = strchr(cmd, '%')) && *(p + 1) == 's') {
889                 int pid, pfd[2];
890                 const gchar *fname;
891
892                 fname  = procmime_get_tmp_file_name(mimeinfo);
893                 if (procmime_get_part(fname, mimeinfo)) goto textview_default;
894
895                 g_snprintf(buf, sizeof(buf), cmd, fname);
896                 debug_print("Viewing text content of type: %s (length: %d) "
897                         "using %s\n", mimeinfo->subtype, mimeinfo->length, buf);
898
899                 if (pipe(pfd) < 0) {
900                         g_snprintf(buf, sizeof(buf),
901                                 "pipe failed for textview\n\n%s\n", strerror(errno));
902                         textview_write_line(textview, buf, conv);
903                         goto textview_default;
904                 }
905                 pid = fork();
906                 if (pid < 0) {
907                         g_snprintf(buf, sizeof(buf),
908                                 "fork failed for textview\n\n%s\n", strerror(errno));
909                         textview_write_line(textview, buf, conv);
910                         close(pfd[0]);
911                         close(pfd[1]);
912                         goto textview_default;
913                 }
914                 if (pid == 0) { /* child */
915                         int rc;
916                         gchar **argv;
917                         argv = strsplit_with_quote(buf, " ", 0);
918                         close(1);
919                         close(pfd[0]);
920                         dup(pfd[1]);
921                         rc = execvp(argv[0], argv);
922                         close(pfd[1]);
923                         printf (_("The command to view attachment "
924                                 "as text failed:\n"
925                                 "    %s\n"
926                                 "Exit code %d\n"), buf, rc);
927                         exit(255);
928                 }
929                 close(pfd[1]);
930                 tmpfp = fdopen(pfd[0], "rb");
931                 while (fgets(buf, sizeof(buf), tmpfp))
932                         textview_write_line(textview, buf, conv);
933                 fclose(tmpfp);
934                 waitpid(pid, pfd, 0);
935                 unlink(fname);
936         } else {
937 textview_default:
938                 tmpfp = g_fopen(mimeinfo->data.filename, "rb");
939                 fseek(tmpfp, mimeinfo->offset, SEEK_SET);
940                 debug_print("Viewing text content of type: %s (length: %d)\n", mimeinfo->subtype, mimeinfo->length);
941                 while ((fgets(buf, sizeof(buf), tmpfp) != NULL) && 
942                        (ftell(tmpfp) <= mimeinfo->offset + mimeinfo->length))
943                         textview_write_line(textview, buf, conv);
944                 fclose(tmpfp);
945         }
946
947         conv_code_converter_destroy(conv);
948         procmime_force_encoding(0);
949 }
950
951 static void textview_show_html(TextView *textview, FILE *fp,
952                                CodeConverter *conv)
953 {
954         SC_HTMLParser *parser;
955         gchar *str;
956
957         parser = sc_html_parser_new(fp, conv);
958         g_return_if_fail(parser != NULL);
959
960         while ((str = sc_html_parse(parser)) != NULL) {
961                 if (parser->state == SC_HTML_HREF) {
962                         /* first time : get and copy the URL */
963                         if (parser->href == NULL) {
964                                 /* ALF - the sylpheed html parser returns an empty string,
965                                  * if still inside an <a>, but already parsed past HREF */
966                                 str = strtok(str, " ");
967                                 if (str) {
968                                         while (str && *str && g_ascii_isspace(*str))
969                                                 str++; 
970                                         parser->href = g_strdup(str);
971                                         /* the URL may (or not) be followed by the
972                                          * referenced text */
973                                         str = strtok(NULL, "");
974                                 }       
975                         }
976                         if (str != NULL)
977                                 textview_write_link(textview, str, parser->href, NULL);
978                 } else
979                         textview_write_line(textview, str, NULL);
980         }
981         textview_write_line(textview, "\n", NULL);
982         sc_html_parser_destroy(parser);
983 }
984
985 static void textview_show_ertf(TextView *textview, FILE *fp,
986                                CodeConverter *conv)
987 {
988         ERTFParser *parser;
989         gchar *str;
990
991         parser = ertf_parser_new(fp, conv);
992         g_return_if_fail(parser != NULL);
993
994         while ((str = ertf_parse(parser)) != NULL) {
995                 textview_write_line(textview, str, NULL);
996         }
997         
998         ertf_parser_destroy(parser);
999 }
1000
1001 #define ADD_TXT_POS(bp_, ep_, pti_) \
1002         if ((last->next = alloca(sizeof(struct txtpos))) != NULL) { \
1003                 last = last->next; \
1004                 last->bp = (bp_); last->ep = (ep_); last->pti = (pti_); \
1005                 last->next = NULL; \
1006         } else { \
1007                 g_warning("alloc error scanning URIs\n"); \
1008                 gtk_text_buffer_insert_with_tags_by_name(buffer, &iter, \
1009                                                          linebuf, -1, \
1010                                                          fg_tag, NULL); \
1011                 return; \
1012         }
1013
1014 /* textview_make_clickable_parts() - colorizes clickable parts */
1015 static void textview_make_clickable_parts(TextView *textview,
1016                                           const gchar *fg_tag,
1017                                           const gchar *uri_tag,
1018                                           const gchar *linebuf,
1019                                           gboolean hdr)
1020 {
1021         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1022         GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
1023         GtkTextIter iter;
1024         gchar *mybuf = g_strdup(linebuf);
1025         
1026         /* parse table - in order of priority */
1027         struct table {
1028                 const gchar *needle; /* token */
1029
1030                 /* token search function */
1031                 gchar    *(*search)     (const gchar *haystack,
1032                                          const gchar *needle);
1033                 /* part parsing function */
1034                 gboolean  (*parse)      (const gchar *start,
1035                                          const gchar *scanpos,
1036                                          const gchar **bp_,
1037                                          const gchar **ep_,
1038                                          gboolean hdr);
1039                 /* part to URI function */
1040                 gchar    *(*build_uri)  (const gchar *bp,
1041                                          const gchar *ep);
1042         };
1043
1044         static struct table parser[] = {
1045                 {"http://",  strcasestr, get_uri_part,   make_uri_string},
1046                 {"https://", strcasestr, get_uri_part,   make_uri_string},
1047                 {"ftp://",   strcasestr, get_uri_part,   make_uri_string},
1048                 {"sftp://",  strcasestr, get_uri_part,   make_uri_string},
1049                 {"www.",     strcasestr, get_uri_part,   make_http_string},
1050                 {"mailto:",  strcasestr, get_uri_part,   make_uri_string},
1051                 {"@",        strcasestr, get_email_part, make_email_string}
1052         };
1053         const gint PARSE_ELEMS = sizeof parser / sizeof parser[0];
1054
1055         gint  n;
1056         const gchar *walk, *bp, *ep;
1057
1058         struct txtpos {
1059                 const gchar     *bp, *ep;       /* text position */
1060                 gint             pti;           /* index in parse table */
1061                 struct txtpos   *next;          /* next */
1062         } head = {NULL, NULL, 0,  NULL}, *last = &head;
1063
1064         if (!g_utf8_validate(linebuf, -1, NULL)) {
1065                 mybuf = g_malloc(strlen(linebuf)*2 +1);
1066                 conv_localetodisp(mybuf, strlen(linebuf)*2 +1, linebuf);
1067         }
1068
1069         gtk_text_buffer_get_end_iter(buffer, &iter);
1070
1071         /* parse for clickable parts, and build a list of begin and end positions  */
1072         for (walk = mybuf, n = 0;;) {
1073                 gint last_index = PARSE_ELEMS;
1074                 gchar *scanpos = NULL;
1075
1076                 /* FIXME: this looks phony. scanning for anything in the parse table */
1077                 for (n = 0; n < PARSE_ELEMS; n++) {
1078                         gchar *tmp;
1079
1080                         tmp = parser[n].search(walk, parser[n].needle);
1081                         if (tmp) {
1082                                 if (scanpos == NULL || tmp < scanpos) {
1083                                         scanpos = tmp;
1084                                         last_index = n;
1085                                 }
1086                         }                                       
1087                 }
1088
1089                 if (scanpos) {
1090                         /* check if URI can be parsed */
1091                         if (parser[last_index].parse(walk, scanpos, &bp, &ep, hdr)
1092                             && (size_t) (ep - bp - 1) > strlen(parser[last_index].needle)) {
1093                                         ADD_TXT_POS(bp, ep, last_index);
1094                                         walk = ep;
1095                         } else
1096                                 walk = scanpos +
1097                                         strlen(parser[last_index].needle);
1098                 } else
1099                         break;
1100         }
1101
1102         /* colorize this line */
1103         if (head.next) {
1104                 const gchar *normal_text = mybuf;
1105
1106                 /* insert URIs */
1107                 for (last = head.next; last != NULL;
1108                      normal_text = last->ep, last = last->next) {
1109                         RemoteURI *uri;
1110                         uri = g_new(RemoteURI, 1);
1111                         if (last->bp - normal_text > 0)
1112                                 gtk_text_buffer_insert_with_tags_by_name
1113                                         (buffer, &iter,
1114                                          normal_text,
1115                                          last->bp - normal_text,
1116                                          fg_tag, NULL);
1117                         uri->uri = parser[last->pti].build_uri(last->bp,
1118                                                                last->ep);
1119                         uri->start = gtk_text_iter_get_offset(&iter);
1120                         gtk_text_buffer_insert_with_tags_by_name
1121                                 (buffer, &iter, last->bp, last->ep - last->bp,
1122                                  uri_tag, fg_tag, NULL);
1123                         uri->end = gtk_text_iter_get_offset(&iter);
1124                         uri->filename = NULL;
1125                         textview->uri_list =
1126                                 g_slist_append(textview->uri_list, uri);
1127                 }
1128
1129                 if (*normal_text)
1130                         gtk_text_buffer_insert_with_tags_by_name
1131                                 (buffer, &iter, normal_text, -1, fg_tag, NULL);
1132         } else {
1133                 gtk_text_buffer_insert_with_tags_by_name
1134                         (buffer, &iter, mybuf, -1, fg_tag, NULL);
1135         }
1136         g_free(mybuf);
1137 }
1138
1139 #undef ADD_TXT_POS
1140
1141 static void textview_write_line(TextView *textview, const gchar *str,
1142                                 CodeConverter *conv)
1143 {
1144         GtkTextView *text;
1145         GtkTextBuffer *buffer;
1146         GtkTextIter iter;
1147         gchar buf[BUFFSIZE];
1148         gchar *fg_color;
1149         gint quotelevel = -1;
1150         gchar quote_tag_str[10];
1151
1152         text = GTK_TEXT_VIEW(textview->text);
1153         buffer = gtk_text_view_get_buffer(text);
1154         gtk_text_buffer_get_end_iter(buffer, &iter);
1155
1156         if (!conv)
1157                 strncpy2(buf, str, sizeof(buf));
1158         else if (conv_convert(conv, buf, sizeof(buf), str) < 0)
1159                 conv_localetodisp(buf, sizeof(buf), str);
1160                 
1161         strcrchomp(buf);
1162         fg_color = NULL;
1163
1164         /* change color of quotation
1165            >, foo>, _> ... ok, <foo>, foo bar>, foo-> ... ng
1166            Up to 3 levels of quotations are detected, and each
1167            level is colored using a different color. */
1168         if (prefs_common.enable_color 
1169             && line_has_quote_char(buf, prefs_common.quote_chars)) {
1170                 quotelevel = get_quote_level(buf, prefs_common.quote_chars);
1171
1172                 /* set up the correct foreground color */
1173                 if (quotelevel > 2) {
1174                         /* recycle colors */
1175                         if (prefs_common.recycle_quote_colors)
1176                                 quotelevel %= 3;
1177                         else
1178                                 quotelevel = 2;
1179                 }
1180         }
1181
1182         if (quotelevel == -1)
1183                 fg_color = NULL;
1184         else {
1185                 g_snprintf(quote_tag_str, sizeof(quote_tag_str),
1186                            "quote%d", quotelevel);
1187                 fg_color = quote_tag_str;
1188         }
1189
1190         if (prefs_common.enable_color && (strcmp(buf,"-- \n") == 0 || textview->is_in_signature)) {
1191                 fg_color = "signature";
1192                 textview->is_in_signature = TRUE;
1193         }
1194
1195         textview_make_clickable_parts(textview, fg_color, "link", buf, FALSE);
1196 }
1197
1198 void textview_write_link(TextView *textview, const gchar *str,
1199                          const gchar *uri, CodeConverter *conv)
1200 {
1201         GdkColor *link_color = NULL;
1202         GtkTextView *text;
1203         GtkTextBuffer *buffer;
1204         GtkTextIter iter;
1205         gchar buf[BUFFSIZE];
1206         gchar *bufp;
1207         RemoteURI *r_uri;
1208
1209         if (!str || *str == '\0')
1210                 return;
1211         if (!uri)
1212                 return;
1213
1214         while (uri && *uri && g_ascii_isspace(*uri))
1215                 uri++;
1216                 
1217         text = GTK_TEXT_VIEW(textview->text);
1218         buffer = gtk_text_view_get_buffer(text);
1219         gtk_text_buffer_get_end_iter(buffer, &iter);
1220
1221         if (!conv)
1222                 strncpy2(buf, str, sizeof(buf));
1223         else if (conv_convert(conv, buf, sizeof(buf), str) < 0)
1224                 conv_utf8todisp(buf, sizeof(buf), str);
1225
1226         if (g_utf8_validate(buf, -1, NULL) == FALSE)
1227                 return;
1228
1229         strcrchomp(buf);
1230
1231         gtk_text_buffer_get_end_iter(buffer, &iter);
1232         for (bufp = buf; *bufp != '\0'; bufp = g_utf8_next_char(bufp)) {
1233                 gunichar ch;
1234
1235                 ch = g_utf8_get_char(bufp);
1236                 if (!g_unichar_isspace(ch))
1237                         break;
1238         }
1239         if (bufp > buf)
1240                 gtk_text_buffer_insert(buffer, &iter, buf, bufp - buf);
1241
1242         if (prefs_common.enable_color) {
1243                 link_color = &uri_color;
1244         }
1245         r_uri = g_new(RemoteURI, 1);
1246         r_uri->uri = g_strdup(uri);
1247         r_uri->start = gtk_text_iter_get_offset(&iter);
1248         gtk_text_buffer_insert_with_tags_by_name
1249                 (buffer, &iter, bufp, -1, "link", NULL);
1250         r_uri->end = gtk_text_iter_get_offset(&iter);
1251         r_uri->filename = NULL;
1252         textview->uri_list = g_slist_append(textview->uri_list, r_uri);
1253 }
1254
1255 static void textview_set_cursor(GdkWindow *window, GdkCursor *cursor)
1256 {
1257         if (GDK_IS_WINDOW(window))
1258                 gdk_window_set_cursor(window, cursor);
1259 }
1260 void textview_clear(TextView *textview)
1261 {
1262         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1263         GtkTextBuffer *buffer;
1264         GdkWindow *window = gtk_text_view_get_window(text,
1265                                 GTK_TEXT_WINDOW_TEXT);
1266
1267         buffer = gtk_text_view_get_buffer(text);
1268         gtk_text_buffer_set_text(buffer, "", -1);
1269
1270         TEXTVIEW_STATUSBAR_POP(textview);
1271         textview_uri_list_remove_all(textview->uri_list);
1272         textview->uri_list = NULL;
1273         textview->uri_hover = NULL;
1274
1275         textview->body_pos = 0;
1276         if (textview->image) 
1277                 gtk_widget_destroy(textview->image);
1278         textview->image = NULL;
1279
1280         if (textview->messageview->mainwin->cursor_count == 0) {
1281                 textview_set_cursor(window, text_cursor);
1282         } else {
1283                 textview_set_cursor(window, watch_cursor);
1284         }
1285 }
1286
1287 void textview_destroy(TextView *textview)
1288 {
1289         textview_uri_list_remove_all(textview->uri_list);
1290         textview->uri_list = NULL;
1291
1292         g_free(textview);
1293 }
1294
1295 void textview_set_all_headers(TextView *textview, gboolean all_headers)
1296 {
1297         textview->show_all_headers = all_headers;
1298 }
1299
1300 #define CHANGE_TAG_FONT(tagname, font) { \
1301         tag = gtk_text_tag_table_lookup(tags, tagname); \
1302         if (tag) \
1303                 g_object_set(G_OBJECT(tag), "font-desc", font, NULL); \
1304 }
1305
1306 void textview_set_font(TextView *textview, const gchar *codeset)
1307 {
1308         GtkTextTag *tag;
1309         GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview->text));
1310         GtkTextTagTable *tags = gtk_text_buffer_get_tag_table(buffer);
1311         
1312         if (NORMAL_FONT) {
1313                 PangoFontDescription *font_desc, *bold_font_desc;
1314                 font_desc = pango_font_description_from_string
1315                                                 (NORMAL_FONT);
1316                 bold_font_desc = pango_font_description_from_string
1317                                                 (NORMAL_FONT);
1318                 if (font_desc) {
1319                         gtk_widget_modify_font(textview->text, font_desc);
1320                         CHANGE_TAG_FONT("header", font_desc);
1321                         pango_font_description_free(font_desc);
1322                 }
1323                 if (bold_font_desc) {
1324                         pango_font_description_set_weight
1325                                 (bold_font_desc, PANGO_WEIGHT_BOLD);
1326                         CHANGE_TAG_FONT("header_title", bold_font_desc);
1327                         pango_font_description_free(bold_font_desc);
1328                 }
1329         }
1330
1331         if (prefs_common.textfont) {
1332                 PangoFontDescription *font_desc;
1333
1334                 font_desc = pango_font_description_from_string
1335                                                 (prefs_common.textfont);
1336                 if (font_desc) {
1337                         gtk_widget_modify_font(textview->text, font_desc);
1338                         pango_font_description_free(font_desc);
1339                 }
1340         }
1341         gtk_text_view_set_pixels_above_lines(GTK_TEXT_VIEW(textview->text),
1342                                              prefs_common.line_space / 2);
1343         gtk_text_view_set_pixels_below_lines(GTK_TEXT_VIEW(textview->text),
1344                                              prefs_common.line_space / 2);
1345 }
1346
1347 void textview_set_text(TextView *textview, const gchar *text)
1348 {
1349         GtkTextView *view;
1350         GtkTextBuffer *buffer;
1351
1352         g_return_if_fail(textview != NULL);
1353         g_return_if_fail(text != NULL);
1354
1355         textview_clear(textview);
1356
1357         view = GTK_TEXT_VIEW(textview->text);
1358         buffer = gtk_text_view_get_buffer(view);
1359         gtk_text_buffer_set_text(buffer, text, strlen(text));
1360 }
1361
1362 enum
1363 {
1364         H_DATE          = 0,
1365         H_FROM          = 1,
1366         H_TO            = 2,
1367         H_NEWSGROUPS    = 3,
1368         H_SUBJECT       = 4,
1369         H_CC            = 5,
1370         H_REPLY_TO      = 6,
1371         H_FOLLOWUP_TO   = 7,
1372         H_X_MAILER      = 8,
1373         H_X_NEWSREADER  = 9,
1374         H_USER_AGENT    = 10,
1375         H_ORGANIZATION  = 11,
1376 };
1377
1378 void textview_set_position(TextView *textview, gint pos)
1379 {
1380         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1381
1382         gtkut_text_view_set_position(text, pos);
1383 }
1384
1385 static GPtrArray *textview_scan_header(TextView *textview, FILE *fp)
1386 {
1387         gchar buf[BUFFSIZE];
1388         GPtrArray *headers, *sorted_headers;
1389         GSList *disphdr_list;
1390         Header *header;
1391         gint i;
1392
1393         g_return_val_if_fail(fp != NULL, NULL);
1394
1395         if (textview->show_all_headers)
1396                 return procheader_get_header_array_asis(fp);
1397
1398         if (!prefs_common.display_header) {
1399                 while (fgets(buf, sizeof(buf), fp) != NULL)
1400                         if (buf[0] == '\r' || buf[0] == '\n') break;
1401                 return NULL;
1402         }
1403
1404         headers = procheader_get_header_array_asis(fp);
1405
1406         sorted_headers = g_ptr_array_new();
1407
1408         for (disphdr_list = prefs_common.disphdr_list; disphdr_list != NULL;
1409              disphdr_list = disphdr_list->next) {
1410                 DisplayHeaderProp *dp =
1411                         (DisplayHeaderProp *)disphdr_list->data;
1412
1413                 for (i = 0; i < headers->len; i++) {
1414                         header = g_ptr_array_index(headers, i);
1415
1416                         if (procheader_headername_equal(header->name,
1417                                                         dp->name)) {
1418                                 if (dp->hidden)
1419                                         procheader_header_free(header);
1420                                 else
1421                                         g_ptr_array_add(sorted_headers, header);
1422
1423                                 g_ptr_array_remove_index(headers, i);
1424                                 i--;
1425                         }
1426                 }
1427         }
1428
1429         if (prefs_common.show_other_header) {
1430                 for (i = 0; i < headers->len; i++) {
1431                         header = g_ptr_array_index(headers, i);
1432                         g_ptr_array_add(sorted_headers, header);
1433                 }
1434                 g_ptr_array_free(headers, TRUE);
1435         } else
1436                 procheader_header_array_destroy(headers);
1437
1438
1439         return sorted_headers;
1440 }
1441
1442 static void textview_show_face(TextView *textview)
1443 {
1444         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1445         MsgInfo *msginfo = textview->messageview->msginfo;
1446         int x = 0;
1447         
1448         if (prefs_common.display_header_pane
1449         ||  !prefs_common.display_xface)
1450                 goto bail;
1451         
1452         if (!msginfo->face) {
1453                 goto bail;
1454         }
1455
1456         if (textview->image) 
1457                 gtk_widget_destroy(textview->image);
1458         
1459         textview->image = face_get_from_header(msginfo->face);
1460         g_return_if_fail(textview->image != NULL);
1461
1462         gtk_widget_show(textview->image);
1463         
1464         x = textview->text->allocation.width - WIDTH -5;
1465
1466         gtk_text_view_add_child_in_window(text, textview->image, 
1467                 GTK_TEXT_WINDOW_TEXT, x, 5);
1468
1469         gtk_widget_show_all(textview->text);
1470         
1471
1472         return;
1473 bail:
1474         if (textview->image) 
1475                 gtk_widget_destroy(textview->image);
1476         textview->image = NULL; 
1477 }
1478
1479 static void textview_show_icon(TextView *textview, const gchar *stock_id)
1480 {
1481         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1482         int x = 0;
1483         
1484         if (textview->image) 
1485                 gtk_widget_destroy(textview->image);
1486         
1487         textview->image = gtk_image_new_from_stock(stock_id, GTK_ICON_SIZE_DIALOG);
1488         g_return_if_fail(textview->image != NULL);
1489
1490         gtk_widget_show(textview->image);
1491         
1492         x = textview->text->allocation.width - WIDTH -5;
1493
1494         gtk_text_view_add_child_in_window(text, textview->image, 
1495                 GTK_TEXT_WINDOW_TEXT, x, 5);
1496
1497         gtk_widget_show_all(textview->text);
1498         
1499
1500         return;
1501 }
1502
1503 #if HAVE_LIBCOMPFACE
1504 static void textview_show_xface(TextView *textview)
1505 {
1506         MsgInfo *msginfo = textview->messageview->msginfo;
1507         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1508         int x = 0;
1509
1510         if (prefs_common.display_header_pane
1511         ||  !prefs_common.display_xface)
1512                 goto bail;
1513         
1514         if (!msginfo)
1515                 goto bail;
1516
1517         if (msginfo->face)
1518                 return;
1519         
1520         if (!msginfo->xface || strlen(msginfo->xface) < 5) {
1521                 goto bail;
1522         }
1523
1524         if (textview->image) 
1525                 gtk_widget_destroy(textview->image);
1526         
1527         textview->image = xface_get_from_header(msginfo->xface,
1528                                 &textview->text->style->white,
1529                                 textview->text->window);
1530         g_return_if_fail(textview->image != NULL);
1531
1532         gtk_widget_show(textview->image);
1533         
1534         x = textview->text->allocation.width - WIDTH -5;
1535
1536         gtk_text_view_add_child_in_window(text, textview->image, 
1537                 GTK_TEXT_WINDOW_TEXT, x, 5);
1538
1539         gtk_widget_show_all(textview->text);
1540         
1541         return;
1542 bail:
1543         if (textview->image) 
1544                 gtk_widget_destroy(textview->image);
1545         textview->image = NULL;
1546         
1547 }
1548 #endif
1549
1550 static void textview_show_header(TextView *textview, GPtrArray *headers)
1551 {
1552         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1553         GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
1554         GtkTextIter iter;
1555         Header *header;
1556         gint i;
1557
1558         g_return_if_fail(headers != NULL);
1559
1560         for (i = 0; i < headers->len; i++) {
1561                 header = g_ptr_array_index(headers, i);
1562                 g_return_if_fail(header->name != NULL);
1563
1564                 gtk_text_buffer_get_end_iter (buffer, &iter);
1565                 if(prefs_common.trans_hdr == TRUE) {
1566                         gchar *hdr = g_strndup(header->name, strlen(header->name) - 1);
1567                         gchar *trans_hdr = gettext(hdr);
1568                         gtk_text_buffer_insert_with_tags_by_name(buffer,
1569                                 &iter, trans_hdr, -1,
1570                                 "header_title", "header", NULL);
1571                         gtk_text_buffer_insert_with_tags_by_name(buffer,
1572                                 &iter, ":", 1, "header_title", "header", NULL);
1573                         g_free(hdr);
1574                 } else {
1575                         gtk_text_buffer_insert_with_tags_by_name(buffer,
1576                                 &iter, header->name,
1577                                 -1, "header_title", "header", NULL);
1578                 }
1579                 if (header->name[strlen(header->name) - 1] != ' ')
1580                 gtk_text_buffer_insert_with_tags_by_name
1581                                 (buffer, &iter, " ", 1,
1582                                  "header_title", "header", NULL);
1583
1584                 if (procheader_headername_equal(header->name, "Subject") ||
1585                     procheader_headername_equal(header->name, "From")    ||
1586                     procheader_headername_equal(header->name, "To")      ||
1587                     procheader_headername_equal(header->name, "Cc"))
1588                         unfold_line(header->body);
1589
1590                 if ((procheader_headername_equal(header->name, "X-Mailer") ||
1591                      procheader_headername_equal(header->name,
1592                                                  "X-Newsreader")) &&
1593                     strstr(header->body, "Sylpheed-Claws") != NULL) {
1594                         gtk_text_buffer_get_end_iter (buffer, &iter);
1595                         gtk_text_buffer_insert_with_tags_by_name
1596                                 (buffer, &iter, header->body, -1,
1597                                  "header", "emphasis", NULL);
1598                 } else {
1599                         gboolean hdr = 
1600                           procheader_headername_equal(header->name, "From") ||
1601                           procheader_headername_equal(header->name, "To") ||
1602                           procheader_headername_equal(header->name, "Cc") ||
1603                           procheader_headername_equal(header->name, "Bcc") ||
1604                           procheader_headername_equal(header->name, "Reply-To") ||
1605                           procheader_headername_equal(header->name, "Sender");
1606                         textview_make_clickable_parts(textview, "header", 
1607                                                       "link", header->body, 
1608                                                       hdr);
1609                 }
1610                 gtk_text_buffer_get_end_iter (buffer, &iter);
1611                 gtk_text_buffer_insert_with_tags_by_name(buffer, &iter, "\n", 1,
1612                                                          "header", NULL);
1613         }
1614         
1615         textview_show_face(textview);
1616 #if HAVE_LIBCOMPFACE
1617         textview_show_xface(textview);
1618 #endif
1619 }
1620
1621 gboolean textview_search_string(TextView *textview, const gchar *str,
1622                                 gboolean case_sens)
1623 {
1624         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1625
1626         return gtkut_text_view_search_string(text, str, case_sens);
1627 }
1628
1629 gboolean textview_search_string_backward(TextView *textview, const gchar *str,
1630                                          gboolean case_sens)
1631 {
1632         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1633
1634         return gtkut_text_view_search_string_backward(text, str, case_sens);
1635 }
1636
1637 void textview_scroll_one_line(TextView *textview, gboolean up)
1638 {
1639         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1640         GtkAdjustment *vadj = text->vadjustment;
1641         gfloat upper;
1642
1643         if (prefs_common.enable_smooth_scroll) {
1644                 textview_smooth_scroll_one_line(textview, up);
1645                 return;
1646         }
1647
1648         if (!up) {
1649                 upper = vadj->upper - vadj->page_size;
1650                 if (vadj->value < upper) {
1651                         vadj->value += vadj->step_increment;
1652                         vadj->value = MIN(vadj->value, upper);
1653                         g_signal_emit_by_name(G_OBJECT(vadj),
1654                                               "value_changed", 0);
1655                 }
1656         } else {
1657                 if (vadj->value > 0.0) {
1658                         vadj->value -= vadj->step_increment;
1659                         vadj->value = MAX(vadj->value, 0.0);
1660                         g_signal_emit_by_name(G_OBJECT(vadj),
1661                                               "value_changed", 0);
1662                 }
1663         }
1664 }
1665
1666 gboolean textview_scroll_page(TextView *textview, gboolean up)
1667 {
1668         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1669         GtkAdjustment *vadj = text->vadjustment;
1670         gfloat upper;
1671         gfloat page_incr;
1672
1673         if (prefs_common.enable_smooth_scroll)
1674                 return textview_smooth_scroll_page(textview, up);
1675
1676         if (prefs_common.scroll_halfpage)
1677                 page_incr = vadj->page_increment / 2;
1678         else
1679                 page_incr = vadj->page_increment;
1680
1681         if (!up) {
1682                 upper = vadj->upper - vadj->page_size;
1683                 if (vadj->value < upper) {
1684                         vadj->value += page_incr;
1685                         vadj->value = MIN(vadj->value, upper);
1686                         g_signal_emit_by_name(G_OBJECT(vadj),
1687                                               "value_changed", 0);
1688                 } else
1689                         return FALSE;
1690         } else {
1691                 if (vadj->value > 0.0) {
1692                         vadj->value -= page_incr;
1693                         vadj->value = MAX(vadj->value, 0.0);
1694                         g_signal_emit_by_name(G_OBJECT(vadj),
1695                                               "value_changed", 0);
1696                 } else
1697                         return FALSE;
1698         }
1699
1700         return TRUE;
1701 }
1702
1703 static void textview_smooth_scroll_do(TextView *textview,
1704                                       gfloat old_value, gfloat last_value,
1705                                       gint step)
1706 {
1707         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1708         GtkAdjustment *vadj = text->vadjustment;
1709         gint change_value;
1710         gboolean up;
1711         gint i;
1712
1713         if (old_value < last_value) {
1714                 change_value = last_value - old_value;
1715                 up = FALSE;
1716         } else {
1717                 change_value = old_value - last_value;
1718                 up = TRUE;
1719         }
1720
1721         for (i = step; i <= change_value; i += step) {
1722                 vadj->value = old_value + (up ? -i : i);
1723                 g_signal_emit_by_name(G_OBJECT(vadj),
1724                                       "value_changed", 0);
1725         }
1726
1727         vadj->value = last_value;
1728         g_signal_emit_by_name(G_OBJECT(vadj), "value_changed", 0);
1729
1730         gtk_widget_queue_draw(GTK_WIDGET(text));
1731 }
1732
1733 static void textview_smooth_scroll_one_line(TextView *textview, gboolean up)
1734 {
1735         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1736         GtkAdjustment *vadj = text->vadjustment;
1737         gfloat upper;
1738         gfloat old_value;
1739         gfloat last_value;
1740
1741         if (!up) {
1742                 upper = vadj->upper - vadj->page_size;
1743                 if (vadj->value < upper) {
1744                         old_value = vadj->value;
1745                         last_value = vadj->value + vadj->step_increment;
1746                         last_value = MIN(last_value, upper);
1747
1748                         textview_smooth_scroll_do(textview, old_value,
1749                                                   last_value,
1750                                                   prefs_common.scroll_step);
1751                 }
1752         } else {
1753                 if (vadj->value > 0.0) {
1754                         old_value = vadj->value;
1755                         last_value = vadj->value - vadj->step_increment;
1756                         last_value = MAX(last_value, 0.0);
1757
1758                         textview_smooth_scroll_do(textview, old_value,
1759                                                   last_value,
1760                                                   prefs_common.scroll_step);
1761                 }
1762         }
1763 }
1764
1765 static gboolean textview_smooth_scroll_page(TextView *textview, gboolean up)
1766 {
1767         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1768         GtkAdjustment *vadj = text->vadjustment;
1769         gfloat upper;
1770         gfloat page_incr;
1771         gfloat old_value;
1772         gfloat last_value;
1773
1774         if (prefs_common.scroll_halfpage)
1775                 page_incr = vadj->page_increment / 2;
1776         else
1777                 page_incr = vadj->page_increment;
1778
1779         if (!up) {
1780                 upper = vadj->upper - vadj->page_size;
1781                 if (vadj->value < upper) {
1782                         old_value = vadj->value;
1783                         last_value = vadj->value + page_incr;
1784                         last_value = MIN(last_value, upper);
1785
1786                         textview_smooth_scroll_do(textview, old_value,
1787                                                   last_value,
1788                                                   prefs_common.scroll_step);
1789                 } else
1790                         return FALSE;
1791         } else {
1792                 if (vadj->value > 0.0) {
1793                         old_value = vadj->value;
1794                         last_value = vadj->value - page_incr;
1795                         last_value = MAX(last_value, 0.0);
1796
1797                         textview_smooth_scroll_do(textview, old_value,
1798                                                   last_value,
1799                                                   prefs_common.scroll_step);
1800                 } else
1801                         return FALSE;
1802         }
1803
1804         return TRUE;
1805 }
1806
1807 #define KEY_PRESS_EVENT_STOP() \
1808         g_signal_stop_emission_by_name(G_OBJECT(widget), \
1809                                        "key_press_event");
1810
1811 static gint textview_key_pressed(GtkWidget *widget, GdkEventKey *event,
1812                                  TextView *textview)
1813 {
1814         SummaryView *summaryview = NULL;
1815         MessageView *messageview = textview->messageview;
1816
1817         if (!event) return FALSE;
1818         if (messageview->mainwin)
1819                 summaryview = messageview->mainwin->summaryview;
1820
1821         switch (event->keyval) {
1822         case GDK_Tab:
1823         case GDK_Home:
1824         case GDK_Left:
1825         case GDK_Up:
1826         case GDK_Right:
1827         case GDK_Down:
1828         case GDK_Page_Up:
1829         case GDK_Page_Down:
1830         case GDK_End:
1831         case GDK_Control_L:
1832         case GDK_Control_R:
1833                 return FALSE;
1834         case GDK_space:
1835                 if (summaryview)
1836                         summary_pass_key_press_event(summaryview, event);
1837                 else
1838                         textview_scroll_page
1839                                 (textview,
1840                                  (event->state &
1841                                   (GDK_SHIFT_MASK|GDK_MOD1_MASK)) != 0);
1842                 break;
1843         case GDK_BackSpace:
1844                 textview_scroll_page(textview, TRUE);
1845                 break;
1846         case GDK_Return:
1847                 textview_scroll_one_line
1848                         (textview, (event->state &
1849                                     (GDK_SHIFT_MASK|GDK_MOD1_MASK)) != 0);
1850                 break;
1851         case GDK_Delete:
1852                 if (summaryview)
1853                         summary_pass_key_press_event(summaryview, event);
1854                 break;
1855         case GDK_y:
1856         case GDK_t:
1857         case GDK_l:
1858         case GDK_c:
1859                 if ((event->state & (GDK_MOD1_MASK|GDK_CONTROL_MASK)) == 0) {
1860                         KEY_PRESS_EVENT_STOP();
1861                         mimeview_pass_key_press_event(messageview->mimeview,
1862                                                       event);
1863                         break;
1864                 }
1865                 /* possible fall through */
1866         default:
1867                 if (summaryview &&
1868                     event->window != messageview->mainwin->window->window) {
1869                         GdkEventKey tmpev = *event;
1870
1871                         tmpev.window = messageview->mainwin->window->window;
1872                         KEY_PRESS_EVENT_STOP();
1873                         gtk_widget_event(messageview->mainwin->window,
1874                                          (GdkEvent *)&tmpev);
1875                 }
1876                 break;
1877         }
1878
1879         return TRUE;
1880 }
1881
1882 static gboolean textview_motion_notify(GtkWidget *widget,
1883                                        GdkEventMotion *event,
1884                                        TextView *textview)
1885 {
1886         textview_uri_update(textview, event->x, event->y);
1887         gdk_window_get_pointer(widget->window, NULL, NULL, NULL);
1888
1889         return FALSE;
1890 }
1891
1892 static gboolean textview_leave_notify(GtkWidget *widget,
1893                                       GdkEventCrossing *event,
1894                                       TextView *textview)
1895 {
1896         textview_uri_update(textview, -1, -1);
1897
1898         return FALSE;
1899 }
1900
1901 static gboolean textview_visibility_notify(GtkWidget *widget,
1902                                            GdkEventVisibility *event,
1903                                            TextView *textview)
1904 {
1905         gint wx, wy;
1906         GdkWindow *window;
1907
1908         window = gtk_text_view_get_window(GTK_TEXT_VIEW(widget),
1909                                           GTK_TEXT_WINDOW_TEXT);
1910
1911         /* check if occurred for the text window part */
1912         if (window != event->window)
1913                 return FALSE;
1914         
1915         gdk_window_get_pointer(widget->window, &wx, &wy, NULL);
1916         textview_uri_update(textview, wx, wy);
1917
1918         return FALSE;
1919 }
1920
1921 void textview_cursor_wait(TextView *textview)
1922 {
1923         GdkWindow *window = gtk_text_view_get_window(
1924                         GTK_TEXT_VIEW(textview->text),
1925                         GTK_TEXT_WINDOW_TEXT);
1926         textview_set_cursor(window, watch_cursor);
1927 }
1928
1929 void textview_cursor_normal(TextView *textview)
1930 {
1931         GdkWindow *window = gtk_text_view_get_window(
1932                         GTK_TEXT_VIEW(textview->text),
1933                         GTK_TEXT_WINDOW_TEXT);
1934         textview_set_cursor(window, text_cursor);
1935 }
1936
1937 static void textview_uri_update(TextView *textview, gint x, gint y)
1938 {
1939         GtkTextBuffer *buffer;
1940         GtkTextIter start_iter, end_iter;
1941         RemoteURI *uri = NULL;
1942         
1943         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview->text));
1944
1945         if (x != -1 && y != -1) {
1946                 gint bx, by;
1947                 GtkTextIter iter;
1948                 GSList *tags;
1949                 GSList *cur;
1950             
1951                 gtk_text_view_window_to_buffer_coords(GTK_TEXT_VIEW(textview->text), 
1952                                                       GTK_TEXT_WINDOW_WIDGET,
1953                                                       x, y, &bx, &by);
1954                 gtk_text_view_get_iter_at_location(GTK_TEXT_VIEW(textview->text),
1955                                                    &iter, bx, by);
1956
1957                 tags = gtk_text_iter_get_tags(&iter);
1958                 for (cur = tags; cur != NULL; cur = cur->next) {
1959                         GtkTextTag *tag = cur->data;
1960                         char *name;
1961
1962                         g_object_get(G_OBJECT(tag), "name", &name, NULL);
1963                         if (!strcmp(name, "link")
1964                             && textview_get_uri_range(textview, &iter, tag,
1965                                                       &start_iter, &end_iter))
1966                                 uri = textview_get_uri_from_range(textview,
1967                                                                   &iter, tag,
1968                                                                   &start_iter,
1969                                                                   &end_iter);
1970                         g_free(name);
1971
1972                         if (uri)
1973                                 break;
1974                 }
1975                 g_slist_free(tags);
1976         }
1977         
1978         if (uri != textview->uri_hover) {
1979                 GdkWindow *window;
1980
1981                 if (textview->uri_hover)
1982                         gtk_text_buffer_remove_tag_by_name(buffer,
1983                                                            "link-hover",
1984                                                            &textview->uri_hover_start_iter,
1985                                                            &textview->uri_hover_end_iter);
1986                     
1987                 textview->uri_hover = uri;
1988                 if (uri) {
1989                         textview->uri_hover_start_iter = start_iter;
1990                         textview->uri_hover_end_iter = end_iter;
1991                 }
1992                 
1993                 window = gtk_text_view_get_window(GTK_TEXT_VIEW(textview->text),
1994                                                   GTK_TEXT_WINDOW_TEXT);
1995                 if (textview->messageview->mainwin->cursor_count == 0) {
1996                         textview_set_cursor(window, uri ? hand_cursor : text_cursor);
1997                 } else {
1998                         textview_set_cursor(window, watch_cursor);
1999                 }
2000
2001                 TEXTVIEW_STATUSBAR_POP(textview);
2002
2003                 if (uri) {
2004                         char *trimmed_uri;
2005
2006                         gtk_text_buffer_apply_tag_by_name(buffer,
2007                                                           "link-hover",
2008                                                           &start_iter,
2009                                                           &end_iter);
2010
2011                         trimmed_uri = trim_string(uri->uri, 60);
2012                         TEXTVIEW_STATUSBAR_PUSH(textview, trimmed_uri);
2013                         g_free(trimmed_uri);
2014                 }
2015         }
2016 }
2017
2018 static gboolean textview_get_uri_range(TextView *textview,
2019                                        GtkTextIter *iter,
2020                                        GtkTextTag *tag,
2021                                        GtkTextIter *start_iter,
2022                                        GtkTextIter *end_iter)
2023 {
2024         return get_tag_range(iter, tag, start_iter, end_iter);
2025 }
2026
2027 static RemoteURI *textview_get_uri_from_range(TextView *textview,
2028                                               GtkTextIter *iter,
2029                                               GtkTextTag *tag,
2030                                               GtkTextIter *start_iter,
2031                                               GtkTextIter *end_iter)
2032 {
2033         gint start_pos, end_pos, cur_pos;
2034         RemoteURI *uri = NULL;
2035         GSList *cur;
2036
2037         start_pos = gtk_text_iter_get_offset(start_iter);
2038         end_pos = gtk_text_iter_get_offset(end_iter);
2039         cur_pos = gtk_text_iter_get_offset(iter);
2040
2041         for (cur = textview->uri_list; cur != NULL; cur = cur->next) {
2042                 RemoteURI *uri_ = (RemoteURI *)cur->data;
2043                 if (start_pos == uri_->start &&
2044                     end_pos ==  uri_->end) {
2045                         uri = uri_;
2046                         break;
2047                 } else if (start_pos == uri_->start ||
2048                            end_pos == uri_->end) {
2049                         /* in case of contiguous links, textview_get_uri_range
2050                          * returns a broader range (start of 1st link to end
2051                          * of last link).
2052                          * In that case, correct link is the one covering
2053                          * current iter.
2054                          */
2055                         if (uri_->start <= cur_pos && cur_pos <= uri_->end) {
2056                                 uri = uri_;
2057                                 break;
2058                         }
2059                 } 
2060         }
2061
2062         return uri;
2063 }
2064
2065 static RemoteURI *textview_get_uri(TextView *textview,
2066                                    GtkTextIter *iter,
2067                                    GtkTextTag *tag)
2068 {
2069         GtkTextIter start_iter, end_iter;
2070         RemoteURI *uri = NULL;
2071
2072         if (textview_get_uri_range(textview, iter, tag, &start_iter,
2073                                    &end_iter))
2074                 uri = textview_get_uri_from_range(textview, iter, tag,
2075                                                   &start_iter, &end_iter);
2076
2077         return uri;
2078 }
2079
2080 static gboolean textview_uri_button_pressed(GtkTextTag *tag, GObject *obj,
2081                                             GdkEvent *event, GtkTextIter *iter,
2082                                             TextView *textview)
2083 {
2084         GdkEventButton *bevent;
2085         RemoteURI *uri = NULL;
2086
2087         if (!event)
2088                 return FALSE;
2089
2090         if (event->type != GDK_BUTTON_PRESS && event->type != GDK_2BUTTON_PRESS
2091                 && event->type != GDK_MOTION_NOTIFY)
2092                 return FALSE;
2093
2094         uri = textview_get_uri(textview, iter, tag);
2095         if (!uri)
2096                 return FALSE;
2097
2098         bevent = (GdkEventButton *) event;
2099         
2100         /* doubleclick: open compose / add address / browser */
2101         if ((event->type == GDK_BUTTON_PRESS && bevent->button == 1) ||
2102                 bevent->button == 2 || bevent->button == 3) {
2103                 if (uri->filename && !g_ascii_strncasecmp(uri->filename, "sc://", 5)) {
2104                         MimeView *mimeview = 
2105                                 (textview->messageview)?
2106                                         textview->messageview->mimeview:NULL;
2107                         if (mimeview && bevent->button == 1) {
2108                                 mimeview_handle_cmd(mimeview, uri->filename, NULL, uri->data);
2109                         } else if (mimeview && bevent->button == 2 && 
2110                                 !g_ascii_strcasecmp(uri->filename, "sc://select_attachment")) {
2111                                 mimeview_handle_cmd(mimeview, "sc://open_attachment", NULL, uri->data);
2112                         } else if (mimeview && bevent->button == 3 && 
2113                                 !g_ascii_strcasecmp(uri->filename, "sc://select_attachment")) {
2114                                 mimeview_handle_cmd(mimeview, "sc://menu_attachment", bevent, uri->data);
2115                         } 
2116                         return TRUE;
2117                 } else if (!g_ascii_strncasecmp(uri->uri, "mailto:", 7)) {
2118                         if (bevent->button == 3) {
2119                                 g_object_set_data(
2120                                         G_OBJECT(textview->mail_popup_menu),
2121                                         "menu_button", uri);
2122                                 gtk_menu_popup(GTK_MENU(textview->mail_popup_menu), 
2123                                                NULL, NULL, NULL, NULL, 
2124                                                bevent->button, bevent->time);
2125                         } else {
2126                                 PrefsAccount *account = NULL;
2127
2128                                 if (textview->messageview && textview->messageview->msginfo &&
2129                                     textview->messageview->msginfo->folder) {
2130                                         FolderItem   *folder_item;
2131
2132                                         folder_item = textview->messageview->msginfo->folder;
2133                                         if (folder_item->prefs && folder_item->prefs->enable_default_account)
2134                                                 account = account_find_from_id(folder_item->prefs->default_account);
2135                                 }
2136                                 compose_new(account, uri->uri + 7, NULL);
2137                         }
2138                         return TRUE;
2139                 } else if (g_ascii_strncasecmp(uri->uri, "file:", 5)) {
2140                         if (bevent->button == 1 &&
2141                             textview_uri_security_check(textview, uri) == TRUE) 
2142                                         open_uri(uri->uri,
2143                                                  prefs_common.uri_cmd);
2144                         else if (bevent->button == 3) {
2145                                 g_object_set_data(
2146                                         G_OBJECT(textview->link_popup_menu),
2147                                         "menu_button", uri);
2148                                 gtk_menu_popup(GTK_MENU(textview->link_popup_menu), 
2149                                                NULL, NULL, NULL, NULL, 
2150                                                bevent->button, bevent->time);
2151                         }
2152                         return TRUE;
2153                 } else {
2154                         if (bevent->button == 3) {
2155                                 g_object_set_data(
2156                                         G_OBJECT(textview->file_popup_menu),
2157                                         "menu_button", uri);
2158                                 gtk_menu_popup(GTK_MENU(textview->file_popup_menu), 
2159                                                NULL, NULL, NULL, NULL, 
2160                                                bevent->button, bevent->time);
2161                                 return TRUE;
2162                         }
2163                 }
2164         }
2165
2166         return FALSE;
2167 }
2168
2169 /*!
2170  *\brief    Check to see if a web URL has been disguised as a different
2171  *          URL (possible with HTML email).
2172  *
2173  *\param    uri The uri to check
2174  *
2175  *\param    textview The TextView the URL is contained in
2176  *
2177  *\return   gboolean TRUE if the URL is ok, or if the user chose to open
2178  *          it anyway, otherwise FALSE          
2179  */
2180 static gboolean textview_uri_security_check(TextView *textview, RemoteURI *uri)
2181 {
2182         gchar *visible_str;
2183         gboolean retval = TRUE;
2184         GtkTextBuffer *buffer;
2185         GtkTextIter start, end;
2186
2187         if (is_uri_string(uri->uri) == FALSE)
2188                 return TRUE;
2189
2190         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview->text));
2191
2192         gtk_text_buffer_get_iter_at_offset(buffer, &start, uri->start);
2193         gtk_text_buffer_get_iter_at_offset(buffer, &end,   uri->end);
2194
2195         visible_str = gtk_text_buffer_get_text(buffer, &start, &end, FALSE);
2196
2197         if (visible_str == NULL)
2198                 return TRUE;
2199
2200         if (strcmp(visible_str, uri->uri) != 0 && is_uri_string(visible_str)) {
2201                 gchar *uri_path;
2202                 gchar *visible_uri_path;
2203
2204                 uri_path = get_uri_path(uri->uri);
2205                 visible_uri_path = get_uri_path(visible_str);
2206                 if (path_cmp(uri_path, visible_uri_path) != 0)
2207                         retval = FALSE;
2208         }
2209
2210         if (retval == FALSE) {
2211                 gchar *msg;
2212                 AlertValue aval;
2213
2214                 msg = g_markup_printf_escaped(_("The real URL is different from "
2215                                                 "the displayed URL.\n"
2216                                                 "\n"
2217                                                 "<b>Displayed URL:</b> %s\n"
2218                                                 "\n"
2219                                                 "<b>Real URL:</b> %s\n"
2220                                                 "\n"
2221                                                 "Open it anyway?"),
2222                                                visible_str,uri->uri);
2223                 aval = alertpanel_full(_("Phishing attempt warning"), msg,
2224                                        GTK_STOCK_CANCEL, _("_Open URL"), NULL, FALSE,
2225                                        NULL, ALERT_WARNING, G_ALERTDEFAULT);
2226                 g_free(msg);
2227                 if (aval == G_ALERTALTERNATE)
2228                         retval = TRUE;
2229         }
2230
2231         g_free(visible_str);
2232
2233         return retval;
2234 }
2235
2236 static void textview_uri_list_remove_all(GSList *uri_list)
2237 {
2238         GSList *cur;
2239
2240         for (cur = uri_list; cur != NULL; cur = cur->next) {
2241                 if (cur->data) {
2242                         g_free(((RemoteURI *)cur->data)->uri);
2243                         g_free(((RemoteURI *)cur->data)->filename);
2244                         g_free(cur->data);
2245                 }
2246         }
2247
2248         g_slist_free(uri_list);
2249 }
2250
2251 static void open_uri_cb (TextView *textview, guint action, void *data)
2252 {
2253         RemoteURI *uri = g_object_get_data(G_OBJECT(textview->link_popup_menu),
2254                                            "menu_button");
2255         if (uri == NULL)
2256                 return;
2257
2258         if (textview_uri_security_check(textview, uri) == TRUE) 
2259                 open_uri(uri->uri,
2260                          prefs_common.uri_cmd);
2261         g_object_set_data(G_OBJECT(textview->link_popup_menu), "menu_button",
2262                           NULL);
2263 }
2264
2265 static void open_image_cb (TextView *textview, guint action, void *data)
2266 {
2267         RemoteURI *uri = g_object_get_data(G_OBJECT(textview->file_popup_menu),
2268                                            "menu_button");
2269
2270         static gchar *default_cmdline = DEFAULT_IMAGE_VIEWER_CMD;
2271         gchar buf[1024];
2272         const gchar *cmd;
2273         const gchar *def_cmd;
2274         const gchar *p;
2275         gchar *filename = NULL;
2276         gchar *tmp_filename = NULL;
2277
2278         if (uri == NULL)
2279                 return;
2280
2281         if (uri->filename == NULL)
2282                 return;
2283         
2284         filename = g_strdup(uri->filename);
2285         
2286         if (!g_utf8_validate(filename, -1, NULL)) {
2287                 gchar *tmp = conv_filename_to_utf8(filename);
2288                 g_free(filename);
2289                 filename = tmp;
2290         }
2291
2292         subst_for_filename(filename);
2293
2294         tmp_filename = g_filename_from_uri(uri->uri, NULL, NULL);
2295         copy_file(tmp_filename, filename, FALSE);
2296         g_free(tmp_filename);
2297
2298         cmd = prefs_common.mime_image_viewer;
2299         def_cmd = default_cmdline;
2300         
2301         if (cmd && (p = strchr(cmd, '%')) && *(p + 1) == 's' &&
2302             !strchr(p + 2, '%'))
2303                 g_snprintf(buf, sizeof(buf), cmd, filename);
2304         else {
2305                 if (cmd)
2306                         g_warning("Image viewer command line is invalid: '%s'", cmd);
2307                 if (def_cmd)
2308                         g_snprintf(buf, sizeof(buf), def_cmd, filename);
2309                 else
2310                         return;
2311         }
2312
2313         execute_command_line(buf, TRUE);
2314
2315         g_free(filename);
2316
2317         g_object_set_data(G_OBJECT(textview->file_popup_menu), "menu_button",
2318                           NULL);
2319 }
2320
2321 static void save_file_cb (TextView *textview, guint action, void *data)
2322 {
2323         RemoteURI *uri = g_object_get_data(G_OBJECT(textview->file_popup_menu),
2324                                            "menu_button");
2325         gchar *filename = NULL;
2326         gchar *filepath = NULL;
2327         gchar *filedir = NULL;
2328         gchar *tmp_filename = NULL;
2329         if (uri == NULL)
2330                 return;
2331
2332         if (uri->filename == NULL)
2333                 return;
2334         
2335         filename = g_strdup(uri->filename);
2336         
2337         if (!g_utf8_validate(filename, -1, NULL)) {
2338                 gchar *tmp = conv_filename_to_utf8(filename);
2339                 g_free(filename);
2340                 filename = tmp;
2341         }
2342
2343         subst_for_filename(filename);
2344         
2345         if (prefs_common.attach_save_dir)
2346                 filepath = g_strconcat(prefs_common.attach_save_dir,
2347                                        G_DIR_SEPARATOR_S, filename, NULL);
2348         else
2349                 filepath = g_strdup(filename);
2350
2351         g_free(filename);
2352
2353         filename = filesel_select_file_save(_("Save as"), filepath);
2354         if (!filename) {
2355                 g_free(filepath);
2356                 return;
2357         }
2358
2359         if (is_file_exist(filename)) {
2360                 AlertValue aval;
2361                 gchar *res;
2362                 
2363                 res = g_strdup_printf(_("Overwrite existing file '%s'?"),
2364                                       filename);
2365                 aval = alertpanel(_("Overwrite"), res, GTK_STOCK_CANCEL, 
2366                                   GTK_STOCK_OK, NULL);
2367                 g_free(res);                                      
2368                 if (G_ALERTALTERNATE != aval)
2369                         return;
2370         }
2371
2372         tmp_filename = g_filename_from_uri(uri->uri, NULL, NULL);
2373         copy_file(tmp_filename, filename, FALSE);
2374         g_free(tmp_filename);
2375         
2376         filedir = g_path_get_dirname(filename);
2377         if (filedir && strcmp(filedir, ".")) {
2378                 g_free(prefs_common.attach_save_dir);
2379                 prefs_common.attach_save_dir = g_strdup(filedir);
2380         }
2381
2382         g_free(filedir);
2383         g_free(filepath);
2384
2385         g_object_set_data(G_OBJECT(textview->file_popup_menu), "menu_button",
2386                           NULL);
2387 }
2388
2389 static void copy_uri_cb (TextView *textview, guint action, void *data)
2390 {
2391         RemoteURI *uri = g_object_get_data(G_OBJECT(textview->link_popup_menu),
2392                                            "menu_button");
2393         if (uri == NULL)
2394                 return;
2395
2396         gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), uri->uri, -1);
2397         gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), uri->uri, -1);
2398         g_object_set_data(G_OBJECT(textview->link_popup_menu), "menu_button",
2399                           NULL);
2400 }
2401
2402 static void add_uri_to_addrbook_cb (TextView *textview, guint action, void *data)
2403 {
2404         gchar *fromname, *fromaddress;
2405         RemoteURI *uri = g_object_get_data(G_OBJECT(textview->mail_popup_menu),
2406                                            "menu_button");
2407         if (uri == NULL)
2408                 return;
2409
2410         /* extract url */
2411         fromaddress = g_strdup(uri->uri + 7);
2412         /* Hiroyuki: please put this function in utils.c! */
2413         fromname = procheader_get_fromname(fromaddress);
2414         extract_address(fromaddress);
2415         g_message("adding from textview %s <%s>", fromname, fromaddress);
2416         /* Add to address book - Match */
2417         addressbook_add_contact( fromname, fromaddress, NULL );
2418
2419         g_free(fromaddress);
2420         g_free(fromname);
2421 }
2422
2423 static void mail_to_uri_cb (TextView *textview, guint action, void *data)
2424 {
2425         PrefsAccount *account = NULL;
2426         RemoteURI *uri = g_object_get_data(G_OBJECT(textview->mail_popup_menu),
2427                                            "menu_button");
2428         if (uri == NULL)
2429                 return;
2430
2431         if (textview->messageview && textview->messageview->msginfo &&
2432             textview->messageview->msginfo->folder) {
2433                 FolderItem   *folder_item;
2434
2435                 folder_item = textview->messageview->msginfo->folder;
2436                 if (folder_item->prefs && folder_item->prefs->enable_default_account)
2437                         account = account_find_from_id(folder_item->prefs->default_account);
2438         }
2439         compose_new(account, uri->uri + 7, NULL);
2440 }
2441
2442 static void copy_mail_to_uri_cb (TextView *textview, guint action, void *data)
2443 {
2444         RemoteURI *uri = g_object_get_data(G_OBJECT(textview->mail_popup_menu),
2445                                            "menu_button");
2446         if (uri == NULL)
2447                 return;
2448
2449         gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), uri->uri +7, -1);
2450         gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), uri->uri +7, -1);
2451         g_object_set_data(G_OBJECT(textview->mail_popup_menu), "menu_button",
2452                           NULL);
2453 }
2454