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