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