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