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