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