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