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