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