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