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