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