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