cefe1500fbb66db764cf759e918503f9236f74b0
[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 Claws Mail 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 (textview->scrolledwin->allocation.width - 100 > 0 &&
677                                     w > textview->scrolledwin->allocation.width - 100)
678                                         pixbuf = gdk_pixbuf_new_from_file_at_scale(filename, 
679                                                 textview->scrolledwin->allocation.width - 100, 
680                                                 -1, TRUE, &error);
681                                 else
682                                         pixbuf = gdk_pixbuf_new_from_file(filename, &error);
683                         }
684                         if (error != NULL) {
685                                 g_warning("%s\n", error->message);
686                                 g_error_free(error);
687                         }
688                         if (!pixbuf) {
689                                 g_warning("Can't load the image.");
690                                 g_free(filename);
691                                 END_TIMING();
692                                 return;
693                         }
694
695                         uri_str = g_filename_to_uri(filename, NULL, NULL);
696                         if (uri_str) {
697                                 uri = g_new0(ClickableText, 1);
698                                 uri->uri = uri_str;
699                                 uri->start = gtk_text_iter_get_offset(&iter);
700                                 
701                                 gtk_text_buffer_insert_pixbuf(buffer, &iter, pixbuf);
702                                 
703                                 uri->end = uri->start + 1;
704                                 uri->filename = procmime_get_part_file_name(mimeinfo);
705                                 textview->uri_list =
706                                         g_slist_prepend(textview->uri_list, uri);
707                                 
708                                 gtk_text_buffer_insert(buffer, &iter, " ", 1);
709                                 gtk_text_buffer_get_iter_at_offset(buffer, &start_iter, uri->start);    
710                                 gtk_text_buffer_apply_tag_by_name(buffer, "link", 
711                                                 &start_iter, &iter);
712                         } else {
713                                 gtk_text_buffer_insert_pixbuf(buffer, &iter, pixbuf);
714                                 gtk_text_buffer_insert(buffer, &iter, " ", 1);
715                         }
716
717                         g_object_unref(pixbuf);
718                         g_free(filename);
719                         END_TIMING();
720                         GTK_EVENTS_FLUSH();
721                 }
722         } else if (mimeinfo->type == MIMETYPE_TEXT) {
723                 if (prefs_common.display_header && (charcount > 0))
724                         gtk_text_buffer_insert(buffer, &iter, "\n", 1);
725
726                 textview_write_body(textview, mimeinfo);
727         }
728         END_TIMING();
729 }
730
731 static void recursive_add_parts(TextView *textview, GNode *node)
732 {
733         GNode * iter;
734         MimeInfo *mimeinfo;
735         START_TIMING("");
736
737         mimeinfo = (MimeInfo *) node->data;
738         
739         textview_add_part(textview, mimeinfo);
740         
741         if ((mimeinfo->type != MIMETYPE_MULTIPART) &&
742             (mimeinfo->type != MIMETYPE_MESSAGE)) {
743                 END_TIMING();
744                 return;
745         }
746         if (g_ascii_strcasecmp(mimeinfo->subtype, "alternative") == 0) {
747                 GNode * prefered_body;
748                 int prefered_score;
749                 
750                 /*
751                   text/plain : score 3
752                   text/ *    : score 2
753                   other      : score 1
754                 */
755                 prefered_body = NULL;
756                 prefered_score = 0;
757                 
758                 for (iter = g_node_first_child(node) ; iter != NULL ;
759                      iter = g_node_next_sibling(iter)) {
760                         int score;
761                         MimeInfo * submime;
762                         
763                         score = 1;
764                         submime = (MimeInfo *) iter->data;
765                         if (submime->type == MIMETYPE_TEXT)
766                                 score = 2;
767                         
768                         if (submime->subtype != NULL) {
769                                 if (g_ascii_strcasecmp(submime->subtype, "plain") == 0)
770                                         score = 3;
771                         }
772                         
773                         if (score > prefered_score) {
774                                 prefered_score = score;
775                                 prefered_body = iter;
776                         }
777                 }
778                 
779                 if (prefered_body != NULL) {
780                         recursive_add_parts(textview, prefered_body);
781                 }
782         }
783         else {
784                 for (iter = g_node_first_child(node) ; iter != NULL ;
785                      iter = g_node_next_sibling(iter)) {
786                         recursive_add_parts(textview, iter);
787                 }
788         }
789         END_TIMING();
790 }
791
792 static void textview_add_parts(TextView *textview, MimeInfo *mimeinfo)
793 {
794         g_return_if_fail(mimeinfo != NULL);
795         
796         recursive_add_parts(textview, mimeinfo->node);
797 }
798
799 void textview_show_error(TextView *textview)
800 {
801         GtkTextView *text;
802         GtkTextBuffer *buffer;
803         GtkTextIter iter;
804
805         textview_set_font(textview, NULL);
806         textview_clear(textview);
807
808         text = GTK_TEXT_VIEW(textview->text);
809         buffer = gtk_text_view_get_buffer(text);
810         gtk_text_buffer_get_start_iter(buffer, &iter);
811
812         TEXTVIEW_INSERT(_("\n"
813                       "  This message can't be displayed.\n"
814                       "  This is probably due to a network error.\n"
815                       "\n"
816                       "  Use "));
817         TEXTVIEW_INSERT_LINK(_("'View Log'"), "sc://view_log", NULL);
818         TEXTVIEW_INSERT(_(" in the Tools menu for more information."));
819         textview_show_icon(textview, GTK_STOCK_DIALOG_ERROR);
820
821 }
822
823 void textview_show_mime_part(TextView *textview, MimeInfo *partinfo)
824 {
825         GtkTextView *text;
826         GtkTextBuffer *buffer;
827         GtkTextIter iter;
828
829         if (!partinfo) return;
830
831         textview_set_font(textview, NULL);
832         textview_clear(textview);
833
834         text = GTK_TEXT_VIEW(textview->text);
835         buffer = gtk_text_view_get_buffer(text);
836         gtk_text_buffer_get_start_iter(buffer, &iter);
837
838         TEXTVIEW_INSERT("\n");
839         TEXTVIEW_INSERT(_("  The following can be performed on this part by\n"));
840         TEXTVIEW_INSERT(_("  right-clicking the icon or list item:\n"));
841
842         TEXTVIEW_INSERT(_("     - To save, select "));
843         TEXTVIEW_INSERT_LINK(_("'Save as...'"), "sc://save_as", NULL);
844         TEXTVIEW_INSERT(_(" (Shortcut key: 'y')\n"));
845         TEXTVIEW_INSERT(_("     - To display as text, select "));
846         TEXTVIEW_INSERT_LINK(_("'Display as text'"), "sc://display_as_text", NULL);
847         TEXTVIEW_INSERT(_(" (Shortcut key: 't')\n"));
848         TEXTVIEW_INSERT(_("     - To open with an external program, select "));
849         TEXTVIEW_INSERT_LINK(_("'Open'"), "sc://open", NULL);
850         TEXTVIEW_INSERT(_(" (Shortcut key: 'l')\n"));
851         TEXTVIEW_INSERT(_("       (alternately double-click, or click the middle "));
852         TEXTVIEW_INSERT(_("mouse button)\n"));
853         TEXTVIEW_INSERT(_("     - Or use "));
854         TEXTVIEW_INSERT_LINK(_("'Open with...'"), "sc://open_with", NULL);
855         TEXTVIEW_INSERT(_(" (Shortcut key: 'o')\n"));
856         textview_show_icon(textview, GTK_STOCK_DIALOG_INFO);
857 }
858
859 static void textview_write_body(TextView *textview, MimeInfo *mimeinfo)
860 {
861         FILE *tmpfp;
862         gchar buf[BUFFSIZE];
863         CodeConverter *conv;
864         const gchar *charset, *p, *cmd;
865         GSList *cur;
866         int lines = 0;
867         
868         if (textview->messageview->forced_charset)
869                 charset = textview->messageview->forced_charset;
870         else
871                 charset = procmime_mimeinfo_get_parameter(mimeinfo, "charset");
872
873         textview_set_font(textview, charset);
874
875         conv = conv_code_converter_new(charset);
876
877         procmime_force_encoding(textview->messageview->forced_encoding);
878         
879         textview->is_in_signature = FALSE;
880
881         procmime_decode_content(mimeinfo);
882
883         if (!g_ascii_strcasecmp(mimeinfo->subtype, "html") &&
884             prefs_common.render_html) {
885                 gchar *filename;
886                 
887                 filename = procmime_get_tmp_file_name(mimeinfo);
888                 if (procmime_get_part(filename, mimeinfo) == 0) {
889                         tmpfp = g_fopen(filename, "rb");
890                         textview_show_html(textview, tmpfp, conv);
891                         fclose(tmpfp);
892                         g_unlink(filename);
893                 }
894                 g_free(filename);
895         } else if (!g_ascii_strcasecmp(mimeinfo->subtype, "enriched")) {
896                 gchar *filename;
897                 
898                 filename = procmime_get_tmp_file_name(mimeinfo);
899                 if (procmime_get_part(filename, mimeinfo) == 0) {
900                         tmpfp = g_fopen(filename, "rb");
901                         textview_show_ertf(textview, tmpfp, conv);
902                         fclose(tmpfp);
903                         g_unlink(filename);
904                 }
905                 g_free(filename);
906 #ifndef G_OS_WIN32
907         } else if ( g_ascii_strcasecmp(mimeinfo->subtype, "plain") &&
908                    (cmd = prefs_common.mime_textviewer) && *cmd &&
909                    (p = strchr(cmd, '%')) && *(p + 1) == 's') {
910                 int pid, pfd[2];
911                 const gchar *fname;
912
913                 fname  = procmime_get_tmp_file_name(mimeinfo);
914                 if (procmime_get_part(fname, mimeinfo)) goto textview_default;
915
916                 g_snprintf(buf, sizeof(buf), cmd, fname);
917                 debug_print("Viewing text content of type: %s (length: %d) "
918                         "using %s\n", mimeinfo->subtype, mimeinfo->length, buf);
919
920                 if (pipe(pfd) < 0) {
921                         g_snprintf(buf, sizeof(buf),
922                                 "pipe failed for textview\n\n%s\n", strerror(errno));
923                         textview_write_line(textview, buf, conv, TRUE);
924                         goto textview_default;
925                 }
926                 pid = fork();
927                 if (pid < 0) {
928                         g_snprintf(buf, sizeof(buf),
929                                 "fork failed for textview\n\n%s\n", strerror(errno));
930                         textview_write_line(textview, buf, conv, TRUE);
931                         close(pfd[0]);
932                         close(pfd[1]);
933                         goto textview_default;
934                 }
935                 if (pid == 0) { /* child */
936                         int rc;
937                         gchar **argv;
938                         argv = strsplit_with_quote(buf, " ", 0);
939                         close(1);
940                         close(pfd[0]);
941                         dup(pfd[1]);
942                         rc = execvp(argv[0], argv);
943                         close(pfd[1]);
944                         printf (_("The command to view attachment "
945                                 "as text failed:\n"
946                                 "    %s\n"
947                                 "Exit code %d\n"), buf, rc);
948                         exit(255);
949                 }
950                 close(pfd[1]);
951                 tmpfp = fdopen(pfd[0], "rb");
952                 while (fgets(buf, sizeof(buf), tmpfp)) {
953                         textview_write_line(textview, buf, conv, TRUE);
954                         
955                         lines++;
956                         if (lines % 500 == 0)
957                                 GTK_EVENTS_FLUSH();
958                         if (textview->stop_loading) {
959                                 fclose(tmpfp);
960                                 waitpid(pid, pfd, 0);
961                                 unlink(fname);
962                                 return;
963                         }
964                 }
965
966                 fclose(tmpfp);
967                 waitpid(pid, pfd, 0);
968                 unlink(fname);
969 #endif
970         } else {
971 textview_default:
972                 lines = 0;
973                 tmpfp = g_fopen(mimeinfo->data.filename, "rb");
974                 fseek(tmpfp, mimeinfo->offset, SEEK_SET);
975                 debug_print("Viewing text content of type: %s (length: %d)\n", mimeinfo->subtype, mimeinfo->length);
976                 while ((ftell(tmpfp) < mimeinfo->offset + mimeinfo->length) &&
977                        (fgets(buf, sizeof(buf), tmpfp) != NULL)) {
978                         textview_write_line(textview, buf, conv, TRUE);
979                         lines++;
980                         if (lines % 500 == 0)
981                                 GTK_EVENTS_FLUSH();
982                         if (textview->stop_loading) {
983                                 fclose(tmpfp);
984                                 return;
985                         }
986                 }
987                 fclose(tmpfp);
988         }
989
990         conv_code_converter_destroy(conv);
991         procmime_force_encoding(0);
992
993         lines = 0;
994         textview->uri_list = g_slist_reverse(textview->uri_list);
995         for (cur = textview->uri_list; cur; cur = cur->next) {
996                 ClickableText *uri = (ClickableText *)cur->data;
997                 if (!uri->is_quote)
998                         continue;
999                 if (!prefs_common.hide_quotes ||
1000                     uri->quote_level+1 < prefs_common.hide_quotes) {
1001                         textview_toggle_quote(textview, cur, uri, TRUE);
1002                         lines++;
1003                         if (lines % 500 == 0)
1004                                 GTK_EVENTS_FLUSH();
1005                         if (textview->stop_loading) {
1006                                 return;
1007                         }
1008                 }
1009         }
1010 }
1011
1012 static void textview_show_html(TextView *textview, FILE *fp,
1013                                CodeConverter *conv)
1014 {
1015         SC_HTMLParser *parser;
1016         gchar *str;
1017         gint lines = 0;
1018
1019         parser = sc_html_parser_new(fp, conv);
1020         g_return_if_fail(parser != NULL);
1021
1022         while ((str = sc_html_parse(parser)) != NULL) {
1023                 if (parser->state == SC_HTML_HREF) {
1024                         /* first time : get and copy the URL */
1025                         if (parser->href == NULL) {
1026                                 /* ALF - the claws html parser returns an empty string,
1027                                  * if still inside an <a>, but already parsed past HREF */
1028                                 str = strtok(str, " ");
1029                                 if (str) {
1030                                         while (str && *str && g_ascii_isspace(*str))
1031                                                 str++; 
1032                                         parser->href = g_strdup(str);
1033                                         /* the URL may (or not) be followed by the
1034                                          * referenced text */
1035                                         str = strtok(NULL, "");
1036                                 }       
1037                         }
1038                         if (str != NULL)
1039                                 textview_write_link(textview, str, parser->href, NULL);
1040                 } else
1041                         textview_write_line(textview, str, NULL, FALSE);
1042                 lines++;
1043                 if (lines % 500 == 0)
1044                         GTK_EVENTS_FLUSH();
1045                 if (textview->stop_loading) {
1046                         return;
1047                 }
1048         }
1049         textview_write_line(textview, "\n", NULL, FALSE);
1050         sc_html_parser_destroy(parser);
1051 }
1052
1053 static void textview_show_ertf(TextView *textview, FILE *fp,
1054                                CodeConverter *conv)
1055 {
1056         ERTFParser *parser;
1057         gchar *str;
1058         gint lines = 0;
1059
1060         parser = ertf_parser_new(fp, conv);
1061         g_return_if_fail(parser != NULL);
1062
1063         while ((str = ertf_parse(parser)) != NULL) {
1064                 textview_write_line(textview, str, NULL, FALSE);
1065                 lines++;
1066                 if (lines % 500 == 0)
1067                         GTK_EVENTS_FLUSH();
1068                 if (textview->stop_loading) {
1069                         return;
1070                 }
1071         }
1072         
1073         ertf_parser_destroy(parser);
1074 }
1075
1076 #define ADD_TXT_POS(bp_, ep_, pti_) \
1077         if ((last->next = alloca(sizeof(struct txtpos))) != NULL) { \
1078                 last = last->next; \
1079                 last->bp = (bp_); last->ep = (ep_); last->pti = (pti_); \
1080                 last->next = NULL; \
1081         } else { \
1082                 g_warning("alloc error scanning URIs\n"); \
1083                 gtk_text_buffer_insert_with_tags_by_name(buffer, &iter, \
1084                                                          linebuf, -1, \
1085                                                          fg_tag, NULL); \
1086                 return; \
1087         }
1088
1089 #define ADD_TXT_POS_LATER(bp_, ep_, pti_) \
1090         if ((last->next = alloca(sizeof(struct txtpos))) != NULL) { \
1091                 last = last->next; \
1092                 last->bp = (bp_); last->ep = (ep_); last->pti = (pti_); \
1093                 last->next = NULL; \
1094         } else { \
1095                 g_warning("alloc error scanning URIs\n"); \
1096         }
1097
1098 /* textview_make_clickable_parts() - colorizes clickable parts */
1099 static void textview_make_clickable_parts(TextView *textview,
1100                                           const gchar *fg_tag,
1101                                           const gchar *uri_tag,
1102                                           const gchar *linebuf,
1103                                           gboolean hdr)
1104 {
1105         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1106         GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
1107         GtkTextIter iter;
1108         gchar *mybuf = g_strdup(linebuf);
1109         
1110         /* parse table - in order of priority */
1111         struct table {
1112                 const gchar *needle; /* token */
1113
1114                 /* token search function */
1115                 gchar    *(*search)     (const gchar *haystack,
1116                                          const gchar *needle);
1117                 /* part parsing function */
1118                 gboolean  (*parse)      (const gchar *start,
1119                                          const gchar *scanpos,
1120                                          const gchar **bp_,
1121                                          const gchar **ep_,
1122                                          gboolean hdr);
1123                 /* part to URI function */
1124                 gchar    *(*build_uri)  (const gchar *bp,
1125                                          const gchar *ep);
1126         };
1127
1128         static struct table parser[] = {
1129                 {"http://",  strcasestr, get_uri_part,   make_uri_string},
1130                 {"https://", strcasestr, get_uri_part,   make_uri_string},
1131                 {"ftp://",   strcasestr, get_uri_part,   make_uri_string},
1132                 {"sftp://",  strcasestr, get_uri_part,   make_uri_string},
1133                 {"www.",     strcasestr, get_uri_part,   make_http_string},
1134                 {"mailto:",  strcasestr, get_uri_part,   make_uri_string},
1135                 {"@",        strcasestr, get_email_part, make_email_string}
1136         };
1137         const gint PARSE_ELEMS = sizeof parser / sizeof parser[0];
1138
1139         gint  n;
1140         const gchar *walk, *bp, *ep;
1141
1142         struct txtpos {
1143                 const gchar     *bp, *ep;       /* text position */
1144                 gint             pti;           /* index in parse table */
1145                 struct txtpos   *next;          /* next */
1146         } head = {NULL, NULL, 0,  NULL}, *last = &head;
1147
1148         if (!g_utf8_validate(linebuf, -1, NULL)) {
1149                 g_free(mybuf);
1150                 mybuf = g_malloc(strlen(linebuf)*2 +1);
1151                 conv_localetodisp(mybuf, strlen(linebuf)*2 +1, linebuf);
1152         }
1153
1154         gtk_text_buffer_get_end_iter(buffer, &iter);
1155
1156         /* parse for clickable parts, and build a list of begin and end positions  */
1157         for (walk = mybuf, n = 0;;) {
1158                 gint last_index = PARSE_ELEMS;
1159                 gchar *scanpos = NULL;
1160
1161                 /* FIXME: this looks phony. scanning for anything in the parse table */
1162                 for (n = 0; n < PARSE_ELEMS; n++) {
1163                         gchar *tmp;
1164
1165                         tmp = parser[n].search(walk, parser[n].needle);
1166                         if (tmp) {
1167                                 if (scanpos == NULL || tmp < scanpos) {
1168                                         scanpos = tmp;
1169                                         last_index = n;
1170                                 }
1171                         }                                       
1172                 }
1173
1174                 if (scanpos) {
1175                         /* check if URI can be parsed */
1176                         if (parser[last_index].parse(walk, scanpos, &bp, &ep, hdr)
1177                             && (size_t) (ep - bp - 1) > strlen(parser[last_index].needle)) {
1178                                         ADD_TXT_POS(bp, ep, last_index);
1179                                         walk = ep;
1180                         } else
1181                                 walk = scanpos +
1182                                         strlen(parser[last_index].needle);
1183                 } else
1184                         break;
1185         }
1186
1187         /* colorize this line */
1188         if (head.next) {
1189                 const gchar *normal_text = mybuf;
1190
1191                 /* insert URIs */
1192                 for (last = head.next; last != NULL;
1193                      normal_text = last->ep, last = last->next) {
1194                         ClickableText *uri;
1195                         uri = g_new0(ClickableText, 1);
1196                         if (last->bp - normal_text > 0)
1197                                 gtk_text_buffer_insert_with_tags_by_name
1198                                         (buffer, &iter,
1199                                          normal_text,
1200                                          last->bp - normal_text,
1201                                          fg_tag, NULL);
1202                         uri->uri = parser[last->pti].build_uri(last->bp,
1203                                                                last->ep);
1204                         uri->start = gtk_text_iter_get_offset(&iter);
1205                         gtk_text_buffer_insert_with_tags_by_name
1206                                 (buffer, &iter, last->bp, last->ep - last->bp,
1207                                  uri_tag, fg_tag, NULL);
1208                         uri->end = gtk_text_iter_get_offset(&iter);
1209                         uri->filename = NULL;
1210                         textview->uri_list =
1211                                 g_slist_prepend(textview->uri_list, uri);
1212                 }
1213
1214                 if (*normal_text)
1215                         gtk_text_buffer_insert_with_tags_by_name
1216                                 (buffer, &iter, normal_text, -1, fg_tag, NULL);
1217         } else {
1218                 gtk_text_buffer_insert_with_tags_by_name
1219                         (buffer, &iter, mybuf, -1, fg_tag, NULL);
1220         }
1221         g_free(mybuf);
1222 }
1223
1224 /* textview_make_clickable_parts() - colorizes clickable parts */
1225 static void textview_make_clickable_parts_later(TextView *textview,
1226                                           gint start, gint end)
1227 {
1228         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1229         GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
1230         GtkTextIter start_iter, end_iter;
1231         gchar *mybuf;
1232         gint offset = 0;
1233         /* parse table - in order of priority */
1234         struct table {
1235                 const gchar *needle; /* token */
1236
1237                 /* token search function */
1238                 gchar    *(*search)     (const gchar *haystack,
1239                                          const gchar *needle);
1240                 /* part parsing function */
1241                 gboolean  (*parse)      (const gchar *start,
1242                                          const gchar *scanpos,
1243                                          const gchar **bp_,
1244                                          const gchar **ep_,
1245                                          gboolean hdr);
1246                 /* part to URI function */
1247                 gchar    *(*build_uri)  (const gchar *bp,
1248                                          const gchar *ep);
1249         };
1250
1251         static struct table parser[] = {
1252                 {"http://",  strcasestr, get_uri_part,   make_uri_string},
1253                 {"https://", strcasestr, get_uri_part,   make_uri_string},
1254                 {"ftp://",   strcasestr, get_uri_part,   make_uri_string},
1255                 {"sftp://",  strcasestr, get_uri_part,   make_uri_string},
1256                 {"www.",     strcasestr, get_uri_part,   make_http_string},
1257                 {"mailto:",  strcasestr, get_uri_part,   make_uri_string},
1258                 {"@",        strcasestr, get_email_part, make_email_string}
1259         };
1260         const gint PARSE_ELEMS = sizeof parser / sizeof parser[0];
1261
1262         gint  n;
1263         const gchar *walk, *bp, *ep;
1264
1265         struct txtpos {
1266                 const gchar     *bp, *ep;       /* text position */
1267                 gint             pti;           /* index in parse table */
1268                 struct txtpos   *next;          /* next */
1269         } head = {NULL, NULL, 0,  NULL}, *last = &head;
1270
1271         gtk_text_buffer_get_iter_at_offset(buffer, &start_iter, start);
1272         gtk_text_buffer_get_iter_at_offset(buffer, &end_iter, end);
1273         mybuf = gtk_text_buffer_get_text(buffer, &start_iter, &end_iter, FALSE);
1274         offset = gtk_text_iter_get_offset(&start_iter);
1275
1276         /* parse for clickable parts, and build a list of begin and end positions  */
1277         for (walk = mybuf, n = 0;;) {
1278                 gint last_index = PARSE_ELEMS;
1279                 gchar *scanpos = NULL;
1280
1281                 /* FIXME: this looks phony. scanning for anything in the parse table */
1282                 for (n = 0; n < PARSE_ELEMS; n++) {
1283                         gchar *tmp;
1284
1285                         tmp = parser[n].search(walk, parser[n].needle);
1286                         if (tmp) {
1287                                 if (scanpos == NULL || tmp < scanpos) {
1288                                         scanpos = tmp;
1289                                         last_index = n;
1290                                 }
1291                         }                                       
1292                 }
1293
1294                 if (scanpos) {
1295                         /* check if URI can be parsed */
1296                         if (parser[last_index].parse(walk, scanpos, &bp, &ep, FALSE)
1297                             && (size_t) (ep - bp - 1) > strlen(parser[last_index].needle)) {
1298                                         ADD_TXT_POS_LATER(bp, ep, last_index);
1299                                         walk = ep;
1300                         } else
1301                                 walk = scanpos +
1302                                         strlen(parser[last_index].needle);
1303                 } else
1304                         break;
1305         }
1306
1307         /* colorize this line */
1308         if (head.next) {
1309                 /* insert URIs */
1310                 for (last = head.next; last != NULL; last = last->next) {
1311                         ClickableText *uri;
1312                         gint start_offset, end_offset;
1313                         gchar *tmp_str;
1314                         gchar old_char;
1315                         uri = g_new0(ClickableText, 1);
1316                         uri->uri = parser[last->pti].build_uri(last->bp,
1317                                                                last->ep);
1318                         
1319                         tmp_str = mybuf;
1320                         old_char = tmp_str[last->ep - mybuf];
1321                         tmp_str[last->ep - mybuf] = '\0';                                      
1322                         end_offset = g_utf8_strlen(tmp_str, -1);
1323                         tmp_str[last->ep - mybuf] = old_char;
1324                         
1325                         old_char = tmp_str[last->bp - mybuf];
1326                         tmp_str[last->bp - mybuf] = '\0';                                      
1327                         start_offset = g_utf8_strlen(tmp_str, -1);
1328                         tmp_str[last->bp - mybuf] = old_char;
1329                         
1330                         gtk_text_buffer_get_iter_at_offset(buffer, &start_iter, start_offset + offset);
1331                         gtk_text_buffer_get_iter_at_offset(buffer, &end_iter, end_offset + offset);
1332                         
1333                         uri->start = gtk_text_iter_get_offset(&start_iter);
1334                         
1335                         gtk_text_buffer_apply_tag_by_name(buffer, "link", &start_iter, &end_iter);
1336
1337                         uri->end = gtk_text_iter_get_offset(&end_iter);
1338                         uri->filename = NULL;
1339                         textview->uri_list =
1340                                 g_slist_prepend(textview->uri_list, uri);
1341                 }
1342         } 
1343
1344         g_free(mybuf);
1345 }
1346
1347 #undef ADD_TXT_POS
1348
1349 static void textview_write_line(TextView *textview, const gchar *str,
1350                                 CodeConverter *conv, gboolean do_quote_folding)
1351 {
1352         GtkTextView *text;
1353         GtkTextBuffer *buffer;
1354         GtkTextIter iter;
1355         gchar buf[BUFFSIZE];
1356         gchar *fg_color;
1357         gint quotelevel = -1, real_quotelevel = -1;
1358         gchar quote_tag_str[10];
1359
1360         text = GTK_TEXT_VIEW(textview->text);
1361         buffer = gtk_text_view_get_buffer(text);
1362         gtk_text_buffer_get_end_iter(buffer, &iter);
1363
1364         if (!conv)
1365                 strncpy2(buf, str, sizeof(buf));
1366         else if (conv_convert(conv, buf, sizeof(buf), str) < 0)
1367                 conv_localetodisp(buf, sizeof(buf), str);
1368                 
1369         strcrchomp(buf);
1370         fg_color = NULL;
1371
1372         /* change color of quotation
1373            >, foo>, _> ... ok, <foo>, foo bar>, foo-> ... ng
1374            Up to 3 levels of quotations are detected, and each
1375            level is colored using a different color. */
1376         if (prefs_common.enable_color 
1377             && line_has_quote_char(buf, prefs_common.quote_chars)) {
1378                 real_quotelevel = get_quote_level(buf, prefs_common.quote_chars);
1379                 quotelevel = real_quotelevel;
1380                 /* set up the correct foreground color */
1381                 if (quotelevel > 2) {
1382                         /* recycle colors */
1383                         if (prefs_common.recycle_quote_colors)
1384                                 quotelevel %= 3;
1385                         else
1386                                 quotelevel = 2;
1387                 }
1388         }
1389
1390         if (quotelevel == -1)
1391                 fg_color = NULL;
1392         else {
1393                 g_snprintf(quote_tag_str, sizeof(quote_tag_str),
1394                            "quote%d", quotelevel);
1395                 fg_color = quote_tag_str;
1396         }
1397
1398         if (prefs_common.enable_color && (strcmp(buf,"-- \n") == 0 || textview->is_in_signature)) {
1399                 fg_color = "signature";
1400                 textview->is_in_signature = TRUE;
1401         }
1402
1403         if (real_quotelevel > -1 && do_quote_folding) {
1404                 if (!g_utf8_validate(buf, -1, NULL)) {
1405                         gchar *utf8buf = NULL;
1406                         utf8buf = g_malloc(BUFFSIZE);
1407                         conv_localetodisp(utf8buf, BUFFSIZE, buf);
1408                         strncpy2(buf, utf8buf, BUFFSIZE-1);
1409                         g_free(utf8buf);
1410                 }
1411 do_quote:
1412                 if ( previousquotelevel != real_quotelevel ) {
1413                         ClickableText *uri;
1414                         uri = g_new0(ClickableText, 1);
1415                         uri->uri = g_strdup("");
1416                         uri->data = g_strdup(buf);
1417                         uri->start = gtk_text_iter_get_offset(&iter);
1418                         uri->is_quote = TRUE;
1419                         uri->quote_level = real_quotelevel;
1420                         uri->fg_color = g_strdup(fg_color);
1421
1422                         gtk_text_buffer_insert_with_tags_by_name
1423                                         (buffer, &iter, " [...]", -1,
1424                                          "qlink", fg_color, NULL);
1425                         uri->end = gtk_text_iter_get_offset(&iter);
1426                         gtk_text_buffer_insert(buffer, &iter, "  \n", -1);
1427                         
1428                         uri->filename = NULL;
1429                         textview->uri_list =
1430                                 g_slist_prepend(textview->uri_list, uri);
1431                 
1432                         previousquotelevel = real_quotelevel;
1433                 } else {
1434                         GSList *last = textview->uri_list;
1435                         ClickableText *lasturi = (ClickableText *)last->data;
1436                         gint e_len = 0, n_len = 0;
1437                         
1438                         if (lasturi->is_quote == FALSE) {
1439                                 previousquotelevel = -1;
1440                                 goto do_quote;
1441                         }
1442                         e_len = lasturi->data ? strlen(lasturi->data):0;
1443                         n_len = strlen(buf);
1444                         lasturi->data = g_realloc((gchar *)lasturi->data, e_len + n_len + 1);
1445                         strcpy((gchar *)lasturi->data + e_len, buf);
1446                         *((gchar *)lasturi->data + e_len + n_len) = '\0';
1447                 }
1448         } else {
1449                 textview_make_clickable_parts(textview, fg_color, "link", buf, FALSE);
1450                 previousquotelevel = -1;
1451         }
1452 }
1453
1454 void textview_write_link(TextView *textview, const gchar *str,
1455                          const gchar *uri, CodeConverter *conv)
1456 {
1457         GdkColor *link_color = NULL;
1458         GtkTextView *text;
1459         GtkTextBuffer *buffer;
1460         GtkTextIter iter;
1461         gchar buf[BUFFSIZE];
1462         gchar *bufp;
1463         ClickableText *r_uri;
1464
1465         if (!str || *str == '\0')
1466                 return;
1467         if (!uri)
1468                 return;
1469
1470         while (uri && *uri && g_ascii_isspace(*uri))
1471                 uri++;
1472                 
1473         text = GTK_TEXT_VIEW(textview->text);
1474         buffer = gtk_text_view_get_buffer(text);
1475         gtk_text_buffer_get_end_iter(buffer, &iter);
1476
1477         if (!conv)
1478                 strncpy2(buf, str, sizeof(buf));
1479         else if (conv_convert(conv, buf, sizeof(buf), str) < 0)
1480                 conv_utf8todisp(buf, sizeof(buf), str);
1481
1482         if (g_utf8_validate(buf, -1, NULL) == FALSE)
1483                 return;
1484
1485         strcrchomp(buf);
1486
1487         gtk_text_buffer_get_end_iter(buffer, &iter);
1488         for (bufp = buf; *bufp != '\0'; bufp = g_utf8_next_char(bufp)) {
1489                 gunichar ch;
1490
1491                 ch = g_utf8_get_char(bufp);
1492                 if (!g_unichar_isspace(ch))
1493                         break;
1494         }
1495         if (bufp > buf)
1496                 gtk_text_buffer_insert(buffer, &iter, buf, bufp - buf);
1497
1498         if (prefs_common.enable_color) {
1499                 link_color = &uri_color;
1500         }
1501         r_uri = g_new0(ClickableText, 1);
1502         r_uri->uri = g_strdup(uri);
1503         r_uri->start = gtk_text_iter_get_offset(&iter);
1504         gtk_text_buffer_insert_with_tags_by_name
1505                 (buffer, &iter, bufp, -1, "link", NULL);
1506         r_uri->end = gtk_text_iter_get_offset(&iter);
1507         r_uri->filename = NULL;
1508         textview->uri_list = g_slist_prepend(textview->uri_list, r_uri);
1509 }
1510
1511 static void textview_set_cursor(GdkWindow *window, GdkCursor *cursor)
1512 {
1513         if (GDK_IS_WINDOW(window))
1514                 gdk_window_set_cursor(window, cursor);
1515 }
1516 void textview_clear(TextView *textview)
1517 {
1518         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1519         GtkTextBuffer *buffer;
1520         GdkWindow *window = gtk_text_view_get_window(text,
1521                                 GTK_TEXT_WINDOW_TEXT);
1522
1523         buffer = gtk_text_view_get_buffer(text);
1524         gtk_text_buffer_set_text(buffer, "", -1);
1525
1526         TEXTVIEW_STATUSBAR_POP(textview);
1527         textview_uri_list_remove_all(textview->uri_list);
1528         textview->uri_list = NULL;
1529         textview->uri_hover = NULL;
1530
1531         textview->body_pos = 0;
1532         if (textview->image) 
1533                 gtk_widget_destroy(textview->image);
1534         textview->image = NULL;
1535
1536         if (textview->messageview->mainwin->cursor_count == 0) {
1537                 textview_set_cursor(window, text_cursor);
1538         } else {
1539                 textview_set_cursor(window, watch_cursor);
1540         }
1541 }
1542
1543 void textview_destroy(TextView *textview)
1544 {
1545         GtkTextBuffer *buffer;
1546         GtkClipboard *clipboard;
1547
1548         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview->text));
1549         clipboard = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
1550         gtk_text_buffer_remove_selection_clipboard(buffer, clipboard);
1551
1552         textview_uri_list_remove_all(textview->uri_list);
1553         textview->uri_list = NULL;
1554
1555         g_free(textview);
1556 }
1557
1558 void textview_set_all_headers(TextView *textview, gboolean all_headers)
1559 {
1560         textview->show_all_headers = all_headers;
1561 }
1562
1563 #define CHANGE_TAG_FONT(tagname, font) { \
1564         tag = gtk_text_tag_table_lookup(tags, tagname); \
1565         if (tag) \
1566                 g_object_set(G_OBJECT(tag), "font-desc", font, NULL); \
1567 }
1568
1569 void textview_set_font(TextView *textview, const gchar *codeset)
1570 {
1571         GtkTextTag *tag;
1572         GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview->text));
1573         GtkTextTagTable *tags = gtk_text_buffer_get_tag_table(buffer);
1574         
1575         if (NORMAL_FONT) {
1576                 PangoFontDescription *font_desc, *bold_font_desc;
1577                 font_desc = pango_font_description_from_string
1578                                                 (NORMAL_FONT);
1579                 bold_font_desc = pango_font_description_from_string
1580                                                 (NORMAL_FONT);
1581                 if (font_desc) {
1582                         gtk_widget_modify_font(textview->text, font_desc);
1583                         CHANGE_TAG_FONT("header", font_desc);
1584                         pango_font_description_free(font_desc);
1585                 }
1586                 if (bold_font_desc) {
1587                         pango_font_description_set_weight
1588                                 (bold_font_desc, PANGO_WEIGHT_BOLD);
1589                         CHANGE_TAG_FONT("header_title", bold_font_desc);
1590                         pango_font_description_free(bold_font_desc);
1591                 }
1592         }
1593
1594         if (prefs_common.textfont) {
1595                 PangoFontDescription *font_desc;
1596
1597                 font_desc = pango_font_description_from_string
1598                                                 (prefs_common.textfont);
1599                 if (font_desc) {
1600                         gtk_widget_modify_font(textview->text, font_desc);
1601                         pango_font_description_free(font_desc);
1602                 }
1603         }
1604         gtk_text_view_set_pixels_above_lines(GTK_TEXT_VIEW(textview->text),
1605                                              prefs_common.line_space / 2);
1606         gtk_text_view_set_pixels_below_lines(GTK_TEXT_VIEW(textview->text),
1607                                              prefs_common.line_space / 2);
1608 }
1609
1610 void textview_set_text(TextView *textview, const gchar *text)
1611 {
1612         GtkTextView *view;
1613         GtkTextBuffer *buffer;
1614
1615         g_return_if_fail(textview != NULL);
1616         g_return_if_fail(text != NULL);
1617
1618         textview_clear(textview);
1619
1620         view = GTK_TEXT_VIEW(textview->text);
1621         buffer = gtk_text_view_get_buffer(view);
1622         gtk_text_buffer_set_text(buffer, text, strlen(text));
1623 }
1624
1625 enum
1626 {
1627         H_DATE          = 0,
1628         H_FROM          = 1,
1629         H_TO            = 2,
1630         H_NEWSGROUPS    = 3,
1631         H_SUBJECT       = 4,
1632         H_CC            = 5,
1633         H_REPLY_TO      = 6,
1634         H_FOLLOWUP_TO   = 7,
1635         H_X_MAILER      = 8,
1636         H_X_NEWSREADER  = 9,
1637         H_USER_AGENT    = 10,
1638         H_ORGANIZATION  = 11,
1639 };
1640
1641 void textview_set_position(TextView *textview, gint pos)
1642 {
1643         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1644
1645         gtkut_text_view_set_position(text, pos);
1646 }
1647
1648 static gboolean header_is_internal(Header *header)
1649 {
1650         const gchar *internal_hdrs[] = 
1651                 {"AF:", "NF:", "PS:", "SRH:", "SFN:", "DSR:", "MID:", 
1652                  "CFG:", "PT:", "S:", "RQ:", "SSV:", "NSV:", "SSH:", 
1653                  "R:", "MAID:", "SCF:", "RMID:", "FMID:", "NAID:", 
1654                  "X-Claws-Account-Id:", "X-Claws-Sign:", "X-Claws-Encrypt:", 
1655                  "X-Claws-Privacy-System:", "X-Claws-End-Special-Headers:",
1656                  "X-Sylpheed-Account-Id:", "X-Sylpheed-Sign:", "X-Sylpheed-Encrypt:", 
1657                  "X-Sylpheed-Privacy-System:", "X-Sylpheed-End-Special-Headers:",
1658                  NULL};
1659         int i;
1660         
1661         for (i = 0; internal_hdrs[i]; i++) {
1662                 if (!strcmp(header->name, internal_hdrs[i]))
1663                         return TRUE;
1664         }
1665         return FALSE;
1666 }
1667
1668 static GPtrArray *textview_scan_header(TextView *textview, FILE *fp)
1669 {
1670         gchar buf[BUFFSIZE];
1671         GPtrArray *headers, *sorted_headers;
1672         GSList *disphdr_list;
1673         Header *header;
1674         gint i;
1675
1676         g_return_val_if_fail(fp != NULL, NULL);
1677
1678         if (textview->show_all_headers) {
1679                 headers = procheader_get_header_array_asis(fp);
1680                 sorted_headers = g_ptr_array_new();
1681                 for (i = 0; i < headers->len; i++) {
1682                         header = g_ptr_array_index(headers, i);
1683                         if (!header_is_internal(header))
1684                                 g_ptr_array_add(sorted_headers, header);
1685                         else
1686                                 procheader_header_free(header);
1687                 }
1688                 g_ptr_array_free(headers, TRUE);
1689                 return sorted_headers;
1690         }
1691
1692         if (!prefs_common.display_header) {
1693                 while (fgets(buf, sizeof(buf), fp) != NULL)
1694                         if (buf[0] == '\r' || buf[0] == '\n') break;
1695                 return NULL;
1696         }
1697
1698         headers = procheader_get_header_array_asis(fp);
1699
1700         sorted_headers = g_ptr_array_new();
1701
1702         for (disphdr_list = prefs_common.disphdr_list; disphdr_list != NULL;
1703              disphdr_list = disphdr_list->next) {
1704                 DisplayHeaderProp *dp =
1705                         (DisplayHeaderProp *)disphdr_list->data;
1706
1707                 for (i = 0; i < headers->len; i++) {
1708                         header = g_ptr_array_index(headers, i);
1709
1710                         if (procheader_headername_equal(header->name,
1711                                                         dp->name)) {
1712                                 if (dp->hidden)
1713                                         procheader_header_free(header);
1714                                 else
1715                                         g_ptr_array_add(sorted_headers, header);
1716
1717                                 g_ptr_array_remove_index(headers, i);
1718                                 i--;
1719                         }
1720                 }
1721         }
1722
1723         if (prefs_common.show_other_header) {
1724                 for (i = 0; i < headers->len; i++) {
1725                         header = g_ptr_array_index(headers, i);
1726                         if (!header_is_internal(header)) {
1727                                 g_ptr_array_add(sorted_headers, header);
1728                         } else {
1729                                 procheader_header_free(header);
1730                         }
1731                 }
1732                 g_ptr_array_free(headers, TRUE);
1733         } else
1734                 procheader_header_array_destroy(headers);
1735
1736
1737         return sorted_headers;
1738 }
1739
1740 static void textview_show_face(TextView *textview)
1741 {
1742         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1743         MsgInfo *msginfo = textview->messageview->msginfo;
1744         int x = 0;
1745         
1746         if (prefs_common.display_header_pane
1747         ||  !prefs_common.display_xface)
1748                 goto bail;
1749         
1750         if (!msginfo->extradata || !msginfo->extradata->face) {
1751                 goto bail;
1752         }
1753
1754         if (textview->image) 
1755                 gtk_widget_destroy(textview->image);
1756         
1757         textview->image = face_get_from_header(msginfo->extradata->face);
1758         g_return_if_fail(textview->image != NULL);
1759
1760         gtk_widget_show(textview->image);
1761         
1762         x = textview->text->allocation.width - WIDTH -5;
1763
1764         gtk_text_view_add_child_in_window(text, textview->image, 
1765                 GTK_TEXT_WINDOW_TEXT, x, 5);
1766
1767         gtk_widget_show_all(textview->text);
1768         
1769
1770         return;
1771 bail:
1772         if (textview->image) 
1773                 gtk_widget_destroy(textview->image);
1774         textview->image = NULL; 
1775 }
1776
1777 void textview_show_icon(TextView *textview, const gchar *stock_id)
1778 {
1779         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1780         int x = 0;
1781         
1782         if (textview->image) 
1783                 gtk_widget_destroy(textview->image);
1784         
1785         textview->image = gtk_image_new_from_stock(stock_id, GTK_ICON_SIZE_DIALOG);
1786         g_return_if_fail(textview->image != NULL);
1787
1788         gtk_widget_show(textview->image);
1789         
1790         x = textview->text->allocation.width - WIDTH -5;
1791
1792         gtk_text_view_add_child_in_window(text, textview->image, 
1793                 GTK_TEXT_WINDOW_TEXT, x, 5);
1794
1795         gtk_widget_show_all(textview->text);
1796         
1797
1798         return;
1799 }
1800
1801 #if HAVE_LIBCOMPFACE
1802 static void textview_show_xface(TextView *textview)
1803 {
1804         MsgInfo *msginfo = textview->messageview->msginfo;
1805         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1806         int x = 0;
1807         GdkWindow *window = NULL;
1808         
1809         if (prefs_common.display_header_pane
1810         ||  !prefs_common.display_xface)
1811                 goto bail;
1812         
1813         if (!msginfo || !msginfo->extradata)
1814                 goto bail;
1815
1816         if (msginfo->extradata->face)
1817                 return;
1818         
1819         if (!msginfo->extradata->xface || strlen(msginfo->extradata->xface) < 5) {
1820                 goto bail;
1821         }
1822
1823         if (textview->image) 
1824                 gtk_widget_destroy(textview->image);
1825
1826         window = mainwindow_get_mainwindow() ?
1827                         mainwindow_get_mainwindow()->window->window :
1828                         textview->text->window;
1829         textview->image = xface_get_from_header(msginfo->extradata->xface,
1830                                 &textview->text->style->white,
1831                                 window);
1832         g_return_if_fail(textview->image != NULL);
1833
1834         gtk_widget_show(textview->image);
1835         
1836         x = textview->text->allocation.width - WIDTH -5;
1837
1838         gtk_text_view_add_child_in_window(text, textview->image, 
1839                 GTK_TEXT_WINDOW_TEXT, x, 5);
1840
1841         gtk_widget_show_all(textview->text);
1842         
1843         return;
1844 bail:
1845         if (textview->image) 
1846                 gtk_widget_destroy(textview->image);
1847         textview->image = NULL;
1848         
1849 }
1850 #endif
1851
1852 static void textview_show_header(TextView *textview, GPtrArray *headers)
1853 {
1854         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1855         GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
1856         GtkTextIter iter;
1857         Header *header;
1858         gint i;
1859
1860         g_return_if_fail(headers != NULL);
1861
1862         for (i = 0; i < headers->len; i++) {
1863                 header = g_ptr_array_index(headers, i);
1864                 g_return_if_fail(header->name != NULL);
1865
1866                 gtk_text_buffer_get_end_iter (buffer, &iter);
1867                 if(prefs_common.trans_hdr == TRUE) {
1868                         gchar *hdr = g_strndup(header->name, strlen(header->name) - 1);
1869                         gchar *trans_hdr = gettext(hdr);
1870                         gtk_text_buffer_insert_with_tags_by_name(buffer,
1871                                 &iter, trans_hdr, -1,
1872                                 "header_title", "header", NULL);
1873                         gtk_text_buffer_insert_with_tags_by_name(buffer,
1874                                 &iter, ":", 1, "header_title", "header", NULL);
1875                         g_free(hdr);
1876                 } else {
1877                         gtk_text_buffer_insert_with_tags_by_name(buffer,
1878                                 &iter, header->name,
1879                                 -1, "header_title", "header", NULL);
1880                 }
1881                 if (header->name[strlen(header->name) - 1] != ' ')
1882                 gtk_text_buffer_insert_with_tags_by_name
1883                                 (buffer, &iter, " ", 1,
1884                                  "header_title", "header", NULL);
1885
1886                 if (procheader_headername_equal(header->name, "Subject") ||
1887                     procheader_headername_equal(header->name, "From")    ||
1888                     procheader_headername_equal(header->name, "To")      ||
1889                     procheader_headername_equal(header->name, "Cc"))
1890                         unfold_line(header->body);
1891
1892                 if ((procheader_headername_equal(header->name, "X-Mailer") ||
1893                      procheader_headername_equal(header->name,
1894                                                  "X-Newsreader")) &&
1895                     (strstr(header->body, "Claws Mail") != NULL ||
1896                      strstr(header->body, "Sylpheed-Claws") != NULL)) {
1897                         gtk_text_buffer_get_end_iter (buffer, &iter);
1898                         gtk_text_buffer_insert_with_tags_by_name
1899                                 (buffer, &iter, header->body, -1,
1900                                  "header", "emphasis", NULL);
1901                 } else {
1902                         gboolean hdr = 
1903                           procheader_headername_equal(header->name, "From") ||
1904                           procheader_headername_equal(header->name, "To") ||
1905                           procheader_headername_equal(header->name, "Cc") ||
1906                           procheader_headername_equal(header->name, "Bcc") ||
1907                           procheader_headername_equal(header->name, "Reply-To") ||
1908                           procheader_headername_equal(header->name, "Sender");
1909                         textview_make_clickable_parts(textview, "header", 
1910                                                       "hlink", header->body, 
1911                                                       hdr);
1912                 }
1913                 gtk_text_buffer_get_end_iter (buffer, &iter);
1914                 gtk_text_buffer_insert_with_tags_by_name(buffer, &iter, "\n", 1,
1915                                                          "header", NULL);
1916         }
1917         
1918         textview_show_face(textview);
1919 #if HAVE_LIBCOMPFACE
1920         textview_show_xface(textview);
1921 #endif
1922 }
1923
1924 gboolean textview_search_string(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(text, str, case_sens);
1930 }
1931
1932 gboolean textview_search_string_backward(TextView *textview, const gchar *str,
1933                                          gboolean case_sens)
1934 {
1935         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1936
1937         return gtkut_text_view_search_string_backward(text, str, case_sens);
1938 }
1939
1940 void textview_scroll_one_line(TextView *textview, gboolean up)
1941 {
1942         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1943         GtkAdjustment *vadj = text->vadjustment;
1944
1945         gtkutils_scroll_one_line(GTK_WIDGET(text), vadj, up);
1946 }
1947
1948 gboolean textview_scroll_page(TextView *textview, gboolean up)
1949 {
1950         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1951         GtkAdjustment *vadj = text->vadjustment;
1952
1953         return gtkutils_scroll_page(GTK_WIDGET(text), vadj, up);
1954 }
1955
1956 #define KEY_PRESS_EVENT_STOP() \
1957         g_signal_stop_emission_by_name(G_OBJECT(widget), \
1958                                        "key_press_event");
1959
1960 static gint textview_key_pressed(GtkWidget *widget, GdkEventKey *event,
1961                                  TextView *textview)
1962 {
1963         SummaryView *summaryview = NULL;
1964         MessageView *messageview = textview->messageview;
1965
1966         if (!event) return FALSE;
1967         if (messageview->mainwin)
1968                 summaryview = messageview->mainwin->summaryview;
1969
1970         switch (event->keyval) {
1971         case GDK_Tab:
1972         case GDK_Home:
1973         case GDK_Left:
1974         case GDK_Up:
1975         case GDK_Right:
1976         case GDK_Down:
1977         case GDK_Page_Up:
1978         case GDK_Page_Down:
1979         case GDK_End:
1980         case GDK_Control_L:
1981         case GDK_Control_R:
1982                 return FALSE;
1983         case GDK_space:
1984                 if (summaryview)
1985                         summary_pass_key_press_event(summaryview, event);
1986                 else
1987                         mimeview_scroll_page
1988                                 (messageview->mimeview,
1989                                  (event->state &
1990                                   (GDK_SHIFT_MASK|GDK_MOD1_MASK)) != 0);
1991                 break;
1992         case GDK_BackSpace:
1993                 mimeview_scroll_page(messageview->mimeview, TRUE);
1994                 break;
1995         case GDK_Return:
1996                 mimeview_scroll_one_line
1997                         (messageview->mimeview, (event->state &
1998                                     (GDK_SHIFT_MASK|GDK_MOD1_MASK)) != 0);
1999                 break;
2000         case GDK_Delete:
2001                 if (summaryview)
2002                         summary_pass_key_press_event(summaryview, event);
2003                 break;
2004         case GDK_y:
2005         case GDK_t:
2006         case GDK_l:
2007         case GDK_c:
2008                 if ((event->state & (GDK_MOD1_MASK|GDK_CONTROL_MASK)) == 0) {
2009                         KEY_PRESS_EVENT_STOP();
2010                         mimeview_pass_key_press_event(messageview->mimeview,
2011                                                       event);
2012                         break;
2013                 }
2014                 /* possible fall through */
2015         default:
2016                 if (summaryview &&
2017                     event->window != messageview->mainwin->window->window) {
2018                         GdkEventKey tmpev = *event;
2019
2020                         tmpev.window = messageview->mainwin->window->window;
2021                         KEY_PRESS_EVENT_STOP();
2022                         gtk_widget_event(messageview->mainwin->window,
2023                                          (GdkEvent *)&tmpev);
2024                 }
2025                 break;
2026         }
2027
2028         return TRUE;
2029 }
2030
2031 static gboolean textview_motion_notify(GtkWidget *widget,
2032                                        GdkEventMotion *event,
2033                                        TextView *textview)
2034 {
2035         if (textview->loading)
2036                 return FALSE;
2037         textview_uri_update(textview, event->x, event->y);
2038         gdk_window_get_pointer(widget->window, NULL, NULL, NULL);
2039
2040         return FALSE;
2041 }
2042
2043 static gboolean textview_leave_notify(GtkWidget *widget,
2044                                       GdkEventCrossing *event,
2045                                       TextView *textview)
2046 {
2047         if (textview->loading)
2048                 return FALSE;
2049         textview_uri_update(textview, -1, -1);
2050
2051         return FALSE;
2052 }
2053
2054 static gboolean textview_visibility_notify(GtkWidget *widget,
2055                                            GdkEventVisibility *event,
2056                                            TextView *textview)
2057 {
2058         gint wx, wy;
2059         GdkWindow *window;
2060
2061         if (textview->loading)
2062                 return FALSE;
2063
2064         window = gtk_text_view_get_window(GTK_TEXT_VIEW(widget),
2065                                           GTK_TEXT_WINDOW_TEXT);
2066
2067         /* check if occurred for the text window part */
2068         if (window != event->window)
2069                 return FALSE;
2070         
2071         gdk_window_get_pointer(widget->window, &wx, &wy, NULL);
2072         textview_uri_update(textview, wx, wy);
2073
2074         return FALSE;
2075 }
2076
2077 void textview_cursor_wait(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, watch_cursor);
2083 }
2084
2085 void textview_cursor_normal(TextView *textview)
2086 {
2087         GdkWindow *window = gtk_text_view_get_window(
2088                         GTK_TEXT_VIEW(textview->text),
2089                         GTK_TEXT_WINDOW_TEXT);
2090         textview_set_cursor(window, text_cursor);
2091 }
2092
2093 static void textview_uri_update(TextView *textview, gint x, gint y)
2094 {
2095         GtkTextBuffer *buffer;
2096         GtkTextIter start_iter, end_iter;
2097         ClickableText *uri = NULL;
2098         
2099         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview->text));
2100
2101         if (x != -1 && y != -1) {
2102                 gint bx, by;
2103                 GtkTextIter iter;
2104                 GSList *tags;
2105                 GSList *cur;
2106                 
2107                 gtk_text_view_window_to_buffer_coords(GTK_TEXT_VIEW(textview->text), 
2108                                                       GTK_TEXT_WINDOW_WIDGET,
2109                                                       x, y, &bx, &by);
2110                 gtk_text_view_get_iter_at_location(GTK_TEXT_VIEW(textview->text),
2111                                                    &iter, bx, by);
2112
2113                 tags = gtk_text_iter_get_tags(&iter);
2114                 for (cur = tags; cur != NULL; cur = cur->next) {
2115                         GtkTextTag *tag = cur->data;
2116                         char *name;
2117
2118                         g_object_get(G_OBJECT(tag), "name", &name, NULL);
2119
2120                         if ((!strcmp(name, "link") || !strcmp(name, "hlink"))
2121                             && textview_get_uri_range(textview, &iter, tag,
2122                                                       &start_iter, &end_iter)) {
2123
2124                                 uri = textview_get_uri_from_range(textview,
2125                                                                   &iter, tag,
2126                                                                   &start_iter,
2127                                                                   &end_iter);
2128                         }
2129                         g_free(name);
2130                         if (uri)
2131                                 break;
2132                 }
2133                 g_slist_free(tags);
2134         }
2135         
2136         if (uri != textview->uri_hover) {
2137                 GdkWindow *window;
2138
2139                 if (textview->uri_hover)
2140                         gtk_text_buffer_remove_tag_by_name(buffer,
2141                                                            "link-hover",
2142                                                            &textview->uri_hover_start_iter,
2143                                                            &textview->uri_hover_end_iter);
2144                     
2145                 textview->uri_hover = uri;
2146                 if (uri) {
2147                         textview->uri_hover_start_iter = start_iter;
2148                         textview->uri_hover_end_iter = end_iter;
2149                 }
2150                 
2151                 window = gtk_text_view_get_window(GTK_TEXT_VIEW(textview->text),
2152                                                   GTK_TEXT_WINDOW_TEXT);
2153                 if (textview->messageview->mainwin->cursor_count == 0) {
2154                         textview_set_cursor(window, uri ? hand_cursor : text_cursor);
2155                 } else {
2156                         textview_set_cursor(window, watch_cursor);
2157                 }
2158
2159                 TEXTVIEW_STATUSBAR_POP(textview);
2160
2161                 if (uri) {
2162                         char *trimmed_uri;
2163
2164                         if (!uri->is_quote)
2165                                 gtk_text_buffer_apply_tag_by_name(buffer,
2166                                                           "link-hover",
2167                                                           &start_iter,
2168                                                           &end_iter);
2169
2170                         trimmed_uri = trim_string(uri->uri, 60);
2171                         TEXTVIEW_STATUSBAR_PUSH(textview, trimmed_uri);
2172                         g_free(trimmed_uri);
2173                 }
2174         }
2175 }
2176
2177 static gboolean textview_get_uri_range(TextView *textview,
2178                                        GtkTextIter *iter,
2179                                        GtkTextTag *tag,
2180                                        GtkTextIter *start_iter,
2181                                        GtkTextIter *end_iter)
2182 {
2183         return get_tag_range(iter, tag, start_iter, end_iter);
2184 }
2185
2186 static ClickableText *textview_get_uri_from_range(TextView *textview,
2187                                               GtkTextIter *iter,
2188                                               GtkTextTag *tag,
2189                                               GtkTextIter *start_iter,
2190                                               GtkTextIter *end_iter)
2191 {
2192         gint start_pos, end_pos, cur_pos;
2193         ClickableText *uri = NULL;
2194         GSList *cur;
2195
2196         start_pos = gtk_text_iter_get_offset(start_iter);
2197         end_pos = gtk_text_iter_get_offset(end_iter);
2198         cur_pos = gtk_text_iter_get_offset(iter);
2199
2200         for (cur = textview->uri_list; cur != NULL; cur = cur->next) {
2201                 ClickableText *uri_ = (ClickableText *)cur->data;
2202                 if (start_pos == uri_->start &&
2203                     end_pos ==  uri_->end) {
2204                         uri = uri_;
2205                         break;
2206                 } 
2207         }
2208         for (cur = textview->uri_list; uri == NULL && cur != NULL; cur = cur->next) {
2209                 ClickableText *uri_ = (ClickableText *)cur->data;
2210                 if (start_pos == uri_->start ||
2211                            end_pos == uri_->end) {
2212                         /* in case of contiguous links, textview_get_uri_range
2213                          * returns a broader range (start of 1st link to end
2214                          * of last link).
2215                          * In that case, correct link is the one covering
2216                          * current iter.
2217                          */
2218                         if (uri_->start <= cur_pos && cur_pos <= uri_->end) {
2219                                 uri = uri_;
2220                                 break;
2221                         }
2222                 } 
2223         }
2224
2225         return uri;
2226 }
2227
2228 static ClickableText *textview_get_uri(TextView *textview,
2229                                    GtkTextIter *iter,
2230                                    GtkTextTag *tag)
2231 {
2232         GtkTextIter start_iter, end_iter;
2233         ClickableText *uri = NULL;
2234
2235         if (textview_get_uri_range(textview, iter, tag, &start_iter,
2236                                    &end_iter))
2237                 uri = textview_get_uri_from_range(textview, iter, tag,
2238                                                   &start_iter, &end_iter);
2239
2240         return uri;
2241 }
2242
2243 static void textview_shift_uris_after(TextView *textview, GSList *start_list, gint start, gint shift)
2244 {
2245         GSList *cur;
2246         if (!start_list)
2247                 start_list = textview->uri_list;
2248
2249         for (cur = start_list; cur; cur = cur->next) {
2250                 ClickableText *uri = (ClickableText *)cur->data;
2251                 if (uri->start <= start)
2252                         continue;
2253                 uri->start += shift;
2254                 uri->end += shift;
2255         }
2256 }
2257
2258 static void textview_remove_uris_in(TextView *textview, gint start, gint end)
2259 {
2260         GSList *cur;
2261         for (cur = textview->uri_list; cur; ) {
2262                 ClickableText *uri = (ClickableText *)cur->data;
2263                 if (uri->start > start && uri->end < end) {
2264                         cur = cur->next;
2265                         textview->uri_list = g_slist_remove(textview->uri_list, uri);
2266                         g_free(uri->uri);
2267                         g_free(uri->filename);
2268                         if (uri->is_quote) {
2269                                 g_free(uri->fg_color);
2270                                 g_free(uri->data); 
2271                                 /* (only free data in quotes uris) */
2272                         }
2273                         g_free(uri);
2274                 } else {
2275                         cur = cur->next;
2276                 }
2277                 
2278         }
2279 }
2280
2281 static void textview_toggle_quote(TextView *textview, GSList *start_list, ClickableText *uri, gboolean expand_only)
2282 {
2283         GtkTextIter start, end;
2284         GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview->text));
2285         
2286         if (!uri->is_quote)
2287                 return;
2288         
2289         if (uri->q_expanded && expand_only)
2290                 return;
2291
2292         gtk_text_buffer_get_iter_at_offset(buffer, &start, uri->start);
2293         gtk_text_buffer_get_iter_at_offset(buffer, &end,   uri->end);
2294         if (textview->uri_hover)
2295                 gtk_text_buffer_remove_tag_by_name(buffer,
2296                                                    "link-hover",
2297                                                    &textview->uri_hover_start_iter,
2298                                                    &textview->uri_hover_end_iter);
2299         textview->uri_hover = NULL;
2300         gtk_text_buffer_remove_tag_by_name(buffer,
2301                                            "qlink",
2302                                            &start,
2303                                            &end);
2304         /* when shifting URIs start and end, we have to do it per-UTF8-char
2305          * so use g_utf8_strlen(). OTOH, when inserting in the text buffer, 
2306          * we have to pass a number of bytes, so use strlen(). disturbing. */
2307          
2308         if (!uri->q_expanded) {
2309                 gtk_text_buffer_get_iter_at_offset(buffer, &start, uri->start);
2310                 gtk_text_buffer_get_iter_at_offset(buffer, &end,   uri->end);
2311                 textview_shift_uris_after(textview, start_list, uri->start, 
2312                         g_utf8_strlen((gchar *)uri->data, -1)-strlen(" [...]\n"));
2313                 gtk_text_buffer_delete(buffer, &start, &end);
2314                 gtk_text_buffer_get_iter_at_offset(buffer, &start, uri->start);
2315                 gtk_text_buffer_insert_with_tags_by_name
2316                                 (buffer, &start, (gchar *)uri->data, 
2317                                  strlen((gchar *)uri->data)-1,
2318                                  "qlink", (gchar *)uri->fg_color, NULL);
2319                 uri->end = gtk_text_iter_get_offset(&start);
2320                 textview_make_clickable_parts_later(textview,
2321                                           uri->start, uri->end);
2322                 uri->q_expanded = TRUE;
2323         } else {
2324                 gtk_text_buffer_get_iter_at_offset(buffer, &start, uri->start);
2325                 gtk_text_buffer_get_iter_at_offset(buffer, &end,   uri->end);
2326                 textview_remove_uris_in(textview, uri->start, uri->end);
2327                 textview_shift_uris_after(textview, start_list, uri->start, 
2328                         strlen(" [...]\n")-g_utf8_strlen((gchar *)uri->data, -1));
2329                 gtk_text_buffer_delete(buffer, &start, &end);
2330                 gtk_text_buffer_get_iter_at_offset(buffer, &start, uri->start);
2331                 gtk_text_buffer_insert_with_tags_by_name
2332                                 (buffer, &start, " [...]", -1,
2333                                  "qlink", (gchar *)uri->fg_color, NULL);
2334                 uri->end = gtk_text_iter_get_offset(&start);
2335                 uri->q_expanded = FALSE;
2336         }
2337         if (textview->messageview->mainwin->cursor_count == 0) {
2338                 textview_cursor_normal(textview);
2339         } else {
2340                 textview_cursor_wait(textview);
2341         }
2342 }
2343 static gboolean textview_uri_button_pressed(GtkTextTag *tag, GObject *obj,
2344                                             GdkEvent *event, GtkTextIter *iter,
2345                                             TextView *textview)
2346 {
2347         GdkEventButton *bevent;
2348         ClickableText *uri = NULL;
2349         char *tagname;
2350         gboolean qlink = FALSE;
2351
2352         if (!event)
2353                 return FALSE;
2354
2355         if (event->type != GDK_BUTTON_PRESS && event->type != GDK_2BUTTON_PRESS
2356                 && event->type != GDK_MOTION_NOTIFY)
2357                 return FALSE;
2358
2359         uri = textview_get_uri(textview, iter, tag);
2360         if (!uri)
2361                 return FALSE;
2362
2363         g_object_get(G_OBJECT(tag), "name", &tagname, NULL);
2364         
2365         if (!strcmp(tagname, "qlink"))
2366                 qlink = TRUE;
2367
2368         g_free(tagname);
2369         
2370         bevent = (GdkEventButton *) event;
2371         
2372         /* doubleclick: open compose / add address / browser */
2373         if (qlink && event->type == GDK_BUTTON_PRESS && bevent->button != 1) {
2374                 /* pass rightclick through */
2375                 return FALSE;
2376         } else if ((event->type == (qlink ? GDK_2BUTTON_PRESS:GDK_BUTTON_PRESS) && bevent->button == 1) ||
2377                 bevent->button == 2 || bevent->button == 3) {
2378                 if (uri->filename && !g_ascii_strncasecmp(uri->filename, "sc://", 5)) {
2379                         MimeView *mimeview = 
2380                                 (textview->messageview)?
2381                                         textview->messageview->mimeview:NULL;
2382                         if (mimeview && bevent->button == 1) {
2383                                 mimeview_handle_cmd(mimeview, uri->filename, NULL, uri->data);
2384                         } else if (mimeview && bevent->button == 2 && 
2385                                 !g_ascii_strcasecmp(uri->filename, "sc://select_attachment")) {
2386                                 mimeview_handle_cmd(mimeview, "sc://open_attachment", NULL, uri->data);
2387                         } else if (mimeview && bevent->button == 3 && 
2388                                 !g_ascii_strcasecmp(uri->filename, "sc://select_attachment")) {
2389                                 mimeview_handle_cmd(mimeview, "sc://menu_attachment", bevent, uri->data);
2390                         } 
2391                         return TRUE;
2392                 } else if (qlink && bevent->button == 1) {
2393                         textview_toggle_quote(textview, NULL, uri, FALSE);
2394                         return TRUE;
2395                 } else if (!g_ascii_strncasecmp(uri->uri, "mailto:", 7)) {
2396                         if (bevent->button == 3) {
2397                                 g_object_set_data(
2398                                         G_OBJECT(textview->mail_popup_menu),
2399                                         "menu_button", uri);
2400                                 gtk_menu_popup(GTK_MENU(textview->mail_popup_menu), 
2401                                                NULL, NULL, NULL, NULL, 
2402                                                bevent->button, bevent->time);
2403                         } else {
2404                                 PrefsAccount *account = NULL;
2405                                 FolderItem   *folder_item = NULL;
2406                                 if (textview->messageview && textview->messageview->msginfo &&
2407                                     textview->messageview->msginfo->folder) {
2408                                         
2409
2410                                         folder_item = textview->messageview->msginfo->folder;
2411                                         if (folder_item->prefs && folder_item->prefs->enable_default_account)
2412                                                 account = account_find_from_id(folder_item->prefs->default_account);
2413                                 }
2414                                 compose_new_with_folderitem(account, folder_item, uri->uri + 7);
2415                         }
2416                         return TRUE;
2417                 } else if (g_ascii_strncasecmp(uri->uri, "file:", 5)) {
2418                         if (bevent->button == 1 &&
2419                             textview_uri_security_check(textview, uri) == TRUE) 
2420                                         open_uri(uri->uri,
2421                                                  prefs_common.uri_cmd);
2422                         else if (bevent->button == 3 && !qlink) {
2423                                 g_object_set_data(
2424                                         G_OBJECT(textview->link_popup_menu),
2425                                         "menu_button", uri);
2426                                 gtk_menu_popup(GTK_MENU(textview->link_popup_menu), 
2427                                                NULL, NULL, NULL, NULL, 
2428                                                bevent->button, bevent->time);
2429                         }
2430                         return TRUE;
2431                 } else {
2432                         if (bevent->button == 3 && !qlink) {
2433                                 g_object_set_data(
2434                                         G_OBJECT(textview->file_popup_menu),
2435                                         "menu_button", uri);
2436                                 gtk_menu_popup(GTK_MENU(textview->file_popup_menu), 
2437                                                NULL, NULL, NULL, NULL, 
2438                                                bevent->button, bevent->time);
2439                                 return TRUE;
2440                         }
2441                 }
2442         }
2443
2444         return FALSE;
2445 }
2446
2447 /*!
2448  *\brief    Check to see if a web URL has been disguised as a different
2449  *          URL (possible with HTML email).
2450  *
2451  *\param    uri The uri to check
2452  *
2453  *\param    textview The TextView the URL is contained in
2454  *
2455  *\return   gboolean TRUE if the URL is ok, or if the user chose to open
2456  *          it anyway, otherwise FALSE          
2457  */
2458 static gboolean textview_uri_security_check(TextView *textview, ClickableText *uri)
2459 {
2460         gchar *visible_str;
2461         gboolean retval = TRUE;
2462         GtkTextBuffer *buffer;
2463         GtkTextIter start, end;
2464
2465         if (is_uri_string(uri->uri) == FALSE)
2466                 return TRUE;
2467
2468         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview->text));
2469
2470         gtk_text_buffer_get_iter_at_offset(buffer, &start, uri->start);
2471         gtk_text_buffer_get_iter_at_offset(buffer, &end,   uri->end);
2472
2473         visible_str = gtk_text_buffer_get_text(buffer, &start, &end, FALSE);
2474
2475         if (visible_str == NULL)
2476                 return TRUE;
2477
2478         if (strcmp(visible_str, uri->uri) != 0 && is_uri_string(visible_str)) {
2479                 gchar *uri_path;
2480                 gchar *visible_uri_path;
2481
2482                 uri_path = get_uri_path(uri->uri);
2483                 visible_uri_path = get_uri_path(visible_str);
2484                 if (path_cmp(uri_path, visible_uri_path) != 0)
2485                         retval = FALSE;
2486         }
2487
2488         if (retval == FALSE) {
2489                 gchar *msg;
2490                 AlertValue aval;
2491
2492                 msg = g_markup_printf_escaped(_("The real URL is different from "
2493                                                 "the displayed URL.\n"
2494                                                 "\n"
2495                                                 "<b>Displayed URL:</b> %s\n"
2496                                                 "\n"
2497                                                 "<b>Real URL:</b> %s\n"
2498                                                 "\n"
2499                                                 "Open it anyway?"),
2500                                                visible_str,uri->uri);
2501                 aval = alertpanel_full(_("Phishing attempt warning"), msg,
2502                                        GTK_STOCK_CANCEL, _("_Open URL"), NULL, FALSE,
2503                                        NULL, ALERT_WARNING, G_ALERTDEFAULT);
2504                 g_free(msg);
2505                 if (aval == G_ALERTALTERNATE)
2506                         retval = TRUE;
2507         }
2508
2509         g_free(visible_str);
2510
2511         return retval;
2512 }
2513
2514 static void textview_uri_list_remove_all(GSList *uri_list)
2515 {
2516         GSList *cur;
2517
2518         for (cur = uri_list; cur != NULL; cur = cur->next) {
2519                 if (cur->data) {
2520                         g_free(((ClickableText *)cur->data)->uri);
2521                         g_free(((ClickableText *)cur->data)->filename);
2522                         if (((ClickableText *)cur->data)->is_quote) {
2523                                 g_free(((ClickableText *)cur->data)->fg_color);
2524                                 g_free(((ClickableText *)cur->data)->data); 
2525                                 /* (only free data in quotes uris) */
2526                         }
2527                         g_free(cur->data);
2528                 }
2529         }
2530
2531         g_slist_free(uri_list);
2532 }
2533
2534 static void open_uri_cb (TextView *textview, guint action, void *data)
2535 {
2536         ClickableText *uri = g_object_get_data(G_OBJECT(textview->link_popup_menu),
2537                                            "menu_button");
2538         if (uri == NULL)
2539                 return;
2540
2541         if (textview_uri_security_check(textview, uri) == TRUE) 
2542                 open_uri(uri->uri,
2543                          prefs_common.uri_cmd);
2544         g_object_set_data(G_OBJECT(textview->link_popup_menu), "menu_button",
2545                           NULL);
2546 }
2547
2548 static void open_image_cb (TextView *textview, guint action, void *data)
2549 {
2550         ClickableText *uri = g_object_get_data(G_OBJECT(textview->file_popup_menu),
2551                                            "menu_button");
2552
2553         gchar *cmd = NULL;
2554         gchar buf[1024];
2555         const gchar *p;
2556         gchar *filename = NULL;
2557         gchar *tmp_filename = NULL;
2558
2559         if (uri == NULL)
2560                 return;
2561
2562         if (uri->filename == NULL)
2563                 return;
2564         
2565         filename = g_strdup(uri->filename);
2566         
2567         if (!g_utf8_validate(filename, -1, NULL)) {
2568                 gchar *tmp = conv_filename_to_utf8(filename);
2569                 g_free(filename);
2570                 filename = tmp;
2571         }
2572
2573         subst_for_filename(filename);
2574
2575         tmp_filename = g_filename_from_uri(uri->uri, NULL, NULL);
2576         copy_file(tmp_filename, filename, FALSE);
2577         g_free(tmp_filename);
2578
2579         cmd = mailcap_get_command_for_type("image/jpeg", filename);
2580         if (cmd == NULL) {
2581                 gboolean remember = FALSE;
2582                 cmd = input_dialog_combo_remember
2583                         (_("Open with"),
2584                          _("Enter the command line to open file:\n"
2585                            "('%s' will be replaced with file name)"),
2586                          prefs_common.mime_open_cmd,
2587                          prefs_common.mime_open_cmd_history,
2588                          TRUE, &remember);
2589                 if (cmd && remember) {
2590                         mailcap_update_default("image/jpeg", cmd);
2591                 }
2592         }
2593         if (cmd && (p = strchr(cmd, '%')) && *(p + 1) == 's' &&
2594             !strchr(p + 2, '%'))
2595                 g_snprintf(buf, sizeof(buf), cmd, filename);
2596         else {
2597                 g_warning("Image viewer command line is invalid: '%s'", cmd);
2598                 return;
2599         }
2600
2601         execute_command_line(buf, TRUE);
2602
2603         g_free(filename);
2604         g_free(cmd);
2605
2606         g_object_set_data(G_OBJECT(textview->file_popup_menu), "menu_button",
2607                           NULL);
2608 }
2609
2610 static void save_file_cb (TextView *textview, guint action, void *data)
2611 {
2612         ClickableText *uri = g_object_get_data(G_OBJECT(textview->file_popup_menu),
2613                                            "menu_button");
2614         gchar *filename = NULL;
2615         gchar *filepath = NULL;
2616         gchar *filedir = NULL;
2617         gchar *tmp_filename = NULL;
2618         if (uri == NULL)
2619                 return;
2620
2621         if (uri->filename == NULL)
2622                 return;
2623         
2624         filename = g_strdup(uri->filename);
2625         
2626         if (!g_utf8_validate(filename, -1, NULL)) {
2627                 gchar *tmp = conv_filename_to_utf8(filename);
2628                 g_free(filename);
2629                 filename = tmp;
2630         }
2631
2632         subst_for_filename(filename);
2633         
2634         if (prefs_common.attach_save_dir)
2635                 filepath = g_strconcat(prefs_common.attach_save_dir,
2636                                        G_DIR_SEPARATOR_S, filename, NULL);
2637         else
2638                 filepath = g_strdup(filename);
2639
2640         g_free(filename);
2641
2642         filename = filesel_select_file_save(_("Save as"), filepath);
2643         if (!filename) {
2644                 g_free(filepath);
2645                 return;
2646         }
2647
2648         if (is_file_exist(filename)) {
2649                 AlertValue aval;
2650                 gchar *res;
2651                 
2652                 res = g_strdup_printf(_("Overwrite existing file '%s'?"),
2653                                       filename);
2654                 aval = alertpanel(_("Overwrite"), res, GTK_STOCK_CANCEL, 
2655                                   GTK_STOCK_OK, NULL);
2656                 g_free(res);                                      
2657                 if (G_ALERTALTERNATE != aval)
2658                         return;
2659         }
2660
2661         tmp_filename = g_filename_from_uri(uri->uri, NULL, NULL);
2662         copy_file(tmp_filename, filename, FALSE);
2663         g_free(tmp_filename);
2664         
2665         filedir = g_path_get_dirname(filename);
2666         if (filedir && strcmp(filedir, ".")) {
2667                 g_free(prefs_common.attach_save_dir);
2668                 prefs_common.attach_save_dir = g_strdup(filedir);
2669         }
2670
2671         g_free(filedir);
2672         g_free(filepath);
2673
2674         g_object_set_data(G_OBJECT(textview->file_popup_menu), "menu_button",
2675                           NULL);
2676 }
2677
2678 static void copy_uri_cb (TextView *textview, guint action, void *data)
2679 {
2680         ClickableText *uri = g_object_get_data(G_OBJECT(textview->link_popup_menu),
2681                                            "menu_button");
2682         if (uri == NULL)
2683                 return;
2684
2685         gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), uri->uri, -1);
2686         gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), uri->uri, -1);
2687         g_object_set_data(G_OBJECT(textview->link_popup_menu), "menu_button",
2688                           NULL);
2689 }
2690
2691 static void add_uri_to_addrbook_cb (TextView *textview, guint action, void *data)
2692 {
2693         gchar *fromname, *fromaddress;
2694         ClickableText *uri = g_object_get_data(G_OBJECT(textview->mail_popup_menu),
2695                                            "menu_button");
2696         if (uri == NULL)
2697                 return;
2698
2699         /* extract url */
2700         fromaddress = g_strdup(uri->uri + 7);
2701         /* Hiroyuki: please put this function in utils.c! */
2702         fromname = procheader_get_fromname(fromaddress);
2703         extract_address(fromaddress);
2704         g_message("adding from textview %s <%s>", fromname, fromaddress);
2705         /* Add to address book - Match */
2706         addressbook_add_contact( fromname, fromaddress, NULL );
2707
2708         g_free(fromaddress);
2709         g_free(fromname);
2710 }
2711
2712 static void mail_to_uri_cb (TextView *textview, guint action, void *data)
2713 {
2714         PrefsAccount *account = NULL;
2715         ClickableText *uri = g_object_get_data(G_OBJECT(textview->mail_popup_menu),
2716                                            "menu_button");
2717         if (uri == NULL)
2718                 return;
2719
2720         if (textview->messageview && textview->messageview->msginfo &&
2721             textview->messageview->msginfo->folder) {
2722                 FolderItem   *folder_item;
2723
2724                 folder_item = textview->messageview->msginfo->folder;
2725                 if (folder_item->prefs && folder_item->prefs->enable_default_account)
2726                         account = account_find_from_id(folder_item->prefs->default_account);
2727         }
2728         compose_new(account, uri->uri + 7, NULL);
2729 }
2730
2731 static void copy_mail_to_uri_cb (TextView *textview, guint action, void *data)
2732 {
2733         ClickableText *uri = g_object_get_data(G_OBJECT(textview->mail_popup_menu),
2734                                            "menu_button");
2735         if (uri == NULL)
2736                 return;
2737
2738         gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), uri->uri +7, -1);
2739         gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), uri->uri +7, -1);
2740         g_object_set_data(G_OBJECT(textview->mail_popup_menu), "menu_button",
2741                           NULL);
2742 }
2743
2744 void textview_get_selection_offsets(TextView *textview, gint *sel_start, gint *sel_end)
2745 {
2746                 GtkTextView *text = GTK_TEXT_VIEW(textview->text);
2747                 GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
2748                 GtkTextIter start, end;
2749                 if (gtk_text_buffer_get_selection_bounds(buffer, &start, &end)) {
2750                         if (sel_start)
2751                                 *sel_start = gtk_text_iter_get_offset(&start);
2752                         if (sel_end)
2753                                 *sel_end = gtk_text_iter_get_offset(&end);
2754                 } else {
2755                         if (sel_start)
2756                                 *sel_start = -1;
2757                         if (sel_end)
2758                                 *sel_end = -1;
2759                 }
2760 }