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