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