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