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