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