0a39b7a9db1245c67289c7ba5b5419df73a23dac
[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\n", 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                         textview_show_html(textview, tmpfp, conv);
1083                         fclose(tmpfp);
1084                         claws_unlink(filename);
1085                 }
1086                 g_free(filename);
1087         } else if (!g_ascii_strcasecmp(mimeinfo->subtype, "enriched")) {
1088                 gchar *filename;
1089                 
1090                 filename = procmime_get_tmp_file_name(mimeinfo);
1091                 if (procmime_get_part(filename, mimeinfo) == 0) {
1092                         tmpfp = g_fopen(filename, "rb");
1093                         if (tmpfp) {
1094                                 textview_show_ertf(textview, tmpfp, conv);
1095                                 fclose(tmpfp);
1096                         }
1097                         claws_unlink(filename);
1098                 }
1099                 g_free(filename);
1100 #ifndef G_OS_WIN32
1101         } else if ( g_ascii_strcasecmp(mimeinfo->subtype, "plain") &&
1102                    (cmd = prefs_common.mime_textviewer) && *cmd &&
1103                    (p = strchr(cmd, '%')) && *(p + 1) == 's') {
1104                 int pid, pfd[2];
1105                 const gchar *fname;
1106
1107                 fname  = procmime_get_tmp_file_name(mimeinfo);
1108                 if (procmime_get_part(fname, mimeinfo)) goto textview_default;
1109
1110                 g_snprintf(buf, sizeof(buf), cmd, fname);
1111                 debug_print("Viewing text content of type: %s (length: %d) "
1112                         "using %s\n", mimeinfo->subtype, mimeinfo->length, buf);
1113
1114                 if (pipe(pfd) < 0) {
1115                         g_snprintf(buf, sizeof(buf),
1116                                 "pipe failed for textview\n\n%s\n", g_strerror(errno));
1117                         textview_write_line(textview, buf, conv, TRUE);
1118                         goto textview_default;
1119                 }
1120                 pid = fork();
1121                 if (pid < 0) {
1122                         g_snprintf(buf, sizeof(buf),
1123                                 "fork failed for textview\n\n%s\n", g_strerror(errno));
1124                         textview_write_line(textview, buf, conv, TRUE);
1125                         close(pfd[0]);
1126                         close(pfd[1]);
1127                         goto textview_default;
1128                 }
1129                 if (pid == 0) { /* child */
1130                         int rc;
1131                         gchar **argv;
1132                         argv = strsplit_with_quote(buf, " ", 0);
1133                         close(1);
1134                         close(pfd[0]);
1135                         rc = dup(pfd[1]);
1136                         rc = execvp(argv[0], argv);
1137                         close(pfd[1]);
1138                         g_print(_("The command to view attachment "
1139                                 "as text failed:\n"
1140                                 "    %s\n"
1141                                 "Exit code %d\n"), buf, rc);
1142                         exit(255);
1143                 }
1144                 close(pfd[1]);
1145                 tmpfp = fdopen(pfd[0], "rb");
1146                 while (fgets(buf, sizeof(buf), tmpfp)) {
1147                         textview_write_line(textview, buf, conv, TRUE);
1148                         
1149                         if (textview->stop_loading) {
1150                                 fclose(tmpfp);
1151                                 waitpid(pid, pfd, 0);
1152                                 g_unlink(fname);
1153                                 return;
1154                         }
1155                 }
1156
1157                 fclose(tmpfp);
1158                 waitpid(pid, pfd, 0);
1159                 g_unlink(fname);
1160 #endif
1161         } else {
1162 textview_default:
1163                 if (!g_ascii_strcasecmp(mimeinfo->subtype, "x-patch")
1164                                 || !g_ascii_strcasecmp(mimeinfo->subtype, "x-diff"))
1165                         textview->is_diff = TRUE;
1166
1167                 if (mimeinfo->content == MIMECONTENT_MEM)
1168                         tmpfp = str_open_as_stream(mimeinfo->data.mem);
1169                 else
1170                         tmpfp = g_fopen(mimeinfo->data.filename, "rb");
1171                 if (!tmpfp) {
1172                         FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1173                         return;
1174                 }
1175                 if (fseek(tmpfp, mimeinfo->offset, SEEK_SET) < 0) {
1176                         FILE_OP_ERROR(mimeinfo->data.filename, "fseek");
1177                         fclose(tmpfp);
1178                         return;
1179                 }
1180                 debug_print("Viewing text content of type: %s (length: %d)\n", mimeinfo->subtype, mimeinfo->length);
1181                 while (((i = ftell(tmpfp)) < mimeinfo->offset + mimeinfo->length) &&
1182                        (fgets(buf, sizeof(buf), tmpfp) != NULL)
1183                        && continue_write) {
1184                         textview_write_line(textview, buf, conv, TRUE);
1185                         if (textview->stop_loading) {
1186                                 fclose(tmpfp);
1187                                 return;
1188                         }
1189                         wrote += ftell(tmpfp)-i;
1190                         if (mimeinfo->length > 1024*1024 
1191                         &&  wrote > 1024*1024
1192                         && !textview->messageview->show_full_text) {
1193                                 continue_write = FALSE;
1194                         }
1195                 }
1196                 fclose(tmpfp);
1197         }
1198
1199         conv_code_converter_destroy(conv);
1200         procmime_force_encoding(0);
1201
1202         textview->uri_list = g_slist_reverse(textview->uri_list);
1203         for (cur = textview->uri_list; cur; cur = cur->next) {
1204                 ClickableText *uri = (ClickableText *)cur->data;
1205                 if (!uri->is_quote)
1206                         continue;
1207                 if (!prefs_common.hide_quotes ||
1208                     uri->quote_level+1 < prefs_common.hide_quotes) {
1209                         textview_toggle_quote(textview, cur, uri, TRUE);
1210                         if (textview->stop_loading) {
1211                                 return;
1212                         }
1213                 }
1214         }
1215         
1216         if (continue_write == FALSE) {
1217                 messageview_show_partial_display(
1218                         textview->messageview, 
1219                         textview->messageview->msginfo,
1220                         mimeinfo->length);
1221         }
1222         GTK_EVENTS_FLUSH();
1223 }
1224
1225 static void textview_show_html(TextView *textview, FILE *fp,
1226                                CodeConverter *conv)
1227 {
1228         SC_HTMLParser *parser;
1229         gchar *str;
1230         gint lines = 0;
1231
1232         parser = sc_html_parser_new(fp, conv);
1233         cm_return_if_fail(parser != NULL);
1234
1235         while ((str = sc_html_parse(parser)) != NULL) {
1236                 if (parser->state == SC_HTML_HREF) {
1237                         /* first time : get and copy the URL */
1238                         if (parser->href == NULL) {
1239                                 /* ALF - the claws html parser returns an empty string,
1240                                  * if still inside an <a>, but already parsed past HREF */
1241                                 str = strtok(str, " ");
1242                                 if (str) {
1243                                         while (str && *str && g_ascii_isspace(*str))
1244                                                 str++; 
1245                                         parser->href = g_strdup(str);
1246                                         /* the URL may (or not) be followed by the
1247                                          * referenced text */
1248                                         str = strtok(NULL, "");
1249                                 }       
1250                         }
1251                         if (str != NULL)
1252                                 textview_write_link(textview, str, parser->href, NULL);
1253                 } else
1254                         textview_write_line(textview, str, NULL, FALSE);
1255                 lines++;
1256                 if (lines % 500 == 0)
1257                         GTK_EVENTS_FLUSH();
1258                 if (textview->stop_loading) {
1259                         return;
1260                 }
1261         }
1262         textview_write_line(textview, "\n", NULL, FALSE);
1263         sc_html_parser_destroy(parser);
1264 }
1265
1266 static void textview_show_ertf(TextView *textview, FILE *fp,
1267                                CodeConverter *conv)
1268 {
1269         ERTFParser *parser;
1270         gchar *str;
1271         gint lines = 0;
1272
1273         parser = ertf_parser_new(fp, conv);
1274         cm_return_if_fail(parser != NULL);
1275
1276         while ((str = ertf_parse(parser)) != NULL) {
1277                 textview_write_line(textview, str, NULL, FALSE);
1278                 lines++;
1279                 if (lines % 500 == 0)
1280                         GTK_EVENTS_FLUSH();
1281                 if (textview->stop_loading) {
1282                         return;
1283                 }
1284         }
1285         
1286         ertf_parser_destroy(parser);
1287 }
1288
1289 #define ADD_TXT_POS(bp_, ep_, pti_) \
1290         if ((last->next = alloca(sizeof(struct txtpos))) != NULL) { \
1291                 last = last->next; \
1292                 last->bp = (bp_); last->ep = (ep_); last->pti = (pti_); \
1293                 last->next = NULL; \
1294         } else { \
1295                 g_warning("alloc error scanning URIs\n"); \
1296                 gtk_text_buffer_insert_with_tags_by_name(buffer, &iter, \
1297                                                          linebuf, -1, \
1298                                                          fg_tag, NULL); \
1299                 return; \
1300         }
1301
1302 #define ADD_TXT_POS_LATER(bp_, ep_, pti_) \
1303         if ((last->next = alloca(sizeof(struct txtpos))) != NULL) { \
1304                 last = last->next; \
1305                 last->bp = (bp_); last->ep = (ep_); last->pti = (pti_); \
1306                 last->next = NULL; \
1307         } else { \
1308                 g_warning("alloc error scanning URIs\n"); \
1309         }
1310
1311 /* textview_make_clickable_parts() - colorizes clickable parts */
1312 static void textview_make_clickable_parts(TextView *textview,
1313                                           const gchar *fg_tag,
1314                                           const gchar *uri_tag,
1315                                           const gchar *linebuf,
1316                                           gboolean hdr)
1317 {
1318         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1319         GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
1320         GtkTextIter iter;
1321         gchar *mybuf = g_strdup(linebuf);
1322         
1323         /* parse table - in order of priority */
1324         struct table {
1325                 const gchar *needle; /* token */
1326
1327                 /* token search function */
1328                 gchar    *(*search)     (const gchar *haystack,
1329                                          const gchar *needle);
1330                 /* part parsing function */
1331                 gboolean  (*parse)      (const gchar *start,
1332                                          const gchar *scanpos,
1333                                          const gchar **bp_,
1334                                          const gchar **ep_,
1335                                          gboolean hdr);
1336                 /* part to URI function */
1337                 gchar    *(*build_uri)  (const gchar *bp,
1338                                          const gchar *ep);
1339         };
1340
1341         static struct table parser[] = {
1342                 {"http://",  strcasestr, get_uri_part,   make_uri_string},
1343                 {"https://", strcasestr, get_uri_part,   make_uri_string},
1344                 {"ftp://",   strcasestr, get_uri_part,   make_uri_string},
1345                 {"sftp://",  strcasestr, get_uri_part,   make_uri_string},
1346                 {"gopher://",strcasestr, get_uri_part,   make_uri_string},
1347                 {"www.",     strcasestr, get_uri_part,   make_http_string},
1348                 {"mailto:",  strcasestr, get_uri_part,   make_uri_string},
1349                 {"@",        strcasestr, get_email_part, make_email_string}
1350         };
1351         const gint PARSE_ELEMS = sizeof parser / sizeof parser[0];
1352
1353         gint  n;
1354         const gchar *walk, *bp, *ep;
1355
1356         struct txtpos {
1357                 const gchar     *bp, *ep;       /* text position */
1358                 gint             pti;           /* index in parse table */
1359                 struct txtpos   *next;          /* next */
1360         } head = {NULL, NULL, 0,  NULL}, *last = &head;
1361
1362         if (!g_utf8_validate(linebuf, -1, NULL)) {
1363                 g_free(mybuf);
1364                 mybuf = g_malloc(strlen(linebuf)*2 +1);
1365                 conv_localetodisp(mybuf, strlen(linebuf)*2 +1, linebuf);
1366         }
1367
1368         gtk_text_buffer_get_end_iter(buffer, &iter);
1369
1370         /* parse for clickable parts, and build a list of begin and end positions  */
1371         for (walk = mybuf;;) {
1372                 gint last_index = PARSE_ELEMS;
1373                 gchar *scanpos = NULL;
1374
1375                 /* FIXME: this looks phony. scanning for anything in the parse table */
1376                 for (n = 0; n < PARSE_ELEMS; n++) {
1377                         gchar *tmp;
1378
1379                         tmp = parser[n].search(walk, parser[n].needle);
1380                         if (tmp) {
1381                                 if (scanpos == NULL || tmp < scanpos) {
1382                                         scanpos = tmp;
1383                                         last_index = n;
1384                                 }
1385                         }                                       
1386                 }
1387
1388                 if (scanpos) {
1389                         /* check if URI can be parsed */
1390                         if (parser[last_index].parse(walk, scanpos, &bp, &ep, hdr)
1391                             && (size_t) (ep - bp - 1) > strlen(parser[last_index].needle)) {
1392                                         ADD_TXT_POS(bp, ep, last_index);
1393                                         walk = ep;
1394                         } else
1395                                 walk = scanpos +
1396                                         strlen(parser[last_index].needle);
1397                 } else
1398                         break;
1399         }
1400
1401         /* colorize this line */
1402         if (head.next) {
1403                 const gchar *normal_text = mybuf;
1404
1405                 /* insert URIs */
1406                 for (last = head.next; last != NULL;
1407                      normal_text = last->ep, last = last->next) {
1408                         ClickableText *uri;
1409                         uri = g_new0(ClickableText, 1);
1410                         if (last->bp - normal_text > 0)
1411                                 gtk_text_buffer_insert_with_tags_by_name
1412                                         (buffer, &iter,
1413                                          normal_text,
1414                                          last->bp - normal_text,
1415                                          fg_tag, NULL);
1416                         uri->uri = parser[last->pti].build_uri(last->bp,
1417                                                                last->ep);
1418                         uri->start = gtk_text_iter_get_offset(&iter);
1419                         gtk_text_buffer_insert_with_tags_by_name
1420                                 (buffer, &iter, last->bp, last->ep - last->bp,
1421                                  uri_tag, fg_tag, NULL);
1422                         uri->end = gtk_text_iter_get_offset(&iter);
1423                         uri->filename = NULL;
1424                         textview->uri_list =
1425                                 g_slist_prepend(textview->uri_list, uri);
1426                 }
1427
1428                 if (*normal_text)
1429                         gtk_text_buffer_insert_with_tags_by_name
1430                                 (buffer, &iter, normal_text, -1, fg_tag, NULL);
1431         } else {
1432                 gtk_text_buffer_insert_with_tags_by_name
1433                         (buffer, &iter, mybuf, -1, fg_tag, NULL);
1434         }
1435         g_free(mybuf);
1436 }
1437
1438 /* textview_make_clickable_parts() - colorizes clickable parts */
1439 static void textview_make_clickable_parts_later(TextView *textview,
1440                                           gint start, gint end)
1441 {
1442         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1443         GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
1444         GtkTextIter start_iter, end_iter;
1445         gchar *mybuf;
1446         gint offset = 0;
1447         /* parse table - in order of priority */
1448         struct table {
1449                 const gchar *needle; /* token */
1450
1451                 /* token search function */
1452                 gchar    *(*search)     (const gchar *haystack,
1453                                          const gchar *needle);
1454                 /* part parsing function */
1455                 gboolean  (*parse)      (const gchar *start,
1456                                          const gchar *scanpos,
1457                                          const gchar **bp_,
1458                                          const gchar **ep_,
1459                                          gboolean hdr);
1460                 /* part to URI function */
1461                 gchar    *(*build_uri)  (const gchar *bp,
1462                                          const gchar *ep);
1463         };
1464
1465         static struct table parser[] = {
1466                 {"http://",  strcasestr, get_uri_part,   make_uri_string},
1467                 {"https://", strcasestr, get_uri_part,   make_uri_string},
1468                 {"ftp://",   strcasestr, get_uri_part,   make_uri_string},
1469                 {"sftp://",  strcasestr, get_uri_part,   make_uri_string},
1470                 {"www.",     strcasestr, get_uri_part,   make_http_string},
1471                 {"mailto:",  strcasestr, get_uri_part,   make_uri_string},
1472                 {"@",        strcasestr, get_email_part, make_email_string}
1473         };
1474         const gint PARSE_ELEMS = sizeof parser / sizeof parser[0];
1475
1476         gint  n;
1477         const gchar *walk, *bp, *ep;
1478
1479         struct txtpos {
1480                 const gchar     *bp, *ep;       /* text position */
1481                 gint             pti;           /* index in parse table */
1482                 struct txtpos   *next;          /* next */
1483         } head = {NULL, NULL, 0,  NULL}, *last = &head;
1484
1485         gtk_text_buffer_get_iter_at_offset(buffer, &start_iter, start);
1486         gtk_text_buffer_get_iter_at_offset(buffer, &end_iter, end);
1487         mybuf = gtk_text_buffer_get_text(buffer, &start_iter, &end_iter, FALSE);
1488         offset = gtk_text_iter_get_offset(&start_iter);
1489
1490         /* parse for clickable parts, and build a list of begin and end positions  */
1491         for (walk = mybuf;;) {
1492                 gint last_index = PARSE_ELEMS;
1493                 gchar *scanpos = NULL;
1494
1495                 /* FIXME: this looks phony. scanning for anything in the parse table */
1496                 for (n = 0; n < PARSE_ELEMS; n++) {
1497                         gchar *tmp;
1498
1499                         tmp = parser[n].search(walk, parser[n].needle);
1500                         if (tmp) {
1501                                 if (scanpos == NULL || tmp < scanpos) {
1502                                         scanpos = tmp;
1503                                         last_index = n;
1504                                 }
1505                         }                                       
1506                 }
1507
1508                 if (scanpos) {
1509                         /* check if URI can be parsed */
1510                         if (parser[last_index].parse(walk, scanpos, &bp, &ep, FALSE)
1511                             && (size_t) (ep - bp - 1) > strlen(parser[last_index].needle)) {
1512                                         ADD_TXT_POS_LATER(bp, ep, last_index);
1513                                         walk = ep;
1514                         } else
1515                                 walk = scanpos +
1516                                         strlen(parser[last_index].needle);
1517                 } else
1518                         break;
1519         }
1520
1521         /* colorize this line */
1522         if (head.next) {
1523                 /* insert URIs */
1524                 for (last = head.next; last != NULL; last = last->next) {
1525                         ClickableText *uri;
1526                         gint start_offset, end_offset;
1527                         gchar *tmp_str;
1528                         gchar old_char;
1529                         uri = g_new0(ClickableText, 1);
1530                         uri->uri = parser[last->pti].build_uri(last->bp,
1531                                                                last->ep);
1532                         
1533                         tmp_str = mybuf;
1534                         old_char = tmp_str[last->ep - mybuf];
1535                         tmp_str[last->ep - mybuf] = '\0';                                      
1536                         end_offset = g_utf8_strlen(tmp_str, -1);
1537                         tmp_str[last->ep - mybuf] = old_char;
1538                         
1539                         old_char = tmp_str[last->bp - mybuf];
1540                         tmp_str[last->bp - mybuf] = '\0';                                      
1541                         start_offset = g_utf8_strlen(tmp_str, -1);
1542                         tmp_str[last->bp - mybuf] = old_char;
1543                         
1544                         gtk_text_buffer_get_iter_at_offset(buffer, &start_iter, start_offset + offset);
1545                         gtk_text_buffer_get_iter_at_offset(buffer, &end_iter, end_offset + offset);
1546                         
1547                         uri->start = gtk_text_iter_get_offset(&start_iter);
1548                         
1549                         gtk_text_buffer_apply_tag_by_name(buffer, "link", &start_iter, &end_iter);
1550
1551                         uri->end = gtk_text_iter_get_offset(&end_iter);
1552                         uri->filename = NULL;
1553                         textview->uri_list =
1554                                 g_slist_prepend(textview->uri_list, uri);
1555                 }
1556         } 
1557
1558         g_free(mybuf);
1559 }
1560
1561 #undef ADD_TXT_POS
1562
1563 static void textview_write_line(TextView *textview, const gchar *str,
1564                                 CodeConverter *conv, gboolean do_quote_folding)
1565 {
1566         GtkTextView *text;
1567         GtkTextBuffer *buffer;
1568         GtkTextIter iter;
1569         gchar buf[BUFFSIZE];
1570         gchar *fg_color;
1571         gint quotelevel = -1, real_quotelevel = -1;
1572         gchar quote_tag_str[10];
1573
1574         text = GTK_TEXT_VIEW(textview->text);
1575         buffer = gtk_text_view_get_buffer(text);
1576         gtk_text_buffer_get_end_iter(buffer, &iter);
1577
1578         if (!conv)
1579                 strncpy2(buf, str, sizeof(buf));
1580         else if (conv_convert(conv, buf, sizeof(buf), str) < 0)
1581                 conv_localetodisp(buf, sizeof(buf), str);
1582                 
1583         strcrchomp(buf);
1584         fg_color = NULL;
1585
1586         /* change color of quotation
1587            >, foo>, _> ... ok, <foo>, foo bar>, foo-> ... ng
1588            Up to 3 levels of quotations are detected, and each
1589            level is colored using a different color. */
1590         if (prefs_common.enable_color 
1591             && line_has_quote_char(buf, prefs_common.quote_chars)) {
1592                 real_quotelevel = get_quote_level(buf, prefs_common.quote_chars);
1593                 quotelevel = real_quotelevel;
1594                 /* set up the correct foreground color */
1595                 if (quotelevel > 2) {
1596                         /* recycle colors */
1597                         if (prefs_common.recycle_quote_colors)
1598                                 quotelevel %= 3;
1599                         else
1600                                 quotelevel = 2;
1601                 }
1602         }
1603
1604         if (quotelevel == -1)
1605                 fg_color = NULL;
1606         else {
1607                 g_snprintf(quote_tag_str, sizeof(quote_tag_str),
1608                            "quote%d", quotelevel);
1609                 fg_color = quote_tag_str;
1610         }
1611
1612         if (prefs_common.enable_color) {
1613                 if (textview->is_diff) {
1614                         if (strncmp(buf, "+++ ", 4) == 0)
1615                                 fg_color = "diff-add-file";
1616                         else if (buf[0] == '+')
1617                                 fg_color = "diff-add";
1618                         else if (strncmp(buf, "--- ", 4) == 0)
1619                                 fg_color = "diff-del-file";
1620                         else if (buf[0] == '-')
1621                                 fg_color = "diff-del";
1622                         else if (strncmp(buf, "@@ ", 3) == 0 &&
1623                                         strcmp(buf+strlen(buf)-4, " @@\n") == 0)
1624                                 fg_color = "diff-hunk";
1625                 } else if (strcmp(buf,"-- \n") == 0
1626                                 || strcmp(buf, "- -- \n") == 0
1627                                 || textview->is_in_signature) {
1628                         fg_color = "signature";
1629                         textview->is_in_signature = TRUE;
1630                 }
1631         }
1632
1633         if (real_quotelevel > -1 && do_quote_folding) {
1634                 if (!g_utf8_validate(buf, -1, NULL)) {
1635                         gchar *utf8buf = NULL;
1636                         utf8buf = g_malloc(BUFFSIZE);
1637                         conv_localetodisp(utf8buf, BUFFSIZE, buf);
1638                         strncpy2(buf, utf8buf, BUFFSIZE-1);
1639                         g_free(utf8buf);
1640                 }
1641 do_quote:
1642                 if ( textview->prev_quote_level != real_quotelevel ) {
1643                         ClickableText *uri;
1644                         uri = g_new0(ClickableText, 1);
1645                         uri->uri = g_strdup("");
1646                         uri->data = g_strdup(buf);
1647                         uri->data_len = strlen(uri->data);
1648                         uri->start = gtk_text_iter_get_offset(&iter);
1649                         uri->is_quote = TRUE;
1650                         uri->quote_level = real_quotelevel;
1651                         uri->fg_color = g_strdup(fg_color);
1652
1653                         gtk_text_buffer_insert_with_tags_by_name
1654                                         (buffer, &iter, " [...]", -1,
1655                                          "qlink", fg_color, NULL);
1656                         uri->end = gtk_text_iter_get_offset(&iter);
1657                         gtk_text_buffer_insert(buffer, &iter, "  \n", -1);
1658                         
1659                         uri->filename = NULL;
1660                         textview->uri_list =
1661                                 g_slist_prepend(textview->uri_list, uri);
1662                 
1663                         textview->prev_quote_level = real_quotelevel;
1664                 } else {
1665                         GSList *last = textview->uri_list;
1666                         ClickableText *lasturi = NULL;
1667                         gint e_len = 0, n_len = 0;
1668                         
1669                         if (textview->uri_list) {
1670                                 lasturi = (ClickableText *)last->data;
1671                         } else {
1672                                 g_print("oops (%d %d)\n",
1673                                         real_quotelevel, textview->prev_quote_level);
1674                         }       
1675                         if (lasturi) {  
1676                                 if (lasturi->is_quote == FALSE) {
1677                                         textview->prev_quote_level = -1;
1678                                         goto do_quote;
1679                                 }
1680                                 e_len = lasturi->data ? lasturi->data_len:0;
1681                                 n_len = strlen(buf);
1682                                 lasturi->data = g_realloc((gchar *)lasturi->data, e_len + n_len + 1);
1683                                 strcpy((gchar *)lasturi->data + e_len, buf);
1684                                 *((gchar *)lasturi->data + e_len + n_len) = '\0';
1685                                 lasturi->data_len += n_len;
1686                         }
1687                 }
1688         } else {
1689                 textview_make_clickable_parts(textview, fg_color, "link", buf, FALSE);
1690                 textview->prev_quote_level = -1;
1691         }
1692 }
1693
1694 void textview_write_link(TextView *textview, const gchar *str,
1695                          const gchar *uri, CodeConverter *conv)
1696 {
1697         GtkTextView *text;
1698         GtkTextBuffer *buffer;
1699         GtkTextIter iter;
1700         gchar buf[BUFFSIZE];
1701         gchar *bufp;
1702         ClickableText *r_uri;
1703
1704         if (!str || *str == '\0')
1705                 return;
1706         if (!uri)
1707                 return;
1708
1709         while (uri && *uri && g_ascii_isspace(*uri))
1710                 uri++;
1711                 
1712         text = GTK_TEXT_VIEW(textview->text);
1713         buffer = gtk_text_view_get_buffer(text);
1714         gtk_text_buffer_get_end_iter(buffer, &iter);
1715
1716         if (!conv)
1717                 strncpy2(buf, str, sizeof(buf));
1718         else if (conv_convert(conv, buf, sizeof(buf), str) < 0)
1719                 conv_utf8todisp(buf, sizeof(buf), str);
1720
1721         if (g_utf8_validate(buf, -1, NULL) == FALSE)
1722                 return;
1723
1724         strcrchomp(buf);
1725
1726         gtk_text_buffer_get_end_iter(buffer, &iter);
1727         for (bufp = buf; *bufp != '\0'; bufp = g_utf8_next_char(bufp)) {
1728                 gunichar ch;
1729
1730                 ch = g_utf8_get_char(bufp);
1731                 if (!g_unichar_isspace(ch))
1732                         break;
1733         }
1734         if (bufp > buf)
1735                 gtk_text_buffer_insert(buffer, &iter, buf, bufp - buf);
1736
1737         r_uri = g_new0(ClickableText, 1);
1738         r_uri->uri = g_strdup(uri);
1739         r_uri->start = gtk_text_iter_get_offset(&iter);
1740         gtk_text_buffer_insert_with_tags_by_name
1741                 (buffer, &iter, bufp, -1, "link", NULL);
1742         r_uri->end = gtk_text_iter_get_offset(&iter);
1743         r_uri->filename = NULL;
1744         textview->uri_list = g_slist_prepend(textview->uri_list, r_uri);
1745 }
1746
1747 static void textview_set_cursor(GdkWindow *window, GdkCursor *cursor)
1748 {
1749         if (GDK_IS_WINDOW(window))
1750                 gdk_window_set_cursor(window, cursor);
1751 }
1752 void textview_clear(TextView *textview)
1753 {
1754         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1755         GtkTextBuffer *buffer;
1756         GdkWindow *window = gtk_text_view_get_window(text,
1757                                 GTK_TEXT_WINDOW_TEXT);
1758
1759         buffer = gtk_text_view_get_buffer(text);
1760         gtk_text_buffer_set_text(buffer, "", -1);
1761         if (gtk_text_buffer_get_mark(buffer, "body_start"))
1762                 gtk_text_buffer_delete_mark_by_name(buffer, "body_start");
1763         if (gtk_text_buffer_get_mark(buffer, "body_end"))
1764                 gtk_text_buffer_delete_mark_by_name(buffer, "body_end");
1765
1766         TEXTVIEW_STATUSBAR_POP(textview);
1767         textview_uri_list_remove_all(textview->uri_list);
1768         textview->uri_list = NULL;
1769         textview->uri_hover = NULL;
1770         textview->prev_quote_level = -1;
1771
1772         textview->body_pos = 0;
1773         if (textview->image) 
1774                 gtk_widget_destroy(textview->image);
1775         textview->image = NULL;
1776         textview->avatar_type = 0;
1777
1778         if (textview->messageview->mainwin->cursor_count == 0) {
1779                 textview_set_cursor(window, text_cursor);
1780         } else {
1781                 textview_set_cursor(window, watch_cursor);
1782         }
1783 }
1784
1785 void textview_destroy(TextView *textview)
1786 {
1787         GtkTextBuffer *buffer;
1788         GtkClipboard *clipboard;
1789
1790         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview->text));
1791         clipboard = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
1792         gtk_text_buffer_remove_selection_clipboard(buffer, clipboard);
1793
1794         textview_uri_list_remove_all(textview->uri_list);
1795         textview->uri_list = NULL;
1796         textview->prev_quote_level = -1;
1797
1798         g_free(textview);
1799 }
1800
1801 #define CHANGE_TAG_FONT(tagname, font) { \
1802         tag = gtk_text_tag_table_lookup(tags, tagname); \
1803         if (tag) \
1804                 g_object_set(G_OBJECT(tag), "font-desc", font, NULL); \
1805 }
1806
1807 void textview_set_font(TextView *textview, const gchar *codeset)
1808 {
1809         GtkTextTag *tag;
1810         GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview->text));
1811         GtkTextTagTable *tags = gtk_text_buffer_get_tag_table(buffer);
1812         PangoFontDescription *font_desc, *bold_font_desc;
1813
1814         font_desc = pango_font_description_from_string
1815                                         (NORMAL_FONT);
1816         if (font_desc) {
1817                 gtk_widget_modify_font(textview->text, font_desc);
1818                 CHANGE_TAG_FONT("header", font_desc);
1819                 CHANGE_TAG_FONT("hlink", font_desc);
1820                 pango_font_description_free(font_desc);
1821         }
1822         if (prefs_common.derive_from_normal_font || !BOLD_FONT) {
1823                 bold_font_desc = pango_font_description_from_string
1824                                                 (NORMAL_FONT);
1825                 if (bold_font_desc)
1826                         pango_font_description_set_weight
1827                                 (bold_font_desc, PANGO_WEIGHT_BOLD);
1828         } else {
1829                 bold_font_desc = pango_font_description_from_string
1830                                                 (BOLD_FONT);
1831         }
1832         if (bold_font_desc) {
1833                 CHANGE_TAG_FONT("header_title", bold_font_desc);
1834                 pango_font_description_free(bold_font_desc);
1835         }
1836
1837         if (prefs_common.textfont) {
1838                 PangoFontDescription *font_desc;
1839
1840                 font_desc = pango_font_description_from_string
1841                                                 (prefs_common.textfont);
1842                 if (font_desc) {
1843                         gtk_widget_modify_font(textview->text, font_desc);
1844                         pango_font_description_free(font_desc);
1845                 }
1846         }
1847         gtk_text_view_set_pixels_above_lines(GTK_TEXT_VIEW(textview->text),
1848                                              prefs_common.line_space / 2);
1849         gtk_text_view_set_pixels_below_lines(GTK_TEXT_VIEW(textview->text),
1850                                              prefs_common.line_space / 2);
1851 }
1852
1853 void textview_set_text(TextView *textview, const gchar *text)
1854 {
1855         GtkTextView *view;
1856         GtkTextBuffer *buffer;
1857
1858         cm_return_if_fail(textview != NULL);
1859         cm_return_if_fail(text != NULL);
1860
1861         textview_clear(textview);
1862
1863         view = GTK_TEXT_VIEW(textview->text);
1864         buffer = gtk_text_view_get_buffer(view);
1865         gtk_text_buffer_set_text(buffer, text, strlen(text));
1866 }
1867
1868 enum
1869 {
1870         H_DATE          = 0,
1871         H_FROM          = 1,
1872         H_TO            = 2,
1873         H_NEWSGROUPS    = 3,
1874         H_SUBJECT       = 4,
1875         H_CC            = 5,
1876         H_REPLY_TO      = 6,
1877         H_FOLLOWUP_TO   = 7,
1878         H_X_MAILER      = 8,
1879         H_X_NEWSREADER  = 9,
1880         H_USER_AGENT    = 10,
1881         H_ORGANIZATION  = 11,
1882 };
1883
1884 void textview_set_position(TextView *textview, gint pos)
1885 {
1886         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1887
1888         gtkut_text_view_set_position(text, pos);
1889 }
1890
1891 static GPtrArray *textview_scan_header(TextView *textview, FILE *fp)
1892 {
1893         gchar buf[BUFFSIZE];
1894         GPtrArray *headers, *sorted_headers;
1895         GSList *disphdr_list;
1896         Header *header;
1897         gint i;
1898
1899         cm_return_val_if_fail(fp != NULL, NULL);
1900
1901         if (prefs_common.show_all_headers) {
1902                 headers = procheader_get_header_array_asis(fp);
1903                 sorted_headers = g_ptr_array_new();
1904                 for (i = 0; i < headers->len; i++) {
1905                         header = g_ptr_array_index(headers, i);
1906                         if (!procheader_header_is_internal(header->name))
1907                                 g_ptr_array_add(sorted_headers, header);
1908                         else
1909                                 procheader_header_free(header);
1910                 }
1911                 g_ptr_array_free(headers, TRUE);
1912                 return sorted_headers;
1913         }
1914
1915         if (!prefs_common.display_header) {
1916                 while (fgets(buf, sizeof(buf), fp) != NULL)
1917                         if (buf[0] == '\r' || buf[0] == '\n') break;
1918                 return NULL;
1919         }
1920
1921         headers = procheader_get_header_array_asis(fp);
1922
1923         sorted_headers = g_ptr_array_new();
1924
1925         for (disphdr_list = prefs_common.disphdr_list; disphdr_list != NULL;
1926              disphdr_list = disphdr_list->next) {
1927                 DisplayHeaderProp *dp =
1928                         (DisplayHeaderProp *)disphdr_list->data;
1929
1930                 for (i = 0; i < headers->len; i++) {
1931                         header = g_ptr_array_index(headers, i);
1932
1933                         if (procheader_headername_equal(header->name,
1934                                                         dp->name)) {
1935                                 if (dp->hidden)
1936                                         procheader_header_free(header);
1937                                 else
1938                                         g_ptr_array_add(sorted_headers, header);
1939
1940                                 g_ptr_array_remove_index(headers, i);
1941                                 i--;
1942                         }
1943                 }
1944         }
1945
1946         if (prefs_common.show_other_header) {
1947                 for (i = 0; i < headers->len; i++) {
1948                         header = g_ptr_array_index(headers, i);
1949                         if (!procheader_header_is_internal(header->name)) {
1950                                 g_ptr_array_add(sorted_headers, header);
1951                         } else {
1952                                 procheader_header_free(header);
1953                         }
1954                 }
1955                 g_ptr_array_free(headers, TRUE);
1956         } else
1957                 procheader_header_array_destroy(headers);
1958
1959
1960         return sorted_headers;
1961 }
1962
1963 static void textview_show_avatar(TextView *textview)
1964 {
1965         GtkAllocation allocation;
1966         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1967         MsgInfo *msginfo = textview->messageview->msginfo;
1968         int x = 0;
1969         AvatarRender *avatarr;
1970         
1971         if (prefs_common.display_header_pane || !prefs_common.display_xface)
1972                 goto bail;
1973         
1974         avatarr = avatars_avatarrender_new(msginfo);
1975         hooks_invoke(AVATAR_IMAGE_RENDER_HOOKLIST, avatarr);
1976
1977         if (!avatarr->image) {
1978                 avatars_avatarrender_free(avatarr);
1979                 goto bail;
1980         }
1981
1982         if (textview->image) 
1983                 gtk_widget_destroy(textview->image);
1984         
1985         textview->image = avatarr->image;
1986         textview->avatar_type = avatarr->type;
1987         avatarr->image = NULL; /* avoid destroying */
1988         avatars_avatarrender_free(avatarr);
1989
1990         gtk_widget_show(textview->image);
1991         
1992         gtk_widget_get_allocation(textview->text, &allocation);
1993         x = allocation.width - WIDTH -5;
1994
1995         gtk_text_view_add_child_in_window(text, textview->image, 
1996                 GTK_TEXT_WINDOW_TEXT, x, 5);
1997
1998         gtk_widget_show_all(textview->text);
1999
2000         return;
2001 bail:
2002         if (textview->image) 
2003                 gtk_widget_destroy(textview->image);
2004         textview->image = NULL; 
2005         textview->avatar_type = 0;
2006 }
2007
2008 void textview_show_icon(TextView *textview, const gchar *stock_id)
2009 {
2010         GtkAllocation allocation;
2011         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
2012         int x = 0;
2013         
2014         if (textview->image) 
2015                 gtk_widget_destroy(textview->image);
2016         
2017         textview->image = gtk_image_new_from_stock(stock_id, GTK_ICON_SIZE_DIALOG);
2018         cm_return_if_fail(textview->image != NULL);
2019
2020         gtk_widget_show(textview->image);
2021         
2022         gtk_widget_get_allocation(textview->text, &allocation);
2023         x = allocation.width - WIDTH -5;
2024
2025         gtk_text_view_add_child_in_window(text, textview->image, 
2026                 GTK_TEXT_WINDOW_TEXT, x, 5);
2027
2028         gtk_widget_show_all(textview->text);
2029         
2030
2031         return;
2032 }
2033
2034 static void textview_save_contact_pic(TextView *textview)
2035 {
2036 #ifndef USE_NEW_ADDRBOOK
2037         MsgInfo *msginfo = textview->messageview->msginfo;
2038         gchar *filename = NULL;
2039         GError *error = NULL;
2040         GdkPixbuf *picture = NULL;
2041
2042         if (!msginfo->extradata || !msginfo->extradata->avatars)
2043                 return;
2044
2045         if (textview->avatar_type > AVATAR_FACE)
2046                 return;
2047
2048         if (textview->image) 
2049                 picture = gtk_image_get_pixbuf(GTK_IMAGE(textview->image));
2050
2051         filename = addrindex_get_picture_file(msginfo->from);
2052         if (!filename)
2053                 return;
2054         if (!is_file_exist(filename)) {
2055                 gdk_pixbuf_save(picture, filename, "png", &error, NULL);
2056                 if (error) {
2057                         g_warning(_("Failed to save image: \n%s"),
2058                                         error->message);
2059                         g_error_free(error);
2060                 }
2061         }
2062         g_free(filename);
2063 #else
2064         /* new address book */
2065 #endif
2066 }
2067
2068 static void textview_show_contact_pic(TextView *textview)
2069 {
2070 #ifndef USE_NEW_ADDRBOOK
2071         MsgInfo *msginfo = textview->messageview->msginfo;
2072         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
2073         int x = 0;
2074         gchar *filename = NULL;
2075         GError *error = NULL;
2076         GdkPixbuf *picture = NULL;
2077         gint w, h;
2078         GtkAllocation allocation;
2079
2080         if (prefs_common.display_header_pane
2081                 || !prefs_common.display_xface)
2082                 goto bail;
2083         
2084         if (msginfo->extradata && msginfo->extradata->avatars)
2085                 return;
2086
2087         if (textview->image) 
2088                 gtk_widget_destroy(textview->image);
2089
2090         filename = addrindex_get_picture_file(msginfo->from);
2091         
2092         if (!filename)
2093                 goto bail;
2094         if (!is_file_exist(filename)) {
2095                 g_free(filename);
2096                 goto bail;
2097         }
2098
2099         gdk_pixbuf_get_file_info(filename, &w, &h);
2100         
2101         if (w > 48 || h > 48)
2102                 picture = gdk_pixbuf_new_from_file_at_scale(filename, 
2103                                                 48, 48, TRUE, &error);
2104         else
2105                 picture = gdk_pixbuf_new_from_file(filename, &error);
2106
2107         if (error) {
2108                 debug_print("Failed to import image: \n%s",
2109                                 error->message);
2110                 g_error_free(error);
2111                 goto bail;
2112         }
2113         g_free(filename);
2114
2115         if (picture) {
2116                 textview->image = gtk_image_new_from_pixbuf(picture);
2117                 g_object_unref(picture);
2118         }
2119         cm_return_if_fail(textview->image != NULL);
2120
2121         gtk_widget_show(textview->image);
2122         
2123         gtk_widget_get_allocation(textview->text, &allocation);
2124         x = allocation.width - WIDTH -5;
2125
2126         gtk_text_view_add_child_in_window(text, textview->image, 
2127                 GTK_TEXT_WINDOW_TEXT, x, 5);
2128
2129         gtk_widget_show_all(textview->text);
2130         
2131         return;
2132 bail:
2133         if (textview->image) 
2134                 gtk_widget_destroy(textview->image);
2135         textview->image = NULL;
2136         textview->avatar_type = 0;
2137 #else
2138         /* new address book */
2139 #endif  
2140 }
2141
2142 static gint textview_tag_cmp_list(gconstpointer a, gconstpointer b)
2143 {
2144         gint id_a = GPOINTER_TO_INT(a);
2145         gint id_b = GPOINTER_TO_INT(b);
2146         const gchar *tag_a = tags_get_tag(id_a);
2147         const gchar *tag_b = tags_get_tag(id_b);
2148         
2149         if (tag_a == NULL)
2150                 return tag_b == NULL ? 0:1;
2151         
2152         if (tag_b == NULL)
2153                 return 1;
2154
2155         return g_utf8_collate(tag_a, tag_b);
2156 }
2157
2158
2159 static void textview_show_tags(TextView *textview)
2160 {
2161         MsgInfo *msginfo = textview->messageview->msginfo;
2162         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
2163         GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
2164         GtkTextIter iter;
2165         ClickableText *uri;
2166         GSList *cur, *orig;
2167         gboolean found_tag = FALSE;
2168         
2169         if (!msginfo->tags)
2170                 return;
2171         
2172         cur = orig = g_slist_sort(g_slist_copy(msginfo->tags), textview_tag_cmp_list);
2173
2174         for (; cur; cur = cur->next) {
2175                 if (tags_get_tag(GPOINTER_TO_INT(cur->data)) != NULL) {
2176                         found_tag = TRUE;
2177                         break;
2178                 }
2179         }
2180         if (!found_tag) {
2181                 g_slist_free(orig);
2182                 return;
2183         }
2184
2185         gtk_text_buffer_get_end_iter (buffer, &iter);
2186         gtk_text_buffer_insert_with_tags_by_name(buffer,
2187                 &iter, _("Tags: "), -1,
2188                 "header_title", "header", "tags", NULL);
2189
2190         for (cur = orig; cur; cur = cur->next) {
2191                 const gchar *cur_tag = tags_get_tag(GPOINTER_TO_INT(cur->data));
2192                 if (!cur_tag)
2193                         continue;
2194                 uri = g_new0(ClickableText, 1);
2195                 uri->uri = g_strdup("");
2196                 uri->start = gtk_text_iter_get_offset(&iter);
2197                 gtk_text_buffer_insert_with_tags_by_name(buffer, &iter, 
2198                         cur_tag, -1,
2199                         "link", "header", "tags", NULL);
2200                 uri->end = gtk_text_iter_get_offset(&iter);
2201                 uri->filename = g_strdup_printf("sc://search_tags:%s", cur_tag);
2202                 uri->data = NULL;
2203                 textview->uri_list =
2204                         g_slist_prepend(textview->uri_list, uri);
2205                 if (cur->next && tags_get_tag(GPOINTER_TO_INT(cur->next->data)))
2206                         gtk_text_buffer_insert_with_tags_by_name(buffer, &iter, ", ", 2,
2207                                 "header", "tags", NULL);
2208                 else
2209                         gtk_text_buffer_insert_with_tags_by_name(buffer, &iter, " ", 1,
2210                                 "header", "tags", NULL);
2211         }
2212         g_slist_free(orig);
2213
2214         gtk_text_buffer_insert_with_tags_by_name(buffer, &iter, "\n", 1,
2215                 "header", "tags", NULL);
2216 }
2217
2218 static void textview_show_header(TextView *textview, GPtrArray *headers)
2219 {
2220         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
2221         GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
2222         GtkTextIter iter;
2223         Header *header;
2224         gint i;
2225
2226         cm_return_if_fail(headers != NULL);
2227
2228         for (i = 0; i < headers->len; i++) {
2229                 header = g_ptr_array_index(headers, i);
2230                 cm_return_if_fail(header->name != NULL);
2231
2232                 gtk_text_buffer_get_end_iter (buffer, &iter);
2233                 if(prefs_common.trans_hdr == TRUE) {
2234                         gchar *hdr = g_strndup(header->name, strlen(header->name) - 1);
2235                         gchar *trans_hdr = gettext(hdr);
2236                         gtk_text_buffer_insert_with_tags_by_name(buffer,
2237                                 &iter, trans_hdr, -1,
2238                                 "header_title", "header", NULL);
2239                         gtk_text_buffer_insert_with_tags_by_name(buffer,
2240                                 &iter, ":", 1, "header_title", "header", NULL);
2241                         g_free(hdr);
2242                 } else {
2243                         gtk_text_buffer_insert_with_tags_by_name(buffer,
2244                                 &iter, header->name,
2245                                 -1, "header_title", "header", NULL);
2246                 }
2247                 if (header->name[strlen(header->name) - 1] != ' ')
2248                 gtk_text_buffer_insert_with_tags_by_name
2249                                 (buffer, &iter, " ", 1,
2250                                  "header_title", "header", NULL);
2251
2252                 if (procheader_headername_equal(header->name, "Subject") ||
2253                     procheader_headername_equal(header->name, "From")    ||
2254                     procheader_headername_equal(header->name, "To")      ||
2255                     procheader_headername_equal(header->name, "Cc"))
2256                         unfold_line(header->body);
2257                 
2258                 if (procheader_headername_equal(header->name, "Date") &&
2259                     prefs_common.msgview_date_format) {
2260                         gchar hbody[80];
2261                         
2262                         procheader_date_parse(hbody, header->body, sizeof(hbody));
2263                         gtk_text_buffer_get_end_iter (buffer, &iter);
2264                         gtk_text_buffer_insert_with_tags_by_name
2265                                 (buffer, &iter, hbody, -1, "header", NULL);
2266                 } else if ((procheader_headername_equal(header->name, "X-Mailer") ||
2267                                 procheader_headername_equal(header->name,
2268                                                  "X-Newsreader")) &&
2269                                 (strstr(header->body, "Claws Mail") != NULL ||
2270                                 strstr(header->body, "Sylpheed-Claws") != NULL)) {
2271                         gtk_text_buffer_get_end_iter (buffer, &iter);
2272                         gtk_text_buffer_insert_with_tags_by_name
2273                                 (buffer, &iter, header->body, -1,
2274                                  "header", "emphasis", NULL);
2275                 } else {
2276                         gboolean hdr = 
2277                           procheader_headername_equal(header->name, "From") ||
2278                           procheader_headername_equal(header->name, "To") ||
2279                           procheader_headername_equal(header->name, "Cc") ||
2280                           procheader_headername_equal(header->name, "Bcc") ||
2281                           procheader_headername_equal(header->name, "Reply-To") ||
2282                           procheader_headername_equal(header->name, "Sender");
2283                         textview_make_clickable_parts(textview, "header", 
2284                                                       "hlink", header->body, 
2285                                                       hdr);
2286                 }
2287                 gtk_text_buffer_get_end_iter (buffer, &iter);
2288                 gtk_text_buffer_insert_with_tags_by_name(buffer, &iter, "\n", 1,
2289                                                          "header", NULL);
2290         }
2291         
2292         textview_show_avatar(textview);
2293
2294         textview_save_contact_pic(textview);
2295         textview_show_contact_pic(textview);
2296 }
2297
2298 gboolean textview_search_string(TextView *textview, const gchar *str,
2299                                 gboolean case_sens)
2300 {
2301         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
2302
2303         return gtkut_text_view_search_string(text, str, case_sens);
2304 }
2305
2306 gboolean textview_search_string_backward(TextView *textview, const gchar *str,
2307                                          gboolean case_sens)
2308 {
2309         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
2310
2311         return gtkut_text_view_search_string_backward(text, str, case_sens);
2312 }
2313
2314 void textview_scroll_one_line(TextView *textview, gboolean up)
2315 {
2316         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
2317         GtkAdjustment *vadj = gtk_text_view_get_vadjustment(text);
2318
2319         gtkutils_scroll_one_line(GTK_WIDGET(text), vadj, up);
2320 }
2321
2322 gboolean textview_scroll_page(TextView *textview, gboolean up)
2323 {
2324         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
2325         GtkAdjustment *vadj = gtk_text_view_get_vadjustment(text);
2326
2327         return gtkutils_scroll_page(GTK_WIDGET(text), vadj, up);
2328 }
2329
2330 void textview_scroll_max(TextView *textview, gboolean up)
2331 {
2332         GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview->text));
2333         GtkTextIter iter;
2334         
2335         if (up) {
2336                 gtk_text_buffer_get_start_iter(buffer, &iter);
2337                 gtk_text_view_scroll_to_iter(GTK_TEXT_VIEW(textview->text),
2338                                                 &iter, 0.0, TRUE, 0.0, 1.0);
2339         
2340         } else {
2341                 gtk_text_buffer_get_end_iter(buffer, &iter);
2342                 gtk_text_view_scroll_to_iter(GTK_TEXT_VIEW(textview->text),
2343                                                 &iter, 0.0, TRUE, 0.0, 0.0);
2344         }
2345 }
2346
2347 #define KEY_PRESS_EVENT_STOP() \
2348         g_signal_stop_emission_by_name(G_OBJECT(widget), \
2349                                        "key_press_event");
2350
2351 static gint textview_key_pressed(GtkWidget *widget, GdkEventKey *event,
2352                                  TextView *textview)
2353 {
2354         GdkWindow *window = NULL;
2355         SummaryView *summaryview = NULL;
2356         MessageView *messageview = textview->messageview;
2357
2358         if (!event) return FALSE;
2359         if (messageview->mainwin)
2360                 summaryview = messageview->mainwin->summaryview;
2361
2362         switch (event->keyval) {
2363         case GDK_KEY_Tab:
2364         case GDK_KEY_Left:
2365         case GDK_KEY_Up:
2366         case GDK_KEY_Right:
2367         case GDK_KEY_Down:
2368         case GDK_KEY_Page_Up:
2369         case GDK_KEY_Page_Down:
2370         case GDK_KEY_Control_L:
2371         case GDK_KEY_Control_R:
2372                 return FALSE;
2373         case GDK_KEY_Home:
2374         case GDK_KEY_End:
2375                 textview_scroll_max(textview,(event->keyval == GDK_KEY_Home));
2376                 return TRUE;
2377         case GDK_KEY_space:
2378                 if (summaryview)
2379                         summary_pass_key_press_event(summaryview, event);
2380                 else
2381                         mimeview_scroll_page
2382                                 (messageview->mimeview,
2383                                  (event->state &
2384                                   (GDK_SHIFT_MASK|GDK_MOD1_MASK)) != 0);
2385                 break;
2386         case GDK_KEY_BackSpace:
2387                 mimeview_scroll_page(messageview->mimeview, TRUE);
2388                 break;
2389         case GDK_KEY_Return:
2390         case GDK_KEY_KP_Enter:
2391                 mimeview_scroll_one_line
2392                         (messageview->mimeview, (event->state &
2393                                     (GDK_SHIFT_MASK|GDK_MOD1_MASK)) != 0);
2394                 break;
2395         case GDK_KEY_Delete:
2396                 if (summaryview)
2397                         summary_pass_key_press_event(summaryview, event);
2398                 break;
2399         default:
2400                 if (messageview->mainwin) {
2401                         window = gtk_widget_get_window(messageview->mainwin->window);
2402                         if (summaryview &&
2403                             event->window != window) {
2404                                 GdkEventKey tmpev = *event;
2405
2406                                 tmpev.window = window;
2407                                 KEY_PRESS_EVENT_STOP();
2408                                 gtk_widget_event(messageview->mainwin->window,
2409                                                  (GdkEvent *)&tmpev);
2410                         }
2411                 }
2412                 break;
2413         }
2414
2415         return TRUE;
2416 }
2417
2418 static gboolean textview_motion_notify(GtkWidget *widget,
2419                                        GdkEventMotion *event,
2420                                        TextView *textview)
2421 {
2422         if (textview->loading)
2423                 return FALSE;
2424         textview_uri_update(textview, event->x, event->y);
2425         gdk_window_get_pointer(gtk_widget_get_window(widget), NULL, NULL, NULL);
2426
2427         return FALSE;
2428 }
2429
2430 static gboolean textview_leave_notify(GtkWidget *widget,
2431                                       GdkEventCrossing *event,
2432                                       TextView *textview)
2433 {
2434         if (textview->loading)
2435                 return FALSE;
2436         textview_uri_update(textview, -1, -1);
2437
2438         return FALSE;
2439 }
2440
2441 static gboolean textview_visibility_notify(GtkWidget *widget,
2442                                            GdkEventVisibility *event,
2443                                            TextView *textview)
2444 {
2445         gint wx, wy;
2446         GdkWindow *window;
2447
2448         if (textview->loading)
2449                 return FALSE;
2450
2451         window = gtk_text_view_get_window(GTK_TEXT_VIEW(widget),
2452                                           GTK_TEXT_WINDOW_TEXT);
2453
2454         /* check if occurred for the text window part */
2455         if (window != event->window)
2456                 return FALSE;
2457         
2458         gdk_window_get_pointer(gtk_widget_get_window(widget), &wx, &wy, NULL);
2459         textview_uri_update(textview, wx, wy);
2460
2461         return FALSE;
2462 }
2463
2464 void textview_cursor_wait(TextView *textview)
2465 {
2466         GdkWindow *window = gtk_text_view_get_window(
2467                         GTK_TEXT_VIEW(textview->text),
2468                         GTK_TEXT_WINDOW_TEXT);
2469         textview_set_cursor(window, watch_cursor);
2470 }
2471
2472 void textview_cursor_normal(TextView *textview)
2473 {
2474         GdkWindow *window = gtk_text_view_get_window(
2475                         GTK_TEXT_VIEW(textview->text),
2476                         GTK_TEXT_WINDOW_TEXT);
2477         textview_set_cursor(window, text_cursor);
2478 }
2479
2480 static void textview_uri_update(TextView *textview, gint x, gint y)
2481 {
2482         GtkTextBuffer *buffer;
2483         GtkTextIter start_iter, end_iter;
2484         ClickableText *uri = NULL;
2485         
2486         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview->text));
2487
2488         if (x != -1 && y != -1) {
2489                 gint bx, by;
2490                 GtkTextIter iter;
2491                 GSList *tags;
2492                 GSList *cur;
2493                 
2494                 gtk_text_view_window_to_buffer_coords(GTK_TEXT_VIEW(textview->text), 
2495                                                       GTK_TEXT_WINDOW_WIDGET,
2496                                                       x, y, &bx, &by);
2497                 gtk_text_view_get_iter_at_location(GTK_TEXT_VIEW(textview->text),
2498                                                    &iter, bx, by);
2499
2500                 tags = gtk_text_iter_get_tags(&iter);
2501                 for (cur = tags; cur != NULL; cur = cur->next) {
2502                         GtkTextTag *tag = cur->data;
2503                         char *name;
2504
2505                         g_object_get(G_OBJECT(tag), "name", &name, NULL);
2506
2507                         if ((!strcmp(name, "link") || !strcmp(name, "hlink"))
2508                             && textview_get_uri_range(textview, &iter, tag,
2509                                                       &start_iter, &end_iter)) {
2510
2511                                 uri = textview_get_uri_from_range(textview,
2512                                                                   &iter, tag,
2513                                                                   &start_iter,
2514                                                                   &end_iter);
2515                         }
2516                         g_free(name);
2517                         if (uri)
2518                                 break;
2519                 }
2520                 g_slist_free(tags);
2521         }
2522         
2523         if (uri != textview->uri_hover) {
2524                 GdkWindow *window;
2525
2526                 if (textview->uri_hover)
2527                         gtk_text_buffer_remove_tag_by_name(buffer,
2528                                                            "link-hover",
2529                                                            &textview->uri_hover_start_iter,
2530                                                            &textview->uri_hover_end_iter);
2531                     
2532                 textview->uri_hover = uri;
2533                 if (uri) {
2534                         textview->uri_hover_start_iter = start_iter;
2535                         textview->uri_hover_end_iter = end_iter;
2536                 }
2537                 
2538                 window = gtk_text_view_get_window(GTK_TEXT_VIEW(textview->text),
2539                                                   GTK_TEXT_WINDOW_TEXT);
2540                 if (textview->messageview->mainwin->cursor_count == 0) {
2541                         textview_set_cursor(window, uri ? hand_cursor : text_cursor);
2542                 } else {
2543                         textview_set_cursor(window, watch_cursor);
2544                 }
2545
2546                 TEXTVIEW_STATUSBAR_POP(textview);
2547
2548                 if (uri) {
2549                         if (!uri->is_quote)
2550                                 gtk_text_buffer_apply_tag_by_name(buffer,
2551                                                           "link-hover",
2552                                                           &start_iter,
2553                                                           &end_iter);
2554                         TEXTVIEW_STATUSBAR_PUSH(textview, uri->uri);
2555                 }
2556         }
2557 }
2558
2559 static gboolean textview_get_uri_range(TextView *textview,
2560                                        GtkTextIter *iter,
2561                                        GtkTextTag *tag,
2562                                        GtkTextIter *start_iter,
2563                                        GtkTextIter *end_iter)
2564 {
2565         return get_tag_range(iter, tag, start_iter, end_iter);
2566 }
2567
2568 static ClickableText *textview_get_uri_from_range(TextView *textview,
2569                                               GtkTextIter *iter,
2570                                               GtkTextTag *tag,
2571                                               GtkTextIter *start_iter,
2572                                               GtkTextIter *end_iter)
2573 {
2574         gint start_pos, end_pos, cur_pos;
2575         ClickableText *uri = NULL;
2576         GSList *cur;
2577
2578         start_pos = gtk_text_iter_get_offset(start_iter);
2579         end_pos = gtk_text_iter_get_offset(end_iter);
2580         cur_pos = gtk_text_iter_get_offset(iter);
2581
2582         for (cur = textview->uri_list; cur != NULL; cur = cur->next) {
2583                 ClickableText *uri_ = (ClickableText *)cur->data;
2584                 if (start_pos == uri_->start &&
2585                     end_pos ==  uri_->end) {
2586                         uri = uri_;
2587                         break;
2588                 } 
2589         }
2590         for (cur = textview->uri_list; uri == NULL && cur != NULL; cur = cur->next) {
2591                 ClickableText *uri_ = (ClickableText *)cur->data;
2592                 if (start_pos == uri_->start ||
2593                            end_pos == uri_->end) {
2594                         /* in case of contiguous links, textview_get_uri_range
2595                          * returns a broader range (start of 1st link to end
2596                          * of last link).
2597                          * In that case, correct link is the one covering
2598                          * current iter.
2599                          */
2600                         if (uri_->start <= cur_pos && cur_pos <= uri_->end) {
2601                                 uri = uri_;
2602                                 break;
2603                         }
2604                 } 
2605         }
2606
2607         return uri;
2608 }
2609
2610 static ClickableText *textview_get_uri(TextView *textview,
2611                                    GtkTextIter *iter,
2612                                    GtkTextTag *tag)
2613 {
2614         GtkTextIter start_iter, end_iter;
2615         ClickableText *uri = NULL;
2616
2617         if (textview_get_uri_range(textview, iter, tag, &start_iter,
2618                                    &end_iter))
2619                 uri = textview_get_uri_from_range(textview, iter, tag,
2620                                                   &start_iter, &end_iter);
2621
2622         return uri;
2623 }
2624
2625 static void textview_shift_uris_after(TextView *textview, GSList *start_list, gint start, gint shift)
2626 {
2627         GSList *cur;
2628         if (!start_list)
2629                 start_list = textview->uri_list;
2630
2631         for (cur = start_list; cur; cur = cur->next) {
2632                 ClickableText *uri = (ClickableText *)cur->data;
2633                 if (uri->start <= start)
2634                         continue;
2635                 uri->start += shift;
2636                 uri->end += shift;
2637         }
2638 }
2639
2640 static void textview_remove_uris_in(TextView *textview, gint start, gint end)
2641 {
2642         GSList *cur;
2643         for (cur = textview->uri_list; cur; ) {
2644                 ClickableText *uri = (ClickableText *)cur->data;
2645                 if (uri->start > start && uri->end < end) {
2646                         cur = cur->next;
2647                         textview->uri_list = g_slist_remove(textview->uri_list, uri);
2648                         g_free(uri->uri);
2649                         g_free(uri->filename);
2650                         if (uri->is_quote) {
2651                                 g_free(uri->fg_color);
2652                                 g_free(uri->data); 
2653                                 /* (only free data in quotes uris) */
2654                         }
2655                         g_free(uri);
2656                 } else {
2657                         cur = cur->next;
2658                 }
2659                 
2660         }
2661 }
2662
2663 static void textview_toggle_quote(TextView *textview, GSList *start_list, ClickableText *uri, gboolean expand_only)
2664 {
2665         GtkTextIter start, end;
2666         GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview->text));
2667         
2668         if (!uri->is_quote)
2669                 return;
2670         
2671         if (uri->q_expanded && expand_only)
2672                 return;
2673
2674         gtk_text_buffer_get_iter_at_offset(buffer, &start, uri->start);
2675         gtk_text_buffer_get_iter_at_offset(buffer, &end,   uri->end);
2676         if (textview->uri_hover)
2677                 gtk_text_buffer_remove_tag_by_name(buffer,
2678                                                    "link-hover",
2679                                                    &textview->uri_hover_start_iter,
2680                                                    &textview->uri_hover_end_iter);
2681         textview->uri_hover = NULL;
2682         gtk_text_buffer_remove_tag_by_name(buffer,
2683                                            "qlink",
2684                                            &start,
2685                                            &end);
2686         /* when shifting URIs start and end, we have to do it per-UTF8-char
2687          * so use g_utf8_strlen(). OTOH, when inserting in the text buffer, 
2688          * we have to pass a number of bytes, so use strlen(). disturbing. */
2689          
2690         if (!uri->q_expanded) {
2691                 gtk_text_buffer_get_iter_at_offset(buffer, &start, uri->start);
2692                 gtk_text_buffer_get_iter_at_offset(buffer, &end,   uri->end);
2693                 textview_shift_uris_after(textview, start_list, uri->start, 
2694                         g_utf8_strlen((gchar *)uri->data, -1)-strlen(" [...]\n"));
2695                 gtk_text_buffer_delete(buffer, &start, &end);
2696                 gtk_text_buffer_get_iter_at_offset(buffer, &start, uri->start);
2697                 gtk_text_buffer_insert_with_tags_by_name
2698                                 (buffer, &start, (gchar *)uri->data, 
2699                                  strlen((gchar *)uri->data)-1,
2700                                  "qlink", (gchar *)uri->fg_color, NULL);
2701                 uri->end = gtk_text_iter_get_offset(&start);
2702                 textview_make_clickable_parts_later(textview,
2703                                           uri->start, uri->end);
2704                 uri->q_expanded = TRUE;
2705         } else {
2706                 gtk_text_buffer_get_iter_at_offset(buffer, &start, uri->start);
2707                 gtk_text_buffer_get_iter_at_offset(buffer, &end,   uri->end);
2708                 textview_remove_uris_in(textview, uri->start, uri->end);
2709                 textview_shift_uris_after(textview, start_list, uri->start, 
2710                         strlen(" [...]\n")-g_utf8_strlen((gchar *)uri->data, -1));
2711                 gtk_text_buffer_delete(buffer, &start, &end);
2712                 gtk_text_buffer_get_iter_at_offset(buffer, &start, uri->start);
2713                 gtk_text_buffer_insert_with_tags_by_name
2714                                 (buffer, &start, " [...]", -1,
2715                                  "qlink", (gchar *)uri->fg_color, NULL);
2716                 uri->end = gtk_text_iter_get_offset(&start);
2717                 uri->q_expanded = FALSE;
2718         }
2719         if (textview->messageview->mainwin->cursor_count == 0) {
2720                 textview_cursor_normal(textview);
2721         } else {
2722                 textview_cursor_wait(textview);
2723         }
2724 }
2725 static gboolean textview_uri_button_pressed(GtkTextTag *tag, GObject *obj,
2726                                             GdkEvent *event, GtkTextIter *iter,
2727                                             TextView *textview)
2728 {
2729         GdkEventButton *bevent;
2730         ClickableText *uri = NULL;
2731         char *tagname;
2732         gboolean qlink = FALSE;
2733
2734         if (!event)
2735                 return FALSE;
2736
2737         if (event->type != GDK_BUTTON_PRESS && event->type != GDK_2BUTTON_PRESS
2738                 && event->type != GDK_MOTION_NOTIFY)
2739                 return FALSE;
2740
2741         uri = textview_get_uri(textview, iter, tag);
2742         if (!uri)
2743                 return FALSE;
2744
2745         g_object_get(G_OBJECT(tag), "name", &tagname, NULL);
2746         
2747         if (!strcmp(tagname, "qlink"))
2748                 qlink = TRUE;
2749
2750         g_free(tagname);
2751         
2752         bevent = (GdkEventButton *) event;
2753         
2754         /* doubleclick: open compose / add address / browser */
2755         if (qlink && event->type == GDK_BUTTON_PRESS && bevent->button != 1) {
2756                 /* pass rightclick through */
2757                 return FALSE;
2758         } else if ((event->type == (qlink ? GDK_2BUTTON_PRESS:GDK_BUTTON_PRESS) && bevent->button == 1) ||
2759                 bevent->button == 2 || bevent->button == 3) {
2760                 if (uri->filename && !g_ascii_strncasecmp(uri->filename, "sc://", 5)) {
2761                         MimeView *mimeview = 
2762                                 (textview->messageview)?
2763                                         textview->messageview->mimeview:NULL;
2764                         if (mimeview && bevent->button == 1) {
2765                                 mimeview_handle_cmd(mimeview, uri->filename, NULL, uri->data);
2766                         } else if (mimeview && bevent->button == 2 && 
2767                                 !g_ascii_strcasecmp(uri->filename, "sc://select_attachment")) {
2768                                 mimeview_handle_cmd(mimeview, "sc://open_attachment", NULL, uri->data);
2769                         } else if (mimeview && bevent->button == 3 && 
2770                                 !g_ascii_strcasecmp(uri->filename, "sc://select_attachment")) {
2771                                 mimeview_handle_cmd(mimeview, "sc://menu_attachment", bevent, uri->data);
2772                         } 
2773                         return TRUE;
2774                 } else if (qlink && bevent->button == 1) {
2775                         if (prefs_common.hide_quoted)
2776                                 textview_toggle_quote(textview, NULL, uri, FALSE);
2777                         return TRUE;
2778                 } else if (!g_ascii_strncasecmp(uri->uri, "mailto:", 7)) {
2779                         if (bevent->button == 3) {
2780                                 g_object_set_data(
2781                                         G_OBJECT(textview->mail_popup_menu),
2782                                         "menu_button", uri);
2783                                 gtk_menu_popup(GTK_MENU(textview->mail_popup_menu), 
2784                                                NULL, NULL, NULL, NULL, 
2785                                                bevent->button, bevent->time);
2786                         } else {
2787                                 PrefsAccount *account = NULL;
2788                                 FolderItem   *folder_item = NULL;
2789                                 Compose *compose;
2790                                 
2791                                 if (textview->messageview && textview->messageview->msginfo &&
2792                                     textview->messageview->msginfo->folder) {
2793                                         
2794
2795                                         folder_item = textview->messageview->msginfo->folder;
2796                                         if (folder_item->prefs && folder_item->prefs->enable_default_account)
2797                                                 account = account_find_from_id(folder_item->prefs->default_account);
2798                                         if (!account)
2799                                                 account = account_find_from_item(folder_item);
2800                                 }
2801                                 compose = compose_new_with_folderitem(account,
2802                                                                 folder_item, uri->uri + 7);
2803                                 compose_check_for_email_account(compose);
2804                         }
2805                         return TRUE;
2806                 } else if (g_ascii_strncasecmp(uri->uri, "file:", 5)) {
2807                         if (bevent->button == 1 &&
2808                             textview_uri_security_check(textview, uri) == TRUE) 
2809                                         open_uri(uri->uri,
2810                                                  prefs_common_get_uri_cmd());
2811                         else if (bevent->button == 3 && !qlink) {
2812                                 g_object_set_data(
2813                                         G_OBJECT(textview->link_popup_menu),
2814                                         "menu_button", uri);
2815                                 gtk_menu_popup(GTK_MENU(textview->link_popup_menu), 
2816                                                NULL, NULL, NULL, NULL, 
2817                                                bevent->button, bevent->time);
2818                         }
2819                         return TRUE;
2820                 } else {
2821                         if (bevent->button == 3 && !qlink) {
2822                                 g_object_set_data(
2823                                         G_OBJECT(textview->file_popup_menu),
2824                                         "menu_button", uri);
2825                                 gtk_menu_popup(GTK_MENU(textview->file_popup_menu), 
2826                                                NULL, NULL, NULL, NULL, 
2827                                                bevent->button, bevent->time);
2828                                 return TRUE;
2829                         }
2830                 }
2831         }
2832
2833         return FALSE;
2834 }
2835
2836 gchar *textview_get_visible_uri         (TextView       *textview, 
2837                                          ClickableText  *uri)
2838 {
2839         GtkTextBuffer *buffer;
2840         GtkTextIter start, end;
2841
2842         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview->text));
2843
2844         gtk_text_buffer_get_iter_at_offset(buffer, &start, uri->start);
2845         gtk_text_buffer_get_iter_at_offset(buffer, &end,   uri->end);
2846
2847         return gtk_text_buffer_get_text(buffer, &start, &end, FALSE);
2848 }
2849
2850 /*!
2851  *\brief    Check to see if a web URL has been disguised as a different
2852  *          URL (possible with HTML email).
2853  *
2854  *\param    uri The uri to check
2855  *
2856  *\param    textview The TextView the URL is contained in
2857  *
2858  *\return   gboolean TRUE if the URL is ok, or if the user chose to open
2859  *          it anyway, otherwise FALSE          
2860  */
2861 gboolean textview_uri_security_check(TextView *textview, ClickableText *uri)
2862 {
2863         gchar *visible_str;
2864         gboolean retval = TRUE;
2865
2866         if (is_uri_string(uri->uri) == FALSE)
2867                 return TRUE;
2868
2869         visible_str = textview_get_visible_uri(textview, uri);
2870         if (visible_str == NULL)
2871                 return TRUE;
2872
2873         g_strstrip(visible_str);
2874
2875         if (strcmp(visible_str, uri->uri) != 0 && is_uri_string(visible_str)) {
2876                 gchar *uri_path;
2877                 gchar *visible_uri_path;
2878
2879                 uri_path = get_uri_path(uri->uri);
2880                 visible_uri_path = get_uri_path(visible_str);
2881                 if (path_cmp(uri_path, visible_uri_path) != 0)
2882                         retval = FALSE;
2883         }
2884
2885         if (retval == FALSE) {
2886                 gchar *msg;
2887                 AlertValue aval;
2888
2889                 msg = g_markup_printf_escaped(_("The real URL is different from "
2890                                                 "the displayed URL.\n"
2891                                                 "\n"
2892                                                 "<b>Displayed URL:</b> %s\n"
2893                                                 "\n"
2894                                                 "<b>Real URL:</b> %s\n"
2895                                                 "\n"
2896                                                 "Open it anyway?"),
2897                                                visible_str,uri->uri);
2898                 aval = alertpanel_full(_("Phishing attempt warning"), msg,
2899                                        GTK_STOCK_CANCEL, _("_Open URL"), NULL, FALSE,
2900                                        NULL, ALERT_WARNING, G_ALERTDEFAULT);
2901                 g_free(msg);
2902                 if (aval == G_ALERTALTERNATE)
2903                         retval = TRUE;
2904         }
2905
2906         g_free(visible_str);
2907
2908         return retval;
2909 }
2910
2911 static void textview_uri_list_remove_all(GSList *uri_list)
2912 {
2913         GSList *cur;
2914
2915         for (cur = uri_list; cur != NULL; cur = cur->next) {
2916                 if (cur->data) {
2917                         g_free(((ClickableText *)cur->data)->uri);
2918                         g_free(((ClickableText *)cur->data)->filename);
2919                         if (((ClickableText *)cur->data)->is_quote) {
2920                                 g_free(((ClickableText *)cur->data)->fg_color);
2921                                 g_free(((ClickableText *)cur->data)->data); 
2922                                 /* (only free data in quotes uris) */
2923                         }
2924                         g_free(cur->data);
2925                 }
2926         }
2927
2928         g_slist_free(uri_list);
2929 }
2930
2931 static void open_uri_cb (GtkAction *action, TextView *textview)
2932 {
2933         ClickableText *uri = g_object_get_data(G_OBJECT(textview->link_popup_menu),
2934                                            "menu_button");
2935         const gchar *raw_url = g_object_get_data(G_OBJECT(textview->link_popup_menu),
2936                                            "raw_url");
2937
2938         if (uri) {
2939                 if (textview_uri_security_check(textview, uri) == TRUE) 
2940                         open_uri(uri->uri,
2941                                  prefs_common_get_uri_cmd());
2942                 g_object_set_data(G_OBJECT(textview->link_popup_menu), "menu_button",
2943                                   NULL);
2944         }
2945         if (raw_url) {
2946                 open_uri(raw_url, prefs_common_get_uri_cmd());
2947                 g_object_set_data(G_OBJECT(textview->link_popup_menu), "raw_url",
2948                                   NULL);
2949         }
2950 }
2951
2952 static void open_image_cb (GtkAction *action, TextView *textview)
2953 {
2954         ClickableText *uri = g_object_get_data(G_OBJECT(textview->file_popup_menu),
2955                                            "menu_button");
2956
2957         gchar *cmd = NULL;
2958         gchar buf[1024];
2959         const gchar *p;
2960         gchar *filename = NULL, *filepath = NULL;
2961         gchar *tmp_filename = NULL;
2962
2963         if (uri == NULL)
2964                 return;
2965
2966         if (uri->filename == NULL)
2967                 return;
2968         
2969         filename = g_strdup(uri->filename);
2970         
2971         if (!g_utf8_validate(filename, -1, NULL)) {
2972                 gchar *tmp = conv_filename_to_utf8(filename);
2973                 g_free(filename);
2974                 filename = tmp;
2975         }
2976
2977         subst_for_filename(filename);
2978
2979         filepath = g_strconcat(get_mime_tmp_dir(), G_DIR_SEPARATOR_S,
2980                                filename, NULL);
2981
2982         tmp_filename = g_filename_from_uri(uri->uri, NULL, NULL);
2983         copy_file(tmp_filename, filepath, FALSE);
2984         g_free(tmp_filename);
2985
2986         cmd = mailcap_get_command_for_type("image/jpeg", filename);
2987         if (cmd == NULL) {
2988                 gboolean remember = FALSE;
2989                 cmd = input_dialog_combo_remember
2990                         (_("Open with"),
2991                          _("Enter the command-line to open file:\n"
2992                            "('%s' will be replaced with file name)"),
2993                          prefs_common.mime_open_cmd,
2994                          prefs_common.mime_open_cmd_history,
2995                          &remember);
2996                 if (cmd && remember) {
2997                         mailcap_update_default("image/jpeg", cmd);
2998                 }
2999         }
3000         if (cmd && (p = strchr(cmd, '%')) && *(p + 1) == 's' &&
3001             !strchr(p + 2, '%'))
3002                 g_snprintf(buf, sizeof(buf), cmd, filepath);
3003         else {
3004                 g_warning("Image viewer command-line is invalid: '%s'", cmd);
3005                 g_free(filepath);
3006                 g_free(filename);
3007                 return;
3008         }
3009
3010         execute_command_line(buf, TRUE);
3011
3012         g_free(filepath);
3013         g_free(filename);
3014         g_free(cmd);
3015
3016         g_object_set_data(G_OBJECT(textview->file_popup_menu), "menu_button",
3017                           NULL);
3018 }
3019
3020 static void save_file_cb (GtkAction *action, TextView *textview)
3021 {
3022         ClickableText *uri = g_object_get_data(G_OBJECT(textview->file_popup_menu),
3023                                            "menu_button");
3024         gchar *filename = NULL;
3025         gchar *filepath = NULL;
3026         gchar *filedir = NULL;
3027         gchar *tmp_filename = NULL;
3028         GtkWidget *window;
3029
3030         if (uri == NULL)
3031                 return;
3032
3033         if (uri->filename == NULL)
3034                 return;
3035         
3036         filename = g_strdup(uri->filename);
3037         
3038         if (!g_utf8_validate(filename, -1, NULL)) {
3039                 gchar *tmp = conv_filename_to_utf8(filename);
3040                 g_free(filename);
3041                 filename = tmp;
3042         }
3043
3044         subst_for_filename(filename);
3045         
3046         if (prefs_common.attach_save_dir && *prefs_common.attach_save_dir)
3047                 filepath = g_strconcat(prefs_common.attach_save_dir,
3048                                        G_DIR_SEPARATOR_S, filename, NULL);
3049         else
3050                 filepath = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
3051                                        filename, NULL);
3052
3053         g_free(filename);
3054
3055         /* Pick correct window to set the file dialog "transient for" */
3056         if (textview->messageview->window != NULL)
3057                 window = textview->messageview->window;
3058         else
3059                 window = textview->messageview->mainwin->window;
3060
3061         manage_window_focus_in(window, NULL, NULL);
3062
3063         filename = filesel_select_file_save(_("Save as"), filepath);
3064         if (!filename) {
3065                 g_free(filepath);
3066                 return;
3067         }
3068
3069         if (is_file_exist(filename)) {
3070                 AlertValue aval;
3071                 gchar *res;
3072                 
3073                 res = g_strdup_printf(_("Overwrite existing file '%s'?"),
3074                                       filename);
3075                 aval = alertpanel(_("Overwrite"), res, GTK_STOCK_CANCEL, 
3076                                   GTK_STOCK_OK, NULL);
3077                 g_free(res);                                      
3078                 if (G_ALERTALTERNATE != aval)
3079                         return;
3080         }
3081
3082         tmp_filename = g_filename_from_uri(uri->uri, NULL, NULL);
3083         copy_file(tmp_filename, filename, FALSE);
3084         g_free(tmp_filename);
3085         
3086         filedir = g_path_get_dirname(filename);
3087         if (filedir && strcmp(filedir, ".")) {
3088                 g_free(prefs_common.attach_save_dir);
3089                 prefs_common.attach_save_dir = g_filename_to_utf8(filedir, -1, NULL, NULL, NULL);
3090         }
3091
3092         g_free(filedir);
3093         g_free(filepath);
3094
3095         g_object_set_data(G_OBJECT(textview->file_popup_menu), "menu_button",
3096                           NULL);
3097 }
3098
3099 static void copy_uri_cb (GtkAction *action, TextView *textview)
3100 {
3101         ClickableText *uri = g_object_get_data(G_OBJECT(textview->link_popup_menu),
3102                                            "menu_button");
3103         const gchar *raw_url =  g_object_get_data(G_OBJECT(textview->link_popup_menu),
3104                                            "raw_url");
3105         if (uri) {
3106                 gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), uri->uri, -1);
3107                 gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), uri->uri, -1);
3108                 g_object_set_data(G_OBJECT(textview->link_popup_menu), "menu_button",
3109                           NULL);
3110         }
3111         if (raw_url) {
3112                 gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), raw_url, -1);
3113                 gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), raw_url, -1);
3114                 g_object_set_data(G_OBJECT(textview->link_popup_menu), "raw_url",
3115                           NULL);
3116         }
3117 }
3118
3119 static void add_uri_to_addrbook_cb (GtkAction *action, TextView *textview)
3120 {
3121         gchar *fromname, *fromaddress;
3122         ClickableText *uri = g_object_get_data(G_OBJECT(textview->mail_popup_menu),
3123                                            "menu_button");
3124         AvatarRender *avatarr = NULL;
3125         GdkPixbuf *picture = NULL;
3126         gboolean use_picture = FALSE;
3127
3128         if (uri == NULL)
3129                 return;
3130
3131         /* extract url */
3132         fromaddress = g_strdup(uri->uri + 7);
3133         
3134         if (textview->messageview->msginfo &&
3135            !strcmp2(fromaddress, textview->messageview->msginfo->from))
3136                 use_picture = TRUE;
3137
3138         fromname = procheader_get_fromname(fromaddress);
3139         extract_address(fromaddress);
3140
3141         if (use_picture) {
3142                 avatarr = avatars_avatarrender_new(textview->messageview->msginfo);
3143                 hooks_invoke(AVATAR_IMAGE_RENDER_HOOKLIST, avatarr);
3144         }
3145
3146         if (avatarr && avatarr->image) {
3147                 picture = gtk_image_get_pixbuf(GTK_IMAGE(avatarr->image));
3148         }
3149         if (avatarr) {
3150                 avatars_avatarrender_free(avatarr);
3151         }
3152
3153 #ifndef USE_NEW_ADDRBOOK
3154         addressbook_add_contact( fromname, fromaddress, NULL, picture);
3155 #else
3156         if (addressadd_selection(fromname, fromaddress, NULL, picture)) {
3157                 debug_print( "addressbook_add_contact - added\n" );
3158         }
3159 #endif
3160
3161         g_free(fromaddress);
3162         g_free(fromname);
3163 }
3164
3165 static void reply_to_uri_cb (GtkAction *action, TextView *textview)
3166 {
3167         ClickableText *uri = g_object_get_data(G_OBJECT(textview->mail_popup_menu),
3168                                            "menu_button");
3169         if (!textview->messageview || !uri)
3170                 return;
3171
3172         compose_reply_to_address (textview->messageview,
3173                                   textview->messageview->msginfo, uri->uri+7);
3174 }
3175
3176 static void mail_to_uri_cb (GtkAction *action, TextView *textview)
3177 {
3178         PrefsAccount *account = NULL;
3179         Compose *compose;
3180         ClickableText *uri = g_object_get_data(G_OBJECT(textview->mail_popup_menu),
3181                                            "menu_button");
3182         if (uri == NULL)
3183                 return;
3184
3185         if (textview->messageview && textview->messageview->msginfo &&
3186             textview->messageview->msginfo->folder) {
3187                 FolderItem   *folder_item;
3188
3189                 folder_item = textview->messageview->msginfo->folder;
3190                 if (folder_item->prefs && folder_item->prefs->enable_default_account)
3191                         account = account_find_from_id(folder_item->prefs->default_account);
3192                 
3193                 compose = compose_new_with_folderitem(account, folder_item, uri->uri+7);
3194         } else {
3195                 compose = compose_new(account, uri->uri + 7, NULL);
3196         }
3197         compose_check_for_email_account(compose);
3198 }
3199
3200 static void copy_mail_to_uri_cb (GtkAction *action, TextView *textview)
3201 {
3202         ClickableText *uri = g_object_get_data(G_OBJECT(textview->mail_popup_menu),
3203                                            "menu_button");
3204         if (uri == NULL)
3205                 return;
3206
3207         gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), uri->uri +7, -1);
3208         gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), uri->uri +7, -1);
3209         g_object_set_data(G_OBJECT(textview->mail_popup_menu), "menu_button",
3210                           NULL);
3211 }
3212
3213 void textview_get_selection_offsets(TextView *textview, gint *sel_start, gint *sel_end)
3214 {
3215                 GtkTextView *text = GTK_TEXT_VIEW(textview->text);
3216                 GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
3217                 GtkTextIter start, end;
3218                 if (gtk_text_buffer_get_selection_bounds(buffer, &start, &end)) {
3219                         if (sel_start)
3220                                 *sel_start = gtk_text_iter_get_offset(&start);
3221                         if (sel_end)
3222                                 *sel_end = gtk_text_iter_get_offset(&end);
3223                 } else {