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