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