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