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