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