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