7fb68daea872cd99b048066e39c9b7ec8304b4de
[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                                         parser->href = g_strdup(str);
911                                         /* the URL may (or not) be followed by the
912                                          * referenced text */
913                                         str = strtok(NULL, "");
914                                 }       
915                         }
916                         if (str != NULL)
917                                 textview_write_link(textview, str, parser->href, NULL);
918                 } else
919                         textview_write_line(textview, str, NULL);
920         }
921         textview_write_line(textview, "\n", NULL);
922         sc_html_parser_destroy(parser);
923 }
924
925 static void textview_show_ertf(TextView *textview, FILE *fp,
926                                CodeConverter *conv)
927 {
928         ERTFParser *parser;
929         gchar *str;
930
931         parser = ertf_parser_new(fp, conv);
932         g_return_if_fail(parser != NULL);
933
934         while ((str = ertf_parse(parser)) != NULL) {
935                 textview_write_line(textview, str, NULL);
936         }
937         
938         ertf_parser_destroy(parser);
939 }
940
941 #define ADD_TXT_POS(bp_, ep_, pti_) \
942         if ((last->next = alloca(sizeof(struct txtpos))) != NULL) { \
943                 last = last->next; \
944                 last->bp = (bp_); last->ep = (ep_); last->pti = (pti_); \
945                 last->next = NULL; \
946         } else { \
947                 g_warning("alloc error scanning URIs\n"); \
948                 gtk_text_buffer_insert_with_tags_by_name(buffer, &iter, \
949                                                          linebuf, -1, \
950                                                          fg_tag, NULL); \
951                 return; \
952         }
953
954 /* textview_make_clickable_parts() - colorizes clickable parts */
955 static void textview_make_clickable_parts(TextView *textview,
956                                           const gchar *fg_tag,
957                                           const gchar *uri_tag,
958                                           const gchar *linebuf,
959                                           gboolean hdr)
960 {
961         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
962         GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
963         GtkTextIter iter;
964         gchar *mybuf = g_strdup(linebuf);
965         
966         /* parse table - in order of priority */
967         struct table {
968                 const gchar *needle; /* token */
969
970                 /* token search function */
971                 gchar    *(*search)     (const gchar *haystack,
972                                          const gchar *needle);
973                 /* part parsing function */
974                 gboolean  (*parse)      (const gchar *start,
975                                          const gchar *scanpos,
976                                          const gchar **bp_,
977                                          const gchar **ep_,
978                                          gboolean hdr);
979                 /* part to URI function */
980                 gchar    *(*build_uri)  (const gchar *bp,
981                                          const gchar *ep);
982         };
983
984         static struct table parser[] = {
985                 {"http://",  strcasestr, get_uri_part,   make_uri_string},
986                 {"https://", strcasestr, get_uri_part,   make_uri_string},
987                 {"ftp://",   strcasestr, get_uri_part,   make_uri_string},
988                 {"www.",     strcasestr, get_uri_part,   make_http_string},
989                 {"mailto:",  strcasestr, get_uri_part,   make_uri_string},
990                 {"@",        strcasestr, get_email_part, make_email_string}
991         };
992         const gint PARSE_ELEMS = sizeof parser / sizeof parser[0];
993
994         gint  n;
995         const gchar *walk, *bp, *ep;
996
997         struct txtpos {
998                 const gchar     *bp, *ep;       /* text position */
999                 gint             pti;           /* index in parse table */
1000                 struct txtpos   *next;          /* next */
1001         } head = {NULL, NULL, 0,  NULL}, *last = &head;
1002
1003         if (!g_utf8_validate(linebuf, -1, NULL)) {
1004                 mybuf = g_malloc(strlen(linebuf)*2 +1);
1005                 conv_localetodisp(mybuf, strlen(linebuf)*2 +1, linebuf);
1006         }
1007
1008         gtk_text_buffer_get_end_iter(buffer, &iter);
1009
1010         /* parse for clickable parts, and build a list of begin and end positions  */
1011         for (walk = mybuf, n = 0;;) {
1012                 gint last_index = PARSE_ELEMS;
1013                 gchar *scanpos = NULL;
1014
1015                 /* FIXME: this looks phony. scanning for anything in the parse table */
1016                 for (n = 0; n < PARSE_ELEMS; n++) {
1017                         gchar *tmp;
1018
1019                         tmp = parser[n].search(walk, parser[n].needle);
1020                         if (tmp) {
1021                                 if (scanpos == NULL || tmp < scanpos) {
1022                                         scanpos = tmp;
1023                                         last_index = n;
1024                                 }
1025                         }                                       
1026                 }
1027
1028                 if (scanpos) {
1029                         /* check if URI can be parsed */
1030                         if (parser[last_index].parse(walk, scanpos, &bp, &ep, hdr)
1031                             && (size_t) (ep - bp - 1) > strlen(parser[last_index].needle)) {
1032                                         ADD_TXT_POS(bp, ep, last_index);
1033                                         walk = ep;
1034                         } else
1035                                 walk = scanpos +
1036                                         strlen(parser[last_index].needle);
1037                 } else
1038                         break;
1039         }
1040
1041         /* colorize this line */
1042         if (head.next) {
1043                 const gchar *normal_text = mybuf;
1044
1045                 /* insert URIs */
1046                 for (last = head.next; last != NULL;
1047                      normal_text = last->ep, last = last->next) {
1048                         RemoteURI *uri;
1049                         uri = g_new(RemoteURI, 1);
1050                         if (last->bp - normal_text > 0)
1051                                 gtk_text_buffer_insert_with_tags_by_name
1052                                         (buffer, &iter,
1053                                          normal_text,
1054                                          last->bp - normal_text,
1055                                          fg_tag, NULL);
1056                         uri->uri = parser[last->pti].build_uri(last->bp,
1057                                                                last->ep);
1058                         uri->start = gtk_text_iter_get_offset(&iter);
1059                         gtk_text_buffer_insert_with_tags_by_name
1060                                 (buffer, &iter, last->bp, last->ep - last->bp,
1061                                  uri_tag, fg_tag, NULL);
1062                         uri->end = gtk_text_iter_get_offset(&iter);
1063                         uri->filename = NULL;
1064                         textview->uri_list =
1065                                 g_slist_append(textview->uri_list, uri);
1066                 }
1067
1068                 if (*normal_text)
1069                         gtk_text_buffer_insert_with_tags_by_name
1070                                 (buffer, &iter, normal_text, -1, fg_tag, NULL);
1071         } else {
1072                 gtk_text_buffer_insert_with_tags_by_name
1073                         (buffer, &iter, mybuf, -1, fg_tag, NULL);
1074         }
1075         g_free(mybuf);
1076 }
1077
1078 #undef ADD_TXT_POS
1079
1080 static void textview_write_line(TextView *textview, const gchar *str,
1081                                 CodeConverter *conv)
1082 {
1083         GtkTextView *text;
1084         GtkTextBuffer *buffer;
1085         GtkTextIter iter;
1086         gchar buf[BUFFSIZE];
1087         gchar *fg_color;
1088         gint quotelevel = -1;
1089         gchar quote_tag_str[10];
1090
1091         text = GTK_TEXT_VIEW(textview->text);
1092         buffer = gtk_text_view_get_buffer(text);
1093         gtk_text_buffer_get_end_iter(buffer, &iter);
1094
1095         if (!conv)
1096                 strncpy2(buf, str, sizeof(buf));
1097         else if (conv_convert(conv, buf, sizeof(buf), str) < 0)
1098                 conv_localetodisp(buf, sizeof(buf), str);
1099                 
1100         strcrchomp(buf);
1101         fg_color = NULL;
1102
1103         /* change color of quotation
1104            >, foo>, _> ... ok, <foo>, foo bar>, foo-> ... ng
1105            Up to 3 levels of quotations are detected, and each
1106            level is colored using a different color. */
1107         if (prefs_common.enable_color 
1108             && line_has_quote_char(buf, prefs_common.quote_chars)) {
1109                 quotelevel = get_quote_level(buf, prefs_common.quote_chars);
1110
1111                 /* set up the correct foreground color */
1112                 if (quotelevel > 2) {
1113                         /* recycle colors */
1114                         if (prefs_common.recycle_quote_colors)
1115                                 quotelevel %= 3;
1116                         else
1117                                 quotelevel = 2;
1118                 }
1119         }
1120
1121         if (quotelevel == -1)
1122                 fg_color = NULL;
1123         else {
1124                 g_snprintf(quote_tag_str, sizeof(quote_tag_str),
1125                            "quote%d", quotelevel);
1126                 fg_color = quote_tag_str;
1127         }
1128
1129         if (prefs_common.enable_color && (strcmp(buf,"-- \n") == 0 || textview->is_in_signature)) {
1130                 fg_color = "signature";
1131                 textview->is_in_signature = TRUE;
1132         }
1133
1134         textview_make_clickable_parts(textview, fg_color, "link", buf, FALSE);
1135 }
1136
1137 void textview_write_link(TextView *textview, const gchar *str,
1138                          const gchar *uri, CodeConverter *conv)
1139 {
1140         GdkColor *link_color = NULL;
1141         GtkTextView *text;
1142         GtkTextBuffer *buffer;
1143         GtkTextIter iter;
1144         gchar buf[BUFFSIZE];
1145         gchar *bufp;
1146         RemoteURI *r_uri;
1147
1148         if (!str || *str == '\0')
1149                 return;
1150         if (!uri)
1151                 return;
1152
1153         text = GTK_TEXT_VIEW(textview->text);
1154         buffer = gtk_text_view_get_buffer(text);
1155         gtk_text_buffer_get_end_iter(buffer, &iter);
1156
1157         if (!conv)
1158                 strncpy2(buf, str, sizeof(buf));
1159         else if (conv_convert(conv, buf, sizeof(buf), str) < 0)
1160                 conv_utf8todisp(buf, sizeof(buf), str);
1161
1162         if (g_utf8_validate(buf, -1, NULL) == FALSE)
1163                 return;
1164
1165         strcrchomp(buf);
1166
1167         gtk_text_buffer_get_end_iter(buffer, &iter);
1168         for (bufp = buf; *bufp != '\0'; bufp = g_utf8_next_char(bufp)) {
1169                 gunichar ch;
1170
1171                 ch = g_utf8_get_char(bufp);
1172                 if (!g_unichar_isspace(ch))
1173                         break;
1174         }
1175         if (bufp > buf)
1176                 gtk_text_buffer_insert(buffer, &iter, buf, bufp - buf);
1177
1178         if (prefs_common.enable_color) {
1179                 link_color = &uri_color;
1180         }
1181         r_uri = g_new(RemoteURI, 1);
1182         r_uri->uri = g_strdup(uri);
1183         r_uri->start = gtk_text_iter_get_offset(&iter);
1184         gtk_text_buffer_insert_with_tags_by_name
1185                 (buffer, &iter, bufp, -1, "link", NULL);
1186         r_uri->end = gtk_text_iter_get_offset(&iter);
1187         r_uri->filename = NULL;
1188         textview->uri_list = g_slist_append(textview->uri_list, r_uri);
1189 }
1190
1191 static void textview_set_cursor(GdkWindow *window, GdkCursor *cursor)
1192 {
1193         if (GDK_IS_WINDOW(window))
1194                 gdk_window_set_cursor(window, cursor);
1195 }
1196 void textview_clear(TextView *textview)
1197 {
1198         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1199         GtkTextBuffer *buffer;
1200         GdkWindow *window = gtk_text_view_get_window(text,
1201                                 GTK_TEXT_WINDOW_TEXT);
1202
1203         buffer = gtk_text_view_get_buffer(text);
1204         gtk_text_buffer_set_text(buffer, "", -1);
1205
1206         TEXTVIEW_STATUSBAR_POP(textview);
1207         textview_uri_list_remove_all(textview->uri_list);
1208         textview->uri_list = NULL;
1209         textview->uri_hover = NULL;
1210
1211         textview->body_pos = 0;
1212         if (textview->image) 
1213                 gtk_widget_destroy(textview->image);
1214         textview->image = NULL;
1215
1216         if (textview->messageview->mainwin->cursor_count == 0) {
1217                 textview_set_cursor(window, text_cursor);
1218         } else {
1219                 textview_set_cursor(window, watch_cursor);
1220         }
1221 }
1222
1223 void textview_destroy(TextView *textview)
1224 {
1225         textview_uri_list_remove_all(textview->uri_list);
1226         textview->uri_list = NULL;
1227
1228         g_free(textview);
1229 }
1230
1231 void textview_set_all_headers(TextView *textview, gboolean all_headers)
1232 {
1233         textview->show_all_headers = all_headers;
1234 }
1235
1236 #define CHANGE_TAG_FONT(tagname, font) { \
1237         tag = gtk_text_tag_table_lookup(tags, tagname); \
1238         if (tag) \
1239                 g_object_set(G_OBJECT(tag), "font-desc", font, NULL); \
1240 }
1241
1242 void textview_set_font(TextView *textview, const gchar *codeset)
1243 {
1244         GtkTextTag *tag;
1245         GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview->text));
1246         GtkTextTagTable *tags = gtk_text_buffer_get_tag_table(buffer);
1247         
1248         if (NORMAL_FONT) {
1249                 PangoFontDescription *font_desc, *bold_font_desc;
1250                 font_desc = pango_font_description_from_string
1251                                                 (NORMAL_FONT);
1252                 bold_font_desc = pango_font_description_from_string
1253                                                 (NORMAL_FONT);
1254                 if (font_desc) {
1255                         gtk_widget_modify_font(textview->text, font_desc);
1256                         CHANGE_TAG_FONT("header", font_desc);
1257                         pango_font_description_free(font_desc);
1258                 }
1259                 if (bold_font_desc) {
1260                         pango_font_description_set_weight
1261                                 (bold_font_desc, PANGO_WEIGHT_BOLD);
1262                         CHANGE_TAG_FONT("header_title", bold_font_desc);
1263                         pango_font_description_free(bold_font_desc);
1264                 }
1265         }
1266
1267         if (prefs_common.textfont) {
1268                 PangoFontDescription *font_desc;
1269
1270                 font_desc = pango_font_description_from_string
1271                                                 (prefs_common.textfont);
1272                 if (font_desc) {
1273                         gtk_widget_modify_font(textview->text, font_desc);
1274                         pango_font_description_free(font_desc);
1275                 }
1276         }
1277         gtk_text_view_set_pixels_above_lines(GTK_TEXT_VIEW(textview->text),
1278                                              prefs_common.line_space / 2);
1279         gtk_text_view_set_pixels_below_lines(GTK_TEXT_VIEW(textview->text),
1280                                              prefs_common.line_space / 2);
1281 }
1282
1283 void textview_set_text(TextView *textview, const gchar *text)
1284 {
1285         GtkTextView *view;
1286         GtkTextBuffer *buffer;
1287
1288         g_return_if_fail(textview != NULL);
1289         g_return_if_fail(text != NULL);
1290
1291         textview_clear(textview);
1292
1293         view = GTK_TEXT_VIEW(textview->text);
1294         buffer = gtk_text_view_get_buffer(view);
1295         gtk_text_buffer_set_text(buffer, text, strlen(text));
1296 }
1297
1298 enum
1299 {
1300         H_DATE          = 0,
1301         H_FROM          = 1,
1302         H_TO            = 2,
1303         H_NEWSGROUPS    = 3,
1304         H_SUBJECT       = 4,
1305         H_CC            = 5,
1306         H_REPLY_TO      = 6,
1307         H_FOLLOWUP_TO   = 7,
1308         H_X_MAILER      = 8,
1309         H_X_NEWSREADER  = 9,
1310         H_USER_AGENT    = 10,
1311         H_ORGANIZATION  = 11,
1312 };
1313
1314 void textview_set_position(TextView *textview, gint pos)
1315 {
1316         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1317
1318         gtkut_text_view_set_position(text, pos);
1319 }
1320
1321 static GPtrArray *textview_scan_header(TextView *textview, FILE *fp)
1322 {
1323         gchar buf[BUFFSIZE];
1324         GPtrArray *headers, *sorted_headers;
1325         GSList *disphdr_list;
1326         Header *header;
1327         gint i;
1328
1329         g_return_val_if_fail(fp != NULL, NULL);
1330
1331         if (textview->show_all_headers)
1332                 return procheader_get_header_array_asis(fp);
1333
1334         if (!prefs_common.display_header) {
1335                 while (fgets(buf, sizeof(buf), fp) != NULL)
1336                         if (buf[0] == '\r' || buf[0] == '\n') break;
1337                 return NULL;
1338         }
1339
1340         headers = procheader_get_header_array_asis(fp);
1341
1342         sorted_headers = g_ptr_array_new();
1343
1344         for (disphdr_list = prefs_common.disphdr_list; disphdr_list != NULL;
1345              disphdr_list = disphdr_list->next) {
1346                 DisplayHeaderProp *dp =
1347                         (DisplayHeaderProp *)disphdr_list->data;
1348
1349                 for (i = 0; i < headers->len; i++) {
1350                         header = g_ptr_array_index(headers, i);
1351
1352                         if (procheader_headername_equal(header->name,
1353                                                         dp->name)) {
1354                                 if (dp->hidden)
1355                                         procheader_header_free(header);
1356                                 else
1357                                         g_ptr_array_add(sorted_headers, header);
1358
1359                                 g_ptr_array_remove_index(headers, i);
1360                                 i--;
1361                         }
1362                 }
1363         }
1364
1365         if (prefs_common.show_other_header) {
1366                 for (i = 0; i < headers->len; i++) {
1367                         header = g_ptr_array_index(headers, i);
1368                         g_ptr_array_add(sorted_headers, header);
1369                 }
1370                 g_ptr_array_free(headers, TRUE);
1371         } else
1372                 procheader_header_array_destroy(headers);
1373
1374
1375         return sorted_headers;
1376 }
1377
1378 static void textview_show_face(TextView *textview)
1379 {
1380         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1381         MsgInfo *msginfo = textview->messageview->msginfo;
1382         int x = 0;
1383         
1384         if (prefs_common.display_header_pane
1385         ||  !prefs_common.display_xface)
1386                 goto bail;
1387         
1388         if (!msginfo->face) {
1389                 goto bail;
1390         }
1391
1392         if (textview->image) 
1393                 gtk_widget_destroy(textview->image);
1394         
1395         textview->image = face_get_from_header(msginfo->face);
1396         g_return_if_fail(textview->image != NULL);
1397
1398         gtk_widget_show(textview->image);
1399         
1400         x = textview->text->allocation.width - WIDTH -5;
1401
1402         gtk_text_view_add_child_in_window(text, textview->image, 
1403                 GTK_TEXT_WINDOW_TEXT, x, 5);
1404
1405         gtk_widget_show_all(textview->text);
1406         
1407
1408         return;
1409 bail:
1410         if (textview->image) 
1411                 gtk_widget_destroy(textview->image);
1412         textview->image = NULL; 
1413 }
1414
1415 static void textview_show_icon(TextView *textview, const gchar *stock_id)
1416 {
1417         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1418         int x = 0;
1419         
1420         if (textview->image) 
1421                 gtk_widget_destroy(textview->image);
1422         
1423         textview->image = gtk_image_new_from_stock(stock_id, GTK_ICON_SIZE_DIALOG);
1424         g_return_if_fail(textview->image != NULL);
1425
1426         gtk_widget_show(textview->image);
1427         
1428         x = textview->text->allocation.width - WIDTH -5;
1429
1430         gtk_text_view_add_child_in_window(text, textview->image, 
1431                 GTK_TEXT_WINDOW_TEXT, x, 5);
1432
1433         gtk_widget_show_all(textview->text);
1434         
1435
1436         return;
1437 }
1438
1439 #if HAVE_LIBCOMPFACE
1440 static void textview_show_xface(TextView *textview)
1441 {
1442         MsgInfo *msginfo = textview->messageview->msginfo;
1443         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1444         int x = 0;
1445
1446         if (prefs_common.display_header_pane
1447         ||  !prefs_common.display_xface)
1448                 goto bail;
1449         
1450         if (!msginfo)
1451                 goto bail;
1452
1453         if (msginfo->face)
1454                 return;
1455         
1456         if (!msginfo->xface || strlen(msginfo->xface) < 5) {
1457                 goto bail;
1458         }
1459
1460         if (textview->image) 
1461                 gtk_widget_destroy(textview->image);
1462         
1463         textview->image = xface_get_from_header(msginfo->xface,
1464                                 &textview->text->style->white,
1465                                 textview->text->window);
1466         g_return_if_fail(textview->image != NULL);
1467
1468         gtk_widget_show(textview->image);
1469         
1470         x = textview->text->allocation.width - WIDTH -5;
1471
1472         gtk_text_view_add_child_in_window(text, textview->image, 
1473                 GTK_TEXT_WINDOW_TEXT, x, 5);
1474
1475         gtk_widget_show_all(textview->text);
1476         
1477         return;
1478 bail:
1479         if (textview->image) 
1480                 gtk_widget_destroy(textview->image);
1481         textview->image = NULL;
1482         
1483 }
1484 #endif
1485
1486 static void textview_show_header(TextView *textview, GPtrArray *headers)
1487 {
1488         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1489         GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
1490         GtkTextIter iter;
1491         Header *header;
1492         gint i;
1493
1494         g_return_if_fail(headers != NULL);
1495
1496         for (i = 0; i < headers->len; i++) {
1497                 header = g_ptr_array_index(headers, i);
1498                 g_return_if_fail(header->name != NULL);
1499
1500                 gtk_text_buffer_get_end_iter (buffer, &iter);
1501                 if(prefs_common.trans_hdr == TRUE) {
1502                         gchar *hdr = g_strndup(header->name, strlen(header->name) - 1);
1503                         gchar *trans_hdr = gettext(hdr);
1504                         gtk_text_buffer_insert_with_tags_by_name(buffer,
1505                                 &iter, trans_hdr, -1,
1506                                 "header_title", "header", NULL);
1507                         gtk_text_buffer_insert_with_tags_by_name(buffer,
1508                                 &iter, ":", 1, "header_title", "header", NULL);
1509                         g_free(hdr);
1510                 } else {
1511                         gtk_text_buffer_insert_with_tags_by_name(buffer,
1512                                 &iter, header->name,
1513                                 -1, "header_title", "header", NULL);
1514                 }
1515                 if (header->name[strlen(header->name) - 1] != ' ')
1516                 gtk_text_buffer_insert_with_tags_by_name
1517                                 (buffer, &iter, " ", 1,
1518                                  "header_title", "header", NULL);
1519
1520                 if (procheader_headername_equal(header->name, "Subject") ||
1521                     procheader_headername_equal(header->name, "From")    ||
1522                     procheader_headername_equal(header->name, "To")      ||
1523                     procheader_headername_equal(header->name, "Cc"))
1524                         unfold_line(header->body);
1525
1526                 if ((procheader_headername_equal(header->name, "X-Mailer") ||
1527                      procheader_headername_equal(header->name,
1528                                                  "X-Newsreader")) &&
1529                     strstr(header->body, "Sylpheed-Claws") != NULL) {
1530                         gtk_text_buffer_get_end_iter (buffer, &iter);
1531                         gtk_text_buffer_insert_with_tags_by_name
1532                                 (buffer, &iter, header->body, -1,
1533                                  "header", "emphasis", NULL);
1534                 } else {
1535                         gboolean hdr = 
1536                           procheader_headername_equal(header->name, "From") ||
1537                           procheader_headername_equal(header->name, "To") ||
1538                           procheader_headername_equal(header->name, "Cc") ||
1539                           procheader_headername_equal(header->name, "Bcc") ||
1540                           procheader_headername_equal(header->name, "Reply-To") ||
1541                           procheader_headername_equal(header->name, "Sender");
1542                         textview_make_clickable_parts(textview, "header", 
1543                                                       "link", header->body, 
1544                                                       hdr);
1545                 }
1546                 gtk_text_buffer_get_end_iter (buffer, &iter);
1547                 gtk_text_buffer_insert_with_tags_by_name(buffer, &iter, "\n", 1,
1548                                                          "header", NULL);
1549         }
1550         
1551         textview_show_face(textview);
1552 #if HAVE_LIBCOMPFACE
1553         textview_show_xface(textview);
1554 #endif
1555 }
1556
1557 gboolean textview_search_string(TextView *textview, const gchar *str,
1558                                 gboolean case_sens)
1559 {
1560         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1561
1562         return gtkut_text_view_search_string(text, str, case_sens);
1563 }
1564
1565 gboolean textview_search_string_backward(TextView *textview, const gchar *str,
1566                                          gboolean case_sens)
1567 {
1568         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1569
1570         return gtkut_text_view_search_string_backward(text, str, case_sens);
1571 }
1572
1573 void textview_scroll_one_line(TextView *textview, gboolean up)
1574 {
1575         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1576         GtkAdjustment *vadj = text->vadjustment;
1577         gfloat upper;
1578
1579         if (prefs_common.enable_smooth_scroll) {
1580                 textview_smooth_scroll_one_line(textview, up);
1581                 return;
1582         }
1583
1584         if (!up) {
1585                 upper = vadj->upper - vadj->page_size;
1586                 if (vadj->value < upper) {
1587                         vadj->value += vadj->step_increment;
1588                         vadj->value = MIN(vadj->value, upper);
1589                         g_signal_emit_by_name(G_OBJECT(vadj),
1590                                               "value_changed", 0);
1591                 }
1592         } else {
1593                 if (vadj->value > 0.0) {
1594                         vadj->value -= vadj->step_increment;
1595                         vadj->value = MAX(vadj->value, 0.0);
1596                         g_signal_emit_by_name(G_OBJECT(vadj),
1597                                               "value_changed", 0);
1598                 }
1599         }
1600 }
1601
1602 gboolean textview_scroll_page(TextView *textview, gboolean up)
1603 {
1604         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1605         GtkAdjustment *vadj = text->vadjustment;
1606         gfloat upper;
1607         gfloat page_incr;
1608
1609         if (prefs_common.enable_smooth_scroll)
1610                 return textview_smooth_scroll_page(textview, up);
1611
1612         if (prefs_common.scroll_halfpage)
1613                 page_incr = vadj->page_increment / 2;
1614         else
1615                 page_incr = vadj->page_increment;
1616
1617         if (!up) {
1618                 upper = vadj->upper - vadj->page_size;
1619                 if (vadj->value < upper) {
1620                         vadj->value += page_incr;
1621                         vadj->value = MIN(vadj->value, upper);
1622                         g_signal_emit_by_name(G_OBJECT(vadj),
1623                                               "value_changed", 0);
1624                 } else
1625                         return FALSE;
1626         } else {
1627                 if (vadj->value > 0.0) {
1628                         vadj->value -= page_incr;
1629                         vadj->value = MAX(vadj->value, 0.0);
1630                         g_signal_emit_by_name(G_OBJECT(vadj),
1631                                               "value_changed", 0);
1632                 } else
1633                         return FALSE;
1634         }
1635
1636         return TRUE;
1637 }
1638
1639 static void textview_smooth_scroll_do(TextView *textview,
1640                                       gfloat old_value, gfloat last_value,
1641                                       gint step)
1642 {
1643         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1644         GtkAdjustment *vadj = text->vadjustment;
1645         gint change_value;
1646         gboolean up;
1647         gint i;
1648
1649         if (old_value < last_value) {
1650                 change_value = last_value - old_value;
1651                 up = FALSE;
1652         } else {
1653                 change_value = old_value - last_value;
1654                 up = TRUE;
1655         }
1656
1657         for (i = step; i <= change_value; i += step) {
1658                 vadj->value = old_value + (up ? -i : i);
1659                 g_signal_emit_by_name(G_OBJECT(vadj),
1660                                       "value_changed", 0);
1661         }
1662
1663         vadj->value = last_value;
1664         g_signal_emit_by_name(G_OBJECT(vadj), "value_changed", 0);
1665
1666         gtk_widget_queue_draw(GTK_WIDGET(text));
1667 }
1668
1669 static void textview_smooth_scroll_one_line(TextView *textview, gboolean up)
1670 {
1671         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1672         GtkAdjustment *vadj = text->vadjustment;
1673         gfloat upper;
1674         gfloat old_value;
1675         gfloat last_value;
1676
1677         if (!up) {
1678                 upper = vadj->upper - vadj->page_size;
1679                 if (vadj->value < upper) {
1680                         old_value = vadj->value;
1681                         last_value = vadj->value + vadj->step_increment;
1682                         last_value = MIN(last_value, upper);
1683
1684                         textview_smooth_scroll_do(textview, old_value,
1685                                                   last_value,
1686                                                   prefs_common.scroll_step);
1687                 }
1688         } else {
1689                 if (vadj->value > 0.0) {
1690                         old_value = vadj->value;
1691                         last_value = vadj->value - vadj->step_increment;
1692                         last_value = MAX(last_value, 0.0);
1693
1694                         textview_smooth_scroll_do(textview, old_value,
1695                                                   last_value,
1696                                                   prefs_common.scroll_step);
1697                 }
1698         }
1699 }
1700
1701 static gboolean textview_smooth_scroll_page(TextView *textview, gboolean up)
1702 {
1703         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1704         GtkAdjustment *vadj = text->vadjustment;
1705         gfloat upper;
1706         gfloat page_incr;
1707         gfloat old_value;
1708         gfloat last_value;
1709
1710         if (prefs_common.scroll_halfpage)
1711                 page_incr = vadj->page_increment / 2;
1712         else
1713                 page_incr = vadj->page_increment;
1714
1715         if (!up) {
1716                 upper = vadj->upper - vadj->page_size;
1717                 if (vadj->value < upper) {
1718                         old_value = vadj->value;
1719                         last_value = vadj->value + page_incr;
1720                         last_value = MIN(last_value, upper);
1721
1722                         textview_smooth_scroll_do(textview, old_value,
1723                                                   last_value,
1724                                                   prefs_common.scroll_step);
1725                 } else
1726                         return FALSE;
1727         } else {
1728                 if (vadj->value > 0.0) {
1729                         old_value = vadj->value;
1730                         last_value = vadj->value - page_incr;
1731                         last_value = MAX(last_value, 0.0);
1732
1733                         textview_smooth_scroll_do(textview, old_value,
1734                                                   last_value,
1735                                                   prefs_common.scroll_step);
1736                 } else
1737                         return FALSE;
1738         }
1739
1740         return TRUE;
1741 }
1742
1743 #define KEY_PRESS_EVENT_STOP() \
1744         g_signal_stop_emission_by_name(G_OBJECT(widget), \
1745                                        "key_press_event");
1746
1747 static gint textview_key_pressed(GtkWidget *widget, GdkEventKey *event,
1748                                  TextView *textview)
1749 {
1750         SummaryView *summaryview = NULL;
1751         MessageView *messageview = textview->messageview;
1752
1753         if (!event) return FALSE;
1754         if (messageview->mainwin)
1755                 summaryview = messageview->mainwin->summaryview;
1756
1757         switch (event->keyval) {
1758         case GDK_Tab:
1759         case GDK_Home:
1760         case GDK_Left:
1761         case GDK_Up:
1762         case GDK_Right:
1763         case GDK_Down:
1764         case GDK_Page_Up:
1765         case GDK_Page_Down:
1766         case GDK_End:
1767         case GDK_Control_L:
1768         case GDK_Control_R:
1769                 return FALSE;
1770         case GDK_space:
1771                 if (summaryview)
1772                         summary_pass_key_press_event(summaryview, event);
1773                 else
1774                         textview_scroll_page
1775                                 (textview,
1776                                  (event->state &
1777                                   (GDK_SHIFT_MASK|GDK_MOD1_MASK)) != 0);
1778                 break;
1779         case GDK_BackSpace:
1780                 textview_scroll_page(textview, TRUE);
1781                 break;
1782         case GDK_Return:
1783                 textview_scroll_one_line
1784                         (textview, (event->state &
1785                                     (GDK_SHIFT_MASK|GDK_MOD1_MASK)) != 0);
1786                 break;
1787         case GDK_Delete:
1788                 if (summaryview)
1789                         summary_pass_key_press_event(summaryview, event);
1790                 break;
1791         case GDK_y:
1792         case GDK_t:
1793         case GDK_l:
1794         case GDK_c:
1795                 if ((event->state & (GDK_MOD1_MASK|GDK_CONTROL_MASK)) == 0) {
1796                         KEY_PRESS_EVENT_STOP();
1797                         mimeview_pass_key_press_event(messageview->mimeview,
1798                                                       event);
1799                         break;
1800                 }
1801                 /* possible fall through */
1802         default:
1803                 if (summaryview &&
1804                     event->window != messageview->mainwin->window->window) {
1805                         GdkEventKey tmpev = *event;
1806
1807                         tmpev.window = messageview->mainwin->window->window;
1808                         KEY_PRESS_EVENT_STOP();
1809                         gtk_widget_event(messageview->mainwin->window,
1810                                          (GdkEvent *)&tmpev);
1811                 }
1812                 break;
1813         }
1814
1815         return TRUE;
1816 }
1817
1818 static gboolean textview_motion_notify(GtkWidget *widget,
1819                                        GdkEventMotion *event,
1820                                        TextView *textview)
1821 {
1822         textview_uri_update(textview, event->x, event->y);
1823         gdk_window_get_pointer(widget->window, NULL, NULL, NULL);
1824
1825         return FALSE;
1826 }
1827
1828 static gboolean textview_leave_notify(GtkWidget *widget,
1829                                       GdkEventCrossing *event,
1830                                       TextView *textview)
1831 {
1832         textview_uri_update(textview, -1, -1);
1833
1834         return FALSE;
1835 }
1836
1837 static gboolean textview_visibility_notify(GtkWidget *widget,
1838                                            GdkEventVisibility *event,
1839                                            TextView *textview)
1840 {
1841         gint wx, wy;
1842         GdkWindow *window;
1843
1844         window = gtk_text_view_get_window(GTK_TEXT_VIEW(widget),
1845                                           GTK_TEXT_WINDOW_TEXT);
1846
1847         /* check if occurred for the text window part */
1848         if (window != event->window)
1849                 return FALSE;
1850         
1851         gdk_window_get_pointer(widget->window, &wx, &wy, NULL);
1852         textview_uri_update(textview, wx, wy);
1853
1854         return FALSE;
1855 }
1856
1857 void textview_cursor_wait(TextView *textview)
1858 {
1859         GdkWindow *window = gtk_text_view_get_window(
1860                         GTK_TEXT_VIEW(textview->text),
1861                         GTK_TEXT_WINDOW_TEXT);
1862         textview_set_cursor(window, watch_cursor);
1863 }
1864
1865 void textview_cursor_normal(TextView *textview)
1866 {
1867         GdkWindow *window = gtk_text_view_get_window(
1868                         GTK_TEXT_VIEW(textview->text),
1869                         GTK_TEXT_WINDOW_TEXT);
1870         textview_set_cursor(window, text_cursor);
1871 }
1872
1873 static void textview_uri_update(TextView *textview, gint x, gint y)
1874 {
1875         GtkTextBuffer *buffer;
1876         GtkTextIter start_iter, end_iter;
1877         RemoteURI *uri = NULL;
1878         
1879         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview->text));
1880
1881         if (x != -1 && y != -1) {
1882                 gint bx, by;
1883                 GtkTextIter iter;
1884                 GSList *tags;
1885                 GSList *cur;
1886             
1887                 gtk_text_view_window_to_buffer_coords(GTK_TEXT_VIEW(textview->text), 
1888                                                       GTK_TEXT_WINDOW_WIDGET,
1889                                                       x, y, &bx, &by);
1890                 gtk_text_view_get_iter_at_location(GTK_TEXT_VIEW(textview->text),
1891                                                    &iter, bx, by);
1892
1893                 tags = gtk_text_iter_get_tags(&iter);
1894                 for (cur = tags; cur != NULL; cur = cur->next) {
1895                         GtkTextTag *tag = cur->data;
1896                         char *name;
1897
1898                         g_object_get(G_OBJECT(tag), "name", &name, NULL);
1899                         if (!strcmp(name, "link")
1900                             && textview_get_uri_range(textview, &iter, tag,
1901                                                       &start_iter, &end_iter))
1902                                 uri = textview_get_uri_from_range(textview,
1903                                                                   &iter, tag,
1904                                                                   &start_iter,
1905                                                                   &end_iter);
1906                         g_free(name);
1907
1908                         if (uri)
1909                                 break;
1910                 }
1911                 g_slist_free(tags);
1912         }
1913         
1914         if (uri != textview->uri_hover) {
1915                 GdkWindow *window;
1916
1917                 if (textview->uri_hover)
1918                         gtk_text_buffer_remove_tag_by_name(buffer,
1919                                                            "link-hover",
1920                                                            &textview->uri_hover_start_iter,
1921                                                            &textview->uri_hover_end_iter);
1922                     
1923                 textview->uri_hover = uri;
1924                 if (uri) {
1925                         textview->uri_hover_start_iter = start_iter;
1926                         textview->uri_hover_end_iter = end_iter;
1927                 }
1928                 
1929                 window = gtk_text_view_get_window(GTK_TEXT_VIEW(textview->text),
1930                                                   GTK_TEXT_WINDOW_TEXT);
1931                 if (textview->messageview->mainwin->cursor_count == 0) {
1932                         textview_set_cursor(window, uri ? hand_cursor : text_cursor);
1933                 } else {
1934                         textview_set_cursor(window, watch_cursor);
1935                 }
1936
1937                 TEXTVIEW_STATUSBAR_POP(textview);
1938
1939                 if (uri) {
1940                         char *trimmed_uri;
1941
1942                         gtk_text_buffer_apply_tag_by_name(buffer,
1943                                                           "link-hover",
1944                                                           &start_iter,
1945                                                           &end_iter);
1946
1947                         trimmed_uri = trim_string(uri->uri, 60);
1948                         TEXTVIEW_STATUSBAR_PUSH(textview, trimmed_uri);
1949                         g_free(trimmed_uri);
1950                 }
1951         }
1952 }
1953
1954 static gboolean textview_get_uri_range(TextView *textview,
1955                                        GtkTextIter *iter,
1956                                        GtkTextTag *tag,
1957                                        GtkTextIter *start_iter,
1958                                        GtkTextIter *end_iter)
1959 {
1960         return get_tag_range(iter, tag, start_iter, end_iter);
1961 }
1962
1963 static RemoteURI *textview_get_uri_from_range(TextView *textview,
1964                                               GtkTextIter *iter,
1965                                               GtkTextTag *tag,
1966                                               GtkTextIter *start_iter,
1967                                               GtkTextIter *end_iter)
1968 {
1969         gint start_pos, end_pos, cur_pos;
1970         RemoteURI *uri = NULL;
1971         GSList *cur;
1972
1973         start_pos = gtk_text_iter_get_offset(start_iter);
1974         end_pos = gtk_text_iter_get_offset(end_iter);
1975         cur_pos = gtk_text_iter_get_offset(iter);
1976
1977         for (cur = textview->uri_list; cur != NULL; cur = cur->next) {
1978                 RemoteURI *uri_ = (RemoteURI *)cur->data;
1979                 if (start_pos == uri_->start &&
1980                     end_pos ==  uri_->end) {
1981                         uri = uri_;
1982                         break;
1983                 } else if (start_pos == uri_->start ||
1984                            end_pos == uri_->end) {
1985                         /* in case of contiguous links, textview_get_uri_range
1986                          * returns a broader range (start of 1st link to end
1987                          * of last link).
1988                          * In that case, correct link is the one covering
1989                          * current iter.
1990                          */
1991                         if (uri_->start <= cur_pos && cur_pos <= uri_->end) {
1992                                 uri = uri_;
1993                                 break;
1994                         }
1995                 } 
1996         }
1997
1998         return uri;
1999 }
2000
2001 static RemoteURI *textview_get_uri(TextView *textview,
2002                                    GtkTextIter *iter,
2003                                    GtkTextTag *tag)
2004 {
2005         GtkTextIter start_iter, end_iter;
2006         RemoteURI *uri = NULL;
2007
2008         if (textview_get_uri_range(textview, iter, tag, &start_iter,
2009                                    &end_iter))
2010                 uri = textview_get_uri_from_range(textview, iter, tag,
2011                                                   &start_iter, &end_iter);
2012
2013         return uri;
2014 }
2015
2016 static gboolean textview_uri_button_pressed(GtkTextTag *tag, GObject *obj,
2017                                             GdkEvent *event, GtkTextIter *iter,
2018                                             TextView *textview)
2019 {
2020         GdkEventButton *bevent;
2021         RemoteURI *uri = NULL;
2022
2023         if (!event)
2024                 return FALSE;
2025
2026         if (event->type != GDK_BUTTON_PRESS && event->type != GDK_2BUTTON_PRESS
2027                 && event->type != GDK_MOTION_NOTIFY)
2028                 return FALSE;
2029
2030         uri = textview_get_uri(textview, iter, tag);
2031         if (!uri)
2032                 return FALSE;
2033
2034         bevent = (GdkEventButton *) event;
2035         
2036         /* doubleclick: open compose / add address / browser */
2037         if ((event->type == GDK_BUTTON_PRESS && bevent->button == 1) ||
2038                 bevent->button == 2 || bevent->button == 3) {
2039                 if (uri->filename && !g_ascii_strncasecmp(uri->filename, "sc://", 5)) {
2040                         if (bevent->button == 1) {
2041                                 MimeView *mimeview = 
2042                                         (textview->messageview)?
2043                                                 textview->messageview->mimeview:NULL;
2044                                 mimeview_handle_cmd(mimeview, uri->filename);
2045                         }
2046                         return TRUE;
2047                 } else if (!g_ascii_strncasecmp(uri->uri, "mailto:", 7)) {
2048                         if (bevent->button == 3) {
2049                                 g_object_set_data(
2050                                         G_OBJECT(textview->mail_popup_menu),
2051                                         "menu_button", uri);
2052                                 gtk_menu_popup(GTK_MENU(textview->mail_popup_menu), 
2053                                                NULL, NULL, NULL, NULL, 
2054                                                bevent->button, bevent->time);
2055                         } else {
2056                                 PrefsAccount *account = NULL;
2057
2058                                 if (textview->messageview && textview->messageview->msginfo &&
2059                                     textview->messageview->msginfo->folder) {
2060                                         FolderItem   *folder_item;
2061
2062                                         folder_item = textview->messageview->msginfo->folder;
2063                                         if (folder_item->prefs && folder_item->prefs->enable_default_account)
2064                                                 account = account_find_from_id(folder_item->prefs->default_account);
2065                                 }
2066                                 compose_new(account, uri->uri + 7, NULL);
2067                         }
2068                         return TRUE;
2069                 } else if (g_ascii_strncasecmp(uri->uri, "file:", 5)) {
2070                         if (bevent->button == 1 &&
2071                             textview_uri_security_check(textview, uri) == TRUE) 
2072                                         open_uri(uri->uri,
2073                                                  prefs_common.uri_cmd);
2074                         else if (bevent->button == 3) {
2075                                 g_object_set_data(
2076                                         G_OBJECT(textview->link_popup_menu),
2077                                         "menu_button", uri);
2078                                 gtk_menu_popup(GTK_MENU(textview->link_popup_menu), 
2079                                                NULL, NULL, NULL, NULL, 
2080                                                bevent->button, bevent->time);
2081                         }
2082                         return TRUE;
2083                 } else {
2084                         if (bevent->button == 3) {
2085                                 g_object_set_data(
2086                                         G_OBJECT(textview->file_popup_menu),
2087                                         "menu_button", uri);
2088                                 gtk_menu_popup(GTK_MENU(textview->file_popup_menu), 
2089                                                NULL, NULL, NULL, NULL, 
2090                                                bevent->button, bevent->time);
2091                                 return TRUE;
2092                         }
2093                 }
2094         }
2095
2096         return FALSE;
2097 }
2098
2099 /*!
2100  *\brief    Check to see if a web URL has been disguised as a different
2101  *          URL (possible with HTML email).
2102  *
2103  *\param    uri The uri to check
2104  *
2105  *\param    textview The TextView the URL is contained in
2106  *
2107  *\return   gboolean TRUE if the URL is ok, or if the user chose to open
2108  *          it anyway, otherwise FALSE          
2109  */
2110 static gboolean textview_uri_security_check(TextView *textview, RemoteURI *uri)
2111 {
2112         gchar *visible_str;
2113         gboolean retval = TRUE;
2114         GtkTextBuffer *buffer;
2115         GtkTextIter start, end;
2116
2117         if (is_uri_string(uri->uri) == FALSE)
2118                 return TRUE;
2119
2120         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview->text));
2121
2122         gtk_text_buffer_get_iter_at_offset(buffer, &start, uri->start);
2123         gtk_text_buffer_get_iter_at_offset(buffer, &end,   uri->end);
2124
2125         visible_str = gtk_text_buffer_get_text(buffer, &start, &end, FALSE);
2126
2127         if (visible_str == NULL)
2128                 return TRUE;
2129
2130         if (strcmp(visible_str, uri->uri) != 0 && is_uri_string(visible_str)) {
2131                 gchar *uri_path;
2132                 gchar *visible_uri_path;
2133
2134                 uri_path = get_uri_path(uri->uri);
2135                 visible_uri_path = get_uri_path(visible_str);
2136                 if (path_cmp(uri_path, visible_uri_path) != 0)
2137                         retval = FALSE;
2138         }
2139
2140         if (retval == FALSE) {
2141                 gchar *msg;
2142                 AlertValue aval;
2143
2144                 msg = g_strdup_printf(_("The real URL (%s) is different from\n"
2145                                         "the apparent URL (%s).\n"
2146                                         "\n"
2147                                         "Open it anyway?"),
2148                                       uri->uri, visible_str);
2149                 aval = alertpanel_full(_("Fake URL warning"), msg,
2150                                        GTK_STOCK_CANCEL, _("_Open URL"), NULL, FALSE,
2151                                        NULL, ALERT_WARNING, G_ALERTDEFAULT);
2152                 g_free(msg);
2153                 if (aval == G_ALERTALTERNATE)
2154                         retval = TRUE;
2155         }
2156
2157         g_free(visible_str);
2158
2159         return retval;
2160 }
2161
2162 static void textview_uri_list_remove_all(GSList *uri_list)
2163 {
2164         GSList *cur;
2165
2166         for (cur = uri_list; cur != NULL; cur = cur->next) {
2167                 if (cur->data) {
2168                         g_free(((RemoteURI *)cur->data)->uri);
2169                         g_free(((RemoteURI *)cur->data)->filename);
2170                         g_free(cur->data);
2171                 }
2172         }
2173
2174         g_slist_free(uri_list);
2175 }
2176
2177 static void open_uri_cb (TextView *textview, guint action, void *data)
2178 {
2179         RemoteURI *uri = g_object_get_data(G_OBJECT(textview->link_popup_menu),
2180                                            "menu_button");
2181         if (uri == NULL)
2182                 return;
2183
2184         if (textview_uri_security_check(textview, uri) == TRUE) 
2185                 open_uri(uri->uri,
2186                          prefs_common.uri_cmd);
2187         g_object_set_data(G_OBJECT(textview->link_popup_menu), "menu_button",
2188                           NULL);
2189 }
2190
2191 static void open_image_cb (TextView *textview, guint action, void *data)
2192 {
2193         RemoteURI *uri = g_object_get_data(G_OBJECT(textview->file_popup_menu),
2194                                            "menu_button");
2195
2196         static gchar *default_cmdline = DEFAULT_IMAGE_VIEWER_CMD;
2197         gchar buf[1024];
2198         const gchar *cmd;
2199         const gchar *def_cmd;
2200         const gchar *p;
2201         gchar *filename = NULL;
2202         gchar *tmp_filename = NULL;
2203
2204         if (uri == NULL)
2205                 return;
2206
2207         if (uri->filename == NULL)
2208                 return;
2209         
2210         filename = g_strdup(uri->filename);
2211         
2212         if (!g_utf8_validate(filename, -1, NULL)) {
2213                 gchar *tmp = conv_filename_to_utf8(filename);
2214                 g_free(filename);
2215                 filename = tmp;
2216         }
2217
2218         subst_for_filename(filename);
2219
2220         tmp_filename = g_filename_from_uri(uri->uri, NULL, NULL);
2221         copy_file(tmp_filename, filename, FALSE);
2222         g_free(tmp_filename);
2223
2224         cmd = prefs_common.mime_image_viewer;
2225         def_cmd = default_cmdline;
2226         
2227         if (cmd && (p = strchr(cmd, '%')) && *(p + 1) == 's' &&
2228             !strchr(p + 2, '%'))
2229                 g_snprintf(buf, sizeof(buf), cmd, filename);
2230         else {
2231                 if (cmd)
2232                         g_warning("Image viewer command line is invalid: '%s'", cmd);
2233                 if (def_cmd)
2234                         g_snprintf(buf, sizeof(buf), def_cmd, filename);
2235                 else
2236                         return;
2237         }
2238
2239         execute_command_line(buf, TRUE);
2240
2241         g_free(filename);
2242
2243         g_object_set_data(G_OBJECT(textview->file_popup_menu), "menu_button",
2244                           NULL);
2245 }
2246
2247 static void save_file_cb (TextView *textview, guint action, void *data)
2248 {
2249         RemoteURI *uri = g_object_get_data(G_OBJECT(textview->file_popup_menu),
2250                                            "menu_button");
2251         gchar *filename = NULL;
2252         gchar *filepath = NULL;
2253         gchar *filedir = NULL;
2254         gchar *tmp_filename = NULL;
2255         if (uri == NULL)
2256                 return;
2257
2258         if (uri->filename == NULL)
2259                 return;
2260         
2261         filename = g_strdup(uri->filename);
2262         
2263         if (!g_utf8_validate(filename, -1, NULL)) {
2264                 gchar *tmp = conv_filename_to_utf8(filename);
2265                 g_free(filename);
2266                 filename = tmp;
2267         }
2268
2269         subst_for_filename(filename);
2270         
2271         if (prefs_common.attach_save_dir)
2272                 filepath = g_strconcat(prefs_common.attach_save_dir,
2273                                        G_DIR_SEPARATOR_S, filename, NULL);
2274         else
2275                 filepath = g_strdup(filename);
2276
2277         g_free(filename);
2278
2279         filename = filesel_select_file_save(_("Save as"), filepath);
2280         if (!filename) {
2281                 g_free(filepath);
2282                 return;
2283         }
2284
2285         if (is_file_exist(filename)) {
2286                 AlertValue aval;
2287                 gchar *res;
2288                 
2289                 res = g_strdup_printf(_("Overwrite existing file '%s'?"),
2290                                       filename);
2291                 aval = alertpanel(_("Overwrite"), res, GTK_STOCK_CANCEL, 
2292                                   GTK_STOCK_OK, NULL);
2293                 g_free(res);                                      
2294                 if (G_ALERTALTERNATE != aval)
2295                         return;
2296         }
2297
2298         tmp_filename = g_filename_from_uri(uri->uri, NULL, NULL);
2299         copy_file(tmp_filename, filename, FALSE);
2300         g_free(tmp_filename);
2301         
2302         filedir = g_path_get_dirname(filename);
2303         if (filedir && strcmp(filedir, ".")) {
2304                 g_free(prefs_common.attach_save_dir);
2305                 prefs_common.attach_save_dir = g_strdup(filedir);
2306         }
2307
2308         g_free(filedir);
2309         g_free(filepath);
2310
2311         g_object_set_data(G_OBJECT(textview->file_popup_menu), "menu_button",
2312                           NULL);
2313 }
2314
2315 static void copy_uri_cb (TextView *textview, guint action, void *data)
2316 {
2317         RemoteURI *uri = g_object_get_data(G_OBJECT(textview->link_popup_menu),
2318                                            "menu_button");
2319         if (uri == NULL)
2320                 return;
2321
2322         gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), uri->uri, -1);
2323         gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), uri->uri, -1);
2324         g_object_set_data(G_OBJECT(textview->link_popup_menu), "menu_button",
2325                           NULL);
2326 }
2327
2328 static void add_uri_to_addrbook_cb (TextView *textview, guint action, void *data)
2329 {
2330         gchar *fromname, *fromaddress;
2331         RemoteURI *uri = g_object_get_data(G_OBJECT(textview->mail_popup_menu),
2332                                            "menu_button");
2333         if (uri == NULL)
2334                 return;
2335
2336         /* extract url */
2337         fromaddress = g_strdup(uri->uri + 7);
2338         /* Hiroyuki: please put this function in utils.c! */
2339         fromname = procheader_get_fromname(fromaddress);
2340         extract_address(fromaddress);
2341         g_message("adding from textview %s <%s>", fromname, fromaddress);
2342         /* Add to address book - Match */
2343         addressbook_add_contact( fromname, fromaddress, NULL );
2344
2345         g_free(fromaddress);
2346         g_free(fromname);
2347 }
2348
2349 static void mail_to_uri_cb (TextView *textview, guint action, void *data)
2350 {
2351         PrefsAccount *account = NULL;
2352         RemoteURI *uri = g_object_get_data(G_OBJECT(textview->mail_popup_menu),
2353                                            "menu_button");
2354         if (uri == NULL)
2355                 return;
2356
2357         if (textview->messageview && textview->messageview->msginfo &&
2358             textview->messageview->msginfo->folder) {
2359                 FolderItem   *folder_item;
2360
2361                 folder_item = textview->messageview->msginfo->folder;
2362                 if (folder_item->prefs && folder_item->prefs->enable_default_account)
2363                         account = account_find_from_id(folder_item->prefs->default_account);
2364         }
2365         compose_new(account, uri->uri + 7, NULL);
2366 }
2367
2368 static void copy_mail_to_uri_cb (TextView *textview, guint action, void *data)
2369 {
2370         RemoteURI *uri = g_object_get_data(G_OBJECT(textview->mail_popup_menu),
2371                                            "menu_button");
2372         if (uri == NULL)
2373                 return;
2374
2375         gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), uri->uri +7, -1);
2376         gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), uri->uri +7, -1);
2377         g_object_set_data(G_OBJECT(textview->mail_popup_menu), "menu_button",
2378                           NULL);
2379 }
2380