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