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