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