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