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