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