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