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