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