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