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