2010-12-22 [colin] 3.7.8cvs19
[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                                         return;
752                                 }
753                                 gtk_text_buffer_insert(buffer, &iter, " ", 1);
754                         }
755
756                         g_object_unref(pixbuf);
757                         g_free(filename);
758                         END_TIMING();
759                         GTK_EVENTS_FLUSH();
760                 }
761         } else if (mimeinfo->type == MIMETYPE_TEXT) {
762                 if (prefs_common.display_header && (charcount > 0))
763                         gtk_text_buffer_insert(buffer, &iter, "\n", 1);
764
765                 textview_write_body(textview, mimeinfo);
766         }
767         END_TIMING();
768 }
769
770 static void recursive_add_parts(TextView *textview, GNode *node)
771 {
772         GNode * iter;
773         MimeInfo *mimeinfo;
774         START_TIMING("");
775
776         mimeinfo = (MimeInfo *) node->data;
777         
778         textview_add_part(textview, mimeinfo);
779 #ifdef GENERIC_UMPC
780         textview_set_position(textview, 0);
781 #endif        
782         if ((mimeinfo->type != MIMETYPE_MULTIPART) &&
783             (mimeinfo->type != MIMETYPE_MESSAGE)) {
784                 END_TIMING();
785                 return;
786         }
787         if (g_ascii_strcasecmp(mimeinfo->subtype, "alternative") == 0) {
788                 GNode * prefered_body;
789                 int prefered_score;
790                 
791                 /*
792                   text/plain : score 3
793                   text/ *    : score 2
794                   other      : score 1
795                 */
796                 prefered_body = NULL;
797                 prefered_score = 0;
798                 
799                 for (iter = g_node_first_child(node) ; iter != NULL ;
800                      iter = g_node_next_sibling(iter)) {
801                         int score;
802                         MimeInfo * submime;
803                         
804                         score = 1;
805                         submime = (MimeInfo *) iter->data;
806                         if (submime->type == MIMETYPE_TEXT)
807                                 score = 2;
808                         
809                         if (submime->subtype != NULL) {
810                                 if (g_ascii_strcasecmp(submime->subtype, "plain") == 0)
811                                         score = 3;
812                         }
813                         
814                         if (score > prefered_score) {
815                                 prefered_score = score;
816                                 prefered_body = iter;
817                         }
818                 }
819                 
820                 if (prefered_body != NULL) {
821                         recursive_add_parts(textview, prefered_body);
822                 }
823         }
824         else {
825                 for (iter = g_node_first_child(node) ; iter != NULL ;
826                      iter = g_node_next_sibling(iter)) {
827                         recursive_add_parts(textview, iter);
828                 }
829         }
830         END_TIMING();
831 }
832
833 static void textview_add_parts(TextView *textview, MimeInfo *mimeinfo)
834 {
835         cm_return_if_fail(mimeinfo != NULL);
836         
837         recursive_add_parts(textview, mimeinfo->node);
838 }
839
840 void textview_show_error(TextView *textview)
841 {
842         GtkTextView *text;
843         GtkTextBuffer *buffer;
844         GtkTextIter iter;
845
846         textview_set_font(textview, NULL);
847         textview_clear(textview);
848
849         text = GTK_TEXT_VIEW(textview->text);
850         buffer = gtk_text_view_get_buffer(text);
851         gtk_text_buffer_get_start_iter(buffer, &iter);
852
853         TEXTVIEW_INSERT(_("\n"
854                       "  This message can't be displayed.\n"
855                       "  This is probably due to a network error.\n"
856                       "\n"
857                       "  Use "));
858         TEXTVIEW_INSERT_LINK(_("'View Log'"), "sc://view_log", NULL);
859         TEXTVIEW_INSERT(_(" in the Tools menu for more information."));
860         textview_show_icon(textview, GTK_STOCK_DIALOG_ERROR);
861 }
862
863 void textview_show_mime_part(TextView *textview, MimeInfo *partinfo)
864 {
865         GtkTextView *text;
866         GtkTextBuffer *buffer;
867         GtkTextIter iter;
868         const gchar *name;
869         gchar *content_type;
870
871         if (!partinfo) return;
872
873         textview_set_font(textview, NULL);
874         textview_clear(textview);
875
876         text = GTK_TEXT_VIEW(textview->text);
877         buffer = gtk_text_view_get_buffer(text);
878         gtk_text_buffer_get_start_iter(buffer, &iter);
879
880         TEXTVIEW_INSERT("\n");
881
882         name = procmime_mimeinfo_get_parameter(partinfo, "filename");
883         if (name == NULL)
884                 name = procmime_mimeinfo_get_parameter(partinfo, "name");
885         if (name != NULL) {
886                 content_type = procmime_get_content_type_str(partinfo->type,
887                                                      partinfo->subtype);
888                 TEXTVIEW_INSERT("  ");
889                 TEXTVIEW_INSERT_BOLD(name);
890                 TEXTVIEW_INSERT(" (");
891                 TEXTVIEW_INSERT(content_type);
892                 TEXTVIEW_INSERT(", ");
893                 TEXTVIEW_INSERT(to_human_readable((goffset)partinfo->length));
894                 TEXTVIEW_INSERT("):\n\n");
895                 
896                 g_free(content_type);
897         }
898         TEXTVIEW_INSERT(_("  The following can be performed on this part\n"));
899 #ifndef GENERIC_UMPC
900         TEXTVIEW_INSERT(_("  by right-clicking the icon or list item:"));
901 #endif
902         TEXTVIEW_INSERT("\n");
903
904         TEXTVIEW_INSERT(_("     - To save, select "));
905         TEXTVIEW_INSERT_LINK(_("'Save as...'"), "sc://save_as", NULL);
906 #ifndef GENERIC_UMPC
907         TEXTVIEW_INSERT(_(" (Shortcut key: 'y')"));
908 #endif
909         TEXTVIEW_INSERT("\n");
910
911         TEXTVIEW_INSERT(_("     - To display as text, select "));
912         TEXTVIEW_INSERT_LINK(_("'Display as text'"), "sc://display_as_text", NULL);
913
914 #ifndef GENERIC_UMPC
915         TEXTVIEW_INSERT(_(" (Shortcut key: 't')"));
916 #endif
917         TEXTVIEW_INSERT("\n");
918
919         TEXTVIEW_INSERT(_("     - To open with an external program, select "));
920         TEXTVIEW_INSERT_LINK(_("'Open'"), "sc://open", NULL);
921
922 #ifndef GENERIC_UMPC
923         TEXTVIEW_INSERT(_(" (Shortcut key: 'l')\n"));
924         TEXTVIEW_INSERT(_("       (alternately double-click, or click the middle "));
925         TEXTVIEW_INSERT(_("mouse button)\n"));
926 #ifndef G_OS_WIN32
927         TEXTVIEW_INSERT(_("     - Or use "));
928         TEXTVIEW_INSERT_LINK(_("'Open with...'"), "sc://open_with", NULL);
929         TEXTVIEW_INSERT(_(" (Shortcut key: 'o')"));
930 #endif
931 #endif
932         TEXTVIEW_INSERT("\n");
933
934         textview_show_icon(textview, GTK_STOCK_DIALOG_INFO);
935 }
936
937 static void textview_write_body(TextView *textview, MimeInfo *mimeinfo)
938 {
939         FILE *tmpfp;
940         gchar buf[BUFFSIZE];
941         CodeConverter *conv;
942         const gchar *charset, *p, *cmd;
943         GSList *cur;
944         gboolean continue_write = TRUE;
945         size_t wrote = 0, i = 0;
946
947         if (textview->messageview->forced_charset)
948                 charset = textview->messageview->forced_charset;
949         else {
950                 /* use supersets transparently when possible */
951                 charset = procmime_mimeinfo_get_parameter(mimeinfo, "charset");
952                 if (charset && !strcasecmp(charset, CS_ISO_8859_1))
953                         charset = CS_WINDOWS_1252;
954                 else if (charset && !strcasecmp(charset, CS_X_GBK))
955                         charset = CS_GB18030;
956                 else if (charset && !strcasecmp(charset, CS_GBK))
957                         charset = CS_GB18030;
958                 else if (charset && !strcasecmp(charset, CS_GB2312))
959                         charset = CS_GB18030;
960         }
961
962         textview_set_font(textview, charset);
963
964         conv = conv_code_converter_new(charset);
965
966         procmime_force_encoding(textview->messageview->forced_encoding);
967         
968         textview->is_in_signature = FALSE;
969
970         procmime_decode_content(mimeinfo);
971
972         if (!g_ascii_strcasecmp(mimeinfo->subtype, "html") &&
973             prefs_common.render_html) {
974                 gchar *filename;
975                 
976                 filename = procmime_get_tmp_file_name(mimeinfo);
977                 if (procmime_get_part(filename, mimeinfo) == 0) {
978                         tmpfp = g_fopen(filename, "rb");
979                         textview_show_html(textview, tmpfp, conv);
980                         fclose(tmpfp);
981                         claws_unlink(filename);
982                 }
983                 g_free(filename);
984         } else if (!g_ascii_strcasecmp(mimeinfo->subtype, "enriched")) {
985                 gchar *filename;
986                 
987                 filename = procmime_get_tmp_file_name(mimeinfo);
988                 if (procmime_get_part(filename, mimeinfo) == 0) {
989                         tmpfp = g_fopen(filename, "rb");
990                         textview_show_ertf(textview, tmpfp, conv);
991                         fclose(tmpfp);
992                         claws_unlink(filename);
993                 }
994                 g_free(filename);
995 #ifndef G_OS_WIN32
996         } else if ( g_ascii_strcasecmp(mimeinfo->subtype, "plain") &&
997                    (cmd = prefs_common.mime_textviewer) && *cmd &&
998                    (p = strchr(cmd, '%')) && *(p + 1) == 's') {
999                 int pid, pfd[2];
1000                 const gchar *fname;
1001
1002                 fname  = procmime_get_tmp_file_name(mimeinfo);
1003                 if (procmime_get_part(fname, mimeinfo)) goto textview_default;
1004
1005                 g_snprintf(buf, sizeof(buf), cmd, fname);
1006                 debug_print("Viewing text content of type: %s (length: %d) "
1007                         "using %s\n", mimeinfo->subtype, mimeinfo->length, buf);
1008
1009                 if (pipe(pfd) < 0) {
1010                         g_snprintf(buf, sizeof(buf),
1011                                 "pipe failed for textview\n\n%s\n", strerror(errno));
1012                         textview_write_line(textview, buf, conv, TRUE);
1013                         goto textview_default;
1014                 }
1015                 pid = fork();
1016                 if (pid < 0) {
1017                         g_snprintf(buf, sizeof(buf),
1018                                 "fork failed for textview\n\n%s\n", strerror(errno));
1019                         textview_write_line(textview, buf, conv, TRUE);
1020                         close(pfd[0]);
1021                         close(pfd[1]);
1022                         goto textview_default;
1023                 }
1024                 if (pid == 0) { /* child */
1025                         int rc;
1026                         gchar **argv;
1027                         argv = strsplit_with_quote(buf, " ", 0);
1028                         close(1);
1029                         close(pfd[0]);
1030                         rc = dup(pfd[1]);
1031                         rc = execvp(argv[0], argv);
1032                         close(pfd[1]);
1033                         g_print(_("The command to view attachment "
1034                                 "as text failed:\n"
1035                                 "    %s\n"
1036                                 "Exit code %d\n"), buf, rc);
1037                         exit(255);
1038                 }
1039                 close(pfd[1]);
1040                 tmpfp = fdopen(pfd[0], "rb");
1041                 while (fgets(buf, sizeof(buf), tmpfp)) {
1042                         textview_write_line(textview, buf, conv, TRUE);
1043                         
1044                         if (textview->stop_loading) {
1045                                 fclose(tmpfp);
1046                                 waitpid(pid, pfd, 0);
1047                                 g_unlink(fname);
1048                                 return;
1049                         }
1050                 }
1051
1052                 fclose(tmpfp);
1053                 waitpid(pid, pfd, 0);
1054                 g_unlink(fname);
1055 #endif
1056         } else {
1057 textview_default:
1058                 if (mimeinfo->content == MIMECONTENT_MEM)
1059                         tmpfp = str_open_as_stream(mimeinfo->data.mem);
1060                 else
1061                         tmpfp = g_fopen(mimeinfo->data.filename, "rb");
1062                 if (!tmpfp) {
1063                         FILE_OP_ERROR(mimeinfo->data.filename, "fopen");
1064                         return;
1065                 }
1066                 fseek(tmpfp, mimeinfo->offset, SEEK_SET);
1067                 debug_print("Viewing text content of type: %s (length: %d)\n", mimeinfo->subtype, mimeinfo->length);
1068                 while (((i = ftell(tmpfp)) < mimeinfo->offset + mimeinfo->length) &&
1069                        (fgets(buf, sizeof(buf), tmpfp) != NULL)
1070                        && continue_write) {
1071                         textview_write_line(textview, buf, conv, TRUE);
1072                         if (textview->stop_loading) {
1073                                 fclose(tmpfp);
1074                                 return;
1075                         }
1076                         wrote += ftell(tmpfp)-i;
1077                         if (mimeinfo->length > 1024*1024 
1078                         &&  wrote > 1024*1024
1079                         && !textview->messageview->show_full_text) {
1080                                 continue_write = FALSE;
1081                         }
1082                 }
1083                 fclose(tmpfp);
1084         }
1085
1086         conv_code_converter_destroy(conv);
1087         procmime_force_encoding(0);
1088
1089         textview->uri_list = g_slist_reverse(textview->uri_list);
1090         for (cur = textview->uri_list; cur; cur = cur->next) {
1091                 ClickableText *uri = (ClickableText *)cur->data;
1092                 if (!uri->is_quote)
1093                         continue;
1094                 if (!prefs_common.hide_quotes ||
1095                     uri->quote_level+1 < prefs_common.hide_quotes) {
1096                         textview_toggle_quote(textview, cur, uri, TRUE);
1097                         if (textview->stop_loading) {
1098                                 return;
1099                         }
1100                 }
1101         }
1102         
1103         if (continue_write == FALSE) {
1104                 messageview_show_partial_display(
1105                         textview->messageview, 
1106                         textview->messageview->msginfo,
1107                         mimeinfo->length);
1108         }
1109         GTK_EVENTS_FLUSH();
1110 }
1111
1112 static void textview_show_html(TextView *textview, FILE *fp,
1113                                CodeConverter *conv)
1114 {
1115         SC_HTMLParser *parser;
1116         gchar *str;
1117         gint lines = 0;
1118
1119         parser = sc_html_parser_new(fp, conv);
1120         cm_return_if_fail(parser != NULL);
1121
1122         while ((str = sc_html_parse(parser)) != NULL) {
1123                 if (parser->state == SC_HTML_HREF) {
1124                         /* first time : get and copy the URL */
1125                         if (parser->href == NULL) {
1126                                 /* ALF - the claws html parser returns an empty string,
1127                                  * if still inside an <a>, but already parsed past HREF */
1128                                 str = strtok(str, " ");
1129                                 if (str) {
1130                                         while (str && *str && g_ascii_isspace(*str))
1131                                                 str++; 
1132                                         parser->href = g_strdup(str);
1133                                         /* the URL may (or not) be followed by the
1134                                          * referenced text */
1135                                         str = strtok(NULL, "");
1136                                 }       
1137                         }
1138                         if (str != NULL)
1139                                 textview_write_link(textview, str, parser->href, NULL);
1140                 } else
1141                         textview_write_line(textview, str, NULL, FALSE);
1142                 lines++;
1143                 if (lines % 500 == 0)
1144                         GTK_EVENTS_FLUSH();
1145                 if (textview->stop_loading) {
1146                         return;
1147                 }
1148         }
1149         textview_write_line(textview, "\n", NULL, FALSE);
1150         sc_html_parser_destroy(parser);
1151 }
1152
1153 static void textview_show_ertf(TextView *textview, FILE *fp,
1154                                CodeConverter *conv)
1155 {
1156         ERTFParser *parser;
1157         gchar *str;
1158         gint lines = 0;
1159
1160         parser = ertf_parser_new(fp, conv);
1161         cm_return_if_fail(parser != NULL);
1162
1163         while ((str = ertf_parse(parser)) != NULL) {
1164                 textview_write_line(textview, str, NULL, FALSE);
1165                 lines++;
1166                 if (lines % 500 == 0)
1167                         GTK_EVENTS_FLUSH();
1168                 if (textview->stop_loading) {
1169                         return;
1170                 }
1171         }
1172         
1173         ertf_parser_destroy(parser);
1174 }
1175
1176 #define ADD_TXT_POS(bp_, ep_, pti_) \
1177         if ((last->next = alloca(sizeof(struct txtpos))) != NULL) { \
1178                 last = last->next; \
1179                 last->bp = (bp_); last->ep = (ep_); last->pti = (pti_); \
1180                 last->next = NULL; \
1181         } else { \
1182                 g_warning("alloc error scanning URIs\n"); \
1183                 gtk_text_buffer_insert_with_tags_by_name(buffer, &iter, \
1184                                                          linebuf, -1, \
1185                                                          fg_tag, NULL); \
1186                 return; \
1187         }
1188
1189 #define ADD_TXT_POS_LATER(bp_, ep_, pti_) \
1190         if ((last->next = alloca(sizeof(struct txtpos))) != NULL) { \
1191                 last = last->next; \
1192                 last->bp = (bp_); last->ep = (ep_); last->pti = (pti_); \
1193                 last->next = NULL; \
1194         } else { \
1195                 g_warning("alloc error scanning URIs\n"); \
1196         }
1197
1198 /* textview_make_clickable_parts() - colorizes clickable parts */
1199 static void textview_make_clickable_parts(TextView *textview,
1200                                           const gchar *fg_tag,
1201                                           const gchar *uri_tag,
1202                                           const gchar *linebuf,
1203                                           gboolean hdr)
1204 {
1205         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1206         GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
1207         GtkTextIter iter;
1208         gchar *mybuf = g_strdup(linebuf);
1209         
1210         /* parse table - in order of priority */
1211         struct table {
1212                 const gchar *needle; /* token */
1213
1214                 /* token search function */
1215                 gchar    *(*search)     (const gchar *haystack,
1216                                          const gchar *needle);
1217                 /* part parsing function */
1218                 gboolean  (*parse)      (const gchar *start,
1219                                          const gchar *scanpos,
1220                                          const gchar **bp_,
1221                                          const gchar **ep_,
1222                                          gboolean hdr);
1223                 /* part to URI function */
1224                 gchar    *(*build_uri)  (const gchar *bp,
1225                                          const gchar *ep);
1226         };
1227
1228         static struct table parser[] = {
1229                 {"http://",  strcasestr, get_uri_part,   make_uri_string},
1230                 {"https://", strcasestr, get_uri_part,   make_uri_string},
1231                 {"ftp://",   strcasestr, get_uri_part,   make_uri_string},
1232                 {"sftp://",  strcasestr, get_uri_part,   make_uri_string},
1233                 {"gopher://",strcasestr, get_uri_part,   make_uri_string},
1234                 {"www.",     strcasestr, get_uri_part,   make_http_string},
1235                 {"mailto:",  strcasestr, get_uri_part,   make_uri_string},
1236                 {"@",        strcasestr, get_email_part, make_email_string}
1237         };
1238         const gint PARSE_ELEMS = sizeof parser / sizeof parser[0];
1239
1240         gint  n;
1241         const gchar *walk, *bp, *ep;
1242
1243         struct txtpos {
1244                 const gchar     *bp, *ep;       /* text position */
1245                 gint             pti;           /* index in parse table */
1246                 struct txtpos   *next;          /* next */
1247         } head = {NULL, NULL, 0,  NULL}, *last = &head;
1248
1249         if (!g_utf8_validate(linebuf, -1, NULL)) {
1250                 g_free(mybuf);
1251                 mybuf = g_malloc(strlen(linebuf)*2 +1);
1252                 conv_localetodisp(mybuf, strlen(linebuf)*2 +1, linebuf);
1253         }
1254
1255         gtk_text_buffer_get_end_iter(buffer, &iter);
1256
1257         /* parse for clickable parts, and build a list of begin and end positions  */
1258         for (walk = mybuf, n = 0;;) {
1259                 gint last_index = PARSE_ELEMS;
1260                 gchar *scanpos = NULL;
1261
1262                 /* FIXME: this looks phony. scanning for anything in the parse table */
1263                 for (n = 0; n < PARSE_ELEMS; n++) {
1264                         gchar *tmp;
1265
1266                         tmp = parser[n].search(walk, parser[n].needle);
1267                         if (tmp) {
1268                                 if (scanpos == NULL || tmp < scanpos) {
1269                                         scanpos = tmp;
1270                                         last_index = n;
1271                                 }
1272                         }                                       
1273                 }
1274
1275                 if (scanpos) {
1276                         /* check if URI can be parsed */
1277                         if (parser[last_index].parse(walk, scanpos, &bp, &ep, hdr)
1278                             && (size_t) (ep - bp - 1) > strlen(parser[last_index].needle)) {
1279                                         ADD_TXT_POS(bp, ep, last_index);
1280                                         walk = ep;
1281                         } else
1282                                 walk = scanpos +
1283                                         strlen(parser[last_index].needle);
1284                 } else
1285                         break;
1286         }
1287
1288         /* colorize this line */
1289         if (head.next) {
1290                 const gchar *normal_text = mybuf;
1291
1292                 /* insert URIs */
1293                 for (last = head.next; last != NULL;
1294                      normal_text = last->ep, last = last->next) {
1295                         ClickableText *uri;
1296                         uri = g_new0(ClickableText, 1);
1297                         if (last->bp - normal_text > 0)
1298                                 gtk_text_buffer_insert_with_tags_by_name
1299                                         (buffer, &iter,
1300                                          normal_text,
1301                                          last->bp - normal_text,
1302                                          fg_tag, NULL);
1303                         uri->uri = parser[last->pti].build_uri(last->bp,
1304                                                                last->ep);
1305                         uri->start = gtk_text_iter_get_offset(&iter);
1306                         gtk_text_buffer_insert_with_tags_by_name
1307                                 (buffer, &iter, last->bp, last->ep - last->bp,
1308                                  uri_tag, fg_tag, NULL);
1309                         uri->end = gtk_text_iter_get_offset(&iter);
1310                         uri->filename = NULL;
1311                         textview->uri_list =
1312                                 g_slist_prepend(textview->uri_list, uri);
1313                 }
1314
1315                 if (*normal_text)
1316                         gtk_text_buffer_insert_with_tags_by_name
1317                                 (buffer, &iter, normal_text, -1, fg_tag, NULL);
1318         } else {
1319                 gtk_text_buffer_insert_with_tags_by_name
1320                         (buffer, &iter, mybuf, -1, fg_tag, NULL);
1321         }
1322         g_free(mybuf);
1323 }
1324
1325 /* textview_make_clickable_parts() - colorizes clickable parts */
1326 static void textview_make_clickable_parts_later(TextView *textview,
1327                                           gint start, gint end)
1328 {
1329         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1330         GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
1331         GtkTextIter start_iter, end_iter;
1332         gchar *mybuf;
1333         gint offset = 0;
1334         /* parse table - in order of priority */
1335         struct table {
1336                 const gchar *needle; /* token */
1337
1338                 /* token search function */
1339                 gchar    *(*search)     (const gchar *haystack,
1340                                          const gchar *needle);
1341                 /* part parsing function */
1342                 gboolean  (*parse)      (const gchar *start,
1343                                          const gchar *scanpos,
1344                                          const gchar **bp_,
1345                                          const gchar **ep_,
1346                                          gboolean hdr);
1347                 /* part to URI function */
1348                 gchar    *(*build_uri)  (const gchar *bp,
1349                                          const gchar *ep);
1350         };
1351
1352         static struct table parser[] = {
1353                 {"http://",  strcasestr, get_uri_part,   make_uri_string},
1354                 {"https://", strcasestr, get_uri_part,   make_uri_string},
1355                 {"ftp://",   strcasestr, get_uri_part,   make_uri_string},
1356                 {"sftp://",  strcasestr, get_uri_part,   make_uri_string},
1357                 {"www.",     strcasestr, get_uri_part,   make_http_string},
1358                 {"mailto:",  strcasestr, get_uri_part,   make_uri_string},
1359                 {"@",        strcasestr, get_email_part, make_email_string}
1360         };
1361         const gint PARSE_ELEMS = sizeof parser / sizeof parser[0];
1362
1363         gint  n;
1364         const gchar *walk, *bp, *ep;
1365
1366         struct txtpos {
1367                 const gchar     *bp, *ep;       /* text position */
1368                 gint             pti;           /* index in parse table */
1369                 struct txtpos   *next;          /* next */
1370         } head = {NULL, NULL, 0,  NULL}, *last = &head;
1371
1372         gtk_text_buffer_get_iter_at_offset(buffer, &start_iter, start);
1373         gtk_text_buffer_get_iter_at_offset(buffer, &end_iter, end);
1374         mybuf = gtk_text_buffer_get_text(buffer, &start_iter, &end_iter, FALSE);
1375         offset = gtk_text_iter_get_offset(&start_iter);
1376
1377         /* parse for clickable parts, and build a list of begin and end positions  */
1378         for (walk = mybuf, n = 0;;) {
1379                 gint last_index = PARSE_ELEMS;
1380                 gchar *scanpos = NULL;
1381
1382                 /* FIXME: this looks phony. scanning for anything in the parse table */
1383                 for (n = 0; n < PARSE_ELEMS; n++) {
1384                         gchar *tmp;
1385
1386                         tmp = parser[n].search(walk, parser[n].needle);
1387                         if (tmp) {
1388                                 if (scanpos == NULL || tmp < scanpos) {
1389                                         scanpos = tmp;
1390                                         last_index = n;
1391                                 }
1392                         }                                       
1393                 }
1394
1395                 if (scanpos) {
1396                         /* check if URI can be parsed */
1397                         if (parser[last_index].parse(walk, scanpos, &bp, &ep, FALSE)
1398                             && (size_t) (ep - bp - 1) > strlen(parser[last_index].needle)) {
1399                                         ADD_TXT_POS_LATER(bp, ep, last_index);
1400                                         walk = ep;
1401                         } else
1402                                 walk = scanpos +
1403                                         strlen(parser[last_index].needle);
1404                 } else
1405                         break;
1406         }
1407
1408         /* colorize this line */
1409         if (head.next) {
1410                 /* insert URIs */
1411                 for (last = head.next; last != NULL; last = last->next) {
1412                         ClickableText *uri;
1413                         gint start_offset, end_offset;
1414                         gchar *tmp_str;
1415                         gchar old_char;
1416                         uri = g_new0(ClickableText, 1);
1417                         uri->uri = parser[last->pti].build_uri(last->bp,
1418                                                                last->ep);
1419                         
1420                         tmp_str = mybuf;
1421                         old_char = tmp_str[last->ep - mybuf];
1422                         tmp_str[last->ep - mybuf] = '\0';                                      
1423                         end_offset = g_utf8_strlen(tmp_str, -1);
1424                         tmp_str[last->ep - mybuf] = old_char;
1425                         
1426                         old_char = tmp_str[last->bp - mybuf];
1427                         tmp_str[last->bp - mybuf] = '\0';                                      
1428                         start_offset = g_utf8_strlen(tmp_str, -1);
1429                         tmp_str[last->bp - mybuf] = old_char;
1430                         
1431                         gtk_text_buffer_get_iter_at_offset(buffer, &start_iter, start_offset + offset);
1432                         gtk_text_buffer_get_iter_at_offset(buffer, &end_iter, end_offset + offset);
1433                         
1434                         uri->start = gtk_text_iter_get_offset(&start_iter);
1435                         
1436                         gtk_text_buffer_apply_tag_by_name(buffer, "link", &start_iter, &end_iter);
1437
1438                         uri->end = gtk_text_iter_get_offset(&end_iter);
1439                         uri->filename = NULL;
1440                         textview->uri_list =
1441                                 g_slist_prepend(textview->uri_list, uri);
1442                 }
1443         } 
1444
1445         g_free(mybuf);
1446 }
1447
1448 #undef ADD_TXT_POS
1449
1450 static void textview_write_line(TextView *textview, const gchar *str,
1451                                 CodeConverter *conv, gboolean do_quote_folding)
1452 {
1453         GtkTextView *text;
1454         GtkTextBuffer *buffer;
1455         GtkTextIter iter;
1456         gchar buf[BUFFSIZE];
1457         gchar *fg_color;
1458         gint quotelevel = -1, real_quotelevel = -1;
1459         gchar quote_tag_str[10];
1460
1461         text = GTK_TEXT_VIEW(textview->text);
1462         buffer = gtk_text_view_get_buffer(text);
1463         gtk_text_buffer_get_end_iter(buffer, &iter);
1464
1465         if (!conv)
1466                 strncpy2(buf, str, sizeof(buf));
1467         else if (conv_convert(conv, buf, sizeof(buf), str) < 0)
1468                 conv_localetodisp(buf, sizeof(buf), str);
1469                 
1470         strcrchomp(buf);
1471         fg_color = NULL;
1472
1473         /* change color of quotation
1474            >, foo>, _> ... ok, <foo>, foo bar>, foo-> ... ng
1475            Up to 3 levels of quotations are detected, and each
1476            level is colored using a different color. */
1477         if (prefs_common.enable_color 
1478             && line_has_quote_char(buf, prefs_common.quote_chars)) {
1479                 real_quotelevel = get_quote_level(buf, prefs_common.quote_chars);
1480                 quotelevel = real_quotelevel;
1481                 /* set up the correct foreground color */
1482                 if (quotelevel > 2) {
1483                         /* recycle colors */
1484                         if (prefs_common.recycle_quote_colors)
1485                                 quotelevel %= 3;
1486                         else
1487                                 quotelevel = 2;
1488                 }
1489         }
1490
1491         if (quotelevel == -1)
1492                 fg_color = NULL;
1493         else {
1494                 g_snprintf(quote_tag_str, sizeof(quote_tag_str),
1495                            "quote%d", quotelevel);
1496                 fg_color = quote_tag_str;
1497         }
1498
1499         if (prefs_common.enable_color && 
1500             (strcmp(buf,"-- \n") == 0 || strcmp(buf, "- -- \n") == 0 || textview->is_in_signature)) {
1501                 fg_color = "signature";
1502                 textview->is_in_signature = TRUE;
1503         }
1504
1505         if (real_quotelevel > -1 && do_quote_folding) {
1506                 if (!g_utf8_validate(buf, -1, NULL)) {
1507                         gchar *utf8buf = NULL;
1508                         utf8buf = g_malloc(BUFFSIZE);
1509                         conv_localetodisp(utf8buf, BUFFSIZE, buf);
1510                         strncpy2(buf, utf8buf, BUFFSIZE-1);
1511                         g_free(utf8buf);
1512                 }
1513 do_quote:
1514                 if ( textview->prev_quote_level != real_quotelevel ) {
1515                         ClickableText *uri;
1516                         uri = g_new0(ClickableText, 1);
1517                         uri->uri = g_strdup("");
1518                         uri->data = g_strdup(buf);
1519                         uri->start = gtk_text_iter_get_offset(&iter);
1520                         uri->is_quote = TRUE;
1521                         uri->quote_level = real_quotelevel;
1522                         uri->fg_color = g_strdup(fg_color);
1523
1524                         gtk_text_buffer_insert_with_tags_by_name
1525                                         (buffer, &iter, " [...]", -1,
1526                                          "qlink", fg_color, NULL);
1527                         uri->end = gtk_text_iter_get_offset(&iter);
1528                         gtk_text_buffer_insert(buffer, &iter, "  \n", -1);
1529                         
1530                         uri->filename = NULL;
1531                         textview->uri_list =
1532                                 g_slist_prepend(textview->uri_list, uri);
1533                 
1534                         textview->prev_quote_level = real_quotelevel;
1535                 } else {
1536                         GSList *last = textview->uri_list;
1537                         ClickableText *lasturi = NULL;
1538                         gint e_len = 0, n_len = 0;
1539                         
1540                         if (textview->uri_list) {
1541                                 lasturi = (ClickableText *)last->data;
1542                         } else {
1543                                 g_print("oops (%d %d)\n",
1544                                         real_quotelevel, textview->prev_quote_level);
1545                         }       
1546                         if (lasturi) {  
1547                                 if (lasturi->is_quote == FALSE) {
1548                                         textview->prev_quote_level = -1;
1549                                         goto do_quote;
1550                                 }
1551                                 e_len = lasturi->data ? strlen(lasturi->data):0;
1552                                 n_len = strlen(buf);
1553                                 lasturi->data = g_realloc((gchar *)lasturi->data, e_len + n_len + 1);
1554                                 strcpy((gchar *)lasturi->data + e_len, buf);
1555                                 *((gchar *)lasturi->data + e_len + n_len) = '\0';
1556                         }
1557                 }
1558         } else {
1559                 textview_make_clickable_parts(textview, fg_color, "link", buf, FALSE);
1560                 textview->prev_quote_level = -1;
1561         }
1562 }
1563
1564 void textview_write_link(TextView *textview, const gchar *str,
1565                          const gchar *uri, CodeConverter *conv)
1566 {
1567         GdkColor *link_color = NULL;
1568         GtkTextView *text;
1569         GtkTextBuffer *buffer;
1570         GtkTextIter iter;
1571         gchar buf[BUFFSIZE];
1572         gchar *bufp;
1573         ClickableText *r_uri;
1574
1575         if (!str || *str == '\0')
1576                 return;
1577         if (!uri)
1578                 return;
1579
1580         while (uri && *uri && g_ascii_isspace(*uri))
1581                 uri++;
1582                 
1583         text = GTK_TEXT_VIEW(textview->text);
1584         buffer = gtk_text_view_get_buffer(text);
1585         gtk_text_buffer_get_end_iter(buffer, &iter);
1586
1587         if (!conv)
1588                 strncpy2(buf, str, sizeof(buf));
1589         else if (conv_convert(conv, buf, sizeof(buf), str) < 0)
1590                 conv_utf8todisp(buf, sizeof(buf), str);
1591
1592         if (g_utf8_validate(buf, -1, NULL) == FALSE)
1593                 return;
1594
1595         strcrchomp(buf);
1596
1597         gtk_text_buffer_get_end_iter(buffer, &iter);
1598         for (bufp = buf; *bufp != '\0'; bufp = g_utf8_next_char(bufp)) {
1599                 gunichar ch;
1600
1601                 ch = g_utf8_get_char(bufp);
1602                 if (!g_unichar_isspace(ch))
1603                         break;
1604         }
1605         if (bufp > buf)
1606                 gtk_text_buffer_insert(buffer, &iter, buf, bufp - buf);
1607
1608         if (prefs_common.enable_color) {
1609                 link_color = &uri_color;
1610         }
1611         r_uri = g_new0(ClickableText, 1);
1612         r_uri->uri = g_strdup(uri);
1613         r_uri->start = gtk_text_iter_get_offset(&iter);
1614         gtk_text_buffer_insert_with_tags_by_name
1615                 (buffer, &iter, bufp, -1, "link", NULL);
1616         r_uri->end = gtk_text_iter_get_offset(&iter);
1617         r_uri->filename = NULL;
1618         textview->uri_list = g_slist_prepend(textview->uri_list, r_uri);
1619 }
1620
1621 static void textview_set_cursor(GdkWindow *window, GdkCursor *cursor)
1622 {
1623         if (GDK_IS_WINDOW(window))
1624                 gdk_window_set_cursor(window, cursor);
1625 }
1626 void textview_clear(TextView *textview)
1627 {
1628         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1629         GtkTextBuffer *buffer;
1630         GdkWindow *window = gtk_text_view_get_window(text,
1631                                 GTK_TEXT_WINDOW_TEXT);
1632
1633         buffer = gtk_text_view_get_buffer(text);
1634         gtk_text_buffer_set_text(buffer, "", -1);
1635
1636         TEXTVIEW_STATUSBAR_POP(textview);
1637         textview_uri_list_remove_all(textview->uri_list);
1638         textview->uri_list = NULL;
1639         textview->uri_hover = NULL;
1640         textview->prev_quote_level = -1;
1641
1642         textview->body_pos = 0;
1643         if (textview->image) 
1644                 gtk_widget_destroy(textview->image);
1645         textview->image = NULL;
1646
1647         if (textview->messageview->mainwin->cursor_count == 0) {
1648                 textview_set_cursor(window, text_cursor);
1649         } else {
1650                 textview_set_cursor(window, watch_cursor);
1651         }
1652 }
1653
1654 void textview_destroy(TextView *textview)
1655 {
1656         GtkTextBuffer *buffer;
1657         GtkClipboard *clipboard;
1658
1659         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview->text));
1660         clipboard = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
1661         gtk_text_buffer_remove_selection_clipboard(buffer, clipboard);
1662
1663         textview_uri_list_remove_all(textview->uri_list);
1664         textview->uri_list = NULL;
1665         textview->prev_quote_level = -1;
1666
1667         g_free(textview);
1668 }
1669
1670 void textview_set_all_headers(TextView *textview, gboolean all_headers)
1671 {
1672         textview->show_all_headers = all_headers;
1673 }
1674
1675 #define CHANGE_TAG_FONT(tagname, font) { \
1676         tag = gtk_text_tag_table_lookup(tags, tagname); \
1677         if (tag) \
1678                 g_object_set(G_OBJECT(tag), "font-desc", font, NULL); \
1679 }
1680
1681 void textview_set_font(TextView *textview, const gchar *codeset)
1682 {
1683         GtkTextTag *tag;
1684         GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview->text));
1685         GtkTextTagTable *tags = gtk_text_buffer_get_tag_table(buffer);
1686         PangoFontDescription *font_desc, *bold_font_desc;
1687
1688         font_desc = pango_font_description_from_string
1689                                         (NORMAL_FONT);
1690         if (font_desc) {
1691                 gtk_widget_modify_font(textview->text, font_desc);
1692                 CHANGE_TAG_FONT("header", font_desc);
1693                 CHANGE_TAG_FONT("hlink", font_desc);
1694                 pango_font_description_free(font_desc);
1695         }
1696         if (prefs_common.derive_from_normal_font || !BOLD_FONT) {
1697                 bold_font_desc = pango_font_description_from_string
1698                                                 (NORMAL_FONT);
1699                 if (bold_font_desc)
1700                         pango_font_description_set_weight
1701                                 (bold_font_desc, PANGO_WEIGHT_BOLD);
1702         } else {
1703                 bold_font_desc = pango_font_description_from_string
1704                                                 (BOLD_FONT);
1705         }
1706         if (bold_font_desc) {
1707                 CHANGE_TAG_FONT("header_title", bold_font_desc);
1708                 pango_font_description_free(bold_font_desc);
1709         }
1710
1711         if (prefs_common.textfont) {
1712                 PangoFontDescription *font_desc;
1713
1714                 font_desc = pango_font_description_from_string
1715                                                 (prefs_common.textfont);
1716                 if (font_desc) {
1717                         gtk_widget_modify_font(textview->text, font_desc);
1718                         pango_font_description_free(font_desc);
1719                 }
1720         }
1721         gtk_text_view_set_pixels_above_lines(GTK_TEXT_VIEW(textview->text),
1722                                              prefs_common.line_space / 2);
1723         gtk_text_view_set_pixels_below_lines(GTK_TEXT_VIEW(textview->text),
1724                                              prefs_common.line_space / 2);
1725 }
1726
1727 void textview_set_text(TextView *textview, const gchar *text)
1728 {
1729         GtkTextView *view;
1730         GtkTextBuffer *buffer;
1731
1732         cm_return_if_fail(textview != NULL);
1733         cm_return_if_fail(text != NULL);
1734
1735         textview_clear(textview);
1736
1737         view = GTK_TEXT_VIEW(textview->text);
1738         buffer = gtk_text_view_get_buffer(view);
1739         gtk_text_buffer_set_text(buffer, text, strlen(text));
1740 }
1741
1742 enum
1743 {
1744         H_DATE          = 0,
1745         H_FROM          = 1,
1746         H_TO            = 2,
1747         H_NEWSGROUPS    = 3,
1748         H_SUBJECT       = 4,
1749         H_CC            = 5,
1750         H_REPLY_TO      = 6,
1751         H_FOLLOWUP_TO   = 7,
1752         H_X_MAILER      = 8,
1753         H_X_NEWSREADER  = 9,
1754         H_USER_AGENT    = 10,
1755         H_ORGANIZATION  = 11,
1756 };
1757
1758 void textview_set_position(TextView *textview, gint pos)
1759 {
1760         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1761
1762         gtkut_text_view_set_position(text, pos);
1763 }
1764
1765 static gboolean header_is_internal(Header *header)
1766 {
1767         const gchar *internal_hdrs[] = 
1768                 {"AF:", "NF:", "PS:", "SRH:", "SFN:", "DSR:", "MID:", 
1769                  "CFG:", "PT:", "S:", "RQ:", "SSV:", "NSV:", "SSH:", 
1770                  "R:", "MAID:", "SCF:", "RMID:", "FMID:", "NAID:", 
1771                  "X-Claws-Account-Id:", "X-Claws-Sign:", "X-Claws-Encrypt:", 
1772                  "X-Claws-Privacy-System:", "X-Claws-End-Special-Headers:",
1773                  "X-Sylpheed-Account-Id:", "X-Sylpheed-Sign:", "X-Sylpheed-Encrypt:", 
1774                  "X-Claws-Auto-Wrapping:", "X-Claws-Auto-Indent:",
1775                  "X-Sylpheed-Privacy-System:", "X-Sylpheed-End-Special-Headers:",
1776                  NULL};
1777         int i;
1778         
1779         for (i = 0; internal_hdrs[i]; i++) {
1780                 if (!strcmp(header->name, internal_hdrs[i]))
1781                         return TRUE;
1782         }
1783         return FALSE;
1784 }
1785
1786 static GPtrArray *textview_scan_header(TextView *textview, FILE *fp)
1787 {
1788         gchar buf[BUFFSIZE];
1789         GPtrArray *headers, *sorted_headers;
1790         GSList *disphdr_list;
1791         Header *header;
1792         gint i;
1793
1794         cm_return_val_if_fail(fp != NULL, NULL);
1795
1796         if (textview->show_all_headers) {
1797                 headers = procheader_get_header_array_asis(fp);
1798                 sorted_headers = g_ptr_array_new();
1799                 for (i = 0; i < headers->len; i++) {
1800                         header = g_ptr_array_index(headers, i);
1801                         if (!header_is_internal(header))
1802                                 g_ptr_array_add(sorted_headers, header);
1803                         else
1804                                 procheader_header_free(header);
1805                 }
1806                 g_ptr_array_free(headers, TRUE);
1807                 return sorted_headers;
1808         }
1809
1810         if (!prefs_common.display_header) {
1811                 while (fgets(buf, sizeof(buf), fp) != NULL)
1812                         if (buf[0] == '\r' || buf[0] == '\n') break;
1813                 return NULL;
1814         }
1815
1816         headers = procheader_get_header_array_asis(fp);
1817
1818         sorted_headers = g_ptr_array_new();
1819
1820         for (disphdr_list = prefs_common.disphdr_list; disphdr_list != NULL;
1821              disphdr_list = disphdr_list->next) {
1822                 DisplayHeaderProp *dp =
1823                         (DisplayHeaderProp *)disphdr_list->data;
1824
1825                 for (i = 0; i < headers->len; i++) {
1826                         header = g_ptr_array_index(headers, i);
1827
1828                         if (procheader_headername_equal(header->name,
1829                                                         dp->name)) {
1830                                 if (dp->hidden)
1831                                         procheader_header_free(header);
1832                                 else
1833                                         g_ptr_array_add(sorted_headers, header);
1834
1835                                 g_ptr_array_remove_index(headers, i);
1836                                 i--;
1837                         }
1838                 }
1839         }
1840
1841         if (prefs_common.show_other_header) {
1842                 for (i = 0; i < headers->len; i++) {
1843                         header = g_ptr_array_index(headers, i);
1844                         if (!header_is_internal(header)) {
1845                                 g_ptr_array_add(sorted_headers, header);
1846                         } else {
1847                                 procheader_header_free(header);
1848                         }
1849                 }
1850                 g_ptr_array_free(headers, TRUE);
1851         } else
1852                 procheader_header_array_destroy(headers);
1853
1854
1855         return sorted_headers;
1856 }
1857
1858 static void textview_show_face(TextView *textview)
1859 {
1860         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1861         MsgInfo *msginfo = textview->messageview->msginfo;
1862         int x = 0;
1863         
1864         if (prefs_common.display_header_pane
1865         ||  !prefs_common.display_xface)
1866                 goto bail;
1867         
1868         if (!msginfo->extradata || !msginfo->extradata->face) {
1869                 goto bail;
1870         }
1871
1872         if (textview->image) 
1873                 gtk_widget_destroy(textview->image);
1874         
1875         textview->image = face_get_from_header(msginfo->extradata->face);
1876         cm_return_if_fail(textview->image != NULL);
1877
1878         gtk_widget_show(textview->image);
1879         
1880         x = textview->text->allocation.width - WIDTH -5;
1881
1882         gtk_text_view_add_child_in_window(text, textview->image, 
1883                 GTK_TEXT_WINDOW_TEXT, x, 5);
1884
1885         gtk_widget_show_all(textview->text);
1886         
1887
1888         return;
1889 bail:
1890         if (textview->image) 
1891                 gtk_widget_destroy(textview->image);
1892         textview->image = NULL; 
1893 }
1894
1895 void textview_show_icon(TextView *textview, const gchar *stock_id)
1896 {
1897         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1898         int x = 0;
1899         
1900         if (textview->image) 
1901                 gtk_widget_destroy(textview->image);
1902         
1903         textview->image = gtk_image_new_from_stock(stock_id, GTK_ICON_SIZE_DIALOG);
1904         cm_return_if_fail(textview->image != NULL);
1905
1906         gtk_widget_show(textview->image);
1907         
1908         x = textview->text->allocation.width - WIDTH -5;
1909
1910         gtk_text_view_add_child_in_window(text, textview->image, 
1911                 GTK_TEXT_WINDOW_TEXT, x, 5);
1912
1913         gtk_widget_show_all(textview->text);
1914         
1915
1916         return;
1917 }
1918
1919 #if HAVE_LIBCOMPFACE
1920 static void textview_show_xface(TextView *textview)
1921 {
1922         MsgInfo *msginfo = textview->messageview->msginfo;
1923         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1924         int x = 0;
1925         GdkWindow *window = NULL;
1926         
1927         if (prefs_common.display_header_pane
1928         ||  !prefs_common.display_xface)
1929                 goto bail;
1930         
1931         if (!msginfo || !msginfo->extradata)
1932                 goto bail;
1933
1934         if (msginfo->extradata->face)
1935                 return;
1936         
1937         if (!msginfo->extradata->xface || strlen(msginfo->extradata->xface) < 5) {
1938                 goto bail;
1939         }
1940
1941         if (textview->image) 
1942                 gtk_widget_destroy(textview->image);
1943
1944         window = mainwindow_get_mainwindow() ?
1945                         mainwindow_get_mainwindow()->window->window :
1946                         textview->text->window;
1947         textview->image = xface_get_from_header(msginfo->extradata->xface,
1948                                 &textview->text->style->white,
1949                                 window);
1950         cm_return_if_fail(textview->image != NULL);
1951
1952         gtk_widget_show(textview->image);
1953         
1954         x = textview->text->allocation.width - WIDTH -5;
1955
1956         gtk_text_view_add_child_in_window(text, textview->image, 
1957                 GTK_TEXT_WINDOW_TEXT, x, 5);
1958
1959         gtk_widget_show_all(textview->text);
1960         
1961         return;
1962 bail:
1963         if (textview->image) 
1964                 gtk_widget_destroy(textview->image);
1965         textview->image = NULL;
1966         
1967 }
1968 #endif
1969
1970 static void textview_save_contact_pic(TextView *textview)
1971 {
1972         MsgInfo *msginfo = textview->messageview->msginfo;
1973         gchar *filename = NULL;
1974         GError *error = NULL;
1975         GdkPixbuf *picture = NULL;
1976                                 
1977         if (!msginfo->extradata || (!msginfo->extradata->face && !msginfo->extradata->xface))
1978                 return;
1979
1980         if (textview->image) 
1981                 picture = gtk_image_get_pixbuf(GTK_IMAGE(textview->image));
1982
1983         filename = addrindex_get_picture_file(msginfo->from);
1984         if (!filename)
1985                 return;
1986         if (!is_file_exist(filename)) {
1987                 gdk_pixbuf_save(picture, filename, "png", &error, NULL);
1988                 if (error) {
1989                         g_warning(_("Failed to save image: \n%s"),
1990                                         error->message);
1991                         g_error_free(error);
1992                 }
1993         }
1994         g_free(filename);
1995 }
1996
1997 static void textview_show_contact_pic(TextView *textview)
1998 {
1999         MsgInfo *msginfo = textview->messageview->msginfo;
2000         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
2001         int x = 0;
2002         gchar *filename = NULL;
2003         GError *error = NULL;
2004         GdkPixbuf *picture = NULL;
2005         gint w, h;
2006                                 
2007         if (prefs_common.display_header_pane
2008         ||  !prefs_common.display_xface)
2009                 goto bail;
2010         
2011         if (msginfo->extradata && (msginfo->extradata->face || msginfo->extradata->xface))
2012                 return;
2013
2014         if (textview->image) 
2015                 gtk_widget_destroy(textview->image);
2016
2017         filename = addrindex_get_picture_file(msginfo->from);
2018         
2019         if (!filename)
2020                 goto bail;
2021         if (!is_file_exist(filename)) {
2022                 g_free(filename);
2023                 goto bail;
2024         }
2025
2026         gdk_pixbuf_get_file_info(filename, &w, &h);
2027         
2028         if (w > 48 || h > 48)
2029                 picture = gdk_pixbuf_new_from_file_at_scale(filename, 
2030                                                 48, 48, TRUE, &error);
2031         else
2032                 picture = gdk_pixbuf_new_from_file(filename, &error);
2033
2034         if (error) {
2035                 debug_print("Failed to import image: \n%s",
2036                                 error->message);
2037                 g_error_free(error);
2038                 goto bail;
2039         }
2040         g_free(filename);
2041
2042         if (picture) {
2043                 textview->image = gtk_image_new_from_pixbuf(picture);
2044                 g_object_unref(picture);
2045         }
2046         cm_return_if_fail(textview->image != NULL);
2047
2048         gtk_widget_show(textview->image);
2049         
2050         x = textview->text->allocation.width - WIDTH -5;
2051
2052         gtk_text_view_add_child_in_window(text, textview->image, 
2053                 GTK_TEXT_WINDOW_TEXT, x, 5);
2054
2055         gtk_widget_show_all(textview->text);
2056         
2057         return;
2058 bail:
2059         if (textview->image) 
2060                 gtk_widget_destroy(textview->image);
2061         textview->image = NULL;
2062         
2063 }
2064
2065 static gint textview_tag_cmp_list(gconstpointer a, gconstpointer b)
2066 {
2067         gint id_a = GPOINTER_TO_INT(a);
2068         gint id_b = GPOINTER_TO_INT(b);
2069         const gchar *tag_a = tags_get_tag(id_a);
2070         const gchar *tag_b = tags_get_tag(id_b);
2071         
2072         if (tag_a == NULL)
2073                 return tag_b == NULL ? 0:1;
2074         
2075         if (tag_b == NULL)
2076                 return tag_a == NULL ? 0:1;
2077
2078         return g_utf8_collate(tag_a, tag_b);
2079 }
2080
2081
2082 static void textview_show_tags(TextView *textview)
2083 {
2084         MsgInfo *msginfo = textview->messageview->msginfo;
2085         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
2086         GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
2087         GtkTextIter iter;
2088         ClickableText *uri;
2089         GSList *cur, *orig;
2090         gboolean found_tag = FALSE;
2091         
2092         if (!msginfo->tags)
2093                 return;
2094         
2095         cur = orig = g_slist_sort(g_slist_copy(msginfo->tags), textview_tag_cmp_list);
2096
2097         for (; cur; cur = cur->next) {
2098                 if (tags_get_tag(GPOINTER_TO_INT(cur->data)) != NULL) {
2099                         found_tag = TRUE;
2100                         break;
2101                 }
2102         }
2103         if (!found_tag) {
2104                 g_slist_free(orig);
2105                 return;
2106         }
2107
2108         gtk_text_buffer_get_end_iter (buffer, &iter);
2109         gtk_text_buffer_insert_with_tags_by_name(buffer,
2110                 &iter, _("Tags: "), -1,
2111                 "header_title", "header", "tags", NULL);
2112
2113         for (cur = orig; cur; cur = cur->next) {
2114                 const gchar *cur_tag = tags_get_tag(GPOINTER_TO_INT(cur->data));
2115                 if (!cur_tag)
2116                         continue;
2117                 uri = g_new0(ClickableText, 1);
2118                 uri->uri = g_strdup("");
2119                 uri->start = gtk_text_iter_get_offset(&iter);
2120                 gtk_text_buffer_insert_with_tags_by_name(buffer, &iter, 
2121                         cur_tag, -1,
2122                         "link", "header", "tags", NULL);
2123                 uri->end = gtk_text_iter_get_offset(&iter);
2124                 uri->filename = g_strdup_printf("sc://search_tags:%s", cur_tag);
2125                 uri->data = NULL;
2126                 textview->uri_list =
2127                         g_slist_prepend(textview->uri_list, uri);
2128                 if (cur->next && tags_get_tag(GPOINTER_TO_INT(cur->next->data)))
2129                         gtk_text_buffer_insert_with_tags_by_name(buffer, &iter, ", ", 2,
2130                                 "header", "tags", NULL);
2131                 else
2132                         gtk_text_buffer_insert_with_tags_by_name(buffer, &iter, " ", 1,
2133                                 "header", "tags", NULL);
2134         }
2135         g_slist_free(orig);
2136
2137         gtk_text_buffer_insert_with_tags_by_name(buffer, &iter, "\n", 1,
2138                 "header", "tags", NULL);
2139 }
2140
2141 static void textview_show_header(TextView *textview, GPtrArray *headers)
2142 {
2143         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
2144         GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
2145         GtkTextIter iter;
2146         Header *header;
2147         gint i;
2148
2149         cm_return_if_fail(headers != NULL);
2150
2151         for (i = 0; i < headers->len; i++) {
2152                 header = g_ptr_array_index(headers, i);
2153                 cm_return_if_fail(header->name != NULL);
2154
2155                 gtk_text_buffer_get_end_iter (buffer, &iter);
2156                 if(prefs_common.trans_hdr == TRUE) {
2157                         gchar *hdr = g_strndup(header->name, strlen(header->name) - 1);
2158                         gchar *trans_hdr = gettext(hdr);
2159                         gtk_text_buffer_insert_with_tags_by_name(buffer,
2160                                 &iter, trans_hdr, -1,
2161                                 "header_title", "header", NULL);
2162                         gtk_text_buffer_insert_with_tags_by_name(buffer,
2163                                 &iter, ":", 1, "header_title", "header", NULL);
2164                         g_free(hdr);
2165                 } else {
2166                         gtk_text_buffer_insert_with_tags_by_name(buffer,
2167                                 &iter, header->name,
2168                                 -1, "header_title", "header", NULL);
2169                 }
2170                 if (header->name[strlen(header->name) - 1] != ' ')
2171                 gtk_text_buffer_insert_with_tags_by_name
2172                                 (buffer, &iter, " ", 1,
2173                                  "header_title", "header", NULL);
2174
2175                 if (procheader_headername_equal(header->name, "Subject") ||
2176                     procheader_headername_equal(header->name, "From")    ||
2177                     procheader_headername_equal(header->name, "To")      ||
2178                     procheader_headername_equal(header->name, "Cc"))
2179                         unfold_line(header->body);
2180
2181                 if ((procheader_headername_equal(header->name, "X-Mailer") ||
2182                      procheader_headername_equal(header->name,
2183                                                  "X-Newsreader")) &&
2184                     (strstr(header->body, "Claws Mail") != NULL ||
2185                      strstr(header->body, "Sylpheed-Claws") != NULL)) {
2186                         gtk_text_buffer_get_end_iter (buffer, &iter);
2187                         gtk_text_buffer_insert_with_tags_by_name
2188                                 (buffer, &iter, header->body, -1,
2189                                  "header", "emphasis", NULL);
2190                 } else {
2191                         gboolean hdr = 
2192                           procheader_headername_equal(header->name, "From") ||
2193                           procheader_headername_equal(header->name, "To") ||
2194                           procheader_headername_equal(header->name, "Cc") ||
2195                           procheader_headername_equal(header->name, "Bcc") ||
2196                           procheader_headername_equal(header->name, "Reply-To") ||
2197                           procheader_headername_equal(header->name, "Sender");
2198                         textview_make_clickable_parts(textview, "header", 
2199                                                       "hlink", header->body, 
2200                                                       hdr);
2201                 }
2202                 gtk_text_buffer_get_end_iter (buffer, &iter);
2203                 gtk_text_buffer_insert_with_tags_by_name(buffer, &iter, "\n", 1,
2204                                                          "header", NULL);
2205         }
2206         
2207         textview_show_face(textview);
2208 #if HAVE_LIBCOMPFACE
2209         textview_show_xface(textview);
2210 #endif
2211         textview_save_contact_pic(textview);
2212         textview_show_contact_pic(textview);
2213 }
2214
2215 gboolean textview_search_string(TextView *textview, const gchar *str,
2216                                 gboolean case_sens)
2217 {
2218         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
2219
2220         return gtkut_text_view_search_string(text, str, case_sens);
2221 }
2222
2223 gboolean textview_search_string_backward(TextView *textview, const gchar *str,
2224                                          gboolean case_sens)
2225 {
2226         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
2227
2228         return gtkut_text_view_search_string_backward(text, str, case_sens);
2229 }
2230
2231 void textview_scroll_one_line(TextView *textview, gboolean up)
2232 {
2233         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
2234         GtkAdjustment *vadj = text->vadjustment;
2235
2236         gtkutils_scroll_one_line(GTK_WIDGET(text), vadj, up);
2237 }
2238
2239 gboolean textview_scroll_page(TextView *textview, gboolean up)
2240 {
2241         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
2242         GtkAdjustment *vadj = text->vadjustment;
2243
2244         return gtkutils_scroll_page(GTK_WIDGET(text), vadj, up);
2245 }
2246
2247 #define KEY_PRESS_EVENT_STOP() \
2248         g_signal_stop_emission_by_name(G_OBJECT(widget), \
2249                                        "key_press_event");
2250
2251 static gint textview_key_pressed(GtkWidget *widget, GdkEventKey *event,
2252                                  TextView *textview)
2253 {
2254         SummaryView *summaryview = NULL;
2255         MessageView *messageview = textview->messageview;
2256
2257         if (!event) return FALSE;
2258         if (messageview->mainwin)
2259                 summaryview = messageview->mainwin->summaryview;
2260
2261         switch (event->keyval) {
2262         case GDK_Tab:
2263         case GDK_Home:
2264         case GDK_Left:
2265         case GDK_Up:
2266         case GDK_Right:
2267         case GDK_Down:
2268         case GDK_Page_Up:
2269         case GDK_Page_Down:
2270         case GDK_End:
2271         case GDK_Control_L:
2272         case GDK_Control_R:
2273                 return FALSE;
2274         case GDK_space:
2275                 if (summaryview)
2276                         summary_pass_key_press_event(summaryview, event);
2277                 else
2278                         mimeview_scroll_page
2279                                 (messageview->mimeview,
2280                                  (event->state &
2281                                   (GDK_SHIFT_MASK|GDK_MOD1_MASK)) != 0);
2282                 break;
2283         case GDK_BackSpace:
2284                 mimeview_scroll_page(messageview->mimeview, TRUE);
2285                 break;
2286         case GDK_Return:
2287         case GDK_KP_Enter:
2288                 mimeview_scroll_one_line
2289                         (messageview->mimeview, (event->state &
2290                                     (GDK_SHIFT_MASK|GDK_MOD1_MASK)) != 0);
2291                 break;
2292         case GDK_Delete:
2293                 if (summaryview)
2294                         summary_pass_key_press_event(summaryview, event);
2295                 break;
2296         case GDK_y:
2297         case GDK_t:
2298         case GDK_l:
2299         case GDK_o:
2300         case GDK_c:
2301         case GDK_a:
2302                 if ((event->state & (GDK_MOD1_MASK|GDK_CONTROL_MASK)) == 0) {
2303                         KEY_PRESS_EVENT_STOP();
2304                         mimeview_pass_key_press_event(messageview->mimeview,
2305                                                       event);
2306                         break;
2307                 }
2308                 /* possible fall through */
2309         default:
2310                 if (summaryview &&
2311                     event->window != messageview->mainwin->window->window) {
2312                         GdkEventKey tmpev = *event;
2313
2314                         tmpev.window = messageview->mainwin->window->window;
2315                         KEY_PRESS_EVENT_STOP();
2316                         gtk_widget_event(messageview->mainwin->window,
2317                                          (GdkEvent *)&tmpev);
2318                 }
2319                 break;
2320         }
2321
2322         return TRUE;
2323 }
2324
2325 static gboolean textview_motion_notify(GtkWidget *widget,
2326                                        GdkEventMotion *event,
2327                                        TextView *textview)
2328 {
2329         if (textview->loading)
2330                 return FALSE;
2331         textview_uri_update(textview, event->x, event->y);
2332         gdk_window_get_pointer(widget->window, NULL, NULL, NULL);
2333
2334         return FALSE;
2335 }
2336
2337 static gboolean textview_leave_notify(GtkWidget *widget,
2338                                       GdkEventCrossing *event,
2339                                       TextView *textview)
2340 {
2341         if (textview->loading)
2342                 return FALSE;
2343         textview_uri_update(textview, -1, -1);
2344
2345         return FALSE;
2346 }
2347
2348 static gboolean textview_visibility_notify(GtkWidget *widget,
2349                                            GdkEventVisibility *event,
2350                                            TextView *textview)
2351 {
2352         gint wx, wy;
2353         GdkWindow *window;
2354
2355         if (textview->loading)
2356                 return FALSE;
2357
2358         window = gtk_text_view_get_window(GTK_TEXT_VIEW(widget),
2359                                           GTK_TEXT_WINDOW_TEXT);
2360
2361         /* check if occurred for the text window part */
2362         if (window != event->window)
2363                 return FALSE;
2364         
2365         gdk_window_get_pointer(widget->window, &wx, &wy, NULL);
2366         textview_uri_update(textview, wx, wy);
2367
2368         return FALSE;
2369 }
2370
2371 void textview_cursor_wait(TextView *textview)
2372 {
2373         GdkWindow *window = gtk_text_view_get_window(
2374                         GTK_TEXT_VIEW(textview->text),
2375                         GTK_TEXT_WINDOW_TEXT);
2376         textview_set_cursor(window, watch_cursor);
2377 }
2378
2379 void textview_cursor_normal(TextView *textview)
2380 {
2381         GdkWindow *window = gtk_text_view_get_window(
2382                         GTK_TEXT_VIEW(textview->text),
2383                         GTK_TEXT_WINDOW_TEXT);
2384         textview_set_cursor(window, text_cursor);
2385 }
2386
2387 static void textview_uri_update(TextView *textview, gint x, gint y)
2388 {
2389         GtkTextBuffer *buffer;
2390         GtkTextIter start_iter, end_iter;
2391         ClickableText *uri = NULL;
2392         
2393         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview->text));
2394
2395         if (x != -1 && y != -1) {
2396                 gint bx, by;
2397                 GtkTextIter iter;
2398                 GSList *tags;
2399                 GSList *cur;
2400                 
2401                 gtk_text_view_window_to_buffer_coords(GTK_TEXT_VIEW(textview->text), 
2402                                                       GTK_TEXT_WINDOW_WIDGET,
2403                                                       x, y, &bx, &by);
2404                 gtk_text_view_get_iter_at_location(GTK_TEXT_VIEW(textview->text),
2405                                                    &iter, bx, by);
2406
2407                 tags = gtk_text_iter_get_tags(&iter);
2408                 for (cur = tags; cur != NULL; cur = cur->next) {
2409                         GtkTextTag *tag = cur->data;
2410                         char *name;
2411
2412                         g_object_get(G_OBJECT(tag), "name", &name, NULL);
2413
2414                         if ((!strcmp(name, "link") || !strcmp(name, "hlink"))
2415                             && textview_get_uri_range(textview, &iter, tag,
2416                                                       &start_iter, &end_iter)) {
2417
2418                                 uri = textview_get_uri_from_range(textview,
2419                                                                   &iter, tag,
2420                                                                   &start_iter,
2421                                                                   &end_iter);
2422                         }
2423                         g_free(name);
2424                         if (uri)
2425                                 break;
2426                 }
2427                 g_slist_free(tags);
2428         }
2429         
2430         if (uri != textview->uri_hover) {
2431                 GdkWindow *window;
2432
2433                 if (textview->uri_hover)
2434                         gtk_text_buffer_remove_tag_by_name(buffer,
2435                                                            "link-hover",
2436                                                            &textview->uri_hover_start_iter,
2437                                                            &textview->uri_hover_end_iter);
2438                     
2439                 textview->uri_hover = uri;
2440                 if (uri) {
2441                         textview->uri_hover_start_iter = start_iter;
2442                         textview->uri_hover_end_iter = end_iter;
2443                 }
2444                 
2445                 window = gtk_text_view_get_window(GTK_TEXT_VIEW(textview->text),
2446                                                   GTK_TEXT_WINDOW_TEXT);
2447                 if (textview->messageview->mainwin->cursor_count == 0) {
2448                         textview_set_cursor(window, uri ? hand_cursor : text_cursor);
2449                 } else {
2450                         textview_set_cursor(window, watch_cursor);
2451                 }
2452
2453                 TEXTVIEW_STATUSBAR_POP(textview);
2454
2455                 if (uri) {
2456                         if (!uri->is_quote)
2457                                 gtk_text_buffer_apply_tag_by_name(buffer,
2458                                                           "link-hover",
2459                                                           &start_iter,
2460                                                           &end_iter);
2461                         TEXTVIEW_STATUSBAR_PUSH(textview, uri->uri);
2462                 }
2463         }
2464 }
2465
2466 static gboolean textview_get_uri_range(TextView *textview,
2467                                        GtkTextIter *iter,
2468                                        GtkTextTag *tag,
2469                                        GtkTextIter *start_iter,
2470                                        GtkTextIter *end_iter)
2471 {
2472         return get_tag_range(iter, tag, start_iter, end_iter);
2473 }
2474
2475 static ClickableText *textview_get_uri_from_range(TextView *textview,
2476                                               GtkTextIter *iter,
2477                                               GtkTextTag *tag,
2478                                               GtkTextIter *start_iter,
2479                                               GtkTextIter *end_iter)
2480 {
2481         gint start_pos, end_pos, cur_pos;
2482         ClickableText *uri = NULL;
2483         GSList *cur;
2484
2485         start_pos = gtk_text_iter_get_offset(start_iter);
2486         end_pos = gtk_text_iter_get_offset(end_iter);
2487         cur_pos = gtk_text_iter_get_offset(iter);
2488
2489         for (cur = textview->uri_list; cur != NULL; cur = cur->next) {
2490                 ClickableText *uri_ = (ClickableText *)cur->data;
2491                 if (start_pos == uri_->start &&
2492                     end_pos ==  uri_->end) {
2493                         uri = uri_;
2494                         break;
2495                 } 
2496         }
2497         for (cur = textview->uri_list; uri == NULL && cur != NULL; cur = cur->next) {
2498                 ClickableText *uri_ = (ClickableText *)cur->data;
2499                 if (start_pos == uri_->start ||
2500                            end_pos == uri_->end) {
2501                         /* in case of contiguous links, textview_get_uri_range
2502                          * returns a broader range (start of 1st link to end
2503                          * of last link).
2504                          * In that case, correct link is the one covering
2505                          * current iter.
2506                          */
2507                         if (uri_->start <= cur_pos && cur_pos <= uri_->end) {
2508                                 uri = uri_;
2509                                 break;
2510                         }
2511                 } 
2512         }
2513
2514         return uri;
2515 }
2516
2517 static ClickableText *textview_get_uri(TextView *textview,
2518                                    GtkTextIter *iter,
2519                                    GtkTextTag *tag)
2520 {
2521         GtkTextIter start_iter, end_iter;
2522         ClickableText *uri = NULL;
2523
2524         if (textview_get_uri_range(textview, iter, tag, &start_iter,
2525                                    &end_iter))
2526                 uri = textview_get_uri_from_range(textview, iter, tag,
2527                                                   &start_iter, &end_iter);
2528
2529         return uri;
2530 }
2531
2532 static void textview_shift_uris_after(TextView *textview, GSList *start_list, gint start, gint shift)
2533 {
2534         GSList *cur;
2535         if (!start_list)
2536                 start_list = textview->uri_list;
2537
2538         for (cur = start_list; cur; cur = cur->next) {
2539                 ClickableText *uri = (ClickableText *)cur->data;
2540                 if (uri->start <= start)
2541                         continue;
2542                 uri->start += shift;
2543                 uri->end += shift;
2544         }
2545 }
2546
2547 static void textview_remove_uris_in(TextView *textview, gint start, gint end)
2548 {
2549         GSList *cur;
2550         for (cur = textview->uri_list; cur; ) {
2551                 ClickableText *uri = (ClickableText *)cur->data;
2552                 if (uri->start > start && uri->end < end) {
2553                         cur = cur->next;
2554                         textview->uri_list = g_slist_remove(textview->uri_list, uri);
2555                         g_free(uri->uri);
2556                         g_free(uri->filename);
2557                         if (uri->is_quote) {
2558                                 g_free(uri->fg_color);
2559                                 g_free(uri->data); 
2560                                 /* (only free data in quotes uris) */
2561                         }
2562                         g_free(uri);
2563                 } else {
2564                         cur = cur->next;
2565                 }
2566                 
2567         }
2568 }
2569
2570 static void textview_toggle_quote(TextView *textview, GSList *start_list, ClickableText *uri, gboolean expand_only)
2571 {
2572         GtkTextIter start, end;
2573         GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview->text));
2574         
2575         if (!uri->is_quote)
2576                 return;
2577         
2578         if (uri->q_expanded && expand_only)
2579                 return;
2580
2581         gtk_text_buffer_get_iter_at_offset(buffer, &start, uri->start);
2582         gtk_text_buffer_get_iter_at_offset(buffer, &end,   uri->end);
2583         if (textview->uri_hover)
2584                 gtk_text_buffer_remove_tag_by_name(buffer,
2585                                                    "link-hover",
2586                                                    &textview->uri_hover_start_iter,
2587                                                    &textview->uri_hover_end_iter);
2588         textview->uri_hover = NULL;
2589         gtk_text_buffer_remove_tag_by_name(buffer,
2590                                            "qlink",
2591                                            &start,
2592                                            &end);
2593         /* when shifting URIs start and end, we have to do it per-UTF8-char
2594          * so use g_utf8_strlen(). OTOH, when inserting in the text buffer, 
2595          * we have to pass a number of bytes, so use strlen(). disturbing. */
2596          
2597         if (!uri->q_expanded) {
2598                 gtk_text_buffer_get_iter_at_offset(buffer, &start, uri->start);
2599                 gtk_text_buffer_get_iter_at_offset(buffer, &end,   uri->end);
2600                 textview_shift_uris_after(textview, start_list, uri->start, 
2601                         g_utf8_strlen((gchar *)uri->data, -1)-strlen(" [...]\n"));
2602                 gtk_text_buffer_delete(buffer, &start, &end);
2603                 gtk_text_buffer_get_iter_at_offset(buffer, &start, uri->start);
2604                 gtk_text_buffer_insert_with_tags_by_name
2605                                 (buffer, &start, (gchar *)uri->data, 
2606                                  strlen((gchar *)uri->data)-1,
2607                                  "qlink", (gchar *)uri->fg_color, NULL);
2608                 uri->end = gtk_text_iter_get_offset(&start);
2609                 textview_make_clickable_parts_later(textview,
2610                                           uri->start, uri->end);
2611                 uri->q_expanded = TRUE;
2612         } else {
2613                 gtk_text_buffer_get_iter_at_offset(buffer, &start, uri->start);
2614                 gtk_text_buffer_get_iter_at_offset(buffer, &end,   uri->end);
2615                 textview_remove_uris_in(textview, uri->start, uri->end);
2616                 textview_shift_uris_after(textview, start_list, uri->start, 
2617                         strlen(" [...]\n")-g_utf8_strlen((gchar *)uri->data, -1));
2618                 gtk_text_buffer_delete(buffer, &start, &end);
2619                 gtk_text_buffer_get_iter_at_offset(buffer, &start, uri->start);
2620                 gtk_text_buffer_insert_with_tags_by_name
2621                                 (buffer, &start, " [...]", -1,
2622                                  "qlink", (gchar *)uri->fg_color, NULL);
2623                 uri->end = gtk_text_iter_get_offset(&start);
2624                 uri->q_expanded = FALSE;
2625         }
2626         if (textview->messageview->mainwin->cursor_count == 0) {
2627                 textview_cursor_normal(textview);
2628         } else {
2629                 textview_cursor_wait(textview);
2630         }
2631 }
2632 static gboolean textview_uri_button_pressed(GtkTextTag *tag, GObject *obj,
2633                                             GdkEvent *event, GtkTextIter *iter,
2634                                             TextView *textview)
2635 {
2636         GdkEventButton *bevent;
2637         ClickableText *uri = NULL;
2638         char *tagname;
2639         gboolean qlink = FALSE;
2640
2641         if (!event)
2642                 return FALSE;
2643
2644         if (event->type != GDK_BUTTON_PRESS && event->type != GDK_2BUTTON_PRESS
2645                 && event->type != GDK_MOTION_NOTIFY)
2646                 return FALSE;
2647
2648         uri = textview_get_uri(textview, iter, tag);
2649         if (!uri)
2650                 return FALSE;
2651
2652         g_object_get(G_OBJECT(tag), "name", &tagname, NULL);
2653         
2654         if (!strcmp(tagname, "qlink"))
2655                 qlink = TRUE;
2656
2657         g_free(tagname);
2658         
2659         bevent = (GdkEventButton *) event;
2660         
2661         /* doubleclick: open compose / add address / browser */
2662         if (qlink && event->type == GDK_BUTTON_PRESS && bevent->button != 1) {
2663                 /* pass rightclick through */
2664                 return FALSE;
2665         } else if ((event->type == (qlink ? GDK_2BUTTON_PRESS:GDK_BUTTON_PRESS) && bevent->button == 1) ||
2666                 bevent->button == 2 || bevent->button == 3) {
2667                 if (uri->filename && !g_ascii_strncasecmp(uri->filename, "sc://", 5)) {
2668                         MimeView *mimeview = 
2669                                 (textview->messageview)?
2670                                         textview->messageview->mimeview:NULL;
2671                         if (mimeview && bevent->button == 1) {
2672                                 mimeview_handle_cmd(mimeview, uri->filename, NULL, uri->data);
2673                         } else if (mimeview && bevent->button == 2 && 
2674                                 !g_ascii_strcasecmp(uri->filename, "sc://select_attachment")) {
2675                                 mimeview_handle_cmd(mimeview, "sc://open_attachment", NULL, uri->data);
2676                         } else if (mimeview && bevent->button == 3 && 
2677                                 !g_ascii_strcasecmp(uri->filename, "sc://select_attachment")) {
2678                                 mimeview_handle_cmd(mimeview, "sc://menu_attachment", bevent, uri->data);
2679                         } 
2680                         return TRUE;
2681                 } else if (qlink && bevent->button == 1) {
2682                         if (prefs_common.hide_quoted)
2683                                 textview_toggle_quote(textview, NULL, uri, FALSE);
2684                         return TRUE;
2685                 } else if (!g_ascii_strncasecmp(uri->uri, "mailto:", 7)) {
2686                         if (bevent->button == 3) {
2687                                 g_object_set_data(
2688                                         G_OBJECT(textview->mail_popup_menu),
2689                                         "menu_button", uri);
2690                                 gtk_menu_popup(GTK_MENU(textview->mail_popup_menu), 
2691                                                NULL, NULL, NULL, NULL, 
2692                                                bevent->button, bevent->time);
2693                         } else {
2694                                 PrefsAccount *account = NULL;
2695                                 FolderItem   *folder_item = NULL;
2696                                 Compose *compose;
2697                                 
2698                                 if (textview->messageview && textview->messageview->msginfo &&
2699                                     textview->messageview->msginfo->folder) {
2700                                         
2701
2702                                         folder_item = textview->messageview->msginfo->folder;
2703                                         if (folder_item->prefs && folder_item->prefs->enable_default_account)
2704                                                 account = account_find_from_id(folder_item->prefs->default_account);
2705                                         if (!account)
2706                                                 account = account_find_from_item(folder_item);
2707                                 }
2708                                 compose = compose_new_with_folderitem(account,
2709                                                                 folder_item, uri->uri + 7);
2710                                 compose_check_for_email_account(compose);
2711                         }
2712                         return TRUE;
2713                 } else if (g_ascii_strncasecmp(uri->uri, "file:", 5)) {
2714                         if (bevent->button == 1 &&
2715                             textview_uri_security_check(textview, uri) == TRUE) 
2716                                         open_uri(uri->uri,
2717                                                  prefs_common_get_uri_cmd());
2718                         else if (bevent->button == 3 && !qlink) {
2719                                 g_object_set_data(
2720                                         G_OBJECT(textview->link_popup_menu),
2721                                         "menu_button", uri);
2722                                 gtk_menu_popup(GTK_MENU(textview->link_popup_menu), 
2723                                                NULL, NULL, NULL, NULL, 
2724                                                bevent->button, bevent->time);
2725                         }
2726                         return TRUE;
2727                 } else {
2728                         if (bevent->button == 3 && !qlink) {
2729                                 g_object_set_data(
2730                                         G_OBJECT(textview->file_popup_menu),
2731                                         "menu_button", uri);
2732                                 gtk_menu_popup(GTK_MENU(textview->file_popup_menu), 
2733                                                NULL, NULL, NULL, NULL, 
2734                                                bevent->button, bevent->time);
2735                                 return TRUE;
2736                         }
2737                 }
2738         }
2739
2740         return FALSE;
2741 }
2742
2743 gchar *textview_get_visible_uri         (TextView       *textview, 
2744                                          ClickableText  *uri)
2745 {
2746         GtkTextBuffer *buffer;
2747         GtkTextIter start, end;
2748
2749         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview->text));
2750
2751         gtk_text_buffer_get_iter_at_offset(buffer, &start, uri->start);
2752         gtk_text_buffer_get_iter_at_offset(buffer, &end,   uri->end);
2753
2754         return gtk_text_buffer_get_text(buffer, &start, &end, FALSE);
2755 }
2756
2757 /*!
2758  *\brief    Check to see if a web URL has been disguised as a different
2759  *          URL (possible with HTML email).
2760  *
2761  *\param    uri The uri to check
2762  *
2763  *\param    textview The TextView the URL is contained in
2764  *
2765  *\return   gboolean TRUE if the URL is ok, or if the user chose to open
2766  *          it anyway, otherwise FALSE          
2767  */
2768 gboolean textview_uri_security_check(TextView *textview, ClickableText *uri)
2769 {
2770         gchar *visible_str;
2771         gboolean retval = TRUE;
2772
2773         if (is_uri_string(uri->uri) == FALSE)
2774                 return TRUE;
2775
2776         visible_str = textview_get_visible_uri(textview, uri);
2777         if (visible_str == NULL)
2778                 return TRUE;
2779
2780         g_strstrip(visible_str);
2781
2782         if (strcmp(visible_str, uri->uri) != 0 && is_uri_string(visible_str)) {
2783                 gchar *uri_path;
2784                 gchar *visible_uri_path;
2785
2786                 uri_path = get_uri_path(uri->uri);
2787                 visible_uri_path = get_uri_path(visible_str);
2788                 if (path_cmp(uri_path, visible_uri_path) != 0)
2789                         retval = FALSE;
2790         }
2791
2792         if (retval == FALSE) {
2793                 gchar *msg;
2794                 AlertValue aval;
2795
2796                 msg = g_markup_printf_escaped(_("The real URL is different from "
2797                                                 "the displayed URL.\n"
2798                                                 "\n"
2799                                                 "<b>Displayed URL:</b> %s\n"
2800                                                 "\n"
2801                                                 "<b>Real URL:</b> %s\n"
2802                                                 "\n"
2803                                                 "Open it anyway?"),
2804                                                visible_str,uri->uri);
2805                 aval = alertpanel_full(_("Phishing attempt warning"), msg,
2806                                        GTK_STOCK_CANCEL, _("_Open URL"), NULL, FALSE,
2807                                        NULL, ALERT_WARNING, G_ALERTDEFAULT);
2808                 g_free(msg);
2809                 if (aval == G_ALERTALTERNATE)
2810                         retval = TRUE;
2811         }
2812
2813         g_free(visible_str);
2814
2815         return retval;
2816 }
2817
2818 static void textview_uri_list_remove_all(GSList *uri_list)
2819 {
2820         GSList *cur;
2821
2822         for (cur = uri_list; cur != NULL; cur = cur->next) {
2823                 if (cur->data) {
2824                         g_free(((ClickableText *)cur->data)->uri);
2825                         g_free(((ClickableText *)cur->data)->filename);
2826                         if (((ClickableText *)cur->data)->is_quote) {
2827                                 g_free(((ClickableText *)cur->data)->fg_color);
2828                                 g_free(((ClickableText *)cur->data)->data); 
2829                                 /* (only free data in quotes uris) */
2830                         }
2831                         g_free(cur->data);
2832                 }
2833         }
2834
2835         g_slist_free(uri_list);
2836 }
2837
2838 static void open_uri_cb (GtkAction *action, TextView *textview)
2839 {
2840         ClickableText *uri = g_object_get_data(G_OBJECT(textview->link_popup_menu),
2841                                            "menu_button");
2842         const gchar *raw_url = g_object_get_data(G_OBJECT(textview->link_popup_menu),
2843                                            "raw_url");
2844
2845         if (uri) {
2846                 if (textview_uri_security_check(textview, uri) == TRUE) 
2847                         open_uri(uri->uri,
2848                                  prefs_common_get_uri_cmd());
2849                 g_object_set_data(G_OBJECT(textview->link_popup_menu), "menu_button",
2850                                   NULL);
2851         }
2852         if (raw_url) {
2853                 open_uri(raw_url, prefs_common_get_uri_cmd());
2854                 g_object_set_data(G_OBJECT(textview->link_popup_menu), "raw_url",
2855                                   NULL);
2856         }
2857 }
2858
2859 static void open_image_cb (GtkAction *action, TextView *textview)
2860 {
2861         ClickableText *uri = g_object_get_data(G_OBJECT(textview->file_popup_menu),
2862                                            "menu_button");
2863
2864         gchar *cmd = NULL;
2865         gchar buf[1024];
2866         const gchar *p;
2867         gchar *filename = NULL;
2868         gchar *tmp_filename = NULL;
2869
2870         if (uri == NULL)
2871                 return;
2872
2873         if (uri->filename == NULL)
2874                 return;
2875         
2876         filename = g_strdup(uri->filename);
2877         
2878         if (!g_utf8_validate(filename, -1, NULL)) {
2879                 gchar *tmp = conv_filename_to_utf8(filename);
2880                 g_free(filename);
2881                 filename = tmp;
2882         }
2883
2884         subst_for_filename(filename);
2885
2886         tmp_filename = g_filename_from_uri(uri->uri, NULL, NULL);
2887         copy_file(tmp_filename, filename, FALSE);
2888         g_free(tmp_filename);
2889
2890         cmd = mailcap_get_command_for_type("image/jpeg", filename);
2891         if (cmd == NULL) {
2892                 gboolean remember = FALSE;
2893                 cmd = input_dialog_combo_remember
2894                         (_("Open with"),
2895                          _("Enter the command-line to open file:\n"
2896                            "('%s' will be replaced with file name)"),
2897                          prefs_common.mime_open_cmd,
2898                          prefs_common.mime_open_cmd_history,
2899                          &remember);
2900                 if (cmd && remember) {
2901                         mailcap_update_default("image/jpeg", cmd);
2902                 }
2903         }
2904         if (cmd && (p = strchr(cmd, '%')) && *(p + 1) == 's' &&
2905             !strchr(p + 2, '%'))
2906                 g_snprintf(buf, sizeof(buf), cmd, filename);
2907         else {
2908                 g_warning("Image viewer command-line is invalid: '%s'", cmd);
2909                 return;
2910         }
2911
2912         execute_command_line(buf, TRUE);
2913
2914         g_free(filename);
2915         g_free(cmd);
2916
2917         g_object_set_data(G_OBJECT(textview->file_popup_menu), "menu_button",
2918                           NULL);
2919 }
2920
2921 static void save_file_cb (GtkAction *action, TextView *textview)
2922 {
2923         ClickableText *uri = g_object_get_data(G_OBJECT(textview->file_popup_menu),
2924                                            "menu_button");
2925         gchar *filename = NULL;
2926         gchar *filepath = NULL;
2927         gchar *filedir = NULL;
2928         gchar *tmp_filename = NULL;
2929         if (uri == NULL)
2930                 return;
2931
2932         if (uri->filename == NULL)
2933                 return;
2934         
2935         filename = g_strdup(uri->filename);
2936         
2937         if (!g_utf8_validate(filename, -1, NULL)) {
2938                 gchar *tmp = conv_filename_to_utf8(filename);
2939                 g_free(filename);
2940                 filename = tmp;
2941         }
2942
2943         subst_for_filename(filename);
2944         
2945         if (prefs_common.attach_save_dir && *prefs_common.attach_save_dir)
2946                 filepath = g_strconcat(prefs_common.attach_save_dir,
2947                                        G_DIR_SEPARATOR_S, filename, NULL);
2948         else
2949                 filepath = g_strdup(filename);
2950
2951         g_free(filename);
2952
2953         filename = filesel_select_file_save(_("Save as"), filepath);
2954         if (!filename) {
2955                 g_free(filepath);
2956                 return;
2957         }
2958
2959         if (is_file_exist(filename)) {
2960                 AlertValue aval;
2961                 gchar *res;
2962                 
2963                 res = g_strdup_printf(_("Overwrite existing file '%s'?"),
2964                                       filename);
2965                 aval = alertpanel(_("Overwrite"), res, GTK_STOCK_CANCEL, 
2966                                   GTK_STOCK_OK, NULL);
2967                 g_free(res);                                      
2968                 if (G_ALERTALTERNATE != aval)
2969                         return;
2970         }
2971
2972         tmp_filename = g_filename_from_uri(uri->uri, NULL, NULL);
2973         copy_file(tmp_filename, filename, FALSE);
2974         g_free(tmp_filename);
2975         
2976         filedir = g_path_get_dirname(filename);
2977         if (filedir && strcmp(filedir, ".")) {
2978                 g_free(prefs_common.attach_save_dir);
2979                 prefs_common.attach_save_dir = g_filename_to_utf8(filedir, -1, NULL, NULL, NULL);
2980         }
2981
2982         g_free(filedir);
2983         g_free(filepath);
2984
2985         g_object_set_data(G_OBJECT(textview->file_popup_menu), "menu_button",
2986                           NULL);
2987 }
2988
2989 static void copy_uri_cb (GtkAction *action, TextView *textview)
2990 {
2991         ClickableText *uri = g_object_get_data(G_OBJECT(textview->link_popup_menu),
2992                                            "menu_button");
2993         const gchar *raw_url =  g_object_get_data(G_OBJECT(textview->link_popup_menu),
2994                                            "raw_url");
2995         if (uri) {
2996                 gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), uri->uri, -1);
2997                 gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), uri->uri, -1);
2998                 g_object_set_data(G_OBJECT(textview->link_popup_menu), "menu_button",
2999                           NULL);
3000         }
3001         if (raw_url) {
3002                 gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), raw_url, -1);
3003                 gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), raw_url, -1);
3004                 g_object_set_data(G_OBJECT(textview->link_popup_menu), "raw_url",
3005                           NULL);
3006         }
3007 }
3008
3009 static void add_uri_to_addrbook_cb (GtkAction *action, TextView *textview)
3010 {
3011         gchar *fromname, *fromaddress;
3012         ClickableText *uri = g_object_get_data(G_OBJECT(textview->mail_popup_menu),
3013                                            "menu_button");
3014         GtkWidget *image = NULL;
3015         GdkPixbuf *picture = NULL;
3016         gboolean use_picture = FALSE;
3017         if (uri == NULL)
3018                 return;
3019
3020         /* extract url */
3021         fromaddress = g_strdup(uri->uri + 7);
3022         
3023         if (textview->messageview->msginfo &&
3024            !strcmp2(fromaddress, textview->messageview->msginfo->from))
3025                 use_picture = TRUE;
3026
3027         fromname = procheader_get_fromname(fromaddress);
3028         extract_address(fromaddress);
3029
3030         if (use_picture && 
3031             textview->messageview->msginfo &&
3032             textview->messageview->msginfo->extradata &&
3033             textview->messageview->msginfo->extradata->face) {
3034                 image = face_get_from_header(textview->messageview->msginfo->extradata->face);
3035         }
3036 #if HAVE_LIBCOMPFACE 
3037         else if (use_picture && 
3038                  textview->messageview->msginfo &&
3039                  textview->messageview->msginfo->extradata &&
3040                  textview->messageview->msginfo->extradata->xface) {
3041                 image = xface_get_from_header(textview->messageview->msginfo->extradata->xface,
3042                                 &textview->text->style->white,
3043                                 mainwindow_get_mainwindow()->window->window);   
3044         }
3045 #endif
3046         if (image)
3047                 picture = gtk_image_get_pixbuf(GTK_IMAGE(image));
3048
3049         addressbook_add_contact( fromname, fromaddress, NULL, picture);
3050
3051         g_free(fromaddress);
3052         g_free(fromname);
3053 }
3054
3055 static void reply_to_uri_cb (GtkAction *action, TextView *textview)
3056 {
3057         ClickableText *uri = g_object_get_data(G_OBJECT(textview->mail_popup_menu),
3058                                            "menu_button");
3059         if (!textview->messageview || !uri)
3060                 return;
3061
3062         compose_reply_to_address (textview->messageview,
3063                                   textview->messageview->msginfo, uri->uri+7);
3064 }
3065
3066 static void mail_to_uri_cb (GtkAction *action, TextView *textview)
3067 {
3068         PrefsAccount *account = NULL;
3069         Compose *compose;
3070         ClickableText *uri = g_object_get_data(G_OBJECT(textview->mail_popup_menu),
3071                                            "menu_button");
3072         if (uri == NULL)
3073                 return;
3074
3075         if (textview->messageview && textview->messageview->msginfo &&
3076             textview->messageview->msginfo->folder) {
3077                 FolderItem   *folder_item;
3078
3079                 folder_item = textview->messageview->msginfo->folder;
3080                 if (folder_item->prefs && folder_item->prefs->enable_default_account)
3081                         account = account_find_from_id(folder_item->prefs->default_account);
3082                 
3083                 compose = compose_new_with_folderitem(account, folder_item, uri->uri+7);
3084         } else {
3085                 compose = compose_new(account, uri->uri + 7, NULL);
3086         }
3087         compose_check_for_email_account(compose);
3088 }
3089
3090 static void copy_mail_to_uri_cb (GtkAction *action, TextView *textview)
3091 {
3092         ClickableText *uri = g_object_get_data(G_OBJECT(textview->mail_popup_menu),
3093                                            "menu_button");
3094         if (uri == NULL)
3095                 return;
3096
3097         gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), uri->uri +7, -1);
3098         gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), uri->uri +7, -1);
3099         g_object_set_data(G_OBJECT(textview->mail_popup_menu), "menu_button",
3100                           NULL);
3101 }
3102
3103 void textview_get_selection_offsets(TextView *textview, gint *sel_start, gint *sel_end)
3104 {
3105                 GtkTextView *text = GTK_TEXT_VIEW(textview->text);
3106                 GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
3107                 GtkTextIter start, end;
3108                 if (gtk_text_buffer_get_selection_bounds(buffer, &start, &end)) {
3109                         if (sel_start)
3110                                 *sel_start = gtk_text_iter_get_offset(&start);
3111                         if (sel_end)
3112                                 *sel_end = gtk_text_iter_get_offset(&end);
3113                 } else {
3114                         if (sel_start)
3115                                 *sel_start = -1;
3116                         if (sel_end)
3117                                 *sel_end = -1;
3118                 }
3119 }