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