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