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