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