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