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