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