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