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