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