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