5226e208f8f50d5bc85f3fc6d9a256eb1373fa23
[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-Sylpheed-Privacy-System:", "X-Sylpheed-End-Special-Headers:",
1768                  NULL};
1769         int i;
1770         
1771         for (i = 0; internal_hdrs[i]; i++) {
1772                 if (!strcmp(header->name, internal_hdrs[i]))
1773                         return TRUE;
1774         }
1775         return FALSE;
1776 }
1777
1778 static GPtrArray *textview_scan_header(TextView *textview, FILE *fp)
1779 {
1780         gchar buf[BUFFSIZE];
1781         GPtrArray *headers, *sorted_headers;
1782         GSList *disphdr_list;
1783         Header *header;
1784         gint i;
1785
1786         cm_return_val_if_fail(fp != NULL, NULL);
1787
1788         if (textview->show_all_headers) {
1789                 headers = procheader_get_header_array_asis(fp);
1790                 sorted_headers = g_ptr_array_new();
1791                 for (i = 0; i < headers->len; i++) {
1792                         header = g_ptr_array_index(headers, i);
1793                         if (!header_is_internal(header))
1794                                 g_ptr_array_add(sorted_headers, header);
1795                         else
1796                                 procheader_header_free(header);
1797                 }
1798                 g_ptr_array_free(headers, TRUE);
1799                 return sorted_headers;
1800         }
1801
1802         if (!prefs_common.display_header) {
1803                 while (fgets(buf, sizeof(buf), fp) != NULL)
1804                         if (buf[0] == '\r' || buf[0] == '\n') break;
1805                 return NULL;
1806         }
1807
1808         headers = procheader_get_header_array_asis(fp);
1809
1810         sorted_headers = g_ptr_array_new();
1811
1812         for (disphdr_list = prefs_common.disphdr_list; disphdr_list != NULL;
1813              disphdr_list = disphdr_list->next) {
1814                 DisplayHeaderProp *dp =
1815                         (DisplayHeaderProp *)disphdr_list->data;
1816
1817                 for (i = 0; i < headers->len; i++) {
1818                         header = g_ptr_array_index(headers, i);
1819
1820                         if (procheader_headername_equal(header->name,
1821                                                         dp->name)) {
1822                                 if (dp->hidden)
1823                                         procheader_header_free(header);
1824                                 else
1825                                         g_ptr_array_add(sorted_headers, header);
1826
1827                                 g_ptr_array_remove_index(headers, i);
1828                                 i--;
1829                         }
1830                 }
1831         }
1832
1833         if (prefs_common.show_other_header) {
1834                 for (i = 0; i < headers->len; i++) {
1835                         header = g_ptr_array_index(headers, i);
1836                         if (!header_is_internal(header)) {
1837                                 g_ptr_array_add(sorted_headers, header);
1838                         } else {
1839                                 procheader_header_free(header);
1840                         }
1841                 }
1842                 g_ptr_array_free(headers, TRUE);
1843         } else
1844                 procheader_header_array_destroy(headers);
1845
1846
1847         return sorted_headers;
1848 }
1849
1850 static void textview_show_face(TextView *textview)
1851 {
1852         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1853         MsgInfo *msginfo = textview->messageview->msginfo;
1854         int x = 0;
1855         
1856         if (prefs_common.display_header_pane
1857         ||  !prefs_common.display_xface)
1858                 goto bail;
1859         
1860         if (!msginfo->extradata || !msginfo->extradata->face) {
1861                 goto bail;
1862         }
1863
1864         if (textview->image) 
1865                 gtk_widget_destroy(textview->image);
1866         
1867         textview->image = face_get_from_header(msginfo->extradata->face);
1868         cm_return_if_fail(textview->image != NULL);
1869
1870         gtk_widget_show(textview->image);
1871         
1872         x = textview->text->allocation.width - WIDTH -5;
1873
1874         gtk_text_view_add_child_in_window(text, textview->image, 
1875                 GTK_TEXT_WINDOW_TEXT, x, 5);
1876
1877         gtk_widget_show_all(textview->text);
1878         
1879
1880         return;
1881 bail:
1882         if (textview->image) 
1883                 gtk_widget_destroy(textview->image);
1884         textview->image = NULL; 
1885 }
1886
1887 void textview_show_icon(TextView *textview, const gchar *stock_id)
1888 {
1889         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1890         int x = 0;
1891         
1892         if (textview->image) 
1893                 gtk_widget_destroy(textview->image);
1894         
1895         textview->image = gtk_image_new_from_stock(stock_id, GTK_ICON_SIZE_DIALOG);
1896         cm_return_if_fail(textview->image != NULL);
1897
1898         gtk_widget_show(textview->image);
1899         
1900         x = textview->text->allocation.width - WIDTH -5;
1901
1902         gtk_text_view_add_child_in_window(text, textview->image, 
1903                 GTK_TEXT_WINDOW_TEXT, x, 5);
1904
1905         gtk_widget_show_all(textview->text);
1906         
1907
1908         return;
1909 }
1910
1911 #if HAVE_LIBCOMPFACE
1912 static void textview_show_xface(TextView *textview)
1913 {
1914         MsgInfo *msginfo = textview->messageview->msginfo;
1915         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1916         int x = 0;
1917         GdkWindow *window = NULL;
1918         
1919         if (prefs_common.display_header_pane
1920         ||  !prefs_common.display_xface)
1921                 goto bail;
1922         
1923         if (!msginfo || !msginfo->extradata)
1924                 goto bail;
1925
1926         if (msginfo->extradata->face)
1927                 return;
1928         
1929         if (!msginfo->extradata->xface || strlen(msginfo->extradata->xface) < 5) {
1930                 goto bail;
1931         }
1932
1933         if (textview->image) 
1934                 gtk_widget_destroy(textview->image);
1935
1936         window = mainwindow_get_mainwindow() ?
1937                         mainwindow_get_mainwindow()->window->window :
1938                         textview->text->window;
1939         textview->image = xface_get_from_header(msginfo->extradata->xface,
1940                                 &textview->text->style->white,
1941                                 window);
1942         cm_return_if_fail(textview->image != NULL);
1943
1944         gtk_widget_show(textview->image);
1945         
1946         x = textview->text->allocation.width - WIDTH -5;
1947
1948         gtk_text_view_add_child_in_window(text, textview->image, 
1949                 GTK_TEXT_WINDOW_TEXT, x, 5);
1950
1951         gtk_widget_show_all(textview->text);
1952         
1953         return;
1954 bail:
1955         if (textview->image) 
1956                 gtk_widget_destroy(textview->image);
1957         textview->image = NULL;
1958         
1959 }
1960 #endif
1961
1962 static void textview_save_contact_pic(TextView *textview)
1963 {
1964         MsgInfo *msginfo = textview->messageview->msginfo;
1965         gchar *filename = NULL;
1966         GError *error = NULL;
1967         GdkPixbuf *picture = NULL;
1968                                 
1969         if (!msginfo->extradata || (!msginfo->extradata->face && !msginfo->extradata->xface))
1970                 return;
1971
1972         if (textview->image) 
1973                 picture = gtk_image_get_pixbuf(GTK_IMAGE(textview->image));
1974
1975         filename = addrindex_get_picture_file(msginfo->from);
1976         if (!filename)
1977                 return;
1978         if (!is_file_exist(filename)) {
1979                 gdk_pixbuf_save(picture, filename, "png", &error, NULL);
1980                 if (error) {
1981                         g_warning(_("Failed to save image: \n%s"),
1982                                         error->message);
1983                         g_error_free(error);
1984                 }
1985         }
1986         g_free(filename);
1987 }
1988
1989 static void textview_show_contact_pic(TextView *textview)
1990 {
1991         MsgInfo *msginfo = textview->messageview->msginfo;
1992         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1993         int x = 0;
1994         gchar *filename = NULL;
1995         GError *error = NULL;
1996         GdkPixbuf *picture = NULL;
1997         gint w, h;
1998                                 
1999         if (prefs_common.display_header_pane
2000         ||  !prefs_common.display_xface)
2001                 goto bail;
2002         
2003         if (msginfo->extradata && (msginfo->extradata->face || msginfo->extradata->xface))
2004                 return;
2005
2006         if (textview->image) 
2007                 gtk_widget_destroy(textview->image);
2008
2009         filename = addrindex_get_picture_file(msginfo->from);
2010         
2011         if (!filename)
2012                 goto bail;
2013         if (!is_file_exist(filename)) {
2014                 g_free(filename);
2015                 goto bail;
2016         }
2017
2018         gdk_pixbuf_get_file_info(filename, &w, &h);
2019         
2020         if (w > 48 || h > 48)
2021                 picture = gdk_pixbuf_new_from_file_at_scale(filename, 
2022                                                 48, 48, TRUE, &error);
2023         else
2024                 picture = gdk_pixbuf_new_from_file(filename, &error);
2025
2026         if (error) {
2027                 debug_print("Failed to import image: \n%s",
2028                                 error->message);
2029                 g_error_free(error);
2030                 goto bail;
2031         }
2032         g_free(filename);
2033
2034         if (picture) {
2035                 textview->image = gtk_image_new_from_pixbuf(picture);
2036                 g_object_unref(picture);
2037         }
2038         cm_return_if_fail(textview->image != NULL);
2039
2040         gtk_widget_show(textview->image);
2041         
2042         x = textview->text->allocation.width - WIDTH -5;
2043
2044         gtk_text_view_add_child_in_window(text, textview->image, 
2045                 GTK_TEXT_WINDOW_TEXT, x, 5);
2046
2047         gtk_widget_show_all(textview->text);
2048         
2049         return;
2050 bail:
2051         if (textview->image) 
2052                 gtk_widget_destroy(textview->image);
2053         textview->image = NULL;
2054         
2055 }
2056
2057 static gint textview_tag_cmp_list(gconstpointer a, gconstpointer b)
2058 {
2059         gint id_a = GPOINTER_TO_INT(a);
2060         gint id_b = GPOINTER_TO_INT(b);
2061         const gchar *tag_a = tags_get_tag(id_a);
2062         const gchar *tag_b = tags_get_tag(id_b);
2063         
2064         if (tag_a == NULL)
2065                 return tag_b == NULL ? 0:1;
2066         
2067         if (tag_b == NULL)
2068                 return tag_a == NULL ? 0:1;
2069
2070         return g_utf8_collate(tag_a, tag_b);
2071 }
2072
2073
2074 static void textview_show_tags(TextView *textview)
2075 {
2076         MsgInfo *msginfo = textview->messageview->msginfo;
2077         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
2078         GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
2079         GtkTextIter iter;
2080         ClickableText *uri;
2081         GSList *cur, *orig;
2082         gboolean found_tag = FALSE;
2083         
2084         if (!msginfo->tags)
2085                 return;
2086         
2087         cur = orig = g_slist_sort(g_slist_copy(msginfo->tags), textview_tag_cmp_list);
2088
2089         for (; cur; cur = cur->next) {
2090                 if (tags_get_tag(GPOINTER_TO_INT(cur->data)) != NULL) {
2091                         found_tag = TRUE;
2092                         break;
2093                 }
2094         }
2095         if (!found_tag) {
2096                 g_slist_free(orig);
2097                 return;
2098         }
2099
2100         gtk_text_buffer_get_end_iter (buffer, &iter);
2101         gtk_text_buffer_insert_with_tags_by_name(buffer,
2102                 &iter, _("Tags: "), -1,
2103                 "header_title", "header", "tags", NULL);
2104
2105         for (cur = orig; cur; cur = cur->next) {
2106                 const gchar *cur_tag = tags_get_tag(GPOINTER_TO_INT(cur->data));
2107                 if (!cur_tag)
2108                         continue;
2109                 uri = g_new0(ClickableText, 1);
2110                 uri->uri = g_strdup("");
2111                 uri->start = gtk_text_iter_get_offset(&iter);
2112                 gtk_text_buffer_insert_with_tags_by_name(buffer, &iter, 
2113                         cur_tag, -1,
2114                         "link", "header", "tags", NULL);
2115                 uri->end = gtk_text_iter_get_offset(&iter);
2116                 uri->filename = g_strdup_printf("sc://search_tags:%s", cur_tag);
2117                 uri->data = NULL;
2118                 textview->uri_list =
2119                         g_slist_prepend(textview->uri_list, uri);
2120                 if (cur->next && tags_get_tag(GPOINTER_TO_INT(cur->next->data)))
2121                         gtk_text_buffer_insert_with_tags_by_name(buffer, &iter, ", ", 2,
2122                                 "header", "tags", NULL);
2123                 else
2124                         gtk_text_buffer_insert_with_tags_by_name(buffer, &iter, " ", 1,
2125                                 "header", "tags", NULL);
2126         }
2127         g_slist_free(orig);
2128
2129         gtk_text_buffer_insert_with_tags_by_name(buffer, &iter, "\n", 1,
2130                 "header", "tags", NULL);
2131 }
2132
2133 static void textview_show_header(TextView *textview, GPtrArray *headers)
2134 {
2135         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
2136         GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
2137         GtkTextIter iter;
2138         Header *header;
2139         gint i;
2140
2141         cm_return_if_fail(headers != NULL);
2142
2143         for (i = 0; i < headers->len; i++) {
2144                 header = g_ptr_array_index(headers, i);
2145                 cm_return_if_fail(header->name != NULL);
2146
2147                 gtk_text_buffer_get_end_iter (buffer, &iter);
2148                 if(prefs_common.trans_hdr == TRUE) {
2149                         gchar *hdr = g_strndup(header->name, strlen(header->name) - 1);
2150                         gchar *trans_hdr = gettext(hdr);
2151                         gtk_text_buffer_insert_with_tags_by_name(buffer,
2152                                 &iter, trans_hdr, -1,
2153                                 "header_title", "header", NULL);
2154                         gtk_text_buffer_insert_with_tags_by_name(buffer,
2155                                 &iter, ":", 1, "header_title", "header", NULL);
2156                         g_free(hdr);
2157                 } else {
2158                         gtk_text_buffer_insert_with_tags_by_name(buffer,
2159                                 &iter, header->name,
2160                                 -1, "header_title", "header", NULL);
2161                 }
2162                 if (header->name[strlen(header->name) - 1] != ' ')
2163                 gtk_text_buffer_insert_with_tags_by_name
2164                                 (buffer, &iter, " ", 1,
2165                                  "header_title", "header", NULL);
2166
2167                 if (procheader_headername_equal(header->name, "Subject") ||
2168                     procheader_headername_equal(header->name, "From")    ||
2169                     procheader_headername_equal(header->name, "To")      ||
2170                     procheader_headername_equal(header->name, "Cc"))
2171                         unfold_line(header->body);
2172
2173                 if ((procheader_headername_equal(header->name, "X-Mailer") ||
2174                      procheader_headername_equal(header->name,
2175                                                  "X-Newsreader")) &&
2176                     (strstr(header->body, "Claws Mail") != NULL ||
2177                      strstr(header->body, "Sylpheed-Claws") != NULL)) {
2178                         gtk_text_buffer_get_end_iter (buffer, &iter);
2179                         gtk_text_buffer_insert_with_tags_by_name
2180                                 (buffer, &iter, header->body, -1,
2181                                  "header", "emphasis", NULL);
2182                 } else {
2183                         gboolean hdr = 
2184                           procheader_headername_equal(header->name, "From") ||
2185                           procheader_headername_equal(header->name, "To") ||
2186                           procheader_headername_equal(header->name, "Cc") ||
2187                           procheader_headername_equal(header->name, "Bcc") ||
2188                           procheader_headername_equal(header->name, "Reply-To") ||
2189                           procheader_headername_equal(header->name, "Sender");
2190                         textview_make_clickable_parts(textview, "header", 
2191                                                       "hlink", header->body, 
2192                                                       hdr);
2193                 }
2194                 gtk_text_buffer_get_end_iter (buffer, &iter);
2195                 gtk_text_buffer_insert_with_tags_by_name(buffer, &iter, "\n", 1,
2196                                                          "header", NULL);
2197         }
2198         
2199         textview_show_face(textview);
2200 #if HAVE_LIBCOMPFACE
2201         textview_show_xface(textview);
2202 #endif
2203         textview_save_contact_pic(textview);
2204         textview_show_contact_pic(textview);
2205 }
2206
2207 gboolean textview_search_string(TextView *textview, const gchar *str,
2208                                 gboolean case_sens)
2209 {
2210         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
2211
2212         return gtkut_text_view_search_string(text, str, case_sens);
2213 }
2214
2215 gboolean textview_search_string_backward(TextView *textview, const gchar *str,
2216                                          gboolean case_sens)
2217 {
2218         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
2219
2220         return gtkut_text_view_search_string_backward(text, str, case_sens);
2221 }
2222
2223 void textview_scroll_one_line(TextView *textview, gboolean up)
2224 {
2225         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
2226         GtkAdjustment *vadj = text->vadjustment;
2227
2228         gtkutils_scroll_one_line(GTK_WIDGET(text), vadj, up);
2229 }
2230
2231 gboolean textview_scroll_page(TextView *textview, gboolean up)
2232 {
2233         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
2234         GtkAdjustment *vadj = text->vadjustment;
2235
2236         return gtkutils_scroll_page(GTK_WIDGET(text), vadj, up);
2237 }
2238
2239 #define KEY_PRESS_EVENT_STOP() \
2240         g_signal_stop_emission_by_name(G_OBJECT(widget), \
2241                                        "key_press_event");
2242
2243 static gint textview_key_pressed(GtkWidget *widget, GdkEventKey *event,
2244                                  TextView *textview)
2245 {
2246         SummaryView *summaryview = NULL;
2247         MessageView *messageview = textview->messageview;
2248
2249         if (!event) return FALSE;
2250         if (messageview->mainwin)
2251                 summaryview = messageview->mainwin->summaryview;
2252
2253         switch (event->keyval) {
2254         case GDK_Tab:
2255         case GDK_Home:
2256         case GDK_Left:
2257         case GDK_Up:
2258         case GDK_Right:
2259         case GDK_Down:
2260         case GDK_Page_Up:
2261         case GDK_Page_Down:
2262         case GDK_End:
2263         case GDK_Control_L:
2264         case GDK_Control_R:
2265                 return FALSE;
2266         case GDK_space:
2267                 if (summaryview)
2268                         summary_pass_key_press_event(summaryview, event);
2269                 else
2270                         mimeview_scroll_page
2271                                 (messageview->mimeview,
2272                                  (event->state &
2273                                   (GDK_SHIFT_MASK|GDK_MOD1_MASK)) != 0);
2274                 break;
2275         case GDK_BackSpace:
2276                 mimeview_scroll_page(messageview->mimeview, TRUE);
2277                 break;
2278         case GDK_Return:
2279         case GDK_KP_Enter:
2280                 mimeview_scroll_one_line
2281                         (messageview->mimeview, (event->state &
2282                                     (GDK_SHIFT_MASK|GDK_MOD1_MASK)) != 0);
2283                 break;
2284         case GDK_Delete:
2285                 if (summaryview)
2286                         summary_pass_key_press_event(summaryview, event);
2287                 break;
2288         case GDK_y:
2289         case GDK_t:
2290         case GDK_l:
2291         case GDK_o:
2292         case GDK_c:
2293         case GDK_a:
2294                 if ((event->state & (GDK_MOD1_MASK|GDK_CONTROL_MASK)) == 0) {
2295                         KEY_PRESS_EVENT_STOP();
2296                         mimeview_pass_key_press_event(messageview->mimeview,
2297                                                       event);
2298                         break;
2299                 }
2300                 /* possible fall through */
2301         default:
2302                 if (summaryview &&
2303                     event->window != messageview->mainwin->window->window) {
2304                         GdkEventKey tmpev = *event;
2305
2306                         tmpev.window = messageview->mainwin->window->window;
2307                         KEY_PRESS_EVENT_STOP();
2308                         gtk_widget_event(messageview->mainwin->window,
2309                                          (GdkEvent *)&tmpev);
2310                 }
2311                 break;
2312         }
2313
2314         return TRUE;
2315 }
2316
2317 static gboolean textview_motion_notify(GtkWidget *widget,
2318                                        GdkEventMotion *event,
2319                                        TextView *textview)
2320 {
2321         if (textview->loading)
2322                 return FALSE;
2323         textview_uri_update(textview, event->x, event->y);
2324         gdk_window_get_pointer(widget->window, NULL, NULL, NULL);
2325
2326         return FALSE;
2327 }
2328
2329 static gboolean textview_leave_notify(GtkWidget *widget,
2330                                       GdkEventCrossing *event,
2331                                       TextView *textview)
2332 {
2333         if (textview->loading)
2334                 return FALSE;
2335         textview_uri_update(textview, -1, -1);
2336
2337         return FALSE;
2338 }
2339
2340 static gboolean textview_visibility_notify(GtkWidget *widget,
2341                                            GdkEventVisibility *event,
2342                                            TextView *textview)
2343 {
2344         gint wx, wy;
2345         GdkWindow *window;
2346
2347         if (textview->loading)
2348                 return FALSE;
2349
2350         window = gtk_text_view_get_window(GTK_TEXT_VIEW(widget),
2351                                           GTK_TEXT_WINDOW_TEXT);
2352
2353         /* check if occurred for the text window part */
2354         if (window != event->window)
2355                 return FALSE;
2356         
2357         gdk_window_get_pointer(widget->window, &wx, &wy, NULL);
2358         textview_uri_update(textview, wx, wy);
2359
2360         return FALSE;
2361 }
2362
2363 void textview_cursor_wait(TextView *textview)
2364 {
2365         GdkWindow *window = gtk_text_view_get_window(
2366                         GTK_TEXT_VIEW(textview->text),
2367                         GTK_TEXT_WINDOW_TEXT);
2368         textview_set_cursor(window, watch_cursor);
2369 }
2370
2371 void textview_cursor_normal(TextView *textview)
2372 {
2373         GdkWindow *window = gtk_text_view_get_window(
2374                         GTK_TEXT_VIEW(textview->text),
2375                         GTK_TEXT_WINDOW_TEXT);
2376         textview_set_cursor(window, text_cursor);
2377 }
2378
2379 static void textview_uri_update(TextView *textview, gint x, gint y)
2380 {
2381         GtkTextBuffer *buffer;
2382         GtkTextIter start_iter, end_iter;
2383         ClickableText *uri = NULL;
2384         
2385         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview->text));
2386
2387         if (x != -1 && y != -1) {
2388                 gint bx, by;
2389                 GtkTextIter iter;
2390                 GSList *tags;
2391                 GSList *cur;
2392                 
2393                 gtk_text_view_window_to_buffer_coords(GTK_TEXT_VIEW(textview->text), 
2394                                                       GTK_TEXT_WINDOW_WIDGET,
2395                                                       x, y, &bx, &by);
2396                 gtk_text_view_get_iter_at_location(GTK_TEXT_VIEW(textview->text),
2397                                                    &iter, bx, by);
2398
2399                 tags = gtk_text_iter_get_tags(&iter);
2400                 for (cur = tags; cur != NULL; cur = cur->next) {
2401                         GtkTextTag *tag = cur->data;
2402                         char *name;
2403
2404                         g_object_get(G_OBJECT(tag), "name", &name, NULL);
2405
2406                         if ((!strcmp(name, "link") || !strcmp(name, "hlink"))
2407                             && textview_get_uri_range(textview, &iter, tag,
2408                                                       &start_iter, &end_iter)) {
2409
2410                                 uri = textview_get_uri_from_range(textview,
2411                                                                   &iter, tag,
2412                                                                   &start_iter,
2413                                                                   &end_iter);
2414                         }
2415                         g_free(name);
2416                         if (uri)
2417                                 break;
2418                 }
2419                 g_slist_free(tags);
2420         }
2421         
2422         if (uri != textview->uri_hover) {
2423                 GdkWindow *window;
2424
2425                 if (textview->uri_hover)
2426                         gtk_text_buffer_remove_tag_by_name(buffer,
2427                                                            "link-hover",
2428                                                            &textview->uri_hover_start_iter,
2429                                                            &textview->uri_hover_end_iter);
2430                     
2431                 textview->uri_hover = uri;
2432                 if (uri) {
2433                         textview->uri_hover_start_iter = start_iter;
2434                         textview->uri_hover_end_iter = end_iter;
2435                 }
2436                 
2437                 window = gtk_text_view_get_window(GTK_TEXT_VIEW(textview->text),
2438                                                   GTK_TEXT_WINDOW_TEXT);
2439                 if (textview->messageview->mainwin->cursor_count == 0) {
2440                         textview_set_cursor(window, uri ? hand_cursor : text_cursor);
2441                 } else {
2442                         textview_set_cursor(window, watch_cursor);
2443                 }
2444
2445                 TEXTVIEW_STATUSBAR_POP(textview);
2446
2447                 if (uri) {
2448                         if (!uri->is_quote)
2449                                 gtk_text_buffer_apply_tag_by_name(buffer,
2450                                                           "link-hover",
2451                                                           &start_iter,
2452                                                           &end_iter);
2453                         TEXTVIEW_STATUSBAR_PUSH(textview, uri->uri);
2454                 }
2455         }
2456 }
2457
2458 static gboolean textview_get_uri_range(TextView *textview,
2459                                        GtkTextIter *iter,
2460                                        GtkTextTag *tag,
2461                                        GtkTextIter *start_iter,
2462                                        GtkTextIter *end_iter)
2463 {
2464         return get_tag_range(iter, tag, start_iter, end_iter);
2465 }
2466
2467 static ClickableText *textview_get_uri_from_range(TextView *textview,
2468                                               GtkTextIter *iter,
2469                                               GtkTextTag *tag,
2470                                               GtkTextIter *start_iter,
2471                                               GtkTextIter *end_iter)
2472 {
2473         gint start_pos, end_pos, cur_pos;
2474         ClickableText *uri = NULL;
2475         GSList *cur;
2476
2477         start_pos = gtk_text_iter_get_offset(start_iter);
2478         end_pos = gtk_text_iter_get_offset(end_iter);
2479         cur_pos = gtk_text_iter_get_offset(iter);
2480
2481         for (cur = textview->uri_list; cur != NULL; cur = cur->next) {
2482                 ClickableText *uri_ = (ClickableText *)cur->data;
2483                 if (start_pos == uri_->start &&
2484                     end_pos ==  uri_->end) {
2485                         uri = uri_;
2486                         break;
2487                 } 
2488         }
2489         for (cur = textview->uri_list; uri == NULL && cur != NULL; cur = cur->next) {
2490                 ClickableText *uri_ = (ClickableText *)cur->data;
2491                 if (start_pos == uri_->start ||
2492                            end_pos == uri_->end) {
2493                         /* in case of contiguous links, textview_get_uri_range
2494                          * returns a broader range (start of 1st link to end
2495                          * of last link).
2496                          * In that case, correct link is the one covering
2497                          * current iter.
2498                          */
2499                         if (uri_->start <= cur_pos && cur_pos <= uri_->end) {
2500                                 uri = uri_;
2501                                 break;
2502                         }
2503                 } 
2504         }
2505
2506         return uri;
2507 }
2508
2509 static ClickableText *textview_get_uri(TextView *textview,
2510                                    GtkTextIter *iter,
2511                                    GtkTextTag *tag)
2512 {
2513         GtkTextIter start_iter, end_iter;
2514         ClickableText *uri = NULL;
2515
2516         if (textview_get_uri_range(textview, iter, tag, &start_iter,
2517                                    &end_iter))
2518                 uri = textview_get_uri_from_range(textview, iter, tag,
2519                                                   &start_iter, &end_iter);
2520
2521         return uri;
2522 }
2523
2524 static void textview_shift_uris_after(TextView *textview, GSList *start_list, gint start, gint shift)
2525 {
2526         GSList *cur;
2527         if (!start_list)
2528                 start_list = textview->uri_list;
2529
2530         for (cur = start_list; cur; cur = cur->next) {
2531                 ClickableText *uri = (ClickableText *)cur->data;
2532                 if (uri->start <= start)
2533                         continue;
2534                 uri->start += shift;
2535                 uri->end += shift;
2536         }
2537 }
2538
2539 static void textview_remove_uris_in(TextView *textview, gint start, gint end)
2540 {
2541         GSList *cur;
2542         for (cur = textview->uri_list; cur; ) {
2543                 ClickableText *uri = (ClickableText *)cur->data;
2544                 if (uri->start > start && uri->end < end) {
2545                         cur = cur->next;
2546                         textview->uri_list = g_slist_remove(textview->uri_list, uri);
2547                         g_free(uri->uri);
2548                         g_free(uri->filename);
2549                         if (uri->is_quote) {
2550                                 g_free(uri->fg_color);
2551                                 g_free(uri->data); 
2552                                 /* (only free data in quotes uris) */
2553                         }
2554                         g_free(uri);
2555                 } else {
2556                         cur = cur->next;
2557                 }
2558                 
2559         }
2560 }
2561
2562 static void textview_toggle_quote(TextView *textview, GSList *start_list, ClickableText *uri, gboolean expand_only)
2563 {
2564         GtkTextIter start, end;
2565         GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview->text));
2566         
2567         if (!uri->is_quote)
2568                 return;
2569         
2570         if (uri->q_expanded && expand_only)
2571                 return;
2572
2573         gtk_text_buffer_get_iter_at_offset(buffer, &start, uri->start);
2574         gtk_text_buffer_get_iter_at_offset(buffer, &end,   uri->end);
2575         if (textview->uri_hover)
2576                 gtk_text_buffer_remove_tag_by_name(buffer,
2577                                                    "link-hover",
2578                                                    &textview->uri_hover_start_iter,
2579                                                    &textview->uri_hover_end_iter);
2580         textview->uri_hover = NULL;
2581         gtk_text_buffer_remove_tag_by_name(buffer,
2582                                            "qlink",
2583                                            &start,
2584                                            &end);
2585         /* when shifting URIs start and end, we have to do it per-UTF8-char
2586          * so use g_utf8_strlen(). OTOH, when inserting in the text buffer, 
2587          * we have to pass a number of bytes, so use strlen(). disturbing. */
2588          
2589         if (!uri->q_expanded) {
2590                 gtk_text_buffer_get_iter_at_offset(buffer, &start, uri->start);
2591                 gtk_text_buffer_get_iter_at_offset(buffer, &end,   uri->end);
2592                 textview_shift_uris_after(textview, start_list, uri->start, 
2593                         g_utf8_strlen((gchar *)uri->data, -1)-strlen(" [...]\n"));
2594                 gtk_text_buffer_delete(buffer, &start, &end);
2595                 gtk_text_buffer_get_iter_at_offset(buffer, &start, uri->start);
2596                 gtk_text_buffer_insert_with_tags_by_name
2597                                 (buffer, &start, (gchar *)uri->data, 
2598                                  strlen((gchar *)uri->data)-1,
2599                                  "qlink", (gchar *)uri->fg_color, NULL);
2600                 uri->end = gtk_text_iter_get_offset(&start);
2601                 textview_make_clickable_parts_later(textview,
2602                                           uri->start, uri->end);
2603                 uri->q_expanded = TRUE;
2604         } else {
2605                 gtk_text_buffer_get_iter_at_offset(buffer, &start, uri->start);
2606                 gtk_text_buffer_get_iter_at_offset(buffer, &end,   uri->end);
2607                 textview_remove_uris_in(textview, uri->start, uri->end);
2608                 textview_shift_uris_after(textview, start_list, uri->start, 
2609                         strlen(" [...]\n")-g_utf8_strlen((gchar *)uri->data, -1));
2610                 gtk_text_buffer_delete(buffer, &start, &end);
2611                 gtk_text_buffer_get_iter_at_offset(buffer, &start, uri->start);
2612                 gtk_text_buffer_insert_with_tags_by_name
2613                                 (buffer, &start, " [...]", -1,
2614                                  "qlink", (gchar *)uri->fg_color, NULL);
2615                 uri->end = gtk_text_iter_get_offset(&start);
2616                 uri->q_expanded = FALSE;
2617         }
2618         if (textview->messageview->mainwin->cursor_count == 0) {
2619                 textview_cursor_normal(textview);
2620         } else {
2621                 textview_cursor_wait(textview);
2622         }
2623 }
2624 static gboolean textview_uri_button_pressed(GtkTextTag *tag, GObject *obj,
2625                                             GdkEvent *event, GtkTextIter *iter,
2626                                             TextView *textview)
2627 {
2628         GdkEventButton *bevent;
2629         ClickableText *uri = NULL;
2630         char *tagname;
2631         gboolean qlink = FALSE;
2632
2633         if (!event)
2634                 return FALSE;
2635
2636         if (event->type != GDK_BUTTON_PRESS && event->type != GDK_2BUTTON_PRESS
2637                 && event->type != GDK_MOTION_NOTIFY)
2638                 return FALSE;
2639
2640         uri = textview_get_uri(textview, iter, tag);
2641         if (!uri)
2642                 return FALSE;
2643
2644         g_object_get(G_OBJECT(tag), "name", &tagname, NULL);
2645         
2646         if (!strcmp(tagname, "qlink"))
2647                 qlink = TRUE;
2648
2649         g_free(tagname);
2650         
2651         bevent = (GdkEventButton *) event;
2652         
2653         /* doubleclick: open compose / add address / browser */
2654         if (qlink && event->type == GDK_BUTTON_PRESS && bevent->button != 1) {
2655                 /* pass rightclick through */
2656                 return FALSE;
2657         } else if ((event->type == (qlink ? GDK_2BUTTON_PRESS:GDK_BUTTON_PRESS) && bevent->button == 1) ||
2658                 bevent->button == 2 || bevent->button == 3) {
2659                 if (uri->filename && !g_ascii_strncasecmp(uri->filename, "sc://", 5)) {
2660                         MimeView *mimeview = 
2661                                 (textview->messageview)?
2662                                         textview->messageview->mimeview:NULL;
2663                         if (mimeview && bevent->button == 1) {
2664                                 mimeview_handle_cmd(mimeview, uri->filename, NULL, uri->data);
2665                         } else if (mimeview && bevent->button == 2 && 
2666                                 !g_ascii_strcasecmp(uri->filename, "sc://select_attachment")) {
2667                                 mimeview_handle_cmd(mimeview, "sc://open_attachment", NULL, uri->data);
2668                         } else if (mimeview && bevent->button == 3 && 
2669                                 !g_ascii_strcasecmp(uri->filename, "sc://select_attachment")) {
2670                                 mimeview_handle_cmd(mimeview, "sc://menu_attachment", bevent, uri->data);
2671                         } 
2672                         return TRUE;
2673                 } else if (qlink && bevent->button == 1) {
2674                         textview_toggle_quote(textview, NULL, uri, FALSE);
2675                         return TRUE;
2676                 } else if (!g_ascii_strncasecmp(uri->uri, "mailto:", 7)) {
2677                         if (bevent->button == 3) {
2678                                 g_object_set_data(
2679                                         G_OBJECT(textview->mail_popup_menu),
2680                                         "menu_button", uri);
2681                                 gtk_menu_popup(GTK_MENU(textview->mail_popup_menu), 
2682                                                NULL, NULL, NULL, NULL, 
2683                                                bevent->button, bevent->time);
2684                         } else {
2685                                 PrefsAccount *account = NULL;
2686                                 FolderItem   *folder_item = NULL;
2687                                 if (textview->messageview && textview->messageview->msginfo &&
2688                                     textview->messageview->msginfo->folder) {
2689                                         
2690
2691                                         folder_item = textview->messageview->msginfo->folder;
2692                                         if (folder_item->prefs && folder_item->prefs->enable_default_account)
2693                                                 account = account_find_from_id(folder_item->prefs->default_account);
2694                                         if (!account)
2695                                                 account = account_find_from_item(folder_item);
2696                                 }
2697                                 compose_new_with_folderitem(account, folder_item, uri->uri + 7);
2698                         }
2699                         return TRUE;
2700                 } else if (g_ascii_strncasecmp(uri->uri, "file:", 5)) {
2701                         if (bevent->button == 1 &&
2702                             textview_uri_security_check(textview, uri) == TRUE) 
2703                                         open_uri(uri->uri,
2704                                                  prefs_common_get_uri_cmd());
2705                         else if (bevent->button == 3 && !qlink) {
2706                                 g_object_set_data(
2707                                         G_OBJECT(textview->link_popup_menu),
2708                                         "menu_button", uri);
2709                                 gtk_menu_popup(GTK_MENU(textview->link_popup_menu), 
2710                                                NULL, NULL, NULL, NULL, 
2711                                                bevent->button, bevent->time);
2712                         }
2713                         return TRUE;
2714                 } else {
2715                         if (bevent->button == 3 && !qlink) {
2716                                 g_object_set_data(
2717                                         G_OBJECT(textview->file_popup_menu),
2718                                         "menu_button", uri);
2719                                 gtk_menu_popup(GTK_MENU(textview->file_popup_menu), 
2720                                                NULL, NULL, NULL, NULL, 
2721                                                bevent->button, bevent->time);
2722                                 return TRUE;
2723                         }
2724                 }
2725         }
2726
2727         return FALSE;
2728 }
2729
2730 gchar *textview_get_visible_uri         (TextView       *textview, 
2731                                          ClickableText  *uri)
2732 {
2733         GtkTextBuffer *buffer;
2734         GtkTextIter start, end;
2735
2736         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview->text));
2737
2738         gtk_text_buffer_get_iter_at_offset(buffer, &start, uri->start);
2739         gtk_text_buffer_get_iter_at_offset(buffer, &end,   uri->end);
2740
2741         return gtk_text_buffer_get_text(buffer, &start, &end, FALSE);
2742 }
2743
2744 /*!
2745  *\brief    Check to see if a web URL has been disguised as a different
2746  *          URL (possible with HTML email).
2747  *
2748  *\param    uri The uri to check
2749  *
2750  *\param    textview The TextView the URL is contained in
2751  *
2752  *\return   gboolean TRUE if the URL is ok, or if the user chose to open
2753  *          it anyway, otherwise FALSE          
2754  */
2755 gboolean textview_uri_security_check(TextView *textview, ClickableText *uri)
2756 {
2757         gchar *visible_str;
2758         gboolean retval = TRUE;
2759
2760         if (is_uri_string(uri->uri) == FALSE)
2761                 return TRUE;
2762
2763         visible_str = textview_get_visible_uri(textview, uri);
2764         if (visible_str == NULL)
2765                 return TRUE;
2766
2767         g_strstrip(visible_str);
2768
2769         if (strcmp(visible_str, uri->uri) != 0 && is_uri_string(visible_str)) {
2770                 gchar *uri_path;
2771                 gchar *visible_uri_path;
2772
2773                 uri_path = get_uri_path(uri->uri);
2774                 visible_uri_path = get_uri_path(visible_str);
2775                 if (path_cmp(uri_path, visible_uri_path) != 0)
2776                         retval = FALSE;
2777         }
2778
2779         if (retval == FALSE) {
2780                 gchar *msg;
2781                 AlertValue aval;
2782
2783                 msg = g_markup_printf_escaped(_("The real URL is different from "
2784                                                 "the displayed URL.\n"
2785                                                 "\n"
2786                                                 "<b>Displayed URL:</b> %s\n"
2787                                                 "\n"
2788                                                 "<b>Real URL:</b> %s\n"
2789                                                 "\n"
2790                                                 "Open it anyway?"),
2791                                                visible_str,uri->uri);
2792                 aval = alertpanel_full(_("Phishing attempt warning"), msg,
2793                                        GTK_STOCK_CANCEL, _("_Open URL"), NULL, FALSE,
2794                                        NULL, ALERT_WARNING, G_ALERTDEFAULT);
2795                 g_free(msg);
2796                 if (aval == G_ALERTALTERNATE)
2797                         retval = TRUE;
2798         }
2799
2800         g_free(visible_str);
2801
2802         return retval;
2803 }
2804
2805 static void textview_uri_list_remove_all(GSList *uri_list)
2806 {
2807         GSList *cur;
2808
2809         for (cur = uri_list; cur != NULL; cur = cur->next) {
2810                 if (cur->data) {
2811                         g_free(((ClickableText *)cur->data)->uri);
2812                         g_free(((ClickableText *)cur->data)->filename);
2813                         if (((ClickableText *)cur->data)->is_quote) {
2814                                 g_free(((ClickableText *)cur->data)->fg_color);
2815                                 g_free(((ClickableText *)cur->data)->data); 
2816                                 /* (only free data in quotes uris) */
2817                         }
2818                         g_free(cur->data);
2819                 }
2820         }
2821
2822         g_slist_free(uri_list);
2823 }
2824
2825 static void open_uri_cb (GtkAction *action, TextView *textview)
2826 {
2827         ClickableText *uri = g_object_get_data(G_OBJECT(textview->link_popup_menu),
2828                                            "menu_button");
2829         const gchar *raw_url = g_object_get_data(G_OBJECT(textview->link_popup_menu),
2830                                            "raw_url");
2831
2832         if (uri) {
2833                 if (textview_uri_security_check(textview, uri) == TRUE) 
2834                         open_uri(uri->uri,
2835                                  prefs_common_get_uri_cmd());
2836                 g_object_set_data(G_OBJECT(textview->link_popup_menu), "menu_button",
2837                                   NULL);
2838         }
2839         if (raw_url) {
2840                 open_uri(raw_url, prefs_common_get_uri_cmd());
2841                 g_object_set_data(G_OBJECT(textview->link_popup_menu), "raw_url",
2842                                   NULL);
2843         }
2844 }
2845
2846 static void open_image_cb (GtkAction *action, TextView *textview)
2847 {
2848         ClickableText *uri = g_object_get_data(G_OBJECT(textview->file_popup_menu),
2849                                            "menu_button");
2850
2851         gchar *cmd = NULL;
2852         gchar buf[1024];
2853         const gchar *p;
2854         gchar *filename = NULL;
2855         gchar *tmp_filename = NULL;
2856
2857         if (uri == NULL)
2858                 return;
2859
2860         if (uri->filename == NULL)
2861                 return;
2862         
2863         filename = g_strdup(uri->filename);
2864         
2865         if (!g_utf8_validate(filename, -1, NULL)) {
2866                 gchar *tmp = conv_filename_to_utf8(filename);
2867                 g_free(filename);
2868                 filename = tmp;
2869         }
2870
2871         subst_for_filename(filename);
2872
2873         tmp_filename = g_filename_from_uri(uri->uri, NULL, NULL);
2874         copy_file(tmp_filename, filename, FALSE);
2875         g_free(tmp_filename);
2876
2877         cmd = mailcap_get_command_for_type("image/jpeg", filename);
2878         if (cmd == NULL) {
2879                 gboolean remember = FALSE;
2880                 cmd = input_dialog_combo_remember
2881                         (_("Open with"),
2882                          _("Enter the command-line to open file:\n"
2883                            "('%s' will be replaced with file name)"),
2884                          prefs_common.mime_open_cmd,
2885                          prefs_common.mime_open_cmd_history,
2886                          &remember);
2887                 if (cmd && remember) {
2888                         mailcap_update_default("image/jpeg", cmd);
2889                 }
2890         }
2891         if (cmd && (p = strchr(cmd, '%')) && *(p + 1) == 's' &&
2892             !strchr(p + 2, '%'))
2893                 g_snprintf(buf, sizeof(buf), cmd, filename);
2894         else {
2895                 g_warning("Image viewer command-line is invalid: '%s'", cmd);
2896                 return;
2897         }
2898
2899         execute_command_line(buf, TRUE);
2900
2901         g_free(filename);
2902         g_free(cmd);
2903
2904         g_object_set_data(G_OBJECT(textview->file_popup_menu), "menu_button",
2905                           NULL);
2906 }
2907
2908 static void save_file_cb (GtkAction *action, TextView *textview)
2909 {
2910         ClickableText *uri = g_object_get_data(G_OBJECT(textview->file_popup_menu),
2911                                            "menu_button");
2912         gchar *filename = NULL;
2913         gchar *filepath = NULL;
2914         gchar *filedir = NULL;
2915         gchar *tmp_filename = NULL;
2916         if (uri == NULL)
2917                 return;
2918
2919         if (uri->filename == NULL)
2920                 return;
2921         
2922         filename = g_strdup(uri->filename);
2923         
2924         if (!g_utf8_validate(filename, -1, NULL)) {
2925                 gchar *tmp = conv_filename_to_utf8(filename);
2926                 g_free(filename);
2927                 filename = tmp;
2928         }
2929
2930         subst_for_filename(filename);
2931         
2932         if (prefs_common.attach_save_dir && *prefs_common.attach_save_dir)
2933                 filepath = g_strconcat(prefs_common.attach_save_dir,
2934                                        G_DIR_SEPARATOR_S, filename, NULL);
2935         else
2936                 filepath = g_strdup(filename);
2937
2938         g_free(filename);
2939
2940         filename = filesel_select_file_save(_("Save as"), filepath);
2941         if (!filename) {
2942                 g_free(filepath);
2943                 return;
2944         }
2945
2946         if (is_file_exist(filename)) {
2947                 AlertValue aval;
2948                 gchar *res;
2949                 
2950                 res = g_strdup_printf(_("Overwrite existing file '%s'?"),
2951                                       filename);
2952                 aval = alertpanel(_("Overwrite"), res, GTK_STOCK_CANCEL, 
2953                                   GTK_STOCK_OK, NULL);
2954                 g_free(res);                                      
2955                 if (G_ALERTALTERNATE != aval)
2956                         return;
2957         }
2958
2959         tmp_filename = g_filename_from_uri(uri->uri, NULL, NULL);
2960         copy_file(tmp_filename, filename, FALSE);
2961         g_free(tmp_filename);
2962         
2963         filedir = g_path_get_dirname(filename);
2964         if (filedir && strcmp(filedir, ".")) {
2965                 g_free(prefs_common.attach_save_dir);
2966                 prefs_common.attach_save_dir = g_filename_to_utf8(filedir, -1, NULL, NULL, NULL);
2967         }
2968
2969         g_free(filedir);
2970         g_free(filepath);
2971
2972         g_object_set_data(G_OBJECT(textview->file_popup_menu), "menu_button",
2973                           NULL);
2974 }
2975
2976 static void copy_uri_cb (GtkAction *action, TextView *textview)
2977 {
2978         ClickableText *uri = g_object_get_data(G_OBJECT(textview->link_popup_menu),
2979                                            "menu_button");
2980         const gchar *raw_url =  g_object_get_data(G_OBJECT(textview->link_popup_menu),
2981                                            "raw_url");
2982         if (uri) {
2983                 gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), uri->uri, -1);
2984                 gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), uri->uri, -1);
2985                 g_object_set_data(G_OBJECT(textview->link_popup_menu), "menu_button",
2986                           NULL);
2987         }
2988         if (raw_url) {
2989                 gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), raw_url, -1);
2990                 gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), raw_url, -1);
2991                 g_object_set_data(G_OBJECT(textview->link_popup_menu), "raw_url",
2992                           NULL);
2993         }
2994 }
2995
2996 static void add_uri_to_addrbook_cb (GtkAction *action, TextView *textview)
2997 {
2998         gchar *fromname, *fromaddress;
2999         ClickableText *uri = g_object_get_data(G_OBJECT(textview->mail_popup_menu),
3000                                            "menu_button");
3001         GtkWidget *image = NULL;
3002         GdkPixbuf *picture = NULL;
3003         gboolean use_picture = FALSE;
3004         if (uri == NULL)
3005                 return;
3006
3007         /* extract url */
3008         fromaddress = g_strdup(uri->uri + 7);
3009         
3010         if (textview->messageview->msginfo &&
3011            !strcmp2(fromaddress, textview->messageview->msginfo->from))
3012                 use_picture = TRUE;
3013
3014         fromname = procheader_get_fromname(fromaddress);
3015         extract_address(fromaddress);
3016
3017         if (use_picture && 
3018             textview->messageview->msginfo &&
3019             textview->messageview->msginfo->extradata &&
3020             textview->messageview->msginfo->extradata->face) {
3021                 image = face_get_from_header(textview->messageview->msginfo->extradata->face);
3022         }
3023 #if HAVE_LIBCOMPFACE 
3024         else if (use_picture && 
3025                  textview->messageview->msginfo &&
3026                  textview->messageview->msginfo->extradata &&
3027                  textview->messageview->msginfo->extradata->xface) {
3028                 image = xface_get_from_header(textview->messageview->msginfo->extradata->xface,
3029                                 &textview->text->style->white,
3030                                 mainwindow_get_mainwindow()->window->window);   
3031         }
3032 #endif
3033         if (image)
3034                 picture = gtk_image_get_pixbuf(GTK_IMAGE(image));
3035
3036         addressbook_add_contact( fromname, fromaddress, NULL, picture);
3037
3038         g_free(fromaddress);
3039         g_free(fromname);
3040 }
3041
3042 static void mail_to_uri_cb (GtkAction *action, TextView *textview)
3043 {
3044         PrefsAccount *account = NULL;
3045         ClickableText *uri = g_object_get_data(G_OBJECT(textview->mail_popup_menu),
3046                                            "menu_button");
3047         if (uri == NULL)
3048                 return;
3049
3050         if (textview->messageview && textview->messageview->msginfo &&
3051             textview->messageview->msginfo->folder) {
3052                 FolderItem   *folder_item;
3053
3054                 folder_item = textview->messageview->msginfo->folder;
3055                 if (folder_item->prefs && folder_item->prefs->enable_default_account)
3056                         account = account_find_from_id(folder_item->prefs->default_account);
3057                 
3058                 compose_new_with_folderitem(account, folder_item, uri->uri+7);
3059         } else {
3060                 compose_new(account, uri->uri + 7, NULL);
3061         }
3062 }
3063
3064 static void copy_mail_to_uri_cb (GtkAction *action, TextView *textview)
3065 {
3066         ClickableText *uri = g_object_get_data(G_OBJECT(textview->mail_popup_menu),
3067                                            "menu_button");
3068         if (uri == NULL)
3069                 return;
3070
3071         gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), uri->uri +7, -1);
3072         gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), uri->uri +7, -1);
3073         g_object_set_data(G_OBJECT(textview->mail_popup_menu), "menu_button",
3074                           NULL);
3075 }
3076
3077 void textview_get_selection_offsets(TextView *textview, gint *sel_start, gint *sel_end)
3078 {
3079                 GtkTextView *text = GTK_TEXT_VIEW(textview->text);
3080                 GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
3081                 GtkTextIter start, end;
3082                 if (gtk_text_buffer_get_selection_bounds(buffer, &start, &end)) {
3083                         if (sel_start)
3084                                 *sel_start = gtk_text_iter_get_offset(&start);
3085                         if (sel_end)
3086                                 *sel_end = gtk_text_iter_get_offset(&end);
3087                 } else {
3088                         if (sel_start)
3089                                 *sel_start = -1;
3090                         if (sel_end)
3091                                 *sel_end = -1;
3092                 }
3093 }