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