c4e571c38bfc39a077dd27ad5104a09f33a0d87c
[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                         int rc;
915                         gchar **argv;
916                         argv = strsplit_with_quote(buf, " ", 0);
917                         close(1);
918                         close(pfd[0]);
919                         dup(pfd[1]);
920                         rc = execvp(argv[0], argv);
921                         close(pfd[1]);
922                         printf (_("The command to view attachment "
923                                 "as text failed:\n"
924                                 "    %s\n"
925                                 "Exit code %d\n"), buf, rc);
926                         exit(255);
927                 }
928                 close(pfd[1]);
929                 tmpfp = fdopen(pfd[0], "rb");
930                 while (fgets(buf, sizeof(buf), tmpfp))
931                         textview_write_line(textview, buf, conv);
932                 fclose(tmpfp);
933                 waitpid(pid, pfd, 0);
934                 unlink(fname);
935         } else {
936 textview_default:
937                 tmpfp = g_fopen(mimeinfo->data.filename, "rb");
938                 fseek(tmpfp, mimeinfo->offset, SEEK_SET);
939                 debug_print("Viewing text content of type: %s (length: %d)\n", mimeinfo->subtype, mimeinfo->length);
940                 while ((fgets(buf, sizeof(buf), tmpfp) != NULL) && 
941                        (ftell(tmpfp) <= mimeinfo->offset + mimeinfo->length))
942                         textview_write_line(textview, buf, conv);
943                 fclose(tmpfp);
944         }
945
946         conv_code_converter_destroy(conv);
947         procmime_force_encoding(0);
948 }
949
950 static void textview_show_html(TextView *textview, FILE *fp,
951                                CodeConverter *conv)
952 {
953         SC_HTMLParser *parser;
954         gchar *str;
955
956         parser = sc_html_parser_new(fp, conv);
957         g_return_if_fail(parser != NULL);
958
959         while ((str = sc_html_parse(parser)) != NULL) {
960                 if (parser->state == SC_HTML_HREF) {
961                         /* first time : get and copy the URL */
962                         if (parser->href == NULL) {
963                                 /* ALF - the sylpheed html parser returns an empty string,
964                                  * if still inside an <a>, but already parsed past HREF */
965                                 str = strtok(str, " ");
966                                 if (str) {
967                                         while (str && *str && g_ascii_isspace(*str))
968                                                 str++; 
969                                         parser->href = g_strdup(str);
970                                         /* the URL may (or not) be followed by the
971                                          * referenced text */
972                                         str = strtok(NULL, "");
973                                 }       
974                         }
975                         if (str != NULL)
976                                 textview_write_link(textview, str, parser->href, NULL);
977                 } else
978                         textview_write_line(textview, str, NULL);
979         }
980         textview_write_line(textview, "\n", NULL);
981         sc_html_parser_destroy(parser);
982 }
983
984 static void textview_show_ertf(TextView *textview, FILE *fp,
985                                CodeConverter *conv)
986 {
987         ERTFParser *parser;
988         gchar *str;
989
990         parser = ertf_parser_new(fp, conv);
991         g_return_if_fail(parser != NULL);
992
993         while ((str = ertf_parse(parser)) != NULL) {
994                 textview_write_line(textview, str, NULL);
995         }
996         
997         ertf_parser_destroy(parser);
998 }
999
1000 #define ADD_TXT_POS(bp_, ep_, pti_) \
1001         if ((last->next = alloca(sizeof(struct txtpos))) != NULL) { \
1002                 last = last->next; \
1003                 last->bp = (bp_); last->ep = (ep_); last->pti = (pti_); \
1004                 last->next = NULL; \
1005         } else { \
1006                 g_warning("alloc error scanning URIs\n"); \
1007                 gtk_text_buffer_insert_with_tags_by_name(buffer, &iter, \
1008                                                          linebuf, -1, \
1009                                                          fg_tag, NULL); \
1010                 return; \
1011         }
1012
1013 /* textview_make_clickable_parts() - colorizes clickable parts */
1014 static void textview_make_clickable_parts(TextView *textview,
1015                                           const gchar *fg_tag,
1016                                           const gchar *uri_tag,
1017                                           const gchar *linebuf,
1018                                           gboolean hdr)
1019 {
1020         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1021         GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
1022         GtkTextIter iter;
1023         gchar *mybuf = g_strdup(linebuf);
1024         
1025         /* parse table - in order of priority */
1026         struct table {
1027                 const gchar *needle; /* token */
1028
1029                 /* token search function */
1030                 gchar    *(*search)     (const gchar *haystack,
1031                                          const gchar *needle);
1032                 /* part parsing function */
1033                 gboolean  (*parse)      (const gchar *start,
1034                                          const gchar *scanpos,
1035                                          const gchar **bp_,
1036                                          const gchar **ep_,
1037                                          gboolean hdr);
1038                 /* part to URI function */
1039                 gchar    *(*build_uri)  (const gchar *bp,
1040                                          const gchar *ep);
1041         };
1042
1043         static struct table parser[] = {
1044                 {"http://",  strcasestr, get_uri_part,   make_uri_string},
1045                 {"https://", strcasestr, get_uri_part,   make_uri_string},
1046                 {"ftp://",   strcasestr, get_uri_part,   make_uri_string},
1047                 {"sftp://",  strcasestr, get_uri_part,   make_uri_string},
1048                 {"www.",     strcasestr, get_uri_part,   make_http_string},
1049                 {"mailto:",  strcasestr, get_uri_part,   make_uri_string},
1050                 {"@",        strcasestr, get_email_part, make_email_string}
1051         };
1052         const gint PARSE_ELEMS = sizeof parser / sizeof parser[0];
1053
1054         gint  n;
1055         const gchar *walk, *bp, *ep;
1056
1057         struct txtpos {
1058                 const gchar     *bp, *ep;       /* text position */
1059                 gint             pti;           /* index in parse table */
1060                 struct txtpos   *next;          /* next */
1061         } head = {NULL, NULL, 0,  NULL}, *last = &head;
1062
1063         if (!g_utf8_validate(linebuf, -1, NULL)) {
1064                 mybuf = g_malloc(strlen(linebuf)*2 +1);
1065                 conv_localetodisp(mybuf, strlen(linebuf)*2 +1, linebuf);
1066         }
1067
1068         gtk_text_buffer_get_end_iter(buffer, &iter);
1069
1070         /* parse for clickable parts, and build a list of begin and end positions  */
1071         for (walk = mybuf, n = 0;;) {
1072                 gint last_index = PARSE_ELEMS;
1073                 gchar *scanpos = NULL;
1074
1075                 /* FIXME: this looks phony. scanning for anything in the parse table */
1076                 for (n = 0; n < PARSE_ELEMS; n++) {
1077                         gchar *tmp;
1078
1079                         tmp = parser[n].search(walk, parser[n].needle);
1080                         if (tmp) {
1081                                 if (scanpos == NULL || tmp < scanpos) {
1082                                         scanpos = tmp;
1083                                         last_index = n;
1084                                 }
1085                         }                                       
1086                 }
1087
1088                 if (scanpos) {
1089                         /* check if URI can be parsed */
1090                         if (parser[last_index].parse(walk, scanpos, &bp, &ep, hdr)
1091                             && (size_t) (ep - bp - 1) > strlen(parser[last_index].needle)) {
1092                                         ADD_TXT_POS(bp, ep, last_index);
1093                                         walk = ep;
1094                         } else
1095                                 walk = scanpos +
1096                                         strlen(parser[last_index].needle);
1097                 } else
1098                         break;
1099         }
1100
1101         /* colorize this line */
1102         if (head.next) {
1103                 const gchar *normal_text = mybuf;
1104
1105                 /* insert URIs */
1106                 for (last = head.next; last != NULL;
1107                      normal_text = last->ep, last = last->next) {
1108                         RemoteURI *uri;
1109                         uri = g_new(RemoteURI, 1);
1110                         if (last->bp - normal_text > 0)
1111                                 gtk_text_buffer_insert_with_tags_by_name
1112                                         (buffer, &iter,
1113                                          normal_text,
1114                                          last->bp - normal_text,
1115                                          fg_tag, NULL);
1116                         uri->uri = parser[last->pti].build_uri(last->bp,
1117                                                                last->ep);
1118                         uri->start = gtk_text_iter_get_offset(&iter);
1119                         gtk_text_buffer_insert_with_tags_by_name
1120                                 (buffer, &iter, last->bp, last->ep - last->bp,
1121                                  uri_tag, fg_tag, NULL);
1122                         uri->end = gtk_text_iter_get_offset(&iter);
1123                         uri->filename = NULL;
1124                         textview->uri_list =
1125                                 g_slist_append(textview->uri_list, uri);
1126                 }
1127
1128                 if (*normal_text)
1129                         gtk_text_buffer_insert_with_tags_by_name
1130                                 (buffer, &iter, normal_text, -1, fg_tag, NULL);
1131         } else {
1132                 gtk_text_buffer_insert_with_tags_by_name
1133                         (buffer, &iter, mybuf, -1, fg_tag, NULL);
1134         }
1135         g_free(mybuf);
1136 }
1137
1138 #undef ADD_TXT_POS
1139
1140 static void textview_write_line(TextView *textview, const gchar *str,
1141                                 CodeConverter *conv)
1142 {
1143         GtkTextView *text;
1144         GtkTextBuffer *buffer;
1145         GtkTextIter iter;
1146         gchar buf[BUFFSIZE];
1147         gchar *fg_color;
1148         gint quotelevel = -1;
1149         gchar quote_tag_str[10];
1150
1151         text = GTK_TEXT_VIEW(textview->text);
1152         buffer = gtk_text_view_get_buffer(text);
1153         gtk_text_buffer_get_end_iter(buffer, &iter);
1154
1155         if (!conv)
1156                 strncpy2(buf, str, sizeof(buf));
1157         else if (conv_convert(conv, buf, sizeof(buf), str) < 0)
1158                 conv_localetodisp(buf, sizeof(buf), str);
1159                 
1160         strcrchomp(buf);
1161         fg_color = NULL;
1162
1163         /* change color of quotation
1164            >, foo>, _> ... ok, <foo>, foo bar>, foo-> ... ng
1165            Up to 3 levels of quotations are detected, and each
1166            level is colored using a different color. */
1167         if (prefs_common.enable_color 
1168             && line_has_quote_char(buf, prefs_common.quote_chars)) {
1169                 quotelevel = get_quote_level(buf, prefs_common.quote_chars);
1170
1171                 /* set up the correct foreground color */
1172                 if (quotelevel > 2) {
1173                         /* recycle colors */
1174                         if (prefs_common.recycle_quote_colors)
1175                                 quotelevel %= 3;
1176                         else
1177                                 quotelevel = 2;
1178                 }
1179         }
1180
1181         if (quotelevel == -1)
1182                 fg_color = NULL;
1183         else {
1184                 g_snprintf(quote_tag_str, sizeof(quote_tag_str),
1185                            "quote%d", quotelevel);
1186                 fg_color = quote_tag_str;
1187         }
1188
1189         if (prefs_common.enable_color && (strcmp(buf,"-- \n") == 0 || textview->is_in_signature)) {
1190                 fg_color = "signature";
1191                 textview->is_in_signature = TRUE;
1192         }
1193
1194         textview_make_clickable_parts(textview, fg_color, "link", buf, FALSE);
1195 }
1196
1197 void textview_write_link(TextView *textview, const gchar *str,
1198                          const gchar *uri, CodeConverter *conv)
1199 {
1200         GdkColor *link_color = NULL;
1201         GtkTextView *text;
1202         GtkTextBuffer *buffer;
1203         GtkTextIter iter;
1204         gchar buf[BUFFSIZE];
1205         gchar *bufp;
1206         RemoteURI *r_uri;
1207
1208         if (!str || *str == '\0')
1209                 return;
1210         if (!uri)
1211                 return;
1212
1213         while (uri && *uri && g_ascii_isspace(*uri))
1214                 uri++;
1215                 
1216         text = GTK_TEXT_VIEW(textview->text);
1217         buffer = gtk_text_view_get_buffer(text);
1218         gtk_text_buffer_get_end_iter(buffer, &iter);
1219
1220         if (!conv)
1221                 strncpy2(buf, str, sizeof(buf));
1222         else if (conv_convert(conv, buf, sizeof(buf), str) < 0)
1223                 conv_utf8todisp(buf, sizeof(buf), str);
1224
1225         if (g_utf8_validate(buf, -1, NULL) == FALSE)
1226                 return;
1227
1228         strcrchomp(buf);
1229
1230         gtk_text_buffer_get_end_iter(buffer, &iter);
1231         for (bufp = buf; *bufp != '\0'; bufp = g_utf8_next_char(bufp)) {
1232                 gunichar ch;
1233
1234                 ch = g_utf8_get_char(bufp);
1235                 if (!g_unichar_isspace(ch))
1236                         break;
1237         }
1238         if (bufp > buf)
1239                 gtk_text_buffer_insert(buffer, &iter, buf, bufp - buf);
1240
1241         if (prefs_common.enable_color) {
1242                 link_color = &uri_color;
1243         }
1244         r_uri = g_new(RemoteURI, 1);
1245         r_uri->uri = g_strdup(uri);
1246         r_uri->start = gtk_text_iter_get_offset(&iter);
1247         gtk_text_buffer_insert_with_tags_by_name
1248                 (buffer, &iter, bufp, -1, "link", NULL);
1249         r_uri->end = gtk_text_iter_get_offset(&iter);
1250         r_uri->filename = NULL;
1251         textview->uri_list = g_slist_append(textview->uri_list, r_uri);
1252 }
1253
1254 static void textview_set_cursor(GdkWindow *window, GdkCursor *cursor)
1255 {
1256         if (GDK_IS_WINDOW(window))
1257                 gdk_window_set_cursor(window, cursor);
1258 }
1259 void textview_clear(TextView *textview)
1260 {
1261         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1262         GtkTextBuffer *buffer;
1263         GdkWindow *window = gtk_text_view_get_window(text,
1264                                 GTK_TEXT_WINDOW_TEXT);
1265
1266         buffer = gtk_text_view_get_buffer(text);
1267         gtk_text_buffer_set_text(buffer, "", -1);
1268
1269         TEXTVIEW_STATUSBAR_POP(textview);
1270         textview_uri_list_remove_all(textview->uri_list);
1271         textview->uri_list = NULL;
1272         textview->uri_hover = NULL;
1273
1274         textview->body_pos = 0;
1275         if (textview->image) 
1276                 gtk_widget_destroy(textview->image);
1277         textview->image = NULL;
1278
1279         if (textview->messageview->mainwin->cursor_count == 0) {
1280                 textview_set_cursor(window, text_cursor);
1281         } else {
1282                 textview_set_cursor(window, watch_cursor);
1283         }
1284 }
1285
1286 void textview_destroy(TextView *textview)
1287 {
1288         textview_uri_list_remove_all(textview->uri_list);
1289         textview->uri_list = NULL;
1290
1291         g_free(textview);
1292 }
1293
1294 void textview_set_all_headers(TextView *textview, gboolean all_headers)
1295 {
1296         textview->show_all_headers = all_headers;
1297 }
1298
1299 #define CHANGE_TAG_FONT(tagname, font) { \
1300         tag = gtk_text_tag_table_lookup(tags, tagname); \
1301         if (tag) \
1302                 g_object_set(G_OBJECT(tag), "font-desc", font, NULL); \
1303 }
1304
1305 void textview_set_font(TextView *textview, const gchar *codeset)
1306 {
1307         GtkTextTag *tag;
1308         GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview->text));
1309         GtkTextTagTable *tags = gtk_text_buffer_get_tag_table(buffer);
1310         
1311         if (NORMAL_FONT) {
1312                 PangoFontDescription *font_desc, *bold_font_desc;
1313                 font_desc = pango_font_description_from_string
1314                                                 (NORMAL_FONT);
1315                 bold_font_desc = pango_font_description_from_string
1316                                                 (NORMAL_FONT);
1317                 if (font_desc) {
1318                         gtk_widget_modify_font(textview->text, font_desc);
1319                         CHANGE_TAG_FONT("header", font_desc);
1320                         pango_font_description_free(font_desc);
1321                 }
1322                 if (bold_font_desc) {
1323                         pango_font_description_set_weight
1324                                 (bold_font_desc, PANGO_WEIGHT_BOLD);
1325                         CHANGE_TAG_FONT("header_title", bold_font_desc);
1326                         pango_font_description_free(bold_font_desc);
1327                 }
1328         }
1329
1330         if (prefs_common.textfont) {
1331                 PangoFontDescription *font_desc;
1332
1333                 font_desc = pango_font_description_from_string
1334                                                 (prefs_common.textfont);
1335                 if (font_desc) {
1336                         gtk_widget_modify_font(textview->text, font_desc);
1337                         pango_font_description_free(font_desc);
1338                 }
1339         }
1340         gtk_text_view_set_pixels_above_lines(GTK_TEXT_VIEW(textview->text),
1341                                              prefs_common.line_space / 2);
1342         gtk_text_view_set_pixels_below_lines(GTK_TEXT_VIEW(textview->text),
1343                                              prefs_common.line_space / 2);
1344 }
1345
1346 void textview_set_text(TextView *textview, const gchar *text)
1347 {
1348         GtkTextView *view;
1349         GtkTextBuffer *buffer;
1350
1351         g_return_if_fail(textview != NULL);
1352         g_return_if_fail(text != NULL);
1353
1354         textview_clear(textview);
1355
1356         view = GTK_TEXT_VIEW(textview->text);
1357         buffer = gtk_text_view_get_buffer(view);
1358         gtk_text_buffer_set_text(buffer, text, strlen(text));
1359 }
1360
1361 enum
1362 {
1363         H_DATE          = 0,
1364         H_FROM          = 1,
1365         H_TO            = 2,
1366         H_NEWSGROUPS    = 3,
1367         H_SUBJECT       = 4,
1368         H_CC            = 5,
1369         H_REPLY_TO      = 6,
1370         H_FOLLOWUP_TO   = 7,
1371         H_X_MAILER      = 8,
1372         H_X_NEWSREADER  = 9,
1373         H_USER_AGENT    = 10,
1374         H_ORGANIZATION  = 11,
1375 };
1376
1377 void textview_set_position(TextView *textview, gint pos)
1378 {
1379         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1380
1381         gtkut_text_view_set_position(text, pos);
1382 }
1383
1384 static GPtrArray *textview_scan_header(TextView *textview, FILE *fp)
1385 {
1386         gchar buf[BUFFSIZE];
1387         GPtrArray *headers, *sorted_headers;
1388         GSList *disphdr_list;
1389         Header *header;
1390         gint i;
1391
1392         g_return_val_if_fail(fp != NULL, NULL);
1393
1394         if (textview->show_all_headers)
1395                 return procheader_get_header_array_asis(fp);
1396
1397         if (!prefs_common.display_header) {
1398                 while (fgets(buf, sizeof(buf), fp) != NULL)
1399                         if (buf[0] == '\r' || buf[0] == '\n') break;
1400                 return NULL;
1401         }
1402
1403         headers = procheader_get_header_array_asis(fp);
1404
1405         sorted_headers = g_ptr_array_new();
1406
1407         for (disphdr_list = prefs_common.disphdr_list; disphdr_list != NULL;
1408              disphdr_list = disphdr_list->next) {
1409                 DisplayHeaderProp *dp =
1410                         (DisplayHeaderProp *)disphdr_list->data;
1411
1412                 for (i = 0; i < headers->len; i++) {
1413                         header = g_ptr_array_index(headers, i);
1414
1415                         if (procheader_headername_equal(header->name,
1416                                                         dp->name)) {
1417                                 if (dp->hidden)
1418                                         procheader_header_free(header);
1419                                 else
1420                                         g_ptr_array_add(sorted_headers, header);
1421
1422                                 g_ptr_array_remove_index(headers, i);
1423                                 i--;
1424                         }
1425                 }
1426         }
1427
1428         if (prefs_common.show_other_header) {
1429                 for (i = 0; i < headers->len; i++) {
1430                         header = g_ptr_array_index(headers, i);
1431                         g_ptr_array_add(sorted_headers, header);
1432                 }
1433                 g_ptr_array_free(headers, TRUE);
1434         } else
1435                 procheader_header_array_destroy(headers);
1436
1437
1438         return sorted_headers;
1439 }
1440
1441 static void textview_show_face(TextView *textview)
1442 {
1443         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1444         MsgInfo *msginfo = textview->messageview->msginfo;
1445         int x = 0;
1446         
1447         if (prefs_common.display_header_pane
1448         ||  !prefs_common.display_xface)
1449                 goto bail;
1450         
1451         if (!msginfo->face) {
1452                 goto bail;
1453         }
1454
1455         if (textview->image) 
1456                 gtk_widget_destroy(textview->image);
1457         
1458         textview->image = face_get_from_header(msginfo->face);
1459         g_return_if_fail(textview->image != NULL);
1460
1461         gtk_widget_show(textview->image);
1462         
1463         x = textview->text->allocation.width - WIDTH -5;
1464
1465         gtk_text_view_add_child_in_window(text, textview->image, 
1466                 GTK_TEXT_WINDOW_TEXT, x, 5);
1467
1468         gtk_widget_show_all(textview->text);
1469         
1470
1471         return;
1472 bail:
1473         if (textview->image) 
1474                 gtk_widget_destroy(textview->image);
1475         textview->image = NULL; 
1476 }
1477
1478 static void textview_show_icon(TextView *textview, const gchar *stock_id)
1479 {
1480         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1481         int x = 0;
1482         
1483         if (textview->image) 
1484                 gtk_widget_destroy(textview->image);
1485         
1486         textview->image = gtk_image_new_from_stock(stock_id, GTK_ICON_SIZE_DIALOG);
1487         g_return_if_fail(textview->image != NULL);
1488
1489         gtk_widget_show(textview->image);
1490         
1491         x = textview->text->allocation.width - WIDTH -5;
1492
1493         gtk_text_view_add_child_in_window(text, textview->image, 
1494                 GTK_TEXT_WINDOW_TEXT, x, 5);
1495
1496         gtk_widget_show_all(textview->text);
1497         
1498
1499         return;
1500 }
1501
1502 #if HAVE_LIBCOMPFACE
1503 static void textview_show_xface(TextView *textview)
1504 {
1505         MsgInfo *msginfo = textview->messageview->msginfo;
1506         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1507         int x = 0;
1508
1509         if (prefs_common.display_header_pane
1510         ||  !prefs_common.display_xface)
1511                 goto bail;
1512         
1513         if (!msginfo)
1514                 goto bail;
1515
1516         if (msginfo->face)
1517                 return;
1518         
1519         if (!msginfo->xface || strlen(msginfo->xface) < 5) {
1520                 goto bail;
1521         }
1522
1523         if (textview->image) 
1524                 gtk_widget_destroy(textview->image);
1525         
1526         textview->image = xface_get_from_header(msginfo->xface,
1527                                 &textview->text->style->white,
1528                                 textview->text->window);
1529         g_return_if_fail(textview->image != NULL);
1530
1531         gtk_widget_show(textview->image);
1532         
1533         x = textview->text->allocation.width - WIDTH -5;
1534
1535         gtk_text_view_add_child_in_window(text, textview->image, 
1536                 GTK_TEXT_WINDOW_TEXT, x, 5);
1537
1538         gtk_widget_show_all(textview->text);
1539         
1540         return;
1541 bail:
1542         if (textview->image) 
1543                 gtk_widget_destroy(textview->image);
1544         textview->image = NULL;
1545         
1546 }
1547 #endif
1548
1549 static void textview_show_header(TextView *textview, GPtrArray *headers)
1550 {
1551         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1552         GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
1553         GtkTextIter iter;
1554         Header *header;
1555         gint i;
1556
1557         g_return_if_fail(headers != NULL);
1558
1559         for (i = 0; i < headers->len; i++) {
1560                 header = g_ptr_array_index(headers, i);
1561                 g_return_if_fail(header->name != NULL);
1562
1563                 gtk_text_buffer_get_end_iter (buffer, &iter);
1564                 if(prefs_common.trans_hdr == TRUE) {
1565                         gchar *hdr = g_strndup(header->name, strlen(header->name) - 1);
1566                         gchar *trans_hdr = gettext(hdr);
1567                         gtk_text_buffer_insert_with_tags_by_name(buffer,
1568                                 &iter, trans_hdr, -1,
1569                                 "header_title", "header", NULL);
1570                         gtk_text_buffer_insert_with_tags_by_name(buffer,
1571                                 &iter, ":", 1, "header_title", "header", NULL);
1572                         g_free(hdr);
1573                 } else {
1574                         gtk_text_buffer_insert_with_tags_by_name(buffer,
1575                                 &iter, header->name,
1576                                 -1, "header_title", "header", NULL);
1577                 }
1578                 if (header->name[strlen(header->name) - 1] != ' ')
1579                 gtk_text_buffer_insert_with_tags_by_name
1580                                 (buffer, &iter, " ", 1,
1581                                  "header_title", "header", NULL);
1582
1583                 if (procheader_headername_equal(header->name, "Subject") ||
1584                     procheader_headername_equal(header->name, "From")    ||
1585                     procheader_headername_equal(header->name, "To")      ||
1586                     procheader_headername_equal(header->name, "Cc"))
1587                         unfold_line(header->body);
1588
1589                 if ((procheader_headername_equal(header->name, "X-Mailer") ||
1590                      procheader_headername_equal(header->name,
1591                                                  "X-Newsreader")) &&
1592                     strstr(header->body, "Sylpheed-Claws") != NULL) {
1593                         gtk_text_buffer_get_end_iter (buffer, &iter);
1594                         gtk_text_buffer_insert_with_tags_by_name
1595                                 (buffer, &iter, header->body, -1,
1596                                  "header", "emphasis", NULL);
1597                 } else {
1598                         gboolean hdr = 
1599                           procheader_headername_equal(header->name, "From") ||
1600                           procheader_headername_equal(header->name, "To") ||
1601                           procheader_headername_equal(header->name, "Cc") ||
1602                           procheader_headername_equal(header->name, "Bcc") ||
1603                           procheader_headername_equal(header->name, "Reply-To") ||
1604                           procheader_headername_equal(header->name, "Sender");
1605                         textview_make_clickable_parts(textview, "header", 
1606                                                       "link", header->body, 
1607                                                       hdr);
1608                 }
1609                 gtk_text_buffer_get_end_iter (buffer, &iter);
1610                 gtk_text_buffer_insert_with_tags_by_name(buffer, &iter, "\n", 1,
1611                                                          "header", NULL);
1612         }
1613         
1614         textview_show_face(textview);
1615 #if HAVE_LIBCOMPFACE
1616         textview_show_xface(textview);
1617 #endif
1618 }
1619
1620 gboolean textview_search_string(TextView *textview, const gchar *str,
1621                                 gboolean case_sens)
1622 {
1623         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1624
1625         return gtkut_text_view_search_string(text, str, case_sens);
1626 }
1627
1628 gboolean textview_search_string_backward(TextView *textview, const gchar *str,
1629                                          gboolean case_sens)
1630 {
1631         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1632
1633         return gtkut_text_view_search_string_backward(text, str, case_sens);
1634 }
1635
1636 void textview_scroll_one_line(TextView *textview, gboolean up)
1637 {
1638         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1639         GtkAdjustment *vadj = text->vadjustment;
1640         gfloat upper;
1641
1642         if (prefs_common.enable_smooth_scroll) {
1643                 textview_smooth_scroll_one_line(textview, up);
1644                 return;
1645         }
1646
1647         if (!up) {
1648                 upper = vadj->upper - vadj->page_size;
1649                 if (vadj->value < upper) {
1650                         vadj->value += vadj->step_increment;
1651                         vadj->value = MIN(vadj->value, upper);
1652                         g_signal_emit_by_name(G_OBJECT(vadj),
1653                                               "value_changed", 0);
1654                 }
1655         } else {
1656                 if (vadj->value > 0.0) {
1657                         vadj->value -= vadj->step_increment;
1658                         vadj->value = MAX(vadj->value, 0.0);
1659                         g_signal_emit_by_name(G_OBJECT(vadj),
1660                                               "value_changed", 0);
1661                 }
1662         }
1663 }
1664
1665 gboolean textview_scroll_page(TextView *textview, gboolean up)
1666 {
1667         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1668         GtkAdjustment *vadj = text->vadjustment;
1669         gfloat upper;
1670         gfloat page_incr;
1671
1672         if (prefs_common.enable_smooth_scroll)
1673                 return textview_smooth_scroll_page(textview, up);
1674
1675         if (prefs_common.scroll_halfpage)
1676                 page_incr = vadj->page_increment / 2;
1677         else
1678                 page_incr = vadj->page_increment;
1679
1680         if (!up) {
1681                 upper = vadj->upper - vadj->page_size;
1682                 if (vadj->value < upper) {
1683                         vadj->value += page_incr;
1684                         vadj->value = MIN(vadj->value, upper);
1685                         g_signal_emit_by_name(G_OBJECT(vadj),
1686                                               "value_changed", 0);
1687                 } else
1688                         return FALSE;
1689         } else {
1690                 if (vadj->value > 0.0) {
1691                         vadj->value -= page_incr;
1692                         vadj->value = MAX(vadj->value, 0.0);
1693                         g_signal_emit_by_name(G_OBJECT(vadj),
1694                                               "value_changed", 0);
1695                 } else
1696                         return FALSE;
1697         }
1698
1699         return TRUE;
1700 }
1701
1702 static void textview_smooth_scroll_do(TextView *textview,
1703                                       gfloat old_value, gfloat last_value,
1704                                       gint step)
1705 {
1706         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1707         GtkAdjustment *vadj = text->vadjustment;
1708         gint change_value;
1709         gboolean up;
1710         gint i;
1711
1712         if (old_value < last_value) {
1713                 change_value = last_value - old_value;
1714                 up = FALSE;
1715         } else {
1716                 change_value = old_value - last_value;
1717                 up = TRUE;
1718         }
1719
1720         for (i = step; i <= change_value; i += step) {
1721                 vadj->value = old_value + (up ? -i : i);
1722                 g_signal_emit_by_name(G_OBJECT(vadj),
1723                                       "value_changed", 0);
1724         }
1725
1726         vadj->value = last_value;
1727         g_signal_emit_by_name(G_OBJECT(vadj), "value_changed", 0);
1728
1729         gtk_widget_queue_draw(GTK_WIDGET(text));
1730 }
1731
1732 static void textview_smooth_scroll_one_line(TextView *textview, gboolean up)
1733 {
1734         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1735         GtkAdjustment *vadj = text->vadjustment;
1736         gfloat upper;
1737         gfloat old_value;
1738         gfloat last_value;
1739
1740         if (!up) {
1741                 upper = vadj->upper - vadj->page_size;
1742                 if (vadj->value < upper) {
1743                         old_value = vadj->value;
1744                         last_value = vadj->value + vadj->step_increment;
1745                         last_value = MIN(last_value, upper);
1746
1747                         textview_smooth_scroll_do(textview, old_value,
1748                                                   last_value,
1749                                                   prefs_common.scroll_step);
1750                 }
1751         } else {
1752                 if (vadj->value > 0.0) {
1753                         old_value = vadj->value;
1754                         last_value = vadj->value - vadj->step_increment;
1755                         last_value = MAX(last_value, 0.0);
1756
1757                         textview_smooth_scroll_do(textview, old_value,
1758                                                   last_value,
1759                                                   prefs_common.scroll_step);
1760                 }
1761         }
1762 }
1763
1764 static gboolean textview_smooth_scroll_page(TextView *textview, gboolean up)
1765 {
1766         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1767         GtkAdjustment *vadj = text->vadjustment;
1768         gfloat upper;
1769         gfloat page_incr;
1770         gfloat old_value;
1771         gfloat last_value;
1772
1773         if (prefs_common.scroll_halfpage)
1774                 page_incr = vadj->page_increment / 2;
1775         else
1776                 page_incr = vadj->page_increment;
1777
1778         if (!up) {
1779                 upper = vadj->upper - vadj->page_size;
1780                 if (vadj->value < upper) {
1781                         old_value = vadj->value;
1782                         last_value = vadj->value + page_incr;
1783                         last_value = MIN(last_value, upper);
1784
1785                         textview_smooth_scroll_do(textview, old_value,
1786                                                   last_value,
1787                                                   prefs_common.scroll_step);
1788                 } else
1789                         return FALSE;
1790         } else {
1791                 if (vadj->value > 0.0) {
1792                         old_value = vadj->value;
1793                         last_value = vadj->value - page_incr;
1794                         last_value = MAX(last_value, 0.0);
1795
1796                         textview_smooth_scroll_do(textview, old_value,
1797                                                   last_value,
1798                                                   prefs_common.scroll_step);
1799                 } else
1800                         return FALSE;
1801         }
1802
1803         return TRUE;
1804 }
1805
1806 #define KEY_PRESS_EVENT_STOP() \
1807         g_signal_stop_emission_by_name(G_OBJECT(widget), \
1808                                        "key_press_event");
1809
1810 static gint textview_key_pressed(GtkWidget *widget, GdkEventKey *event,
1811                                  TextView *textview)
1812 {
1813         SummaryView *summaryview = NULL;
1814         MessageView *messageview = textview->messageview;
1815
1816         if (!event) return FALSE;
1817         if (messageview->mainwin)
1818                 summaryview = messageview->mainwin->summaryview;
1819
1820         switch (event->keyval) {
1821         case GDK_Tab:
1822         case GDK_Home:
1823         case GDK_Left:
1824         case GDK_Up:
1825         case GDK_Right:
1826         case GDK_Down:
1827         case GDK_Page_Up:
1828         case GDK_Page_Down:
1829         case GDK_End:
1830         case GDK_Control_L:
1831         case GDK_Control_R:
1832                 return FALSE;
1833         case GDK_space:
1834                 if (summaryview)
1835                         summary_pass_key_press_event(summaryview, event);
1836                 else
1837                         textview_scroll_page
1838                                 (textview,
1839                                  (event->state &
1840                                   (GDK_SHIFT_MASK|GDK_MOD1_MASK)) != 0);
1841                 break;
1842         case GDK_BackSpace:
1843                 textview_scroll_page(textview, TRUE);
1844                 break;
1845         case GDK_Return:
1846                 textview_scroll_one_line
1847                         (textview, (event->state &
1848                                     (GDK_SHIFT_MASK|GDK_MOD1_MASK)) != 0);
1849                 break;
1850         case GDK_Delete:
1851                 if (summaryview)
1852                         summary_pass_key_press_event(summaryview, event);
1853                 break;
1854         case GDK_y:
1855         case GDK_t:
1856         case GDK_l:
1857         case GDK_c:
1858                 if ((event->state & (GDK_MOD1_MASK|GDK_CONTROL_MASK)) == 0) {
1859                         KEY_PRESS_EVENT_STOP();
1860                         mimeview_pass_key_press_event(messageview->mimeview,
1861                                                       event);
1862                         break;
1863                 }
1864                 /* possible fall through */
1865         default:
1866                 if (summaryview &&
1867                     event->window != messageview->mainwin->window->window) {
1868                         GdkEventKey tmpev = *event;
1869
1870                         tmpev.window = messageview->mainwin->window->window;
1871                         KEY_PRESS_EVENT_STOP();
1872                         gtk_widget_event(messageview->mainwin->window,
1873                                          (GdkEvent *)&tmpev);
1874                 }
1875                 break;
1876         }
1877
1878         return TRUE;
1879 }
1880
1881 static gboolean textview_motion_notify(GtkWidget *widget,
1882                                        GdkEventMotion *event,
1883                                        TextView *textview)
1884 {
1885         textview_uri_update(textview, event->x, event->y);
1886         gdk_window_get_pointer(widget->window, NULL, NULL, NULL);
1887
1888         return FALSE;
1889 }
1890
1891 static gboolean textview_leave_notify(GtkWidget *widget,
1892                                       GdkEventCrossing *event,
1893                                       TextView *textview)
1894 {
1895         textview_uri_update(textview, -1, -1);
1896
1897         return FALSE;
1898 }
1899
1900 static gboolean textview_visibility_notify(GtkWidget *widget,
1901                                            GdkEventVisibility *event,
1902                                            TextView *textview)
1903 {
1904         gint wx, wy;
1905         GdkWindow *window;
1906
1907         window = gtk_text_view_get_window(GTK_TEXT_VIEW(widget),
1908                                           GTK_TEXT_WINDOW_TEXT);
1909
1910         /* check if occurred for the text window part */
1911         if (window != event->window)
1912                 return FALSE;
1913         
1914         gdk_window_get_pointer(widget->window, &wx, &wy, NULL);
1915         textview_uri_update(textview, wx, wy);
1916
1917         return FALSE;
1918 }
1919
1920 void textview_cursor_wait(TextView *textview)
1921 {
1922         GdkWindow *window = gtk_text_view_get_window(
1923                         GTK_TEXT_VIEW(textview->text),
1924                         GTK_TEXT_WINDOW_TEXT);
1925         textview_set_cursor(window, watch_cursor);
1926 }
1927
1928 void textview_cursor_normal(TextView *textview)
1929 {
1930         GdkWindow *window = gtk_text_view_get_window(
1931                         GTK_TEXT_VIEW(textview->text),
1932                         GTK_TEXT_WINDOW_TEXT);
1933         textview_set_cursor(window, text_cursor);
1934 }
1935
1936 static void textview_uri_update(TextView *textview, gint x, gint y)
1937 {
1938         GtkTextBuffer *buffer;
1939         GtkTextIter start_iter, end_iter;
1940         RemoteURI *uri = NULL;
1941         
1942         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview->text));
1943
1944         if (x != -1 && y != -1) {
1945                 gint bx, by;
1946                 GtkTextIter iter;
1947                 GSList *tags;
1948                 GSList *cur;
1949             
1950                 gtk_text_view_window_to_buffer_coords(GTK_TEXT_VIEW(textview->text), 
1951                                                       GTK_TEXT_WINDOW_WIDGET,
1952                                                       x, y, &bx, &by);
1953                 gtk_text_view_get_iter_at_location(GTK_TEXT_VIEW(textview->text),
1954                                                    &iter, bx, by);
1955
1956                 tags = gtk_text_iter_get_tags(&iter);
1957                 for (cur = tags; cur != NULL; cur = cur->next) {
1958                         GtkTextTag *tag = cur->data;
1959                         char *name;
1960
1961                         g_object_get(G_OBJECT(tag), "name", &name, NULL);
1962                         if (!strcmp(name, "link")
1963                             && textview_get_uri_range(textview, &iter, tag,
1964                                                       &start_iter, &end_iter))
1965                                 uri = textview_get_uri_from_range(textview,
1966                                                                   &iter, tag,
1967                                                                   &start_iter,
1968                                                                   &end_iter);
1969                         g_free(name);
1970
1971                         if (uri)
1972                                 break;
1973                 }
1974                 g_slist_free(tags);
1975         }
1976         
1977         if (uri != textview->uri_hover) {
1978                 GdkWindow *window;
1979
1980                 if (textview->uri_hover)
1981                         gtk_text_buffer_remove_tag_by_name(buffer,
1982                                                            "link-hover",
1983                                                            &textview->uri_hover_start_iter,
1984                                                            &textview->uri_hover_end_iter);
1985                     
1986                 textview->uri_hover = uri;
1987                 if (uri) {
1988                         textview->uri_hover_start_iter = start_iter;
1989                         textview->uri_hover_end_iter = end_iter;
1990                 }
1991                 
1992                 window = gtk_text_view_get_window(GTK_TEXT_VIEW(textview->text),
1993                                                   GTK_TEXT_WINDOW_TEXT);
1994                 if (textview->messageview->mainwin->cursor_count == 0) {
1995                         textview_set_cursor(window, uri ? hand_cursor : text_cursor);
1996                 } else {
1997                         textview_set_cursor(window, watch_cursor);
1998                 }
1999
2000                 TEXTVIEW_STATUSBAR_POP(textview);
2001
2002                 if (uri) {
2003                         char *trimmed_uri;
2004
2005                         gtk_text_buffer_apply_tag_by_name(buffer,
2006                                                           "link-hover",
2007                                                           &start_iter,
2008                                                           &end_iter);
2009
2010                         trimmed_uri = trim_string(uri->uri, 60);
2011                         TEXTVIEW_STATUSBAR_PUSH(textview, trimmed_uri);
2012                         g_free(trimmed_uri);
2013                 }
2014         }
2015 }
2016
2017 static gboolean textview_get_uri_range(TextView *textview,
2018                                        GtkTextIter *iter,
2019                                        GtkTextTag *tag,
2020                                        GtkTextIter *start_iter,
2021                                        GtkTextIter *end_iter)
2022 {
2023         return get_tag_range(iter, tag, start_iter, end_iter);
2024 }
2025
2026 static RemoteURI *textview_get_uri_from_range(TextView *textview,
2027                                               GtkTextIter *iter,
2028                                               GtkTextTag *tag,
2029                                               GtkTextIter *start_iter,
2030                                               GtkTextIter *end_iter)
2031 {
2032         gint start_pos, end_pos, cur_pos;
2033         RemoteURI *uri = NULL;
2034         GSList *cur;
2035
2036         start_pos = gtk_text_iter_get_offset(start_iter);
2037         end_pos = gtk_text_iter_get_offset(end_iter);
2038         cur_pos = gtk_text_iter_get_offset(iter);
2039
2040         for (cur = textview->uri_list; cur != NULL; cur = cur->next) {
2041                 RemoteURI *uri_ = (RemoteURI *)cur->data;
2042                 if (start_pos == uri_->start &&
2043                     end_pos ==  uri_->end) {
2044                         uri = uri_;
2045                         break;
2046                 } else if (start_pos == uri_->start ||
2047                            end_pos == uri_->end) {
2048                         /* in case of contiguous links, textview_get_uri_range
2049                          * returns a broader range (start of 1st link to end
2050                          * of last link).
2051                          * In that case, correct link is the one covering
2052                          * current iter.
2053                          */
2054                         if (uri_->start <= cur_pos && cur_pos <= uri_->end) {
2055                                 uri = uri_;
2056                                 break;
2057                         }
2058                 } 
2059         }
2060
2061         return uri;
2062 }
2063
2064 static RemoteURI *textview_get_uri(TextView *textview,
2065                                    GtkTextIter *iter,
2066                                    GtkTextTag *tag)
2067 {
2068         GtkTextIter start_iter, end_iter;
2069         RemoteURI *uri = NULL;
2070
2071         if (textview_get_uri_range(textview, iter, tag, &start_iter,
2072                                    &end_iter))
2073                 uri = textview_get_uri_from_range(textview, iter, tag,
2074                                                   &start_iter, &end_iter);
2075
2076         return uri;
2077 }
2078
2079 static gboolean textview_uri_button_pressed(GtkTextTag *tag, GObject *obj,
2080                                             GdkEvent *event, GtkTextIter *iter,
2081                                             TextView *textview)
2082 {
2083         GdkEventButton *bevent;
2084         RemoteURI *uri = NULL;
2085
2086         if (!event)
2087                 return FALSE;
2088
2089         if (event->type != GDK_BUTTON_PRESS && event->type != GDK_2BUTTON_PRESS
2090                 && event->type != GDK_MOTION_NOTIFY)
2091                 return FALSE;
2092
2093         uri = textview_get_uri(textview, iter, tag);
2094         if (!uri)
2095                 return FALSE;
2096
2097         bevent = (GdkEventButton *) event;
2098         
2099         /* doubleclick: open compose / add address / browser */
2100         if ((event->type == GDK_BUTTON_PRESS && bevent->button == 1) ||
2101                 bevent->button == 2 || bevent->button == 3) {
2102                 if (uri->filename && !g_ascii_strncasecmp(uri->filename, "sc://", 5)) {
2103                         MimeView *mimeview = 
2104                                 (textview->messageview)?
2105                                         textview->messageview->mimeview:NULL;
2106                         if (mimeview && bevent->button == 1) {
2107                                 mimeview_handle_cmd(mimeview, uri->filename, NULL, uri->data);
2108                         } else if (mimeview && bevent->button == 2 && 
2109                                 !g_ascii_strcasecmp(uri->filename, "sc://select_attachment")) {
2110                                 mimeview_handle_cmd(mimeview, "sc://open_attachment", NULL, uri->data);
2111                         } else if (mimeview && bevent->button == 3 && 
2112                                 !g_ascii_strcasecmp(uri->filename, "sc://select_attachment")) {
2113                                 mimeview_handle_cmd(mimeview, "sc://menu_attachment", bevent, uri->data);
2114                         } 
2115                         return TRUE;
2116                 } else if (!g_ascii_strncasecmp(uri->uri, "mailto:", 7)) {
2117                         if (bevent->button == 3) {
2118                                 g_object_set_data(
2119                                         G_OBJECT(textview->mail_popup_menu),
2120                                         "menu_button", uri);
2121                                 gtk_menu_popup(GTK_MENU(textview->mail_popup_menu), 
2122                                                NULL, NULL, NULL, NULL, 
2123                                                bevent->button, bevent->time);
2124                         } else {
2125                                 PrefsAccount *account = NULL;
2126
2127                                 if (textview->messageview && textview->messageview->msginfo &&
2128                                     textview->messageview->msginfo->folder) {
2129                                         FolderItem   *folder_item;
2130
2131                                         folder_item = textview->messageview->msginfo->folder;
2132                                         if (folder_item->prefs && folder_item->prefs->enable_default_account)
2133                                                 account = account_find_from_id(folder_item->prefs->default_account);
2134                                 }
2135                                 compose_new(account, uri->uri + 7, NULL);
2136                         }
2137                         return TRUE;
2138                 } else if (g_ascii_strncasecmp(uri->uri, "file:", 5)) {
2139                         if (bevent->button == 1 &&
2140                             textview_uri_security_check(textview, uri) == TRUE) 
2141                                         open_uri(uri->uri,
2142                                                  prefs_common.uri_cmd);
2143                         else if (bevent->button == 3) {
2144                                 g_object_set_data(
2145                                         G_OBJECT(textview->link_popup_menu),
2146                                         "menu_button", uri);
2147                                 gtk_menu_popup(GTK_MENU(textview->link_popup_menu), 
2148                                                NULL, NULL, NULL, NULL, 
2149                                                bevent->button, bevent->time);
2150                         }
2151                         return TRUE;
2152                 } else {
2153                         if (bevent->button == 3) {
2154                                 g_object_set_data(
2155                                         G_OBJECT(textview->file_popup_menu),
2156                                         "menu_button", uri);
2157                                 gtk_menu_popup(GTK_MENU(textview->file_popup_menu), 
2158                                                NULL, NULL, NULL, NULL, 
2159                                                bevent->button, bevent->time);
2160                                 return TRUE;
2161                         }
2162                 }
2163         }
2164
2165         return FALSE;
2166 }
2167
2168 /*!
2169  *\brief    Check to see if a web URL has been disguised as a different
2170  *          URL (possible with HTML email).
2171  *
2172  *\param    uri The uri to check
2173  *
2174  *\param    textview The TextView the URL is contained in
2175  *
2176  *\return   gboolean TRUE if the URL is ok, or if the user chose to open
2177  *          it anyway, otherwise FALSE          
2178  */
2179 static gboolean textview_uri_security_check(TextView *textview, RemoteURI *uri)
2180 {
2181         gchar *visible_str;
2182         gboolean retval = TRUE;
2183         GtkTextBuffer *buffer;
2184         GtkTextIter start, end;
2185
2186         if (is_uri_string(uri->uri) == FALSE)
2187                 return TRUE;
2188
2189         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview->text));
2190
2191         gtk_text_buffer_get_iter_at_offset(buffer, &start, uri->start);
2192         gtk_text_buffer_get_iter_at_offset(buffer, &end,   uri->end);
2193
2194         visible_str = gtk_text_buffer_get_text(buffer, &start, &end, FALSE);
2195
2196         if (visible_str == NULL)
2197                 return TRUE;
2198
2199         if (strcmp(visible_str, uri->uri) != 0 && is_uri_string(visible_str)) {
2200                 gchar *uri_path;
2201                 gchar *visible_uri_path;
2202
2203                 uri_path = get_uri_path(uri->uri);
2204                 visible_uri_path = get_uri_path(visible_str);
2205                 if (path_cmp(uri_path, visible_uri_path) != 0)
2206                         retval = FALSE;
2207         }
2208
2209         if (retval == FALSE) {
2210                 gchar *msg;
2211                 AlertValue aval;
2212
2213                 msg = g_markup_printf_escaped(_("The real URL is different from "
2214                                                 "the displayed URL.\n"
2215                                                 "\n"
2216                                                 "<b>Displayed URL:</b> %s\n"
2217                                                 "\n"
2218                                                 "<b>Real URL:</b> %s\n"
2219                                                 "\n"
2220                                                 "Open it anyway?"),
2221                                                visible_str,uri->uri);
2222                 aval = alertpanel_full(_("Phishing attempt warning"), msg,
2223                                        GTK_STOCK_CANCEL, _("_Open URL"), NULL, FALSE,
2224                                        NULL, ALERT_WARNING, G_ALERTDEFAULT);
2225                 g_free(msg);
2226                 if (aval == G_ALERTALTERNATE)
2227                         retval = TRUE;
2228         }
2229
2230         g_free(visible_str);
2231
2232         return retval;
2233 }
2234
2235 static void textview_uri_list_remove_all(GSList *uri_list)
2236 {
2237         GSList *cur;
2238
2239         for (cur = uri_list; cur != NULL; cur = cur->next) {
2240                 if (cur->data) {
2241                         g_free(((RemoteURI *)cur->data)->uri);
2242                         g_free(((RemoteURI *)cur->data)->filename);
2243                         g_free(cur->data);
2244                 }
2245         }
2246
2247         g_slist_free(uri_list);
2248 }
2249
2250 static void open_uri_cb (TextView *textview, guint action, void *data)
2251 {
2252         RemoteURI *uri = g_object_get_data(G_OBJECT(textview->link_popup_menu),
2253                                            "menu_button");
2254         if (uri == NULL)
2255                 return;
2256
2257         if (textview_uri_security_check(textview, uri) == TRUE) 
2258                 open_uri(uri->uri,
2259                          prefs_common.uri_cmd);
2260         g_object_set_data(G_OBJECT(textview->link_popup_menu), "menu_button",
2261                           NULL);
2262 }
2263
2264 static void open_image_cb (TextView *textview, guint action, void *data)
2265 {
2266         RemoteURI *uri = g_object_get_data(G_OBJECT(textview->file_popup_menu),
2267                                            "menu_button");
2268
2269         static gchar *default_cmdline = DEFAULT_IMAGE_VIEWER_CMD;
2270         gchar buf[1024];
2271         const gchar *cmd;
2272         const gchar *def_cmd;
2273         const gchar *p;
2274         gchar *filename = NULL;
2275         gchar *tmp_filename = NULL;
2276
2277         if (uri == NULL)
2278                 return;
2279
2280         if (uri->filename == NULL)
2281                 return;
2282         
2283         filename = g_strdup(uri->filename);
2284         
2285         if (!g_utf8_validate(filename, -1, NULL)) {
2286                 gchar *tmp = conv_filename_to_utf8(filename);
2287                 g_free(filename);
2288                 filename = tmp;
2289         }
2290
2291         subst_for_filename(filename);
2292
2293         tmp_filename = g_filename_from_uri(uri->uri, NULL, NULL);
2294         copy_file(tmp_filename, filename, FALSE);
2295         g_free(tmp_filename);
2296
2297         cmd = prefs_common.mime_image_viewer;
2298         def_cmd = default_cmdline;
2299         
2300         if (cmd && (p = strchr(cmd, '%')) && *(p + 1) == 's' &&
2301             !strchr(p + 2, '%'))
2302                 g_snprintf(buf, sizeof(buf), cmd, filename);
2303         else {
2304                 if (cmd)
2305                         g_warning("Image viewer command line is invalid: '%s'", cmd);
2306                 if (def_cmd)
2307                         g_snprintf(buf, sizeof(buf), def_cmd, filename);
2308                 else
2309                         return;
2310         }
2311
2312         execute_command_line(buf, TRUE);
2313
2314         g_free(filename);
2315
2316         g_object_set_data(G_OBJECT(textview->file_popup_menu), "menu_button",
2317                           NULL);
2318 }
2319
2320 static void save_file_cb (TextView *textview, guint action, void *data)
2321 {
2322         RemoteURI *uri = g_object_get_data(G_OBJECT(textview->file_popup_menu),
2323                                            "menu_button");
2324         gchar *filename = NULL;
2325         gchar *filepath = NULL;
2326         gchar *filedir = NULL;
2327         gchar *tmp_filename = NULL;
2328         if (uri == NULL)
2329                 return;
2330
2331         if (uri->filename == NULL)
2332                 return;
2333         
2334         filename = g_strdup(uri->filename);
2335         
2336         if (!g_utf8_validate(filename, -1, NULL)) {
2337                 gchar *tmp = conv_filename_to_utf8(filename);
2338                 g_free(filename);
2339                 filename = tmp;
2340         }
2341
2342         subst_for_filename(filename);
2343         
2344         if (prefs_common.attach_save_dir)
2345                 filepath = g_strconcat(prefs_common.attach_save_dir,
2346                                        G_DIR_SEPARATOR_S, filename, NULL);
2347         else
2348                 filepath = g_strdup(filename);
2349
2350         g_free(filename);
2351
2352         filename = filesel_select_file_save(_("Save as"), filepath);
2353         if (!filename) {
2354                 g_free(filepath);
2355                 return;
2356         }
2357
2358         if (is_file_exist(filename)) {
2359                 AlertValue aval;
2360                 gchar *res;
2361                 
2362                 res = g_strdup_printf(_("Overwrite existing file '%s'?"),
2363                                       filename);
2364                 aval = alertpanel(_("Overwrite"), res, GTK_STOCK_CANCEL, 
2365                                   GTK_STOCK_OK, NULL);
2366                 g_free(res);                                      
2367                 if (G_ALERTALTERNATE != aval)
2368                         return;
2369         }
2370
2371         tmp_filename = g_filename_from_uri(uri->uri, NULL, NULL);
2372         copy_file(tmp_filename, filename, FALSE);
2373         g_free(tmp_filename);
2374         
2375         filedir = g_path_get_dirname(filename);
2376         if (filedir && strcmp(filedir, ".")) {
2377                 g_free(prefs_common.attach_save_dir);
2378                 prefs_common.attach_save_dir = g_strdup(filedir);
2379         }
2380
2381         g_free(filedir);
2382         g_free(filepath);
2383
2384         g_object_set_data(G_OBJECT(textview->file_popup_menu), "menu_button",
2385                           NULL);
2386 }
2387
2388 static void copy_uri_cb (TextView *textview, guint action, void *data)
2389 {
2390         RemoteURI *uri = g_object_get_data(G_OBJECT(textview->link_popup_menu),
2391                                            "menu_button");
2392         if (uri == NULL)
2393                 return;
2394
2395         gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), uri->uri, -1);
2396         gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), uri->uri, -1);
2397         g_object_set_data(G_OBJECT(textview->link_popup_menu), "menu_button",
2398                           NULL);
2399 }
2400
2401 static void add_uri_to_addrbook_cb (TextView *textview, guint action, void *data)
2402 {
2403         gchar *fromname, *fromaddress;
2404         RemoteURI *uri = g_object_get_data(G_OBJECT(textview->mail_popup_menu),
2405                                            "menu_button");
2406         if (uri == NULL)
2407                 return;
2408
2409         /* extract url */
2410         fromaddress = g_strdup(uri->uri + 7);
2411         /* Hiroyuki: please put this function in utils.c! */
2412         fromname = procheader_get_fromname(fromaddress);
2413         extract_address(fromaddress);
2414         g_message("adding from textview %s <%s>", fromname, fromaddress);
2415         /* Add to address book - Match */
2416         addressbook_add_contact( fromname, fromaddress, NULL );
2417
2418         g_free(fromaddress);
2419         g_free(fromname);
2420 }
2421
2422 static void mail_to_uri_cb (TextView *textview, guint action, void *data)
2423 {
2424         PrefsAccount *account = NULL;
2425         RemoteURI *uri = g_object_get_data(G_OBJECT(textview->mail_popup_menu),
2426                                            "menu_button");
2427         if (uri == NULL)
2428                 return;
2429
2430         if (textview->messageview && textview->messageview->msginfo &&
2431             textview->messageview->msginfo->folder) {
2432                 FolderItem   *folder_item;
2433
2434                 folder_item = textview->messageview->msginfo->folder;
2435                 if (folder_item->prefs && folder_item->prefs->enable_default_account)
2436                         account = account_find_from_id(folder_item->prefs->default_account);
2437         }
2438         compose_new(account, uri->uri + 7, NULL);
2439 }
2440
2441 static void copy_mail_to_uri_cb (TextView *textview, guint action, void *data)
2442 {
2443         RemoteURI *uri = g_object_get_data(G_OBJECT(textview->mail_popup_menu),
2444                                            "menu_button");
2445         if (uri == NULL)
2446                 return;
2447
2448         gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), uri->uri +7, -1);
2449         gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), uri->uri +7, -1);
2450         g_object_set_data(G_OBJECT(textview->mail_popup_menu), "menu_button",
2451                           NULL);
2452 }
2453