2006-03-12 [paul] 2.0.0cvs135
[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                 if(prefs_common.trans_hdr == TRUE) {
1386                         gchar *hdr = g_strndup(header->name, strlen(header->name) - 1);
1387                         gchar *trans_hdr = gettext(hdr);
1388                         gtk_text_buffer_insert_with_tags_by_name(buffer,
1389                                 &iter, trans_hdr, -1,
1390                                 "header_title", "header", NULL);
1391                         gtk_text_buffer_insert_with_tags_by_name(buffer,
1392                                 &iter, ":", 1, "header_title", "header", NULL);
1393                         g_free(hdr);
1394                 } else {
1395                         gtk_text_buffer_insert_with_tags_by_name(buffer,
1396                                 &iter, header->name,
1397                                 -1, "header_title", "header", NULL);
1398                 }
1399                 if (header->name[strlen(header->name) - 1] != ' ')
1400                 gtk_text_buffer_insert_with_tags_by_name
1401                                 (buffer, &iter, " ", 1,
1402                                  "header_title", "header", NULL);
1403
1404                 if (procheader_headername_equal(header->name, "Subject") ||
1405                     procheader_headername_equal(header->name, "From")    ||
1406                     procheader_headername_equal(header->name, "To")      ||
1407                     procheader_headername_equal(header->name, "Cc"))
1408                         unfold_line(header->body);
1409
1410                 if ((procheader_headername_equal(header->name, "X-Mailer") ||
1411                      procheader_headername_equal(header->name,
1412                                                  "X-Newsreader")) &&
1413                     strstr(header->body, "Sylpheed") != NULL) {
1414                         gtk_text_buffer_get_end_iter (buffer, &iter);
1415                         gtk_text_buffer_insert_with_tags_by_name
1416                                 (buffer, &iter, header->body, -1,
1417                                  "header", "emphasis", NULL);
1418                 } else {
1419                         gboolean hdr = 
1420                           procheader_headername_equal(header->name, "From") ||
1421                           procheader_headername_equal(header->name, "To") ||
1422                           procheader_headername_equal(header->name, "Cc") ||
1423                           procheader_headername_equal(header->name, "Bcc");
1424                         textview_make_clickable_parts(textview, "header", 
1425                                                       "link", header->body, 
1426                                                       hdr);
1427                 }
1428                 gtk_text_buffer_get_end_iter (buffer, &iter);
1429                 gtk_text_buffer_insert_with_tags_by_name(buffer, &iter, "\n", 1,
1430                                                          "header", NULL);
1431         }
1432         
1433         textview_show_face(textview);
1434 #if HAVE_LIBCOMPFACE
1435         textview_show_xface(textview);
1436 #endif
1437 }
1438
1439 gboolean textview_search_string(TextView *textview, const gchar *str,
1440                                 gboolean case_sens)
1441 {
1442         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1443
1444         return gtkut_text_view_search_string(text, str, case_sens);
1445 }
1446
1447 gboolean textview_search_string_backward(TextView *textview, const gchar *str,
1448                                          gboolean case_sens)
1449 {
1450         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1451
1452         return gtkut_text_view_search_string_backward(text, str, case_sens);
1453 }
1454
1455 void textview_scroll_one_line(TextView *textview, gboolean up)
1456 {
1457         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1458         GtkAdjustment *vadj = text->vadjustment;
1459         gfloat upper;
1460
1461         if (prefs_common.enable_smooth_scroll) {
1462                 textview_smooth_scroll_one_line(textview, up);
1463                 return;
1464         }
1465
1466         if (!up) {
1467                 upper = vadj->upper - vadj->page_size;
1468                 if (vadj->value < upper) {
1469                         vadj->value += vadj->step_increment;
1470                         vadj->value = MIN(vadj->value, upper);
1471                         g_signal_emit_by_name(G_OBJECT(vadj),
1472                                               "value_changed", 0);
1473                 }
1474         } else {
1475                 if (vadj->value > 0.0) {
1476                         vadj->value -= vadj->step_increment;
1477                         vadj->value = MAX(vadj->value, 0.0);
1478                         g_signal_emit_by_name(G_OBJECT(vadj),
1479                                               "value_changed", 0);
1480                 }
1481         }
1482 }
1483
1484 gboolean textview_scroll_page(TextView *textview, gboolean up)
1485 {
1486         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1487         GtkAdjustment *vadj = text->vadjustment;
1488         gfloat upper;
1489         gfloat page_incr;
1490
1491         if (prefs_common.enable_smooth_scroll)
1492                 return textview_smooth_scroll_page(textview, up);
1493
1494         if (prefs_common.scroll_halfpage)
1495                 page_incr = vadj->page_increment / 2;
1496         else
1497                 page_incr = vadj->page_increment;
1498
1499         if (!up) {
1500                 upper = vadj->upper - vadj->page_size;
1501                 if (vadj->value < upper) {
1502                         vadj->value += page_incr;
1503                         vadj->value = MIN(vadj->value, upper);
1504                         g_signal_emit_by_name(G_OBJECT(vadj),
1505                                               "value_changed", 0);
1506                 } else
1507                         return FALSE;
1508         } else {
1509                 if (vadj->value > 0.0) {
1510                         vadj->value -= page_incr;
1511                         vadj->value = MAX(vadj->value, 0.0);
1512                         g_signal_emit_by_name(G_OBJECT(vadj),
1513                                               "value_changed", 0);
1514                 } else
1515                         return FALSE;
1516         }
1517
1518         return TRUE;
1519 }
1520
1521 static void textview_smooth_scroll_do(TextView *textview,
1522                                       gfloat old_value, gfloat last_value,
1523                                       gint step)
1524 {
1525         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1526         GtkAdjustment *vadj = text->vadjustment;
1527         gint change_value;
1528         gboolean up;
1529         gint i;
1530
1531         if (old_value < last_value) {
1532                 change_value = last_value - old_value;
1533                 up = FALSE;
1534         } else {
1535                 change_value = old_value - last_value;
1536                 up = TRUE;
1537         }
1538
1539         for (i = step; i <= change_value; i += step) {
1540                 vadj->value = old_value + (up ? -i : i);
1541                 g_signal_emit_by_name(G_OBJECT(vadj),
1542                                       "value_changed", 0);
1543         }
1544
1545         vadj->value = last_value;
1546         g_signal_emit_by_name(G_OBJECT(vadj), "value_changed", 0);
1547
1548         gtk_widget_queue_draw(GTK_WIDGET(text));
1549 }
1550
1551 static void textview_smooth_scroll_one_line(TextView *textview, gboolean up)
1552 {
1553         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1554         GtkAdjustment *vadj = text->vadjustment;
1555         gfloat upper;
1556         gfloat old_value;
1557         gfloat last_value;
1558
1559         if (!up) {
1560                 upper = vadj->upper - vadj->page_size;
1561                 if (vadj->value < upper) {
1562                         old_value = vadj->value;
1563                         last_value = vadj->value + vadj->step_increment;
1564                         last_value = MIN(last_value, upper);
1565
1566                         textview_smooth_scroll_do(textview, old_value,
1567                                                   last_value,
1568                                                   prefs_common.scroll_step);
1569                 }
1570         } else {
1571                 if (vadj->value > 0.0) {
1572                         old_value = vadj->value;
1573                         last_value = vadj->value - vadj->step_increment;
1574                         last_value = MAX(last_value, 0.0);
1575
1576                         textview_smooth_scroll_do(textview, old_value,
1577                                                   last_value,
1578                                                   prefs_common.scroll_step);
1579                 }
1580         }
1581 }
1582
1583 static gboolean textview_smooth_scroll_page(TextView *textview, gboolean up)
1584 {
1585         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1586         GtkAdjustment *vadj = text->vadjustment;
1587         gfloat upper;
1588         gfloat page_incr;
1589         gfloat old_value;
1590         gfloat last_value;
1591
1592         if (prefs_common.scroll_halfpage)
1593                 page_incr = vadj->page_increment / 2;
1594         else
1595                 page_incr = vadj->page_increment;
1596
1597         if (!up) {
1598                 upper = vadj->upper - vadj->page_size;
1599                 if (vadj->value < upper) {
1600                         old_value = vadj->value;
1601                         last_value = vadj->value + page_incr;
1602                         last_value = MIN(last_value, upper);
1603
1604                         textview_smooth_scroll_do(textview, old_value,
1605                                                   last_value,
1606                                                   prefs_common.scroll_step);
1607                 } else
1608                         return FALSE;
1609         } else {
1610                 if (vadj->value > 0.0) {
1611                         old_value = vadj->value;
1612                         last_value = vadj->value - page_incr;
1613                         last_value = MAX(last_value, 0.0);
1614
1615                         textview_smooth_scroll_do(textview, old_value,
1616                                                   last_value,
1617                                                   prefs_common.scroll_step);
1618                 } else
1619                         return FALSE;
1620         }
1621
1622         return TRUE;
1623 }
1624
1625 #define KEY_PRESS_EVENT_STOP() \
1626         g_signal_stop_emission_by_name(G_OBJECT(widget), \
1627                                        "key_press_event");
1628
1629 static gint textview_key_pressed(GtkWidget *widget, GdkEventKey *event,
1630                                  TextView *textview)
1631 {
1632         SummaryView *summaryview = NULL;
1633         MessageView *messageview = textview->messageview;
1634
1635         if (!event) return FALSE;
1636         if (messageview->mainwin)
1637                 summaryview = messageview->mainwin->summaryview;
1638
1639         switch (event->keyval) {
1640         case GDK_Tab:
1641         case GDK_Home:
1642         case GDK_Left:
1643         case GDK_Up:
1644         case GDK_Right:
1645         case GDK_Down:
1646         case GDK_Page_Up:
1647         case GDK_Page_Down:
1648         case GDK_End:
1649         case GDK_Control_L:
1650         case GDK_Control_R:
1651                 return FALSE;
1652         case GDK_space:
1653                 if (summaryview)
1654                         summary_pass_key_press_event(summaryview, event);
1655                 else
1656                         textview_scroll_page
1657                                 (textview,
1658                                  (event->state &
1659                                   (GDK_SHIFT_MASK|GDK_MOD1_MASK)) != 0);
1660                 break;
1661         case GDK_BackSpace:
1662                 textview_scroll_page(textview, TRUE);
1663                 break;
1664         case GDK_Return:
1665                 textview_scroll_one_line
1666                         (textview, (event->state &
1667                                     (GDK_SHIFT_MASK|GDK_MOD1_MASK)) != 0);
1668                 break;
1669         case GDK_Delete:
1670                 if (summaryview)
1671                         summary_pass_key_press_event(summaryview, event);
1672                 break;
1673         case GDK_y:
1674         case GDK_t:
1675         case GDK_l:
1676         case GDK_c:
1677                 if ((event->state & (GDK_MOD1_MASK|GDK_CONTROL_MASK)) == 0) {
1678                         KEY_PRESS_EVENT_STOP();
1679                         mimeview_pass_key_press_event(messageview->mimeview,
1680                                                       event);
1681                         break;
1682                 }
1683                 /* possible fall through */
1684         default:
1685                 if (summaryview &&
1686                     event->window != messageview->mainwin->window->window) {
1687                         GdkEventKey tmpev = *event;
1688
1689                         tmpev.window = messageview->mainwin->window->window;
1690                         KEY_PRESS_EVENT_STOP();
1691                         gtk_widget_event(messageview->mainwin->window,
1692                                          (GdkEvent *)&tmpev);
1693                 }
1694                 break;
1695         }
1696
1697         return TRUE;
1698 }
1699
1700 static gboolean textview_motion_notify(GtkWidget *widget,
1701                                        GdkEventMotion *event,
1702                                        TextView *textview)
1703 {
1704         textview_uri_update(textview, event->x, event->y);
1705         gdk_window_get_pointer(widget->window, NULL, NULL, NULL);
1706
1707         return FALSE;
1708 }
1709
1710 static gboolean textview_leave_notify(GtkWidget *widget,
1711                                       GdkEventCrossing *event,
1712                                       TextView *textview)
1713 {
1714         textview_uri_update(textview, -1, -1);
1715
1716         return FALSE;
1717 }
1718
1719 static gboolean textview_visibility_notify(GtkWidget *widget,
1720                                            GdkEventVisibility *event,
1721                                            TextView *textview)
1722 {
1723         gint wx, wy;
1724         GdkWindow *window;
1725
1726         window = gtk_text_view_get_window(GTK_TEXT_VIEW(widget),
1727                                           GTK_TEXT_WINDOW_TEXT);
1728
1729         /* check if occurred for the text window part */
1730         if (window != event->window)
1731                 return FALSE;
1732         
1733         gdk_window_get_pointer(widget->window, &wx, &wy, NULL);
1734         textview_uri_update(textview, wx, wy);
1735
1736         return FALSE;
1737 }
1738
1739 static void textview_uri_update(TextView *textview, gint x, gint y)
1740 {
1741         GtkTextBuffer *buffer;
1742         GtkTextIter start_iter, end_iter;
1743         RemoteURI *uri = NULL;
1744         
1745         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview->text));
1746
1747         if (x != -1 && y != -1) {
1748                 gint bx, by;
1749                 GtkTextIter iter;
1750                 GSList *tags;
1751                 GSList *cur;
1752             
1753                 gtk_text_view_window_to_buffer_coords(GTK_TEXT_VIEW(textview->text), 
1754                                                       GTK_TEXT_WINDOW_WIDGET,
1755                                                       x, y, &bx, &by);
1756                 gtk_text_view_get_iter_at_location(GTK_TEXT_VIEW(textview->text),
1757                                                    &iter, bx, by);
1758
1759                 tags = gtk_text_iter_get_tags(&iter);
1760                 for (cur = tags; cur != NULL; cur = cur->next) {
1761                         GtkTextTag *tag = cur->data;
1762                         char *name;
1763
1764                         g_object_get(G_OBJECT(tag), "name", &name, NULL);
1765                         if (!strcmp(name, "link")
1766                             && textview_get_uri_range(textview, &iter, tag,
1767                                                       &start_iter, &end_iter))
1768                                 uri = textview_get_uri_from_range(textview,
1769                                                                   &iter, tag,
1770                                                                   &start_iter,
1771                                                                   &end_iter);
1772                         g_free(name);
1773
1774                         if (uri)
1775                                 break;
1776                 }
1777                 g_slist_free(tags);
1778         }
1779         
1780         if (uri != textview->uri_hover) {
1781                 GdkWindow *window;
1782
1783                 if (textview->uri_hover)
1784                         gtk_text_buffer_remove_tag_by_name(buffer,
1785                                                            "link-hover",
1786                                                            &textview->uri_hover_start_iter,
1787                                                            &textview->uri_hover_end_iter);
1788                     
1789                 textview->uri_hover = uri;
1790                 if (uri) {
1791                         textview->uri_hover_start_iter = start_iter;
1792                         textview->uri_hover_end_iter = end_iter;
1793                 }
1794                 
1795                 window = gtk_text_view_get_window(GTK_TEXT_VIEW(textview->text),
1796                                                   GTK_TEXT_WINDOW_TEXT);
1797                 gdk_window_set_cursor(window, uri ? hand_cursor : text_cursor);
1798
1799                 TEXTVIEW_STATUSBAR_POP(textview);
1800
1801                 if (uri) {
1802                         char *trimmed_uri;
1803
1804                         gtk_text_buffer_apply_tag_by_name(buffer,
1805                                                           "link-hover",
1806                                                           &start_iter,
1807                                                           &end_iter);
1808
1809                         trimmed_uri = trim_string(uri->uri, 60);
1810                         TEXTVIEW_STATUSBAR_PUSH(textview, trimmed_uri);
1811                         g_free(trimmed_uri);
1812                 }
1813         }
1814 }
1815
1816 static gboolean textview_get_uri_range(TextView *textview,
1817                                        GtkTextIter *iter,
1818                                        GtkTextTag *tag,
1819                                        GtkTextIter *start_iter,
1820                                        GtkTextIter *end_iter)
1821 {
1822         return get_tag_range(iter, tag, start_iter, end_iter);
1823 }
1824
1825 static RemoteURI *textview_get_uri_from_range(TextView *textview,
1826                                               GtkTextIter *iter,
1827                                               GtkTextTag *tag,
1828                                               GtkTextIter *start_iter,
1829                                               GtkTextIter *end_iter)
1830 {
1831         gint start_pos, end_pos, cur_pos;
1832         RemoteURI *uri = NULL;
1833         GSList *cur;
1834
1835         start_pos = gtk_text_iter_get_offset(start_iter);
1836         end_pos = gtk_text_iter_get_offset(end_iter);
1837         cur_pos = gtk_text_iter_get_offset(iter);
1838
1839         for (cur = textview->uri_list; cur != NULL; cur = cur->next) {
1840                 RemoteURI *uri_ = (RemoteURI *)cur->data;
1841                 if (start_pos == uri_->start &&
1842                     end_pos ==  uri_->end) {
1843                         uri = uri_;
1844                         break;
1845                 } else if (start_pos == uri_->start ||
1846                            end_pos == uri_->end) {
1847                         /* in case of contiguous links, textview_get_uri_range
1848                          * returns a broader range (start of 1st link to end
1849                          * of last link).
1850                          * In that case, correct link is the one covering
1851                          * current iter.
1852                          */
1853                         if (uri_->start <= cur_pos && cur_pos <= uri_->end) {
1854                                 uri = uri_;
1855                                 break;
1856                         }
1857                 } 
1858         }
1859
1860         return uri;
1861 }
1862
1863 static RemoteURI *textview_get_uri(TextView *textview,
1864                                    GtkTextIter *iter,
1865                                    GtkTextTag *tag)
1866 {
1867         GtkTextIter start_iter, end_iter;
1868         RemoteURI *uri = NULL;
1869
1870         if (textview_get_uri_range(textview, iter, tag, &start_iter,
1871                                    &end_iter))
1872                 uri = textview_get_uri_from_range(textview, iter, tag,
1873                                                   &start_iter, &end_iter);
1874
1875         return uri;
1876 }
1877
1878 static gboolean textview_uri_button_pressed(GtkTextTag *tag, GObject *obj,
1879                                             GdkEvent *event, GtkTextIter *iter,
1880                                             TextView *textview)
1881 {
1882         GdkEventButton *bevent;
1883         RemoteURI *uri = NULL;
1884
1885         if (!event)
1886                 return FALSE;
1887
1888         if (event->type != GDK_BUTTON_PRESS && event->type != GDK_2BUTTON_PRESS
1889                 && event->type != GDK_MOTION_NOTIFY)
1890                 return FALSE;
1891
1892         uri = textview_get_uri(textview, iter, tag);
1893         if (!uri)
1894                 return FALSE;
1895
1896         bevent = (GdkEventButton *) event;
1897         
1898         /* doubleclick: open compose / add address / browser */
1899         if ((event->type == GDK_BUTTON_PRESS && bevent->button == 1) ||
1900                 bevent->button == 2 || bevent->button == 3) {
1901                 if (!g_ascii_strncasecmp(uri->uri, "mailto:", 7)) {
1902                         if (bevent->button == 3) {
1903                                 g_object_set_data(
1904                                         G_OBJECT(textview->mail_popup_menu),
1905                                         "menu_button", uri);
1906                                 gtk_menu_popup(GTK_MENU(textview->mail_popup_menu), 
1907                                                NULL, NULL, NULL, NULL, 
1908                                                bevent->button, bevent->time);
1909                         } else {
1910                                 PrefsAccount *account = NULL;
1911
1912                                 if (textview->messageview && textview->messageview->msginfo &&
1913                                     textview->messageview->msginfo->folder) {
1914                                         FolderItem   *folder_item;
1915
1916                                         folder_item = textview->messageview->msginfo->folder;
1917                                         if (folder_item->prefs && folder_item->prefs->enable_default_account)
1918                                                 account = account_find_from_id(folder_item->prefs->default_account);
1919                                 }
1920                                 compose_new(account, uri->uri + 7, NULL);
1921                         }
1922                         return TRUE;
1923                 } else if (g_ascii_strncasecmp(uri->uri, "file:", 5)) {
1924                         if (bevent->button == 1 &&
1925                             textview_uri_security_check(textview, uri) == TRUE) 
1926                                         open_uri(uri->uri,
1927                                                  prefs_common.uri_cmd);
1928                         else if (bevent->button == 3) {
1929                                 g_object_set_data(
1930                                         G_OBJECT(textview->link_popup_menu),
1931                                         "menu_button", uri);
1932                                 gtk_menu_popup(GTK_MENU(textview->link_popup_menu), 
1933                                                NULL, NULL, NULL, NULL, 
1934                                                bevent->button, bevent->time);
1935                         }
1936                         return TRUE;
1937                 } else {
1938                         if (bevent->button == 3) {
1939                                 g_object_set_data(
1940                                         G_OBJECT(textview->file_popup_menu),
1941                                         "menu_button", uri);
1942                                 gtk_menu_popup(GTK_MENU(textview->file_popup_menu), 
1943                                                NULL, NULL, NULL, NULL, 
1944                                                bevent->button, bevent->time);
1945                                 return TRUE;
1946                         }
1947                 }
1948         }
1949
1950         return FALSE;
1951 }
1952
1953 /*!
1954  *\brief    Check to see if a web URL has been disguised as a different
1955  *          URL (possible with HTML email).
1956  *
1957  *\param    uri The uri to check
1958  *
1959  *\param    textview The TextView the URL is contained in
1960  *
1961  *\return   gboolean TRUE if the URL is ok, or if the user chose to open
1962  *          it anyway, otherwise FALSE          
1963  */
1964 static gboolean textview_uri_security_check(TextView *textview, RemoteURI *uri)
1965 {
1966         gchar *visible_str;
1967         gboolean retval = TRUE;
1968         GtkTextBuffer *buffer;
1969         GtkTextIter start, end;
1970
1971         if (is_uri_string(uri->uri) == FALSE)
1972                 return TRUE;
1973
1974         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview->text));
1975
1976         gtk_text_buffer_get_iter_at_offset(buffer, &start, uri->start);
1977         gtk_text_buffer_get_iter_at_offset(buffer, &end,   uri->end);
1978
1979         visible_str = gtk_text_buffer_get_text(buffer, &start, &end, FALSE);
1980
1981         if (visible_str == NULL)
1982                 return TRUE;
1983
1984         if (strcmp(visible_str, uri->uri) != 0 && is_uri_string(visible_str)) {
1985                 gchar *uri_path;
1986                 gchar *visible_uri_path;
1987
1988                 uri_path = get_uri_path(uri->uri);
1989                 visible_uri_path = get_uri_path(visible_str);
1990                 if (path_cmp(uri_path, visible_uri_path) != 0)
1991                         retval = FALSE;
1992         }
1993
1994         if (retval == FALSE) {
1995                 gchar *msg;
1996                 AlertValue aval;
1997
1998                 msg = g_strdup_printf(_("The real URL (%s) is different from\n"
1999                                         "the apparent URL (%s).\n"
2000                                         "\n"
2001                                         "Open it anyway?"),
2002                                       uri->uri, visible_str);
2003                 aval = alertpanel_full(_("Fake URL warning"), msg,
2004                                        GTK_STOCK_CANCEL, _("_Open URL"), NULL, FALSE,
2005                                        NULL, ALERT_WARNING, G_ALERTDEFAULT);
2006                 g_free(msg);
2007                 if (aval == G_ALERTALTERNATE)
2008                         retval = TRUE;
2009         }
2010
2011         g_free(visible_str);
2012
2013         return retval;
2014 }
2015
2016 static void textview_uri_list_remove_all(GSList *uri_list)
2017 {
2018         GSList *cur;
2019
2020         for (cur = uri_list; cur != NULL; cur = cur->next) {
2021                 if (cur->data) {
2022                         g_free(((RemoteURI *)cur->data)->uri);
2023                         g_free(((RemoteURI *)cur->data)->filename);
2024                         g_free(cur->data);
2025                 }
2026         }
2027
2028         g_slist_free(uri_list);
2029 }
2030
2031 static void open_uri_cb (TextView *textview, guint action, void *data)
2032 {
2033         RemoteURI *uri = g_object_get_data(G_OBJECT(textview->link_popup_menu),
2034                                            "menu_button");
2035         if (uri == NULL)
2036                 return;
2037
2038         if (textview_uri_security_check(textview, uri) == TRUE) 
2039                 open_uri(uri->uri,
2040                          prefs_common.uri_cmd);
2041         g_object_set_data(G_OBJECT(textview->link_popup_menu), "menu_button",
2042                           NULL);
2043 }
2044
2045 static void open_image_cb (TextView *textview, guint action, void *data)
2046 {
2047         RemoteURI *uri = g_object_get_data(G_OBJECT(textview->file_popup_menu),
2048                                            "menu_button");
2049
2050         static gchar *default_cmdline = DEFAULT_IMAGE_VIEWER_CMD;
2051         gchar buf[1024];
2052         const gchar *cmd;
2053         const gchar *def_cmd;
2054         const gchar *p;
2055         gchar *filename = NULL;
2056         gchar *tmp_filename = NULL;
2057
2058         if (uri == NULL)
2059                 return;
2060
2061         if (uri->filename == NULL)
2062                 return;
2063         
2064         filename = g_strdup(uri->filename);
2065         
2066         if (!g_utf8_validate(filename, -1, NULL)) {
2067                 gchar *tmp = conv_filename_to_utf8(filename);
2068                 g_free(filename);
2069                 filename = tmp;
2070         }
2071
2072         subst_for_filename(filename);
2073
2074         tmp_filename = g_filename_from_uri(uri->uri, NULL, NULL);
2075         copy_file(tmp_filename, filename, FALSE);
2076         g_free(tmp_filename);
2077
2078         cmd = prefs_common.mime_image_viewer;
2079         def_cmd = default_cmdline;
2080         
2081         if (cmd && (p = strchr(cmd, '%')) && *(p + 1) == 's' &&
2082             !strchr(p + 2, '%'))
2083                 g_snprintf(buf, sizeof(buf), cmd, filename);
2084         else {
2085                 if (cmd)
2086                         g_warning("Image viewer command line is invalid: '%s'", cmd);
2087                 if (def_cmd)
2088                         g_snprintf(buf, sizeof(buf), def_cmd, filename);
2089                 else
2090                         return;
2091         }
2092
2093         execute_command_line(buf, TRUE);
2094
2095         g_free(filename);
2096
2097         g_object_set_data(G_OBJECT(textview->file_popup_menu), "menu_button",
2098                           NULL);
2099 }
2100
2101 static void save_file_cb (TextView *textview, guint action, void *data)
2102 {
2103         RemoteURI *uri = g_object_get_data(G_OBJECT(textview->file_popup_menu),
2104                                            "menu_button");
2105         gchar *filename = NULL;
2106         gchar *filepath = NULL;
2107         gchar *filedir = NULL;
2108         gchar *tmp_filename = NULL;
2109         if (uri == NULL)
2110                 return;
2111
2112         if (uri->filename == NULL)
2113                 return;
2114         
2115         filename = g_strdup(uri->filename);
2116         
2117         if (!g_utf8_validate(filename, -1, NULL)) {
2118                 gchar *tmp = conv_filename_to_utf8(filename);
2119                 g_free(filename);
2120                 filename = tmp;
2121         }
2122
2123         subst_for_filename(filename);
2124         
2125         if (prefs_common.attach_save_dir)
2126                 filepath = g_strconcat(prefs_common.attach_save_dir,
2127                                        G_DIR_SEPARATOR_S, filename, NULL);
2128         else
2129                 filepath = g_strdup(filename);
2130
2131         g_free(filename);
2132
2133         filename = filesel_select_file_save(_("Save as"), filepath);
2134         if (!filename) {
2135                 g_free(filepath);
2136                 return;
2137         }
2138
2139         if (is_file_exist(filename)) {
2140                 AlertValue aval;
2141                 gchar *res;
2142                 
2143                 res = g_strdup_printf(_("Overwrite existing file '%s'?"),
2144                                       filename);
2145                 aval = alertpanel(_("Overwrite"), res, GTK_STOCK_CANCEL, 
2146                                   GTK_STOCK_OK, NULL);
2147                 g_free(res);                                      
2148                 if (G_ALERTALTERNATE != aval)
2149                         return;
2150         }
2151
2152         tmp_filename = g_filename_from_uri(uri->uri, NULL, NULL);
2153         copy_file(tmp_filename, filename, FALSE);
2154         g_free(tmp_filename);
2155         
2156         filedir = g_path_get_dirname(filename);
2157         if (filedir && strcmp(filedir, ".")) {
2158                 if (prefs_common.attach_save_dir)
2159                         g_free(prefs_common.attach_save_dir);
2160                 prefs_common.attach_save_dir = g_strdup(filedir);
2161         }
2162
2163         g_free(filedir);
2164         g_free(filepath);
2165
2166         g_object_set_data(G_OBJECT(textview->file_popup_menu), "menu_button",
2167                           NULL);
2168 }
2169
2170 static void copy_uri_cb (TextView *textview, guint action, void *data)
2171 {
2172         RemoteURI *uri = g_object_get_data(G_OBJECT(textview->link_popup_menu),
2173                                            "menu_button");
2174         if (uri == NULL)
2175                 return;
2176
2177         gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), uri->uri, -1);
2178         gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), uri->uri, -1);
2179         g_object_set_data(G_OBJECT(textview->link_popup_menu), "menu_button",
2180                           NULL);
2181 }
2182
2183 static void add_uri_to_addrbook_cb (TextView *textview, guint action, void *data)
2184 {
2185         gchar *fromname, *fromaddress;
2186         RemoteURI *uri = g_object_get_data(G_OBJECT(textview->mail_popup_menu),
2187                                            "menu_button");
2188         if (uri == NULL)
2189                 return;
2190
2191         /* extract url */
2192         fromaddress = g_strdup(uri->uri + 7);
2193         /* Hiroyuki: please put this function in utils.c! */
2194         fromname = procheader_get_fromname(fromaddress);
2195         extract_address(fromaddress);
2196         g_message("adding from textview %s <%s>", fromname, fromaddress);
2197         /* Add to address book - Match */
2198         addressbook_add_contact( fromname, fromaddress, NULL );
2199
2200         g_free(fromaddress);
2201         g_free(fromname);
2202 }
2203
2204 static void mail_to_uri_cb (TextView *textview, guint action, void *data)
2205 {
2206         PrefsAccount *account = NULL;
2207         RemoteURI *uri = g_object_get_data(G_OBJECT(textview->mail_popup_menu),
2208                                            "menu_button");
2209         if (uri == NULL)
2210                 return;
2211
2212         if (textview->messageview && textview->messageview->msginfo &&
2213             textview->messageview->msginfo->folder) {
2214                 FolderItem   *folder_item;
2215
2216                 folder_item = textview->messageview->msginfo->folder;
2217                 if (folder_item->prefs && folder_item->prefs->enable_default_account)
2218                         account = account_find_from_id(folder_item->prefs->default_account);
2219         }
2220         compose_new(account, uri->uri + 7, NULL);
2221 }
2222
2223 static void copy_mail_to_uri_cb (TextView *textview, guint action, void *data)
2224 {
2225         RemoteURI *uri = g_object_get_data(G_OBJECT(textview->mail_popup_menu),
2226                                            "menu_button");
2227         if (uri == NULL)
2228                 return;
2229
2230         gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), uri->uri +7, -1);
2231         gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), uri->uri +7, -1);
2232         g_object_set_data(G_OBJECT(textview->mail_popup_menu), "menu_button",
2233                           NULL);
2234 }
2235