2006-04-06 [mones] 2.1.0cvs7
[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
1164         textview->body_pos = 0;
1165         if (textview->image) 
1166                 gtk_widget_destroy(textview->image);
1167         textview->image = NULL;
1168
1169         if (textview->messageview->mainwin->cursor_count == 0) {
1170                 gdk_window_set_cursor(window, text_cursor);
1171         } else {
1172                 gdk_window_set_cursor(window, watch_cursor);
1173         }
1174 }
1175
1176 void textview_destroy(TextView *textview)
1177 {
1178         textview_uri_list_remove_all(textview->uri_list);
1179         textview->uri_list = NULL;
1180
1181         g_free(textview);
1182 }
1183
1184 void textview_set_all_headers(TextView *textview, gboolean all_headers)
1185 {
1186         textview->show_all_headers = all_headers;
1187 }
1188
1189 #define CHANGE_TAG_FONT(tagname, font) { \
1190         tag = gtk_text_tag_table_lookup(tags, tagname); \
1191         if (tag) \
1192                 g_object_set(G_OBJECT(tag), "font-desc", font, NULL); \
1193 }
1194
1195 void textview_set_font(TextView *textview, const gchar *codeset)
1196 {
1197         GtkTextTag *tag;
1198         GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview->text));
1199         GtkTextTagTable *tags = gtk_text_buffer_get_tag_table(buffer);
1200         
1201         if (NORMAL_FONT) {
1202                 PangoFontDescription *font_desc, *bold_font_desc;
1203                 font_desc = pango_font_description_from_string
1204                                                 (NORMAL_FONT);
1205                 bold_font_desc = pango_font_description_from_string
1206                                                 (NORMAL_FONT);
1207                 if (font_desc) {
1208                         gtk_widget_modify_font(textview->text, font_desc);
1209                         CHANGE_TAG_FONT("header", font_desc);
1210                         pango_font_description_free(font_desc);
1211                 }
1212                 if (bold_font_desc) {
1213                         pango_font_description_set_weight
1214                                 (bold_font_desc, PANGO_WEIGHT_BOLD);
1215                         CHANGE_TAG_FONT("header_title", bold_font_desc);
1216                         pango_font_description_free(bold_font_desc);
1217                 }
1218         }
1219
1220         if (prefs_common.textfont) {
1221                 PangoFontDescription *font_desc;
1222
1223                 font_desc = pango_font_description_from_string
1224                                                 (prefs_common.textfont);
1225                 if (font_desc) {
1226                         gtk_widget_modify_font(textview->text, font_desc);
1227                         pango_font_description_free(font_desc);
1228                 }
1229         }
1230         gtk_text_view_set_pixels_above_lines(GTK_TEXT_VIEW(textview->text),
1231                                              prefs_common.line_space / 2);
1232         gtk_text_view_set_pixels_below_lines(GTK_TEXT_VIEW(textview->text),
1233                                              prefs_common.line_space / 2);
1234 }
1235
1236 void textview_set_text(TextView *textview, const gchar *text)
1237 {
1238         GtkTextView *view;
1239         GtkTextBuffer *buffer;
1240
1241         g_return_if_fail(textview != NULL);
1242         g_return_if_fail(text != NULL);
1243
1244         textview_clear(textview);
1245
1246         view = GTK_TEXT_VIEW(textview->text);
1247         buffer = gtk_text_view_get_buffer(view);
1248         gtk_text_buffer_set_text(buffer, text, strlen(text));
1249 }
1250
1251 enum
1252 {
1253         H_DATE          = 0,
1254         H_FROM          = 1,
1255         H_TO            = 2,
1256         H_NEWSGROUPS    = 3,
1257         H_SUBJECT       = 4,
1258         H_CC            = 5,
1259         H_REPLY_TO      = 6,
1260         H_FOLLOWUP_TO   = 7,
1261         H_X_MAILER      = 8,
1262         H_X_NEWSREADER  = 9,
1263         H_USER_AGENT    = 10,
1264         H_ORGANIZATION  = 11,
1265 };
1266
1267 void textview_set_position(TextView *textview, gint pos)
1268 {
1269         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1270
1271         gtkut_text_view_set_position(text, pos);
1272 }
1273
1274 static GPtrArray *textview_scan_header(TextView *textview, FILE *fp)
1275 {
1276         gchar buf[BUFFSIZE];
1277         GPtrArray *headers, *sorted_headers;
1278         GSList *disphdr_list;
1279         Header *header;
1280         gint i;
1281
1282         g_return_val_if_fail(fp != NULL, NULL);
1283
1284         if (textview->show_all_headers)
1285                 return procheader_get_header_array_asis(fp);
1286
1287         if (!prefs_common.display_header) {
1288                 while (fgets(buf, sizeof(buf), fp) != NULL)
1289                         if (buf[0] == '\r' || buf[0] == '\n') break;
1290                 return NULL;
1291         }
1292
1293         headers = procheader_get_header_array_asis(fp);
1294
1295         sorted_headers = g_ptr_array_new();
1296
1297         for (disphdr_list = prefs_common.disphdr_list; disphdr_list != NULL;
1298              disphdr_list = disphdr_list->next) {
1299                 DisplayHeaderProp *dp =
1300                         (DisplayHeaderProp *)disphdr_list->data;
1301
1302                 for (i = 0; i < headers->len; i++) {
1303                         header = g_ptr_array_index(headers, i);
1304
1305                         if (procheader_headername_equal(header->name,
1306                                                         dp->name)) {
1307                                 if (dp->hidden)
1308                                         procheader_header_free(header);
1309                                 else
1310                                         g_ptr_array_add(sorted_headers, header);
1311
1312                                 g_ptr_array_remove_index(headers, i);
1313                                 i--;
1314                         }
1315                 }
1316         }
1317
1318         if (prefs_common.show_other_header) {
1319                 for (i = 0; i < headers->len; i++) {
1320                         header = g_ptr_array_index(headers, i);
1321                         g_ptr_array_add(sorted_headers, header);
1322                 }
1323                 g_ptr_array_free(headers, TRUE);
1324         } else
1325                 procheader_header_array_destroy(headers);
1326
1327
1328         return sorted_headers;
1329 }
1330
1331 static void textview_show_face(TextView *textview)
1332 {
1333         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1334         MsgInfo *msginfo = textview->messageview->msginfo;
1335         int x = 0;
1336         
1337         if (prefs_common.display_header_pane
1338         ||  !prefs_common.display_xface)
1339                 goto bail;
1340         
1341         if (!msginfo->face) {
1342                 goto bail;
1343         }
1344
1345         if (textview->image) 
1346                 gtk_widget_destroy(textview->image);
1347         
1348         textview->image = face_get_from_header(msginfo->face);
1349         g_return_if_fail(textview->image != NULL);
1350
1351         gtk_widget_show(textview->image);
1352         
1353         x = textview->text->allocation.width - WIDTH -5;
1354
1355         gtk_text_view_add_child_in_window(text, textview->image, 
1356                 GTK_TEXT_WINDOW_TEXT, x, 5);
1357
1358         gtk_widget_show_all(textview->text);
1359         
1360
1361         return;
1362 bail:
1363         if (textview->image) 
1364                 gtk_widget_destroy(textview->image);
1365         textview->image = NULL; 
1366 }
1367
1368 static void textview_show_icon(TextView *textview, const gchar *stock_id)
1369 {
1370         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1371         int x = 0;
1372         
1373         if (textview->image) 
1374                 gtk_widget_destroy(textview->image);
1375         
1376         textview->image = gtk_image_new_from_stock(stock_id, GTK_ICON_SIZE_DIALOG);
1377         g_return_if_fail(textview->image != NULL);
1378
1379         gtk_widget_show(textview->image);
1380         
1381         x = textview->text->allocation.width - WIDTH -5;
1382
1383         gtk_text_view_add_child_in_window(text, textview->image, 
1384                 GTK_TEXT_WINDOW_TEXT, x, 5);
1385
1386         gtk_widget_show_all(textview->text);
1387         
1388
1389         return;
1390 }
1391
1392 #if HAVE_LIBCOMPFACE
1393 static void textview_show_xface(TextView *textview)
1394 {
1395         MsgInfo *msginfo = textview->messageview->msginfo;
1396         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1397         int x = 0;
1398
1399         if (prefs_common.display_header_pane
1400         ||  !prefs_common.display_xface)
1401                 goto bail;
1402         
1403         if (!msginfo)
1404                 goto bail;
1405
1406         if (msginfo->face)
1407                 return;
1408         
1409         if (!msginfo->xface || strlen(msginfo->xface) < 5) {
1410                 goto bail;
1411         }
1412
1413         if (textview->image) 
1414                 gtk_widget_destroy(textview->image);
1415         
1416         textview->image = xface_get_from_header(msginfo->xface,
1417                                 &textview->text->style->white,
1418                                 textview->text->window);
1419         g_return_if_fail(textview->image != NULL);
1420
1421         gtk_widget_show(textview->image);
1422         
1423         x = textview->text->allocation.width - WIDTH -5;
1424
1425         gtk_text_view_add_child_in_window(text, textview->image, 
1426                 GTK_TEXT_WINDOW_TEXT, x, 5);
1427
1428         gtk_widget_show_all(textview->text);
1429         
1430         return;
1431 bail:
1432         if (textview->image) 
1433                 gtk_widget_destroy(textview->image);
1434         textview->image = NULL;
1435         
1436 }
1437 #endif
1438
1439 static void textview_show_header(TextView *textview, GPtrArray *headers)
1440 {
1441         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1442         GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
1443         GtkTextIter iter;
1444         Header *header;
1445         gint i;
1446
1447         g_return_if_fail(headers != NULL);
1448
1449         for (i = 0; i < headers->len; i++) {
1450                 header = g_ptr_array_index(headers, i);
1451                 g_return_if_fail(header->name != NULL);
1452
1453                 gtk_text_buffer_get_end_iter (buffer, &iter);
1454                 if(prefs_common.trans_hdr == TRUE) {
1455                         gchar *hdr = g_strndup(header->name, strlen(header->name) - 1);
1456                         gchar *trans_hdr = gettext(hdr);
1457                         gtk_text_buffer_insert_with_tags_by_name(buffer,
1458                                 &iter, trans_hdr, -1,
1459                                 "header_title", "header", NULL);
1460                         gtk_text_buffer_insert_with_tags_by_name(buffer,
1461                                 &iter, ":", 1, "header_title", "header", NULL);
1462                         g_free(hdr);
1463                 } else {
1464                         gtk_text_buffer_insert_with_tags_by_name(buffer,
1465                                 &iter, header->name,
1466                                 -1, "header_title", "header", NULL);
1467                 }
1468                 if (header->name[strlen(header->name) - 1] != ' ')
1469                 gtk_text_buffer_insert_with_tags_by_name
1470                                 (buffer, &iter, " ", 1,
1471                                  "header_title", "header", NULL);
1472
1473                 if (procheader_headername_equal(header->name, "Subject") ||
1474                     procheader_headername_equal(header->name, "From")    ||
1475                     procheader_headername_equal(header->name, "To")      ||
1476                     procheader_headername_equal(header->name, "Cc"))
1477                         unfold_line(header->body);
1478
1479                 if ((procheader_headername_equal(header->name, "X-Mailer") ||
1480                      procheader_headername_equal(header->name,
1481                                                  "X-Newsreader")) &&
1482                     strstr(header->body, "Sylpheed-Claws") != NULL) {
1483                         gtk_text_buffer_get_end_iter (buffer, &iter);
1484                         gtk_text_buffer_insert_with_tags_by_name
1485                                 (buffer, &iter, header->body, -1,
1486                                  "header", "emphasis", NULL);
1487                 } else {
1488                         gboolean hdr = 
1489                           procheader_headername_equal(header->name, "From") ||
1490                           procheader_headername_equal(header->name, "To") ||
1491                           procheader_headername_equal(header->name, "Cc") ||
1492                           procheader_headername_equal(header->name, "Bcc");
1493                         textview_make_clickable_parts(textview, "header", 
1494                                                       "link", header->body, 
1495                                                       hdr);
1496                 }
1497                 gtk_text_buffer_get_end_iter (buffer, &iter);
1498                 gtk_text_buffer_insert_with_tags_by_name(buffer, &iter, "\n", 1,
1499                                                          "header", NULL);
1500         }
1501         
1502         textview_show_face(textview);
1503 #if HAVE_LIBCOMPFACE
1504         textview_show_xface(textview);
1505 #endif
1506 }
1507
1508 gboolean textview_search_string(TextView *textview, const gchar *str,
1509                                 gboolean case_sens)
1510 {
1511         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1512
1513         return gtkut_text_view_search_string(text, str, case_sens);
1514 }
1515
1516 gboolean textview_search_string_backward(TextView *textview, const gchar *str,
1517                                          gboolean case_sens)
1518 {
1519         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1520
1521         return gtkut_text_view_search_string_backward(text, str, case_sens);
1522 }
1523
1524 void textview_scroll_one_line(TextView *textview, gboolean up)
1525 {
1526         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1527         GtkAdjustment *vadj = text->vadjustment;
1528         gfloat upper;
1529
1530         if (prefs_common.enable_smooth_scroll) {
1531                 textview_smooth_scroll_one_line(textview, up);
1532                 return;
1533         }
1534
1535         if (!up) {
1536                 upper = vadj->upper - vadj->page_size;
1537                 if (vadj->value < upper) {
1538                         vadj->value += vadj->step_increment;
1539                         vadj->value = MIN(vadj->value, upper);
1540                         g_signal_emit_by_name(G_OBJECT(vadj),
1541                                               "value_changed", 0);
1542                 }
1543         } else {
1544                 if (vadj->value > 0.0) {
1545                         vadj->value -= vadj->step_increment;
1546                         vadj->value = MAX(vadj->value, 0.0);
1547                         g_signal_emit_by_name(G_OBJECT(vadj),
1548                                               "value_changed", 0);
1549                 }
1550         }
1551 }
1552
1553 gboolean textview_scroll_page(TextView *textview, gboolean up)
1554 {
1555         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1556         GtkAdjustment *vadj = text->vadjustment;
1557         gfloat upper;
1558         gfloat page_incr;
1559
1560         if (prefs_common.enable_smooth_scroll)
1561                 return textview_smooth_scroll_page(textview, up);
1562
1563         if (prefs_common.scroll_halfpage)
1564                 page_incr = vadj->page_increment / 2;
1565         else
1566                 page_incr = vadj->page_increment;
1567
1568         if (!up) {
1569                 upper = vadj->upper - vadj->page_size;
1570                 if (vadj->value < upper) {
1571                         vadj->value += page_incr;
1572                         vadj->value = MIN(vadj->value, upper);
1573                         g_signal_emit_by_name(G_OBJECT(vadj),
1574                                               "value_changed", 0);
1575                 } else
1576                         return FALSE;
1577         } else {
1578                 if (vadj->value > 0.0) {
1579                         vadj->value -= page_incr;
1580                         vadj->value = MAX(vadj->value, 0.0);
1581                         g_signal_emit_by_name(G_OBJECT(vadj),
1582                                               "value_changed", 0);
1583                 } else
1584                         return FALSE;
1585         }
1586
1587         return TRUE;
1588 }
1589
1590 static void textview_smooth_scroll_do(TextView *textview,
1591                                       gfloat old_value, gfloat last_value,
1592                                       gint step)
1593 {
1594         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1595         GtkAdjustment *vadj = text->vadjustment;
1596         gint change_value;
1597         gboolean up;
1598         gint i;
1599
1600         if (old_value < last_value) {
1601                 change_value = last_value - old_value;
1602                 up = FALSE;
1603         } else {
1604                 change_value = old_value - last_value;
1605                 up = TRUE;
1606         }
1607
1608         for (i = step; i <= change_value; i += step) {
1609                 vadj->value = old_value + (up ? -i : i);
1610                 g_signal_emit_by_name(G_OBJECT(vadj),
1611                                       "value_changed", 0);
1612         }
1613
1614         vadj->value = last_value;
1615         g_signal_emit_by_name(G_OBJECT(vadj), "value_changed", 0);
1616
1617         gtk_widget_queue_draw(GTK_WIDGET(text));
1618 }
1619
1620 static void textview_smooth_scroll_one_line(TextView *textview, gboolean up)
1621 {
1622         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1623         GtkAdjustment *vadj = text->vadjustment;
1624         gfloat upper;
1625         gfloat old_value;
1626         gfloat last_value;
1627
1628         if (!up) {
1629                 upper = vadj->upper - vadj->page_size;
1630                 if (vadj->value < upper) {
1631                         old_value = vadj->value;
1632                         last_value = vadj->value + vadj->step_increment;
1633                         last_value = MIN(last_value, upper);
1634
1635                         textview_smooth_scroll_do(textview, old_value,
1636                                                   last_value,
1637                                                   prefs_common.scroll_step);
1638                 }
1639         } else {
1640                 if (vadj->value > 0.0) {
1641                         old_value = vadj->value;
1642                         last_value = vadj->value - vadj->step_increment;
1643                         last_value = MAX(last_value, 0.0);
1644
1645                         textview_smooth_scroll_do(textview, old_value,
1646                                                   last_value,
1647                                                   prefs_common.scroll_step);
1648                 }
1649         }
1650 }
1651
1652 static gboolean textview_smooth_scroll_page(TextView *textview, gboolean up)
1653 {
1654         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1655         GtkAdjustment *vadj = text->vadjustment;
1656         gfloat upper;
1657         gfloat page_incr;
1658         gfloat old_value;
1659         gfloat last_value;
1660
1661         if (prefs_common.scroll_halfpage)
1662                 page_incr = vadj->page_increment / 2;
1663         else
1664                 page_incr = vadj->page_increment;
1665
1666         if (!up) {
1667                 upper = vadj->upper - vadj->page_size;
1668                 if (vadj->value < upper) {
1669                         old_value = vadj->value;
1670                         last_value = vadj->value + page_incr;
1671                         last_value = MIN(last_value, upper);
1672
1673                         textview_smooth_scroll_do(textview, old_value,
1674                                                   last_value,
1675                                                   prefs_common.scroll_step);
1676                 } else
1677                         return FALSE;
1678         } else {
1679                 if (vadj->value > 0.0) {
1680                         old_value = vadj->value;
1681                         last_value = vadj->value - page_incr;
1682                         last_value = MAX(last_value, 0.0);
1683
1684                         textview_smooth_scroll_do(textview, old_value,
1685                                                   last_value,
1686                                                   prefs_common.scroll_step);
1687                 } else
1688                         return FALSE;
1689         }
1690
1691         return TRUE;
1692 }
1693
1694 #define KEY_PRESS_EVENT_STOP() \
1695         g_signal_stop_emission_by_name(G_OBJECT(widget), \
1696                                        "key_press_event");
1697
1698 static gint textview_key_pressed(GtkWidget *widget, GdkEventKey *event,
1699                                  TextView *textview)
1700 {
1701         SummaryView *summaryview = NULL;
1702         MessageView *messageview = textview->messageview;
1703
1704         if (!event) return FALSE;
1705         if (messageview->mainwin)
1706                 summaryview = messageview->mainwin->summaryview;
1707
1708         switch (event->keyval) {
1709         case GDK_Tab:
1710         case GDK_Home:
1711         case GDK_Left:
1712         case GDK_Up:
1713         case GDK_Right:
1714         case GDK_Down:
1715         case GDK_Page_Up:
1716         case GDK_Page_Down:
1717         case GDK_End:
1718         case GDK_Control_L:
1719         case GDK_Control_R:
1720                 return FALSE;
1721         case GDK_space:
1722                 if (summaryview)
1723                         summary_pass_key_press_event(summaryview, event);
1724                 else
1725                         textview_scroll_page
1726                                 (textview,
1727                                  (event->state &
1728                                   (GDK_SHIFT_MASK|GDK_MOD1_MASK)) != 0);
1729                 break;
1730         case GDK_BackSpace:
1731                 textview_scroll_page(textview, TRUE);
1732                 break;
1733         case GDK_Return:
1734                 textview_scroll_one_line
1735                         (textview, (event->state &
1736                                     (GDK_SHIFT_MASK|GDK_MOD1_MASK)) != 0);
1737                 break;
1738         case GDK_Delete:
1739                 if (summaryview)
1740                         summary_pass_key_press_event(summaryview, event);
1741                 break;
1742         case GDK_y:
1743         case GDK_t:
1744         case GDK_l:
1745         case GDK_c:
1746                 if ((event->state & (GDK_MOD1_MASK|GDK_CONTROL_MASK)) == 0) {
1747                         KEY_PRESS_EVENT_STOP();
1748                         mimeview_pass_key_press_event(messageview->mimeview,
1749                                                       event);
1750                         break;
1751                 }
1752                 /* possible fall through */
1753         default:
1754                 if (summaryview &&
1755                     event->window != messageview->mainwin->window->window) {
1756                         GdkEventKey tmpev = *event;
1757
1758                         tmpev.window = messageview->mainwin->window->window;
1759                         KEY_PRESS_EVENT_STOP();
1760                         gtk_widget_event(messageview->mainwin->window,
1761                                          (GdkEvent *)&tmpev);
1762                 }
1763                 break;
1764         }
1765
1766         return TRUE;
1767 }
1768
1769 static gboolean textview_motion_notify(GtkWidget *widget,
1770                                        GdkEventMotion *event,
1771                                        TextView *textview)
1772 {
1773         textview_uri_update(textview, event->x, event->y);
1774         gdk_window_get_pointer(widget->window, NULL, NULL, NULL);
1775
1776         return FALSE;
1777 }
1778
1779 static gboolean textview_leave_notify(GtkWidget *widget,
1780                                       GdkEventCrossing *event,
1781                                       TextView *textview)
1782 {
1783         textview_uri_update(textview, -1, -1);
1784
1785         return FALSE;
1786 }
1787
1788 static gboolean textview_visibility_notify(GtkWidget *widget,
1789                                            GdkEventVisibility *event,
1790                                            TextView *textview)
1791 {
1792         gint wx, wy;
1793         GdkWindow *window;
1794
1795         window = gtk_text_view_get_window(GTK_TEXT_VIEW(widget),
1796                                           GTK_TEXT_WINDOW_TEXT);
1797
1798         /* check if occurred for the text window part */
1799         if (window != event->window)
1800                 return FALSE;
1801         
1802         gdk_window_get_pointer(widget->window, &wx, &wy, NULL);
1803         textview_uri_update(textview, wx, wy);
1804
1805         return FALSE;
1806 }
1807
1808 void textview_cursor_wait(TextView *textview)
1809 {
1810         GdkWindow *window = gtk_text_view_get_window(
1811                         GTK_TEXT_VIEW(textview->text),
1812                         GTK_TEXT_WINDOW_TEXT);
1813         gdk_window_set_cursor(window, watch_cursor);
1814 }
1815
1816 void textview_cursor_normal(TextView *textview)
1817 {
1818         GdkWindow *window = gtk_text_view_get_window(
1819                         GTK_TEXT_VIEW(textview->text),
1820                         GTK_TEXT_WINDOW_TEXT);
1821         gdk_window_set_cursor(window, text_cursor);
1822 }
1823
1824 static void textview_uri_update(TextView *textview, gint x, gint y)
1825 {
1826         GtkTextBuffer *buffer;
1827         GtkTextIter start_iter, end_iter;
1828         RemoteURI *uri = NULL;
1829         
1830         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview->text));
1831
1832         if (x != -1 && y != -1) {
1833                 gint bx, by;
1834                 GtkTextIter iter;
1835                 GSList *tags;
1836                 GSList *cur;
1837             
1838                 gtk_text_view_window_to_buffer_coords(GTK_TEXT_VIEW(textview->text), 
1839                                                       GTK_TEXT_WINDOW_WIDGET,
1840                                                       x, y, &bx, &by);
1841                 gtk_text_view_get_iter_at_location(GTK_TEXT_VIEW(textview->text),
1842                                                    &iter, bx, by);
1843
1844                 tags = gtk_text_iter_get_tags(&iter);
1845                 for (cur = tags; cur != NULL; cur = cur->next) {
1846                         GtkTextTag *tag = cur->data;
1847                         char *name;
1848
1849                         g_object_get(G_OBJECT(tag), "name", &name, NULL);
1850                         if (!strcmp(name, "link")
1851                             && textview_get_uri_range(textview, &iter, tag,
1852                                                       &start_iter, &end_iter))
1853                                 uri = textview_get_uri_from_range(textview,
1854                                                                   &iter, tag,
1855                                                                   &start_iter,
1856                                                                   &end_iter);
1857                         g_free(name);
1858
1859                         if (uri)
1860                                 break;
1861                 }
1862                 g_slist_free(tags);
1863         }
1864         
1865         if (uri != textview->uri_hover) {
1866                 GdkWindow *window;
1867
1868                 if (textview->uri_hover)
1869                         gtk_text_buffer_remove_tag_by_name(buffer,
1870                                                            "link-hover",
1871                                                            &textview->uri_hover_start_iter,
1872                                                            &textview->uri_hover_end_iter);
1873                     
1874                 textview->uri_hover = uri;
1875                 if (uri) {
1876                         textview->uri_hover_start_iter = start_iter;
1877                         textview->uri_hover_end_iter = end_iter;
1878                 }
1879                 
1880                 window = gtk_text_view_get_window(GTK_TEXT_VIEW(textview->text),
1881                                                   GTK_TEXT_WINDOW_TEXT);
1882                 if (textview->messageview->mainwin->cursor_count == 0) {
1883                         gdk_window_set_cursor(window, uri ? hand_cursor : text_cursor);
1884                 } else {
1885                         gdk_window_set_cursor(window, watch_cursor);
1886                 }
1887
1888                 TEXTVIEW_STATUSBAR_POP(textview);
1889
1890                 if (uri) {
1891                         char *trimmed_uri;
1892
1893                         gtk_text_buffer_apply_tag_by_name(buffer,
1894                                                           "link-hover",
1895                                                           &start_iter,
1896                                                           &end_iter);
1897
1898                         trimmed_uri = trim_string(uri->uri, 60);
1899                         TEXTVIEW_STATUSBAR_PUSH(textview, trimmed_uri);
1900                         g_free(trimmed_uri);
1901                 }
1902         }
1903 }
1904
1905 static gboolean textview_get_uri_range(TextView *textview,
1906                                        GtkTextIter *iter,
1907                                        GtkTextTag *tag,
1908                                        GtkTextIter *start_iter,
1909                                        GtkTextIter *end_iter)
1910 {
1911         return get_tag_range(iter, tag, start_iter, end_iter);
1912 }
1913
1914 static RemoteURI *textview_get_uri_from_range(TextView *textview,
1915                                               GtkTextIter *iter,
1916                                               GtkTextTag *tag,
1917                                               GtkTextIter *start_iter,
1918                                               GtkTextIter *end_iter)
1919 {
1920         gint start_pos, end_pos, cur_pos;
1921         RemoteURI *uri = NULL;
1922         GSList *cur;
1923
1924         start_pos = gtk_text_iter_get_offset(start_iter);
1925         end_pos = gtk_text_iter_get_offset(end_iter);
1926         cur_pos = gtk_text_iter_get_offset(iter);
1927
1928         for (cur = textview->uri_list; cur != NULL; cur = cur->next) {
1929                 RemoteURI *uri_ = (RemoteURI *)cur->data;
1930                 if (start_pos == uri_->start &&
1931                     end_pos ==  uri_->end) {
1932                         uri = uri_;
1933                         break;
1934                 } else if (start_pos == uri_->start ||
1935                            end_pos == uri_->end) {
1936                         /* in case of contiguous links, textview_get_uri_range
1937                          * returns a broader range (start of 1st link to end
1938                          * of last link).
1939                          * In that case, correct link is the one covering
1940                          * current iter.
1941                          */
1942                         if (uri_->start <= cur_pos && cur_pos <= uri_->end) {
1943                                 uri = uri_;
1944                                 break;
1945                         }
1946                 } 
1947         }
1948
1949         return uri;
1950 }
1951
1952 static RemoteURI *textview_get_uri(TextView *textview,
1953                                    GtkTextIter *iter,
1954                                    GtkTextTag *tag)
1955 {
1956         GtkTextIter start_iter, end_iter;
1957         RemoteURI *uri = NULL;
1958
1959         if (textview_get_uri_range(textview, iter, tag, &start_iter,
1960                                    &end_iter))
1961                 uri = textview_get_uri_from_range(textview, iter, tag,
1962                                                   &start_iter, &end_iter);
1963
1964         return uri;
1965 }
1966
1967 static gboolean textview_uri_button_pressed(GtkTextTag *tag, GObject *obj,
1968                                             GdkEvent *event, GtkTextIter *iter,
1969                                             TextView *textview)
1970 {
1971         GdkEventButton *bevent;
1972         RemoteURI *uri = NULL;
1973
1974         if (!event)
1975                 return FALSE;
1976
1977         if (event->type != GDK_BUTTON_PRESS && event->type != GDK_2BUTTON_PRESS
1978                 && event->type != GDK_MOTION_NOTIFY)
1979                 return FALSE;
1980
1981         uri = textview_get_uri(textview, iter, tag);
1982         if (!uri)
1983                 return FALSE;
1984
1985         bevent = (GdkEventButton *) event;
1986         
1987         /* doubleclick: open compose / add address / browser */
1988         if ((event->type == GDK_BUTTON_PRESS && bevent->button == 1) ||
1989                 bevent->button == 2 || bevent->button == 3) {
1990                 if (uri->filename && !g_ascii_strncasecmp(uri->filename, "sc://", 5)) {
1991                         if (bevent->button == 1) {
1992                                 MimeView *mimeview = 
1993                                         (textview->messageview)?
1994                                                 textview->messageview->mimeview:NULL;
1995                                 mimeview_handle_cmd(mimeview, uri->filename);
1996                         }
1997                         return TRUE;
1998                 } else if (!g_ascii_strncasecmp(uri->uri, "mailto:", 7)) {
1999                         if (bevent->button == 3) {
2000                                 g_object_set_data(
2001                                         G_OBJECT(textview->mail_popup_menu),
2002                                         "menu_button", uri);
2003                                 gtk_menu_popup(GTK_MENU(textview->mail_popup_menu), 
2004                                                NULL, NULL, NULL, NULL, 
2005                                                bevent->button, bevent->time);
2006                         } else {
2007                                 PrefsAccount *account = NULL;
2008
2009                                 if (textview->messageview && textview->messageview->msginfo &&
2010                                     textview->messageview->msginfo->folder) {
2011                                         FolderItem   *folder_item;
2012
2013                                         folder_item = textview->messageview->msginfo->folder;
2014                                         if (folder_item->prefs && folder_item->prefs->enable_default_account)
2015                                                 account = account_find_from_id(folder_item->prefs->default_account);
2016                                 }
2017                                 compose_new(account, uri->uri + 7, NULL);
2018                         }
2019                         return TRUE;
2020                 } else if (g_ascii_strncasecmp(uri->uri, "file:", 5)) {
2021                         if (bevent->button == 1 &&
2022                             textview_uri_security_check(textview, uri) == TRUE) 
2023                                         open_uri(uri->uri,
2024                                                  prefs_common.uri_cmd);
2025                         else if (bevent->button == 3) {
2026                                 g_object_set_data(
2027                                         G_OBJECT(textview->link_popup_menu),
2028                                         "menu_button", uri);
2029                                 gtk_menu_popup(GTK_MENU(textview->link_popup_menu), 
2030                                                NULL, NULL, NULL, NULL, 
2031                                                bevent->button, bevent->time);
2032                         }
2033                         return TRUE;
2034                 } else {
2035                         if (bevent->button == 3) {
2036                                 g_object_set_data(
2037                                         G_OBJECT(textview->file_popup_menu),
2038                                         "menu_button", uri);
2039                                 gtk_menu_popup(GTK_MENU(textview->file_popup_menu), 
2040                                                NULL, NULL, NULL, NULL, 
2041                                                bevent->button, bevent->time);
2042                                 return TRUE;
2043                         }
2044                 }
2045         }
2046
2047         return FALSE;
2048 }
2049
2050 /*!
2051  *\brief    Check to see if a web URL has been disguised as a different
2052  *          URL (possible with HTML email).
2053  *
2054  *\param    uri The uri to check
2055  *
2056  *\param    textview The TextView the URL is contained in
2057  *
2058  *\return   gboolean TRUE if the URL is ok, or if the user chose to open
2059  *          it anyway, otherwise FALSE          
2060  */
2061 static gboolean textview_uri_security_check(TextView *textview, RemoteURI *uri)
2062 {
2063         gchar *visible_str;
2064         gboolean retval = TRUE;
2065         GtkTextBuffer *buffer;
2066         GtkTextIter start, end;
2067
2068         if (is_uri_string(uri->uri) == FALSE)
2069                 return TRUE;
2070
2071         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview->text));
2072
2073         gtk_text_buffer_get_iter_at_offset(buffer, &start, uri->start);
2074         gtk_text_buffer_get_iter_at_offset(buffer, &end,   uri->end);
2075
2076         visible_str = gtk_text_buffer_get_text(buffer, &start, &end, FALSE);
2077
2078         if (visible_str == NULL)
2079                 return TRUE;
2080
2081         if (strcmp(visible_str, uri->uri) != 0 && is_uri_string(visible_str)) {
2082                 gchar *uri_path;
2083                 gchar *visible_uri_path;
2084
2085                 uri_path = get_uri_path(uri->uri);
2086                 visible_uri_path = get_uri_path(visible_str);
2087                 if (path_cmp(uri_path, visible_uri_path) != 0)
2088                         retval = FALSE;
2089         }
2090
2091         if (retval == FALSE) {
2092                 gchar *msg;
2093                 AlertValue aval;
2094
2095                 msg = g_strdup_printf(_("The real URL (%s) is different from\n"
2096                                         "the apparent URL (%s).\n"
2097                                         "\n"
2098                                         "Open it anyway?"),
2099                                       uri->uri, visible_str);
2100                 aval = alertpanel_full(_("Fake URL warning"), msg,
2101                                        GTK_STOCK_CANCEL, _("_Open URL"), NULL, FALSE,
2102                                        NULL, ALERT_WARNING, G_ALERTDEFAULT);
2103                 g_free(msg);
2104                 if (aval == G_ALERTALTERNATE)
2105                         retval = TRUE;
2106         }
2107
2108         g_free(visible_str);
2109
2110         return retval;
2111 }
2112
2113 static void textview_uri_list_remove_all(GSList *uri_list)
2114 {
2115         GSList *cur;
2116
2117         for (cur = uri_list; cur != NULL; cur = cur->next) {
2118                 if (cur->data) {
2119                         g_free(((RemoteURI *)cur->data)->uri);
2120                         g_free(((RemoteURI *)cur->data)->filename);
2121                         g_free(cur->data);
2122                 }
2123         }
2124
2125         g_slist_free(uri_list);
2126 }
2127
2128 static void open_uri_cb (TextView *textview, guint action, void *data)
2129 {
2130         RemoteURI *uri = g_object_get_data(G_OBJECT(textview->link_popup_menu),
2131                                            "menu_button");
2132         if (uri == NULL)
2133                 return;
2134
2135         if (textview_uri_security_check(textview, uri) == TRUE) 
2136                 open_uri(uri->uri,
2137                          prefs_common.uri_cmd);
2138         g_object_set_data(G_OBJECT(textview->link_popup_menu), "menu_button",
2139                           NULL);
2140 }
2141
2142 static void open_image_cb (TextView *textview, guint action, void *data)
2143 {
2144         RemoteURI *uri = g_object_get_data(G_OBJECT(textview->file_popup_menu),
2145                                            "menu_button");
2146
2147         static gchar *default_cmdline = DEFAULT_IMAGE_VIEWER_CMD;
2148         gchar buf[1024];
2149         const gchar *cmd;
2150         const gchar *def_cmd;
2151         const gchar *p;
2152         gchar *filename = NULL;
2153         gchar *tmp_filename = NULL;
2154
2155         if (uri == NULL)
2156                 return;
2157
2158         if (uri->filename == NULL)
2159                 return;
2160         
2161         filename = g_strdup(uri->filename);
2162         
2163         if (!g_utf8_validate(filename, -1, NULL)) {
2164                 gchar *tmp = conv_filename_to_utf8(filename);
2165                 g_free(filename);
2166                 filename = tmp;
2167         }
2168
2169         subst_for_filename(filename);
2170
2171         tmp_filename = g_filename_from_uri(uri->uri, NULL, NULL);
2172         copy_file(tmp_filename, filename, FALSE);
2173         g_free(tmp_filename);
2174
2175         cmd = prefs_common.mime_image_viewer;
2176         def_cmd = default_cmdline;
2177         
2178         if (cmd && (p = strchr(cmd, '%')) && *(p + 1) == 's' &&
2179             !strchr(p + 2, '%'))
2180                 g_snprintf(buf, sizeof(buf), cmd, filename);
2181         else {
2182                 if (cmd)
2183                         g_warning("Image viewer command line is invalid: '%s'", cmd);
2184                 if (def_cmd)
2185                         g_snprintf(buf, sizeof(buf), def_cmd, filename);
2186                 else
2187                         return;
2188         }
2189
2190         execute_command_line(buf, TRUE);
2191
2192         g_free(filename);
2193
2194         g_object_set_data(G_OBJECT(textview->file_popup_menu), "menu_button",
2195                           NULL);
2196 }
2197
2198 static void save_file_cb (TextView *textview, guint action, void *data)
2199 {
2200         RemoteURI *uri = g_object_get_data(G_OBJECT(textview->file_popup_menu),
2201                                            "menu_button");
2202         gchar *filename = NULL;
2203         gchar *filepath = NULL;
2204         gchar *filedir = NULL;
2205         gchar *tmp_filename = NULL;
2206         if (uri == NULL)
2207                 return;
2208
2209         if (uri->filename == NULL)
2210                 return;
2211         
2212         filename = g_strdup(uri->filename);
2213         
2214         if (!g_utf8_validate(filename, -1, NULL)) {
2215                 gchar *tmp = conv_filename_to_utf8(filename);
2216                 g_free(filename);
2217                 filename = tmp;
2218         }
2219
2220         subst_for_filename(filename);
2221         
2222         if (prefs_common.attach_save_dir)
2223                 filepath = g_strconcat(prefs_common.attach_save_dir,
2224                                        G_DIR_SEPARATOR_S, filename, NULL);
2225         else
2226                 filepath = g_strdup(filename);
2227
2228         g_free(filename);
2229
2230         filename = filesel_select_file_save(_("Save as"), filepath);
2231         if (!filename) {
2232                 g_free(filepath);
2233                 return;
2234         }
2235
2236         if (is_file_exist(filename)) {
2237                 AlertValue aval;
2238                 gchar *res;
2239                 
2240                 res = g_strdup_printf(_("Overwrite existing file '%s'?"),
2241                                       filename);
2242                 aval = alertpanel(_("Overwrite"), res, GTK_STOCK_CANCEL, 
2243                                   GTK_STOCK_OK, NULL);
2244                 g_free(res);                                      
2245                 if (G_ALERTALTERNATE != aval)
2246                         return;
2247         }
2248
2249         tmp_filename = g_filename_from_uri(uri->uri, NULL, NULL);
2250         copy_file(tmp_filename, filename, FALSE);
2251         g_free(tmp_filename);
2252         
2253         filedir = g_path_get_dirname(filename);
2254         if (filedir && strcmp(filedir, ".")) {
2255                 g_free(prefs_common.attach_save_dir);
2256                 prefs_common.attach_save_dir = g_strdup(filedir);
2257         }
2258
2259         g_free(filedir);
2260         g_free(filepath);
2261
2262         g_object_set_data(G_OBJECT(textview->file_popup_menu), "menu_button",
2263                           NULL);
2264 }
2265
2266 static void copy_uri_cb (TextView *textview, guint action, void *data)
2267 {
2268         RemoteURI *uri = g_object_get_data(G_OBJECT(textview->link_popup_menu),
2269                                            "menu_button");
2270         if (uri == NULL)
2271                 return;
2272
2273         gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), uri->uri, -1);
2274         gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), uri->uri, -1);
2275         g_object_set_data(G_OBJECT(textview->link_popup_menu), "menu_button",
2276                           NULL);
2277 }
2278
2279 static void add_uri_to_addrbook_cb (TextView *textview, guint action, void *data)
2280 {
2281         gchar *fromname, *fromaddress;
2282         RemoteURI *uri = g_object_get_data(G_OBJECT(textview->mail_popup_menu),
2283                                            "menu_button");
2284         if (uri == NULL)
2285                 return;
2286
2287         /* extract url */
2288         fromaddress = g_strdup(uri->uri + 7);
2289         /* Hiroyuki: please put this function in utils.c! */
2290         fromname = procheader_get_fromname(fromaddress);
2291         extract_address(fromaddress);
2292         g_message("adding from textview %s <%s>", fromname, fromaddress);
2293         /* Add to address book - Match */
2294         addressbook_add_contact( fromname, fromaddress, NULL );
2295
2296         g_free(fromaddress);
2297         g_free(fromname);
2298 }
2299
2300 static void mail_to_uri_cb (TextView *textview, guint action, void *data)
2301 {
2302         PrefsAccount *account = NULL;
2303         RemoteURI *uri = g_object_get_data(G_OBJECT(textview->mail_popup_menu),
2304                                            "menu_button");
2305         if (uri == NULL)
2306                 return;
2307
2308         if (textview->messageview && textview->messageview->msginfo &&
2309             textview->messageview->msginfo->folder) {
2310                 FolderItem   *folder_item;
2311
2312                 folder_item = textview->messageview->msginfo->folder;
2313                 if (folder_item->prefs && folder_item->prefs->enable_default_account)
2314                         account = account_find_from_id(folder_item->prefs->default_account);
2315         }
2316         compose_new(account, uri->uri + 7, NULL);
2317 }
2318
2319 static void copy_mail_to_uri_cb (TextView *textview, guint action, void *data)
2320 {
2321         RemoteURI *uri = g_object_get_data(G_OBJECT(textview->mail_popup_menu),
2322                                            "menu_button");
2323         if (uri == NULL)
2324                 return;
2325
2326         gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), uri->uri +7, -1);
2327         gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), uri->uri +7, -1);
2328         g_object_set_data(G_OBJECT(textview->mail_popup_menu), "menu_button",
2329                           NULL);
2330 }
2331