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