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