2007-07-25 [paul] 2.10.0cvs62
[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         const gchar *name;
848         gchar *content_type;
849
850         if (!partinfo) return;
851
852         textview_set_font(textview, NULL);
853         textview_clear(textview);
854
855         text = GTK_TEXT_VIEW(textview->text);
856         buffer = gtk_text_view_get_buffer(text);
857         gtk_text_buffer_get_start_iter(buffer, &iter);
858
859         TEXTVIEW_INSERT("\n");
860
861         name = procmime_mimeinfo_get_parameter(partinfo, "filename");
862         if (name == NULL)
863                 name = procmime_mimeinfo_get_parameter(partinfo, "name");
864         if (name != NULL) {
865                 content_type = procmime_get_content_type_str(partinfo->type,
866                                                      partinfo->subtype);
867                 TEXTVIEW_INSERT("  ");
868                 TEXTVIEW_INSERT_BOLD(name);
869                 TEXTVIEW_INSERT(" (");
870                 TEXTVIEW_INSERT(content_type);
871                 TEXTVIEW_INSERT(", ");
872                 TEXTVIEW_INSERT(to_human_readable(partinfo->length));
873                 TEXTVIEW_INSERT("):\n\n");
874                 
875                 g_free(content_type);
876         }
877         TEXTVIEW_INSERT(_("  The following can be performed on this part\n"));
878 #ifndef MAEMO
879         TEXTVIEW_INSERT(_("  by right-clicking the icon or list item:"));
880 #endif
881         TEXTVIEW_INSERT("\n");
882
883         TEXTVIEW_INSERT(_("     - To save, select "));
884         TEXTVIEW_INSERT_LINK(_("'Save as...'"), "sc://save_as", NULL);
885 #ifndef MAEMO
886         TEXTVIEW_INSERT(_(" (Shortcut key: 'y')"));
887 #endif
888         TEXTVIEW_INSERT("\n");
889
890         TEXTVIEW_INSERT(_("     - To display as text, select "));
891         TEXTVIEW_INSERT_LINK(_("'Display as text'"), "sc://display_as_text", NULL);
892
893 #ifndef MAEMO
894         TEXTVIEW_INSERT(_(" (Shortcut key: 't')"));
895 #endif
896         TEXTVIEW_INSERT("\n");
897
898         TEXTVIEW_INSERT(_("     - To open with an external program, select "));
899         TEXTVIEW_INSERT_LINK(_("'Open'"), "sc://open", NULL);
900
901 #ifndef MAEMO
902         TEXTVIEW_INSERT(_(" (Shortcut key: 'l')\n"));
903         TEXTVIEW_INSERT(_("       (alternately double-click, or click the middle "));
904         TEXTVIEW_INSERT(_("mouse button)\n"));
905         TEXTVIEW_INSERT(_("     - Or use "));
906         TEXTVIEW_INSERT_LINK(_("'Open with...'"), "sc://open_with", NULL);
907         TEXTVIEW_INSERT(_(" (Shortcut key: 'o')"));
908 #endif
909         TEXTVIEW_INSERT("\n");
910
911         textview_show_icon(textview, GTK_STOCK_DIALOG_INFO);
912 }
913
914 static void textview_write_body(TextView *textview, MimeInfo *mimeinfo)
915 {
916         FILE *tmpfp;
917         gchar buf[BUFFSIZE];
918         CodeConverter *conv;
919         const gchar *charset, *p, *cmd;
920         GSList *cur;
921         int lines = 0;
922         
923         if (textview->messageview->forced_charset)
924                 charset = textview->messageview->forced_charset;
925         else
926                 charset = procmime_mimeinfo_get_parameter(mimeinfo, "charset");
927
928         textview_set_font(textview, charset);
929
930         conv = conv_code_converter_new(charset);
931
932         procmime_force_encoding(textview->messageview->forced_encoding);
933         
934         textview->is_in_signature = FALSE;
935
936         procmime_decode_content(mimeinfo);
937
938         if (!g_ascii_strcasecmp(mimeinfo->subtype, "html") &&
939             prefs_common.render_html) {
940                 gchar *filename;
941                 
942                 filename = procmime_get_tmp_file_name(mimeinfo);
943                 if (procmime_get_part(filename, mimeinfo) == 0) {
944                         tmpfp = g_fopen(filename, "rb");
945                         textview_show_html(textview, tmpfp, conv);
946                         fclose(tmpfp);
947                         g_unlink(filename);
948                 }
949                 g_free(filename);
950         } else if (!g_ascii_strcasecmp(mimeinfo->subtype, "enriched")) {
951                 gchar *filename;
952                 
953                 filename = procmime_get_tmp_file_name(mimeinfo);
954                 if (procmime_get_part(filename, mimeinfo) == 0) {
955                         tmpfp = g_fopen(filename, "rb");
956                         textview_show_ertf(textview, tmpfp, conv);
957                         fclose(tmpfp);
958                         g_unlink(filename);
959                 }
960                 g_free(filename);
961 #ifndef G_OS_WIN32
962         } else if ( g_ascii_strcasecmp(mimeinfo->subtype, "plain") &&
963                    (cmd = prefs_common.mime_textviewer) && *cmd &&
964                    (p = strchr(cmd, '%')) && *(p + 1) == 's') {
965                 int pid, pfd[2];
966                 const gchar *fname;
967
968                 fname  = procmime_get_tmp_file_name(mimeinfo);
969                 if (procmime_get_part(fname, mimeinfo)) goto textview_default;
970
971                 g_snprintf(buf, sizeof(buf), cmd, fname);
972                 debug_print("Viewing text content of type: %s (length: %d) "
973                         "using %s\n", mimeinfo->subtype, mimeinfo->length, buf);
974
975                 if (pipe(pfd) < 0) {
976                         g_snprintf(buf, sizeof(buf),
977                                 "pipe failed for textview\n\n%s\n", strerror(errno));
978                         textview_write_line(textview, buf, conv, TRUE);
979                         goto textview_default;
980                 }
981                 pid = fork();
982                 if (pid < 0) {
983                         g_snprintf(buf, sizeof(buf),
984                                 "fork failed for textview\n\n%s\n", strerror(errno));
985                         textview_write_line(textview, buf, conv, TRUE);
986                         close(pfd[0]);
987                         close(pfd[1]);
988                         goto textview_default;
989                 }
990                 if (pid == 0) { /* child */
991                         int rc;
992                         gchar **argv;
993                         argv = strsplit_with_quote(buf, " ", 0);
994                         close(1);
995                         close(pfd[0]);
996                         dup(pfd[1]);
997                         rc = execvp(argv[0], argv);
998                         close(pfd[1]);
999                         printf (_("The command to view attachment "
1000                                 "as text failed:\n"
1001                                 "    %s\n"
1002                                 "Exit code %d\n"), buf, rc);
1003                         exit(255);
1004                 }
1005                 close(pfd[1]);
1006                 tmpfp = fdopen(pfd[0], "rb");
1007                 while (fgets(buf, sizeof(buf), tmpfp)) {
1008                         textview_write_line(textview, buf, conv, TRUE);
1009                         
1010                         lines++;
1011                         if (lines % 500 == 0)
1012                                 GTK_EVENTS_FLUSH();
1013                         if (textview->stop_loading) {
1014                                 fclose(tmpfp);
1015                                 waitpid(pid, pfd, 0);
1016                                 unlink(fname);
1017                                 return;
1018                         }
1019                 }
1020
1021                 fclose(tmpfp);
1022                 waitpid(pid, pfd, 0);
1023                 unlink(fname);
1024 #endif
1025         } else {
1026 textview_default:
1027                 lines = 0;
1028                 tmpfp = g_fopen(mimeinfo->data.filename, "rb");
1029                 fseek(tmpfp, mimeinfo->offset, SEEK_SET);
1030                 debug_print("Viewing text content of type: %s (length: %d)\n", mimeinfo->subtype, mimeinfo->length);
1031                 while ((ftell(tmpfp) < mimeinfo->offset + mimeinfo->length) &&
1032                        (fgets(buf, sizeof(buf), tmpfp) != NULL)) {
1033                         textview_write_line(textview, buf, conv, TRUE);
1034                         lines++;
1035                         if (lines % 500 == 0)
1036                                 GTK_EVENTS_FLUSH();
1037                         if (textview->stop_loading) {
1038                                 fclose(tmpfp);
1039                                 return;
1040                         }
1041                 }
1042                 fclose(tmpfp);
1043         }
1044
1045         conv_code_converter_destroy(conv);
1046         procmime_force_encoding(0);
1047
1048         lines = 0;
1049         textview->uri_list = g_slist_reverse(textview->uri_list);
1050         for (cur = textview->uri_list; cur; cur = cur->next) {
1051                 ClickableText *uri = (ClickableText *)cur->data;
1052                 if (!uri->is_quote)
1053                         continue;
1054                 if (!prefs_common.hide_quotes ||
1055                     uri->quote_level+1 < prefs_common.hide_quotes) {
1056                         textview_toggle_quote(textview, cur, uri, TRUE);
1057                         lines++;
1058                         if (lines % 500 == 0)
1059                                 GTK_EVENTS_FLUSH();
1060                         if (textview->stop_loading) {
1061                                 return;
1062                         }
1063                 }
1064         }
1065 }
1066
1067 static void textview_show_html(TextView *textview, FILE *fp,
1068                                CodeConverter *conv)
1069 {
1070         SC_HTMLParser *parser;
1071         gchar *str;
1072         gint lines = 0;
1073
1074         parser = sc_html_parser_new(fp, conv);
1075         g_return_if_fail(parser != NULL);
1076
1077         while ((str = sc_html_parse(parser)) != NULL) {
1078                 if (parser->state == SC_HTML_HREF) {
1079                         /* first time : get and copy the URL */
1080                         if (parser->href == NULL) {
1081                                 /* ALF - the claws html parser returns an empty string,
1082                                  * if still inside an <a>, but already parsed past HREF */
1083                                 str = strtok(str, " ");
1084                                 if (str) {
1085                                         while (str && *str && g_ascii_isspace(*str))
1086                                                 str++; 
1087                                         parser->href = g_strdup(str);
1088                                         /* the URL may (or not) be followed by the
1089                                          * referenced text */
1090                                         str = strtok(NULL, "");
1091                                 }       
1092                         }
1093                         if (str != NULL)
1094                                 textview_write_link(textview, str, parser->href, NULL);
1095                 } else
1096                         textview_write_line(textview, str, NULL, FALSE);
1097                 lines++;
1098                 if (lines % 500 == 0)
1099                         GTK_EVENTS_FLUSH();
1100                 if (textview->stop_loading) {
1101                         return;
1102                 }
1103         }
1104         textview_write_line(textview, "\n", NULL, FALSE);
1105         sc_html_parser_destroy(parser);
1106 }
1107
1108 static void textview_show_ertf(TextView *textview, FILE *fp,
1109                                CodeConverter *conv)
1110 {
1111         ERTFParser *parser;
1112         gchar *str;
1113         gint lines = 0;
1114
1115         parser = ertf_parser_new(fp, conv);
1116         g_return_if_fail(parser != NULL);
1117
1118         while ((str = ertf_parse(parser)) != NULL) {
1119                 textview_write_line(textview, str, NULL, FALSE);
1120                 lines++;
1121                 if (lines % 500 == 0)
1122                         GTK_EVENTS_FLUSH();
1123                 if (textview->stop_loading) {
1124                         return;
1125                 }
1126         }
1127         
1128         ertf_parser_destroy(parser);
1129 }
1130
1131 #define ADD_TXT_POS(bp_, ep_, pti_) \
1132         if ((last->next = alloca(sizeof(struct txtpos))) != NULL) { \
1133                 last = last->next; \
1134                 last->bp = (bp_); last->ep = (ep_); last->pti = (pti_); \
1135                 last->next = NULL; \
1136         } else { \
1137                 g_warning("alloc error scanning URIs\n"); \
1138                 gtk_text_buffer_insert_with_tags_by_name(buffer, &iter, \
1139                                                          linebuf, -1, \
1140                                                          fg_tag, NULL); \
1141                 return; \
1142         }
1143
1144 #define ADD_TXT_POS_LATER(bp_, ep_, pti_) \
1145         if ((last->next = alloca(sizeof(struct txtpos))) != NULL) { \
1146                 last = last->next; \
1147                 last->bp = (bp_); last->ep = (ep_); last->pti = (pti_); \
1148                 last->next = NULL; \
1149         } else { \
1150                 g_warning("alloc error scanning URIs\n"); \
1151         }
1152
1153 /* textview_make_clickable_parts() - colorizes clickable parts */
1154 static void textview_make_clickable_parts(TextView *textview,
1155                                           const gchar *fg_tag,
1156                                           const gchar *uri_tag,
1157                                           const gchar *linebuf,
1158                                           gboolean hdr)
1159 {
1160         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1161         GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
1162         GtkTextIter iter;
1163         gchar *mybuf = g_strdup(linebuf);
1164         
1165         /* parse table - in order of priority */
1166         struct table {
1167                 const gchar *needle; /* token */
1168
1169                 /* token search function */
1170                 gchar    *(*search)     (const gchar *haystack,
1171                                          const gchar *needle);
1172                 /* part parsing function */
1173                 gboolean  (*parse)      (const gchar *start,
1174                                          const gchar *scanpos,
1175                                          const gchar **bp_,
1176                                          const gchar **ep_,
1177                                          gboolean hdr);
1178                 /* part to URI function */
1179                 gchar    *(*build_uri)  (const gchar *bp,
1180                                          const gchar *ep);
1181         };
1182
1183         static struct table parser[] = {
1184                 {"http://",  strcasestr, get_uri_part,   make_uri_string},
1185                 {"https://", strcasestr, get_uri_part,   make_uri_string},
1186                 {"ftp://",   strcasestr, get_uri_part,   make_uri_string},
1187                 {"sftp://",  strcasestr, get_uri_part,   make_uri_string},
1188                 {"www.",     strcasestr, get_uri_part,   make_http_string},
1189                 {"mailto:",  strcasestr, get_uri_part,   make_uri_string},
1190                 {"@",        strcasestr, get_email_part, make_email_string}
1191         };
1192         const gint PARSE_ELEMS = sizeof parser / sizeof parser[0];
1193
1194         gint  n;
1195         const gchar *walk, *bp, *ep;
1196
1197         struct txtpos {
1198                 const gchar     *bp, *ep;       /* text position */
1199                 gint             pti;           /* index in parse table */
1200                 struct txtpos   *next;          /* next */
1201         } head = {NULL, NULL, 0,  NULL}, *last = &head;
1202
1203         if (!g_utf8_validate(linebuf, -1, NULL)) {
1204                 g_free(mybuf);
1205                 mybuf = g_malloc(strlen(linebuf)*2 +1);
1206                 conv_localetodisp(mybuf, strlen(linebuf)*2 +1, linebuf);
1207         }
1208
1209         gtk_text_buffer_get_end_iter(buffer, &iter);
1210
1211         /* parse for clickable parts, and build a list of begin and end positions  */
1212         for (walk = mybuf, n = 0;;) {
1213                 gint last_index = PARSE_ELEMS;
1214                 gchar *scanpos = NULL;
1215
1216                 /* FIXME: this looks phony. scanning for anything in the parse table */
1217                 for (n = 0; n < PARSE_ELEMS; n++) {
1218                         gchar *tmp;
1219
1220                         tmp = parser[n].search(walk, parser[n].needle);
1221                         if (tmp) {
1222                                 if (scanpos == NULL || tmp < scanpos) {
1223                                         scanpos = tmp;
1224                                         last_index = n;
1225                                 }
1226                         }                                       
1227                 }
1228
1229                 if (scanpos) {
1230                         /* check if URI can be parsed */
1231                         if (parser[last_index].parse(walk, scanpos, &bp, &ep, hdr)
1232                             && (size_t) (ep - bp - 1) > strlen(parser[last_index].needle)) {
1233                                         ADD_TXT_POS(bp, ep, last_index);
1234                                         walk = ep;
1235                         } else
1236                                 walk = scanpos +
1237                                         strlen(parser[last_index].needle);
1238                 } else
1239                         break;
1240         }
1241
1242         /* colorize this line */
1243         if (head.next) {
1244                 const gchar *normal_text = mybuf;
1245
1246                 /* insert URIs */
1247                 for (last = head.next; last != NULL;
1248                      normal_text = last->ep, last = last->next) {
1249                         ClickableText *uri;
1250                         uri = g_new0(ClickableText, 1);
1251                         if (last->bp - normal_text > 0)
1252                                 gtk_text_buffer_insert_with_tags_by_name
1253                                         (buffer, &iter,
1254                                          normal_text,
1255                                          last->bp - normal_text,
1256                                          fg_tag, NULL);
1257                         uri->uri = parser[last->pti].build_uri(last->bp,
1258                                                                last->ep);
1259                         uri->start = gtk_text_iter_get_offset(&iter);
1260                         gtk_text_buffer_insert_with_tags_by_name
1261                                 (buffer, &iter, last->bp, last->ep - last->bp,
1262                                  uri_tag, fg_tag, NULL);
1263                         uri->end = gtk_text_iter_get_offset(&iter);
1264                         uri->filename = NULL;
1265                         textview->uri_list =
1266                                 g_slist_prepend(textview->uri_list, uri);
1267                 }
1268
1269                 if (*normal_text)
1270                         gtk_text_buffer_insert_with_tags_by_name
1271                                 (buffer, &iter, normal_text, -1, fg_tag, NULL);
1272         } else {
1273                 gtk_text_buffer_insert_with_tags_by_name
1274                         (buffer, &iter, mybuf, -1, fg_tag, NULL);
1275         }
1276         g_free(mybuf);
1277 }
1278
1279 /* textview_make_clickable_parts() - colorizes clickable parts */
1280 static void textview_make_clickable_parts_later(TextView *textview,
1281                                           gint start, gint end)
1282 {
1283         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1284         GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
1285         GtkTextIter start_iter, end_iter;
1286         gchar *mybuf;
1287         gint offset = 0;
1288         /* parse table - in order of priority */
1289         struct table {
1290                 const gchar *needle; /* token */
1291
1292                 /* token search function */
1293                 gchar    *(*search)     (const gchar *haystack,
1294                                          const gchar *needle);
1295                 /* part parsing function */
1296                 gboolean  (*parse)      (const gchar *start,
1297                                          const gchar *scanpos,
1298                                          const gchar **bp_,
1299                                          const gchar **ep_,
1300                                          gboolean hdr);
1301                 /* part to URI function */
1302                 gchar    *(*build_uri)  (const gchar *bp,
1303                                          const gchar *ep);
1304         };
1305
1306         static struct table parser[] = {
1307                 {"http://",  strcasestr, get_uri_part,   make_uri_string},
1308                 {"https://", strcasestr, get_uri_part,   make_uri_string},
1309                 {"ftp://",   strcasestr, get_uri_part,   make_uri_string},
1310                 {"sftp://",  strcasestr, get_uri_part,   make_uri_string},
1311                 {"www.",     strcasestr, get_uri_part,   make_http_string},
1312                 {"mailto:",  strcasestr, get_uri_part,   make_uri_string},
1313                 {"@",        strcasestr, get_email_part, make_email_string}
1314         };
1315         const gint PARSE_ELEMS = sizeof parser / sizeof parser[0];
1316
1317         gint  n;
1318         const gchar *walk, *bp, *ep;
1319
1320         struct txtpos {
1321                 const gchar     *bp, *ep;       /* text position */
1322                 gint             pti;           /* index in parse table */
1323                 struct txtpos   *next;          /* next */
1324         } head = {NULL, NULL, 0,  NULL}, *last = &head;
1325
1326         gtk_text_buffer_get_iter_at_offset(buffer, &start_iter, start);
1327         gtk_text_buffer_get_iter_at_offset(buffer, &end_iter, end);
1328         mybuf = gtk_text_buffer_get_text(buffer, &start_iter, &end_iter, FALSE);
1329         offset = gtk_text_iter_get_offset(&start_iter);
1330
1331         /* parse for clickable parts, and build a list of begin and end positions  */
1332         for (walk = mybuf, n = 0;;) {
1333                 gint last_index = PARSE_ELEMS;
1334                 gchar *scanpos = NULL;
1335
1336                 /* FIXME: this looks phony. scanning for anything in the parse table */
1337                 for (n = 0; n < PARSE_ELEMS; n++) {
1338                         gchar *tmp;
1339
1340                         tmp = parser[n].search(walk, parser[n].needle);
1341                         if (tmp) {
1342                                 if (scanpos == NULL || tmp < scanpos) {
1343                                         scanpos = tmp;
1344                                         last_index = n;
1345                                 }
1346                         }                                       
1347                 }
1348
1349                 if (scanpos) {
1350                         /* check if URI can be parsed */
1351                         if (parser[last_index].parse(walk, scanpos, &bp, &ep, FALSE)
1352                             && (size_t) (ep - bp - 1) > strlen(parser[last_index].needle)) {
1353                                         ADD_TXT_POS_LATER(bp, ep, last_index);
1354                                         walk = ep;
1355                         } else
1356                                 walk = scanpos +
1357                                         strlen(parser[last_index].needle);
1358                 } else
1359                         break;
1360         }
1361
1362         /* colorize this line */
1363         if (head.next) {
1364                 /* insert URIs */
1365                 for (last = head.next; last != NULL; last = last->next) {
1366                         ClickableText *uri;
1367                         gint start_offset, end_offset;
1368                         gchar *tmp_str;
1369                         gchar old_char;
1370                         uri = g_new0(ClickableText, 1);
1371                         uri->uri = parser[last->pti].build_uri(last->bp,
1372                                                                last->ep);
1373                         
1374                         tmp_str = mybuf;
1375                         old_char = tmp_str[last->ep - mybuf];
1376                         tmp_str[last->ep - mybuf] = '\0';                                      
1377                         end_offset = g_utf8_strlen(tmp_str, -1);
1378                         tmp_str[last->ep - mybuf] = old_char;
1379                         
1380                         old_char = tmp_str[last->bp - mybuf];
1381                         tmp_str[last->bp - mybuf] = '\0';                                      
1382                         start_offset = g_utf8_strlen(tmp_str, -1);
1383                         tmp_str[last->bp - mybuf] = old_char;
1384                         
1385                         gtk_text_buffer_get_iter_at_offset(buffer, &start_iter, start_offset + offset);
1386                         gtk_text_buffer_get_iter_at_offset(buffer, &end_iter, end_offset + offset);
1387                         
1388                         uri->start = gtk_text_iter_get_offset(&start_iter);
1389                         
1390                         gtk_text_buffer_apply_tag_by_name(buffer, "link", &start_iter, &end_iter);
1391
1392                         uri->end = gtk_text_iter_get_offset(&end_iter);
1393                         uri->filename = NULL;
1394                         textview->uri_list =
1395                                 g_slist_prepend(textview->uri_list, uri);
1396                 }
1397         } 
1398
1399         g_free(mybuf);
1400 }
1401
1402 #undef ADD_TXT_POS
1403
1404 static void textview_write_line(TextView *textview, const gchar *str,
1405                                 CodeConverter *conv, gboolean do_quote_folding)
1406 {
1407         GtkTextView *text;
1408         GtkTextBuffer *buffer;
1409         GtkTextIter iter;
1410         gchar buf[BUFFSIZE];
1411         gchar *fg_color;
1412         gint quotelevel = -1, real_quotelevel = -1;
1413         gchar quote_tag_str[10];
1414
1415         text = GTK_TEXT_VIEW(textview->text);
1416         buffer = gtk_text_view_get_buffer(text);
1417         gtk_text_buffer_get_end_iter(buffer, &iter);
1418
1419         if (!conv)
1420                 strncpy2(buf, str, sizeof(buf));
1421         else if (conv_convert(conv, buf, sizeof(buf), str) < 0)
1422                 conv_localetodisp(buf, sizeof(buf), str);
1423                 
1424         strcrchomp(buf);
1425         fg_color = NULL;
1426
1427         /* change color of quotation
1428            >, foo>, _> ... ok, <foo>, foo bar>, foo-> ... ng
1429            Up to 3 levels of quotations are detected, and each
1430            level is colored using a different color. */
1431         if (prefs_common.enable_color 
1432             && line_has_quote_char(buf, prefs_common.quote_chars)) {
1433                 real_quotelevel = get_quote_level(buf, prefs_common.quote_chars);
1434                 quotelevel = real_quotelevel;
1435                 /* set up the correct foreground color */
1436                 if (quotelevel > 2) {
1437                         /* recycle colors */
1438                         if (prefs_common.recycle_quote_colors)
1439                                 quotelevel %= 3;
1440                         else
1441                                 quotelevel = 2;
1442                 }
1443         }
1444
1445         if (quotelevel == -1)
1446                 fg_color = NULL;
1447         else {
1448                 g_snprintf(quote_tag_str, sizeof(quote_tag_str),
1449                            "quote%d", quotelevel);
1450                 fg_color = quote_tag_str;
1451         }
1452
1453         if (prefs_common.enable_color && 
1454             (strcmp(buf,"-- \n") == 0 || strcmp(buf, "- -- \n") == 0 || textview->is_in_signature)) {
1455                 fg_color = "signature";
1456                 textview->is_in_signature = TRUE;
1457         }
1458
1459         if (real_quotelevel > -1 && do_quote_folding) {
1460                 if (!g_utf8_validate(buf, -1, NULL)) {
1461                         gchar *utf8buf = NULL;
1462                         utf8buf = g_malloc(BUFFSIZE);
1463                         conv_localetodisp(utf8buf, BUFFSIZE, buf);
1464                         strncpy2(buf, utf8buf, BUFFSIZE-1);
1465                         g_free(utf8buf);
1466                 }
1467 do_quote:
1468                 if ( textview->prev_quote_level != real_quotelevel ) {
1469                         ClickableText *uri;
1470                         uri = g_new0(ClickableText, 1);
1471                         uri->uri = g_strdup("");
1472                         uri->data = g_strdup(buf);
1473                         uri->start = gtk_text_iter_get_offset(&iter);
1474                         uri->is_quote = TRUE;
1475                         uri->quote_level = real_quotelevel;
1476                         uri->fg_color = g_strdup(fg_color);
1477
1478                         gtk_text_buffer_insert_with_tags_by_name
1479                                         (buffer, &iter, " [...]", -1,
1480                                          "qlink", fg_color, NULL);
1481                         uri->end = gtk_text_iter_get_offset(&iter);
1482                         gtk_text_buffer_insert(buffer, &iter, "  \n", -1);
1483                         
1484                         uri->filename = NULL;
1485                         textview->uri_list =
1486                                 g_slist_prepend(textview->uri_list, uri);
1487                 
1488                         textview->prev_quote_level = real_quotelevel;
1489                 } else {
1490                         GSList *last = textview->uri_list;
1491                         ClickableText *lasturi = NULL;
1492                         gint e_len = 0, n_len = 0;
1493                         
1494                         if (textview->uri_list) {
1495                                 lasturi = (ClickableText *)last->data;
1496                         } else {
1497                                 printf("oops (%d %d)\n",
1498                                         real_quotelevel, textview->prev_quote_level);
1499                         }               
1500                         if (lasturi->is_quote == FALSE) {
1501                                 textview->prev_quote_level = -1;
1502                                 goto do_quote;
1503                         }
1504                         e_len = lasturi->data ? strlen(lasturi->data):0;
1505                         n_len = strlen(buf);
1506                         lasturi->data = g_realloc((gchar *)lasturi->data, e_len + n_len + 1);
1507                         strcpy((gchar *)lasturi->data + e_len, buf);
1508                         *((gchar *)lasturi->data + e_len + n_len) = '\0';
1509                 }
1510         } else {
1511                 textview_make_clickable_parts(textview, fg_color, "link", buf, FALSE);
1512                 textview->prev_quote_level = -1;
1513         }
1514 }
1515
1516 void textview_write_link(TextView *textview, const gchar *str,
1517                          const gchar *uri, CodeConverter *conv)
1518 {
1519         GdkColor *link_color = NULL;
1520         GtkTextView *text;
1521         GtkTextBuffer *buffer;
1522         GtkTextIter iter;
1523         gchar buf[BUFFSIZE];
1524         gchar *bufp;
1525         ClickableText *r_uri;
1526
1527         if (!str || *str == '\0')
1528                 return;
1529         if (!uri)
1530                 return;
1531
1532         while (uri && *uri && g_ascii_isspace(*uri))
1533                 uri++;
1534                 
1535         text = GTK_TEXT_VIEW(textview->text);
1536         buffer = gtk_text_view_get_buffer(text);
1537         gtk_text_buffer_get_end_iter(buffer, &iter);
1538
1539         if (!conv)
1540                 strncpy2(buf, str, sizeof(buf));
1541         else if (conv_convert(conv, buf, sizeof(buf), str) < 0)
1542                 conv_utf8todisp(buf, sizeof(buf), str);
1543
1544         if (g_utf8_validate(buf, -1, NULL) == FALSE)
1545                 return;
1546
1547         strcrchomp(buf);
1548
1549         gtk_text_buffer_get_end_iter(buffer, &iter);
1550         for (bufp = buf; *bufp != '\0'; bufp = g_utf8_next_char(bufp)) {
1551                 gunichar ch;
1552
1553                 ch = g_utf8_get_char(bufp);
1554                 if (!g_unichar_isspace(ch))
1555                         break;
1556         }
1557         if (bufp > buf)
1558                 gtk_text_buffer_insert(buffer, &iter, buf, bufp - buf);
1559
1560         if (prefs_common.enable_color) {
1561                 link_color = &uri_color;
1562         }
1563         r_uri = g_new0(ClickableText, 1);
1564         r_uri->uri = g_strdup(uri);
1565         r_uri->start = gtk_text_iter_get_offset(&iter);
1566         gtk_text_buffer_insert_with_tags_by_name
1567                 (buffer, &iter, bufp, -1, "link", NULL);
1568         r_uri->end = gtk_text_iter_get_offset(&iter);
1569         r_uri->filename = NULL;
1570         textview->uri_list = g_slist_prepend(textview->uri_list, r_uri);
1571 }
1572
1573 static void textview_set_cursor(GdkWindow *window, GdkCursor *cursor)
1574 {
1575         if (GDK_IS_WINDOW(window))
1576                 gdk_window_set_cursor(window, cursor);
1577 }
1578 void textview_clear(TextView *textview)
1579 {
1580         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1581         GtkTextBuffer *buffer;
1582         GdkWindow *window = gtk_text_view_get_window(text,
1583                                 GTK_TEXT_WINDOW_TEXT);
1584
1585         buffer = gtk_text_view_get_buffer(text);
1586         gtk_text_buffer_set_text(buffer, "", -1);
1587
1588         TEXTVIEW_STATUSBAR_POP(textview);
1589         textview_uri_list_remove_all(textview->uri_list);
1590         textview->uri_list = NULL;
1591         textview->uri_hover = NULL;
1592         textview->prev_quote_level = -1;
1593
1594         textview->body_pos = 0;
1595         if (textview->image) 
1596                 gtk_widget_destroy(textview->image);
1597         textview->image = NULL;
1598
1599         if (textview->messageview->mainwin->cursor_count == 0) {
1600                 textview_set_cursor(window, text_cursor);
1601         } else {
1602                 textview_set_cursor(window, watch_cursor);
1603         }
1604 }
1605
1606 void textview_destroy(TextView *textview)
1607 {
1608         GtkTextBuffer *buffer;
1609         GtkClipboard *clipboard;
1610
1611         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview->text));
1612         clipboard = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
1613         gtk_text_buffer_remove_selection_clipboard(buffer, clipboard);
1614
1615         textview_uri_list_remove_all(textview->uri_list);
1616         textview->uri_list = NULL;
1617         textview->prev_quote_level = -1;
1618
1619         g_free(textview);
1620 }
1621
1622 void textview_set_all_headers(TextView *textview, gboolean all_headers)
1623 {
1624         textview->show_all_headers = all_headers;
1625 }
1626
1627 #define CHANGE_TAG_FONT(tagname, font) { \
1628         tag = gtk_text_tag_table_lookup(tags, tagname); \
1629         if (tag) \
1630                 g_object_set(G_OBJECT(tag), "font-desc", font, NULL); \
1631 }
1632
1633 void textview_set_font(TextView *textview, const gchar *codeset)
1634 {
1635         GtkTextTag *tag;
1636         GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview->text));
1637         GtkTextTagTable *tags = gtk_text_buffer_get_tag_table(buffer);
1638         
1639         if (NORMAL_FONT) {
1640                 PangoFontDescription *font_desc, *bold_font_desc;
1641                 font_desc = pango_font_description_from_string
1642                                                 (NORMAL_FONT);
1643                 bold_font_desc = pango_font_description_from_string
1644                                                 (NORMAL_FONT);
1645                 if (font_desc) {
1646                         gtk_widget_modify_font(textview->text, font_desc);
1647                         CHANGE_TAG_FONT("header", font_desc);
1648                         CHANGE_TAG_FONT("hlink", font_desc);
1649                         pango_font_description_free(font_desc);
1650                 }
1651                 if (bold_font_desc) {
1652                         pango_font_description_set_weight
1653                                 (bold_font_desc, PANGO_WEIGHT_BOLD);
1654                         CHANGE_TAG_FONT("header_title", bold_font_desc);
1655                         pango_font_description_free(bold_font_desc);
1656                 }
1657         }
1658
1659         if (prefs_common.textfont) {
1660                 PangoFontDescription *font_desc;
1661
1662                 font_desc = pango_font_description_from_string
1663                                                 (prefs_common.textfont);
1664                 if (font_desc) {
1665                         gtk_widget_modify_font(textview->text, font_desc);
1666                         pango_font_description_free(font_desc);
1667                 }
1668         }
1669         gtk_text_view_set_pixels_above_lines(GTK_TEXT_VIEW(textview->text),
1670                                              prefs_common.line_space / 2);
1671         gtk_text_view_set_pixels_below_lines(GTK_TEXT_VIEW(textview->text),
1672                                              prefs_common.line_space / 2);
1673 }
1674
1675 void textview_set_text(TextView *textview, const gchar *text)
1676 {
1677         GtkTextView *view;
1678         GtkTextBuffer *buffer;
1679
1680         g_return_if_fail(textview != NULL);
1681         g_return_if_fail(text != NULL);
1682
1683         textview_clear(textview);
1684
1685         view = GTK_TEXT_VIEW(textview->text);
1686         buffer = gtk_text_view_get_buffer(view);
1687         gtk_text_buffer_set_text(buffer, text, strlen(text));
1688 }
1689
1690 enum
1691 {
1692         H_DATE          = 0,
1693         H_FROM          = 1,
1694         H_TO            = 2,
1695         H_NEWSGROUPS    = 3,
1696         H_SUBJECT       = 4,
1697         H_CC            = 5,
1698         H_REPLY_TO      = 6,
1699         H_FOLLOWUP_TO   = 7,
1700         H_X_MAILER      = 8,
1701         H_X_NEWSREADER  = 9,
1702         H_USER_AGENT    = 10,
1703         H_ORGANIZATION  = 11,
1704 };
1705
1706 void textview_set_position(TextView *textview, gint pos)
1707 {
1708         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1709
1710         gtkut_text_view_set_position(text, pos);
1711 }
1712
1713 static gboolean header_is_internal(Header *header)
1714 {
1715         const gchar *internal_hdrs[] = 
1716                 {"AF:", "NF:", "PS:", "SRH:", "SFN:", "DSR:", "MID:", 
1717                  "CFG:", "PT:", "S:", "RQ:", "SSV:", "NSV:", "SSH:", 
1718                  "R:", "MAID:", "SCF:", "RMID:", "FMID:", "NAID:", 
1719                  "X-Claws-Account-Id:", "X-Claws-Sign:", "X-Claws-Encrypt:", 
1720                  "X-Claws-Privacy-System:", "X-Claws-End-Special-Headers:",
1721                  "X-Sylpheed-Account-Id:", "X-Sylpheed-Sign:", "X-Sylpheed-Encrypt:", 
1722                  "X-Sylpheed-Privacy-System:", "X-Sylpheed-End-Special-Headers:",
1723                  NULL};
1724         int i;
1725         
1726         for (i = 0; internal_hdrs[i]; i++) {
1727                 if (!strcmp(header->name, internal_hdrs[i]))
1728                         return TRUE;
1729         }
1730         return FALSE;
1731 }
1732
1733 static GPtrArray *textview_scan_header(TextView *textview, FILE *fp)
1734 {
1735         gchar buf[BUFFSIZE];
1736         GPtrArray *headers, *sorted_headers;
1737         GSList *disphdr_list;
1738         Header *header;
1739         gint i;
1740
1741         g_return_val_if_fail(fp != NULL, NULL);
1742
1743         if (textview->show_all_headers) {
1744                 headers = procheader_get_header_array_asis(fp);
1745                 sorted_headers = g_ptr_array_new();
1746                 for (i = 0; i < headers->len; i++) {
1747                         header = g_ptr_array_index(headers, i);
1748                         if (!header_is_internal(header))
1749                                 g_ptr_array_add(sorted_headers, header);
1750                         else
1751                                 procheader_header_free(header);
1752                 }
1753                 g_ptr_array_free(headers, TRUE);
1754                 return sorted_headers;
1755         }
1756
1757         if (!prefs_common.display_header) {
1758                 while (fgets(buf, sizeof(buf), fp) != NULL)
1759                         if (buf[0] == '\r' || buf[0] == '\n') break;
1760                 return NULL;
1761         }
1762
1763         headers = procheader_get_header_array_asis(fp);
1764
1765         sorted_headers = g_ptr_array_new();
1766
1767         for (disphdr_list = prefs_common.disphdr_list; disphdr_list != NULL;
1768              disphdr_list = disphdr_list->next) {
1769                 DisplayHeaderProp *dp =
1770                         (DisplayHeaderProp *)disphdr_list->data;
1771
1772                 for (i = 0; i < headers->len; i++) {
1773                         header = g_ptr_array_index(headers, i);
1774
1775                         if (procheader_headername_equal(header->name,
1776                                                         dp->name)) {
1777                                 if (dp->hidden)
1778                                         procheader_header_free(header);
1779                                 else
1780                                         g_ptr_array_add(sorted_headers, header);
1781
1782                                 g_ptr_array_remove_index(headers, i);
1783                                 i--;
1784                         }
1785                 }
1786         }
1787
1788         if (prefs_common.show_other_header) {
1789                 for (i = 0; i < headers->len; i++) {
1790                         header = g_ptr_array_index(headers, i);
1791                         if (!header_is_internal(header)) {
1792                                 g_ptr_array_add(sorted_headers, header);
1793                         } else {
1794                                 procheader_header_free(header);
1795                         }
1796                 }
1797                 g_ptr_array_free(headers, TRUE);
1798         } else
1799                 procheader_header_array_destroy(headers);
1800
1801
1802         return sorted_headers;
1803 }
1804
1805 static void textview_show_face(TextView *textview)
1806 {
1807         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1808         MsgInfo *msginfo = textview->messageview->msginfo;
1809         int x = 0;
1810         
1811         if (prefs_common.display_header_pane
1812         ||  !prefs_common.display_xface)
1813                 goto bail;
1814         
1815         if (!msginfo->extradata || !msginfo->extradata->face) {
1816                 goto bail;
1817         }
1818
1819         if (textview->image) 
1820                 gtk_widget_destroy(textview->image);
1821         
1822         textview->image = face_get_from_header(msginfo->extradata->face);
1823         g_return_if_fail(textview->image != NULL);
1824
1825         gtk_widget_show(textview->image);
1826         
1827         x = textview->text->allocation.width - WIDTH -5;
1828
1829         gtk_text_view_add_child_in_window(text, textview->image, 
1830                 GTK_TEXT_WINDOW_TEXT, x, 5);
1831
1832         gtk_widget_show_all(textview->text);
1833         
1834
1835         return;
1836 bail:
1837         if (textview->image) 
1838                 gtk_widget_destroy(textview->image);
1839         textview->image = NULL; 
1840 }
1841
1842 void textview_show_icon(TextView *textview, const gchar *stock_id)
1843 {
1844         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1845         int x = 0;
1846         
1847         if (textview->image) 
1848                 gtk_widget_destroy(textview->image);
1849         
1850         textview->image = gtk_image_new_from_stock(stock_id, GTK_ICON_SIZE_DIALOG);
1851         g_return_if_fail(textview->image != NULL);
1852
1853         gtk_widget_show(textview->image);
1854         
1855         x = textview->text->allocation.width - WIDTH -5;
1856
1857         gtk_text_view_add_child_in_window(text, textview->image, 
1858                 GTK_TEXT_WINDOW_TEXT, x, 5);
1859
1860         gtk_widget_show_all(textview->text);
1861         
1862
1863         return;
1864 }
1865
1866 #if HAVE_LIBCOMPFACE
1867 static void textview_show_xface(TextView *textview)
1868 {
1869         MsgInfo *msginfo = textview->messageview->msginfo;
1870         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1871         int x = 0;
1872         GdkWindow *window = NULL;
1873         
1874         if (prefs_common.display_header_pane
1875         ||  !prefs_common.display_xface)
1876                 goto bail;
1877         
1878         if (!msginfo || !msginfo->extradata)
1879                 goto bail;
1880
1881         if (msginfo->extradata->face)
1882                 return;
1883         
1884         if (!msginfo->extradata->xface || strlen(msginfo->extradata->xface) < 5) {
1885                 goto bail;
1886         }
1887
1888         if (textview->image) 
1889                 gtk_widget_destroy(textview->image);
1890
1891         window = mainwindow_get_mainwindow() ?
1892                         mainwindow_get_mainwindow()->window->window :
1893                         textview->text->window;
1894         textview->image = xface_get_from_header(msginfo->extradata->xface,
1895                                 &textview->text->style->white,
1896                                 window);
1897         g_return_if_fail(textview->image != NULL);
1898
1899         gtk_widget_show(textview->image);
1900         
1901         x = textview->text->allocation.width - WIDTH -5;
1902
1903         gtk_text_view_add_child_in_window(text, textview->image, 
1904                 GTK_TEXT_WINDOW_TEXT, x, 5);
1905
1906         gtk_widget_show_all(textview->text);
1907         
1908         return;
1909 bail:
1910         if (textview->image) 
1911                 gtk_widget_destroy(textview->image);
1912         textview->image = NULL;
1913         
1914 }
1915 #endif
1916
1917 static void textview_show_tags(TextView *textview)
1918 {
1919         MsgInfo *msginfo = textview->messageview->msginfo;
1920         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1921         GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
1922         GtkTextIter iter;
1923         ClickableText *uri;
1924         GSList *cur;
1925         gboolean found_tag = FALSE;
1926         
1927         if (!msginfo->tags)
1928                 return;
1929         
1930         for (cur = msginfo->tags; cur; cur = cur->next) {
1931                 if (tags_get_tag(GPOINTER_TO_INT(cur->data)) != NULL) {
1932                         found_tag = TRUE;
1933                         break;
1934                 }
1935         }
1936         if (!found_tag) 
1937                 return;
1938
1939         gtk_text_buffer_get_end_iter (buffer, &iter);
1940         gtk_text_buffer_insert_with_tags_by_name(buffer,
1941                 &iter, _("Tags: "), -1,
1942                 "header_title", "header", "tags", NULL);
1943
1944         for (cur = msginfo->tags; cur; cur = cur->next) {
1945                 uri = g_new0(ClickableText, 1);
1946                 uri->uri = g_strdup("");
1947                 uri->start = gtk_text_iter_get_offset(&iter);
1948                 gtk_text_buffer_insert_with_tags_by_name(buffer, &iter, 
1949                         tags_get_tag(GPOINTER_TO_INT(cur->data)), -1,
1950                         "link", "header", "tags", NULL);
1951                 uri->end = gtk_text_iter_get_offset(&iter);
1952                 uri->filename = g_strdup_printf("sc://search_tags:%s", tags_get_tag(GPOINTER_TO_INT(cur->data)));
1953                 uri->data = NULL;
1954                 textview->uri_list =
1955                         g_slist_prepend(textview->uri_list, uri);
1956                 if (cur->next)
1957                         gtk_text_buffer_insert_with_tags_by_name(buffer, &iter, ", ", 2,
1958                                 "header", "tags", NULL);
1959                 else
1960                         gtk_text_buffer_insert_with_tags_by_name(buffer, &iter, " ", 1,
1961                                 "header", "tags", NULL);
1962         }
1963
1964         gtk_text_buffer_insert_with_tags_by_name(buffer, &iter, "\n", 1,
1965                 "header", "tags", NULL);
1966 }
1967
1968 static void textview_show_header(TextView *textview, GPtrArray *headers)
1969 {
1970         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
1971         GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
1972         GtkTextIter iter;
1973         Header *header;
1974         gint i;
1975
1976         g_return_if_fail(headers != NULL);
1977
1978         textview_show_tags(textview);
1979
1980         for (i = 0; i < headers->len; i++) {
1981                 header = g_ptr_array_index(headers, i);
1982                 g_return_if_fail(header->name != NULL);
1983
1984                 gtk_text_buffer_get_end_iter (buffer, &iter);
1985                 if(prefs_common.trans_hdr == TRUE) {
1986                         gchar *hdr = g_strndup(header->name, strlen(header->name) - 1);
1987                         gchar *trans_hdr = gettext(hdr);
1988                         gtk_text_buffer_insert_with_tags_by_name(buffer,
1989                                 &iter, trans_hdr, -1,
1990                                 "header_title", "header", NULL);
1991                         gtk_text_buffer_insert_with_tags_by_name(buffer,
1992                                 &iter, ":", 1, "header_title", "header", NULL);
1993                         g_free(hdr);
1994                 } else {
1995                         gtk_text_buffer_insert_with_tags_by_name(buffer,
1996                                 &iter, header->name,
1997                                 -1, "header_title", "header", NULL);
1998                 }
1999                 if (header->name[strlen(header->name) - 1] != ' ')
2000                 gtk_text_buffer_insert_with_tags_by_name
2001                                 (buffer, &iter, " ", 1,
2002                                  "header_title", "header", NULL);
2003
2004                 if (procheader_headername_equal(header->name, "Subject") ||
2005                     procheader_headername_equal(header->name, "From")    ||
2006                     procheader_headername_equal(header->name, "To")      ||
2007                     procheader_headername_equal(header->name, "Cc"))
2008                         unfold_line(header->body);
2009
2010                 if ((procheader_headername_equal(header->name, "X-Mailer") ||
2011                      procheader_headername_equal(header->name,
2012                                                  "X-Newsreader")) &&
2013                     (strstr(header->body, "Claws Mail") != NULL ||
2014                      strstr(header->body, "Sylpheed-Claws") != NULL)) {
2015                         gtk_text_buffer_get_end_iter (buffer, &iter);
2016                         gtk_text_buffer_insert_with_tags_by_name
2017                                 (buffer, &iter, header->body, -1,
2018                                  "header", "emphasis", NULL);
2019                 } else {
2020                         gboolean hdr = 
2021                           procheader_headername_equal(header->name, "From") ||
2022                           procheader_headername_equal(header->name, "To") ||
2023                           procheader_headername_equal(header->name, "Cc") ||
2024                           procheader_headername_equal(header->name, "Bcc") ||
2025                           procheader_headername_equal(header->name, "Reply-To") ||
2026                           procheader_headername_equal(header->name, "Sender");
2027                         textview_make_clickable_parts(textview, "header", 
2028                                                       "hlink", header->body, 
2029                                                       hdr);
2030                 }
2031                 gtk_text_buffer_get_end_iter (buffer, &iter);
2032                 gtk_text_buffer_insert_with_tags_by_name(buffer, &iter, "\n", 1,
2033                                                          "header", NULL);
2034         }
2035         
2036         textview_show_face(textview);
2037 #if HAVE_LIBCOMPFACE
2038         textview_show_xface(textview);
2039 #endif
2040 }
2041
2042 gboolean textview_search_string(TextView *textview, const gchar *str,
2043                                 gboolean case_sens)
2044 {
2045         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
2046
2047         return gtkut_text_view_search_string(text, str, case_sens);
2048 }
2049
2050 gboolean textview_search_string_backward(TextView *textview, const gchar *str,
2051                                          gboolean case_sens)
2052 {
2053         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
2054
2055         return gtkut_text_view_search_string_backward(text, str, case_sens);
2056 }
2057
2058 void textview_scroll_one_line(TextView *textview, gboolean up)
2059 {
2060         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
2061         GtkAdjustment *vadj = text->vadjustment;
2062
2063         gtkutils_scroll_one_line(GTK_WIDGET(text), vadj, up);
2064 }
2065
2066 gboolean textview_scroll_page(TextView *textview, gboolean up)
2067 {
2068         GtkTextView *text = GTK_TEXT_VIEW(textview->text);
2069         GtkAdjustment *vadj = text->vadjustment;
2070
2071         return gtkutils_scroll_page(GTK_WIDGET(text), vadj, up);
2072 }
2073
2074 #define KEY_PRESS_EVENT_STOP() \
2075         g_signal_stop_emission_by_name(G_OBJECT(widget), \
2076                                        "key_press_event");
2077
2078 static gint textview_key_pressed(GtkWidget *widget, GdkEventKey *event,
2079                                  TextView *textview)
2080 {
2081         SummaryView *summaryview = NULL;
2082         MessageView *messageview = textview->messageview;
2083
2084         if (!event) return FALSE;
2085         if (messageview->mainwin)
2086                 summaryview = messageview->mainwin->summaryview;
2087
2088         switch (event->keyval) {
2089         case GDK_Tab:
2090         case GDK_Home:
2091         case GDK_Left:
2092         case GDK_Up:
2093         case GDK_Right:
2094         case GDK_Down:
2095         case GDK_Page_Up:
2096         case GDK_Page_Down:
2097         case GDK_End:
2098         case GDK_Control_L:
2099         case GDK_Control_R:
2100                 return FALSE;
2101         case GDK_space:
2102                 if (summaryview)
2103                         summary_pass_key_press_event(summaryview, event);
2104                 else
2105                         mimeview_scroll_page
2106                                 (messageview->mimeview,
2107                                  (event->state &
2108                                   (GDK_SHIFT_MASK|GDK_MOD1_MASK)) != 0);
2109                 break;
2110         case GDK_BackSpace:
2111                 mimeview_scroll_page(messageview->mimeview, TRUE);
2112                 break;
2113         case GDK_Return:
2114         case GDK_KP_Enter:
2115                 mimeview_scroll_one_line
2116                         (messageview->mimeview, (event->state &
2117                                     (GDK_SHIFT_MASK|GDK_MOD1_MASK)) != 0);
2118                 break;
2119         case GDK_Delete:
2120                 if (summaryview)
2121                         summary_pass_key_press_event(summaryview, event);
2122                 break;
2123         case GDK_y:
2124         case GDK_t:
2125         case GDK_l:
2126         case GDK_o:
2127         case GDK_c:
2128         case GDK_a:
2129                 if ((event->state & (GDK_MOD1_MASK|GDK_CONTROL_MASK)) == 0) {
2130                         KEY_PRESS_EVENT_STOP();
2131                         mimeview_pass_key_press_event(messageview->mimeview,
2132                                                       event);
2133                         break;
2134                 }
2135                 /* possible fall through */
2136         default:
2137                 if (summaryview &&
2138                     event->window != messageview->mainwin->window->window) {
2139                         GdkEventKey tmpev = *event;
2140
2141                         tmpev.window = messageview->mainwin->window->window;
2142                         KEY_PRESS_EVENT_STOP();
2143                         gtk_widget_event(messageview->mainwin->window,
2144                                          (GdkEvent *)&tmpev);
2145                 }
2146                 break;
2147         }
2148
2149         return TRUE;
2150 }
2151
2152 static gboolean textview_motion_notify(GtkWidget *widget,
2153                                        GdkEventMotion *event,
2154                                        TextView *textview)
2155 {
2156         if (textview->loading)
2157                 return FALSE;
2158         textview_uri_update(textview, event->x, event->y);
2159         gdk_window_get_pointer(widget->window, NULL, NULL, NULL);
2160
2161         return FALSE;
2162 }
2163
2164 static gboolean textview_leave_notify(GtkWidget *widget,
2165                                       GdkEventCrossing *event,
2166                                       TextView *textview)
2167 {
2168         if (textview->loading)
2169                 return FALSE;
2170         textview_uri_update(textview, -1, -1);
2171
2172         return FALSE;
2173 }
2174
2175 static gboolean textview_visibility_notify(GtkWidget *widget,
2176                                            GdkEventVisibility *event,
2177                                            TextView *textview)
2178 {
2179         gint wx, wy;
2180         GdkWindow *window;
2181
2182         if (textview->loading)
2183                 return FALSE;
2184
2185         window = gtk_text_view_get_window(GTK_TEXT_VIEW(widget),
2186                                           GTK_TEXT_WINDOW_TEXT);
2187
2188         /* check if occurred for the text window part */
2189         if (window != event->window)
2190                 return FALSE;
2191         
2192         gdk_window_get_pointer(widget->window, &wx, &wy, NULL);
2193         textview_uri_update(textview, wx, wy);
2194
2195         return FALSE;
2196 }
2197
2198 void textview_cursor_wait(TextView *textview)
2199 {
2200         GdkWindow *window = gtk_text_view_get_window(
2201                         GTK_TEXT_VIEW(textview->text),
2202                         GTK_TEXT_WINDOW_TEXT);
2203         textview_set_cursor(window, watch_cursor);
2204 }
2205
2206 void textview_cursor_normal(TextView *textview)
2207 {
2208         GdkWindow *window = gtk_text_view_get_window(
2209                         GTK_TEXT_VIEW(textview->text),
2210                         GTK_TEXT_WINDOW_TEXT);
2211         textview_set_cursor(window, text_cursor);
2212 }
2213
2214 static void textview_uri_update(TextView *textview, gint x, gint y)
2215 {
2216         GtkTextBuffer *buffer;
2217         GtkTextIter start_iter, end_iter;
2218         ClickableText *uri = NULL;
2219         
2220         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview->text));
2221
2222         if (x != -1 && y != -1) {
2223                 gint bx, by;
2224                 GtkTextIter iter;
2225                 GSList *tags;
2226                 GSList *cur;
2227                 
2228                 gtk_text_view_window_to_buffer_coords(GTK_TEXT_VIEW(textview->text), 
2229                                                       GTK_TEXT_WINDOW_WIDGET,
2230                                                       x, y, &bx, &by);
2231                 gtk_text_view_get_iter_at_location(GTK_TEXT_VIEW(textview->text),
2232                                                    &iter, bx, by);
2233
2234                 tags = gtk_text_iter_get_tags(&iter);
2235                 for (cur = tags; cur != NULL; cur = cur->next) {
2236                         GtkTextTag *tag = cur->data;
2237                         char *name;
2238
2239                         g_object_get(G_OBJECT(tag), "name", &name, NULL);
2240
2241                         if ((!strcmp(name, "link") || !strcmp(name, "hlink"))
2242                             && textview_get_uri_range(textview, &iter, tag,
2243                                                       &start_iter, &end_iter)) {
2244
2245                                 uri = textview_get_uri_from_range(textview,
2246                                                                   &iter, tag,
2247                                                                   &start_iter,
2248                                                                   &end_iter);
2249                         }
2250                         g_free(name);
2251                         if (uri)
2252                                 break;
2253                 }
2254                 g_slist_free(tags);
2255         }
2256         
2257         if (uri != textview->uri_hover) {
2258                 GdkWindow *window;
2259
2260                 if (textview->uri_hover)
2261                         gtk_text_buffer_remove_tag_by_name(buffer,
2262                                                            "link-hover",
2263                                                            &textview->uri_hover_start_iter,
2264                                                            &textview->uri_hover_end_iter);
2265                     
2266                 textview->uri_hover = uri;
2267                 if (uri) {
2268                         textview->uri_hover_start_iter = start_iter;
2269                         textview->uri_hover_end_iter = end_iter;
2270                 }
2271                 
2272                 window = gtk_text_view_get_window(GTK_TEXT_VIEW(textview->text),
2273                                                   GTK_TEXT_WINDOW_TEXT);
2274                 if (textview->messageview->mainwin->cursor_count == 0) {
2275                         textview_set_cursor(window, uri ? hand_cursor : text_cursor);
2276                 } else {
2277                         textview_set_cursor(window, watch_cursor);
2278                 }
2279
2280                 TEXTVIEW_STATUSBAR_POP(textview);
2281
2282                 if (uri) {
2283                         char *trimmed_uri;
2284
2285                         if (!uri->is_quote)
2286                                 gtk_text_buffer_apply_tag_by_name(buffer,
2287                                                           "link-hover",
2288                                                           &start_iter,
2289                                                           &end_iter);
2290
2291                         trimmed_uri = trim_string(uri->uri, 60);
2292                         TEXTVIEW_STATUSBAR_PUSH(textview, trimmed_uri);
2293                         g_free(trimmed_uri);
2294                 }
2295         }
2296 }
2297
2298 static gboolean textview_get_uri_range(TextView *textview,
2299                                        GtkTextIter *iter,
2300                                        GtkTextTag *tag,
2301                                        GtkTextIter *start_iter,
2302                                        GtkTextIter *end_iter)
2303 {
2304         return get_tag_range(iter, tag, start_iter, end_iter);
2305 }
2306
2307 static ClickableText *textview_get_uri_from_range(TextView *textview,
2308                                               GtkTextIter *iter,
2309                                               GtkTextTag *tag,
2310                                               GtkTextIter *start_iter,
2311                                               GtkTextIter *end_iter)
2312 {
2313         gint start_pos, end_pos, cur_pos;
2314         ClickableText *uri = NULL;
2315         GSList *cur;
2316
2317         start_pos = gtk_text_iter_get_offset(start_iter);
2318         end_pos = gtk_text_iter_get_offset(end_iter);
2319         cur_pos = gtk_text_iter_get_offset(iter);
2320
2321         for (cur = textview->uri_list; cur != NULL; cur = cur->next) {
2322                 ClickableText *uri_ = (ClickableText *)cur->data;
2323                 if (start_pos == uri_->start &&
2324                     end_pos ==  uri_->end) {
2325                         uri = uri_;
2326                         break;
2327                 } 
2328         }
2329         for (cur = textview->uri_list; uri == NULL && cur != NULL; cur = cur->next) {
2330                 ClickableText *uri_ = (ClickableText *)cur->data;
2331                 if (start_pos == uri_->start ||
2332                            end_pos == uri_->end) {
2333                         /* in case of contiguous links, textview_get_uri_range
2334                          * returns a broader range (start of 1st link to end
2335                          * of last link).
2336                          * In that case, correct link is the one covering
2337                          * current iter.
2338                          */
2339                         if (uri_->start <= cur_pos && cur_pos <= uri_->end) {
2340                                 uri = uri_;
2341                                 break;
2342                         }
2343                 } 
2344         }
2345
2346         return uri;
2347 }
2348
2349 static ClickableText *textview_get_uri(TextView *textview,
2350                                    GtkTextIter *iter,
2351                                    GtkTextTag *tag)
2352 {
2353         GtkTextIter start_iter, end_iter;
2354         ClickableText *uri = NULL;
2355
2356         if (textview_get_uri_range(textview, iter, tag, &start_iter,
2357                                    &end_iter))
2358                 uri = textview_get_uri_from_range(textview, iter, tag,
2359                                                   &start_iter, &end_iter);
2360
2361         return uri;
2362 }
2363
2364 static void textview_shift_uris_after(TextView *textview, GSList *start_list, gint start, gint shift)
2365 {
2366         GSList *cur;
2367         if (!start_list)
2368                 start_list = textview->uri_list;
2369
2370         for (cur = start_list; cur; cur = cur->next) {
2371                 ClickableText *uri = (ClickableText *)cur->data;
2372                 if (uri->start <= start)
2373                         continue;
2374                 uri->start += shift;
2375                 uri->end += shift;
2376         }
2377 }
2378
2379 static void textview_remove_uris_in(TextView *textview, gint start, gint end)
2380 {
2381         GSList *cur;
2382         for (cur = textview->uri_list; cur; ) {
2383                 ClickableText *uri = (ClickableText *)cur->data;
2384                 if (uri->start > start && uri->end < end) {
2385                         cur = cur->next;
2386                         textview->uri_list = g_slist_remove(textview->uri_list, uri);
2387                         g_free(uri->uri);
2388                         g_free(uri->filename);
2389                         if (uri->is_quote) {
2390                                 g_free(uri->fg_color);
2391                                 g_free(uri->data); 
2392                                 /* (only free data in quotes uris) */
2393                         }
2394                         g_free(uri);
2395                 } else {
2396                         cur = cur->next;
2397                 }
2398                 
2399         }
2400 }
2401
2402 static void textview_toggle_quote(TextView *textview, GSList *start_list, ClickableText *uri, gboolean expand_only)
2403 {
2404         GtkTextIter start, end;
2405         GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview->text));
2406         
2407         if (!uri->is_quote)
2408                 return;
2409         
2410         if (uri->q_expanded && expand_only)
2411                 return;
2412
2413         gtk_text_buffer_get_iter_at_offset(buffer, &start, uri->start);
2414         gtk_text_buffer_get_iter_at_offset(buffer, &end,   uri->end);
2415         if (textview->uri_hover)
2416                 gtk_text_buffer_remove_tag_by_name(buffer,
2417                                                    "link-hover",
2418                                                    &textview->uri_hover_start_iter,
2419                                                    &textview->uri_hover_end_iter);
2420         textview->uri_hover = NULL;
2421         gtk_text_buffer_remove_tag_by_name(buffer,
2422                                            "qlink",
2423                                            &start,
2424                                            &end);
2425         /* when shifting URIs start and end, we have to do it per-UTF8-char
2426          * so use g_utf8_strlen(). OTOH, when inserting in the text buffer, 
2427          * we have to pass a number of bytes, so use strlen(). disturbing. */
2428          
2429         if (!uri->q_expanded) {
2430                 gtk_text_buffer_get_iter_at_offset(buffer, &start, uri->start);
2431                 gtk_text_buffer_get_iter_at_offset(buffer, &end,   uri->end);
2432                 textview_shift_uris_after(textview, start_list, uri->start, 
2433                         g_utf8_strlen((gchar *)uri->data, -1)-strlen(" [...]\n"));
2434                 gtk_text_buffer_delete(buffer, &start, &end);
2435                 gtk_text_buffer_get_iter_at_offset(buffer, &start, uri->start);
2436                 gtk_text_buffer_insert_with_tags_by_name
2437                                 (buffer, &start, (gchar *)uri->data, 
2438                                  strlen((gchar *)uri->data)-1,
2439                                  "qlink", (gchar *)uri->fg_color, NULL);
2440                 uri->end = gtk_text_iter_get_offset(&start);
2441                 textview_make_clickable_parts_later(textview,
2442                                           uri->start, uri->end);
2443                 uri->q_expanded = TRUE;
2444         } else {
2445                 gtk_text_buffer_get_iter_at_offset(buffer, &start, uri->start);
2446                 gtk_text_buffer_get_iter_at_offset(buffer, &end,   uri->end);
2447                 textview_remove_uris_in(textview, uri->start, uri->end);
2448                 textview_shift_uris_after(textview, start_list, uri->start, 
2449                         strlen(" [...]\n")-g_utf8_strlen((gchar *)uri->data, -1));
2450                 gtk_text_buffer_delete(buffer, &start, &end);
2451                 gtk_text_buffer_get_iter_at_offset(buffer, &start, uri->start);
2452                 gtk_text_buffer_insert_with_tags_by_name
2453                                 (buffer, &start, " [...]", -1,
2454                                  "qlink", (gchar *)uri->fg_color, NULL);
2455                 uri->end = gtk_text_iter_get_offset(&start);
2456                 uri->q_expanded = FALSE;
2457         }
2458         if (textview->messageview->mainwin->cursor_count == 0) {
2459                 textview_cursor_normal(textview);
2460         } else {
2461                 textview_cursor_wait(textview);
2462         }
2463 }
2464 static gboolean textview_uri_button_pressed(GtkTextTag *tag, GObject *obj,
2465                                             GdkEvent *event, GtkTextIter *iter,
2466                                             TextView *textview)
2467 {
2468         GdkEventButton *bevent;
2469         ClickableText *uri = NULL;
2470         char *tagname;
2471         gboolean qlink = FALSE;
2472
2473         if (!event)
2474                 return FALSE;
2475
2476         if (event->type != GDK_BUTTON_PRESS && event->type != GDK_2BUTTON_PRESS
2477                 && event->type != GDK_MOTION_NOTIFY)
2478                 return FALSE;
2479
2480         uri = textview_get_uri(textview, iter, tag);
2481         if (!uri)
2482                 return FALSE;
2483
2484         g_object_get(G_OBJECT(tag), "name", &tagname, NULL);
2485         
2486         if (!strcmp(tagname, "qlink"))
2487                 qlink = TRUE;
2488
2489         g_free(tagname);
2490         
2491         bevent = (GdkEventButton *) event;
2492         
2493         /* doubleclick: open compose / add address / browser */
2494         if (qlink && event->type == GDK_BUTTON_PRESS && bevent->button != 1) {
2495                 /* pass rightclick through */
2496                 return FALSE;
2497         } else if ((event->type == (qlink ? GDK_2BUTTON_PRESS:GDK_BUTTON_PRESS) && bevent->button == 1) ||
2498                 bevent->button == 2 || bevent->button == 3) {
2499                 if (uri->filename && !g_ascii_strncasecmp(uri->filename, "sc://", 5)) {
2500                         MimeView *mimeview = 
2501                                 (textview->messageview)?
2502                                         textview->messageview->mimeview:NULL;
2503                         if (mimeview && bevent->button == 1) {
2504                                 mimeview_handle_cmd(mimeview, uri->filename, NULL, uri->data);
2505                         } else if (mimeview && bevent->button == 2 && 
2506                                 !g_ascii_strcasecmp(uri->filename, "sc://select_attachment")) {
2507                                 mimeview_handle_cmd(mimeview, "sc://open_attachment", NULL, uri->data);
2508                         } else if (mimeview && bevent->button == 3 && 
2509                                 !g_ascii_strcasecmp(uri->filename, "sc://select_attachment")) {
2510                                 mimeview_handle_cmd(mimeview, "sc://menu_attachment", bevent, uri->data);
2511                         } 
2512                         return TRUE;
2513                 } else if (qlink && bevent->button == 1) {
2514                         textview_toggle_quote(textview, NULL, uri, FALSE);
2515                         return TRUE;
2516                 } else if (!g_ascii_strncasecmp(uri->uri, "mailto:", 7)) {
2517                         if (bevent->button == 3) {
2518                                 g_object_set_data(
2519                                         G_OBJECT(textview->mail_popup_menu),
2520                                         "menu_button", uri);
2521                                 gtk_menu_popup(GTK_MENU(textview->mail_popup_menu), 
2522                                                NULL, NULL, NULL, NULL, 
2523                                                bevent->button, bevent->time);
2524                         } else {
2525                                 PrefsAccount *account = NULL;
2526                                 FolderItem   *folder_item = NULL;
2527                                 if (textview->messageview && textview->messageview->msginfo &&
2528                                     textview->messageview->msginfo->folder) {
2529                                         
2530
2531                                         folder_item = textview->messageview->msginfo->folder;
2532                                         if (folder_item->prefs && folder_item->prefs->enable_default_account)
2533                                                 account = account_find_from_id(folder_item->prefs->default_account);
2534                                         if (!account)
2535                                                 account = account_find_from_item(folder_item);
2536                                 }
2537                                 compose_new_with_folderitem(account, folder_item, uri->uri + 7);
2538                         }
2539                         return TRUE;
2540                 } else if (g_ascii_strncasecmp(uri->uri, "file:", 5)) {
2541                         if (bevent->button == 1 &&
2542                             textview_uri_security_check(textview, uri) == TRUE) 
2543                                         open_uri(uri->uri,
2544                                                  prefs_common.uri_cmd);
2545                         else if (bevent->button == 3 && !qlink) {
2546                                 g_object_set_data(
2547                                         G_OBJECT(textview->link_popup_menu),
2548                                         "menu_button", uri);
2549                                 gtk_menu_popup(GTK_MENU(textview->link_popup_menu), 
2550                                                NULL, NULL, NULL, NULL, 
2551                                                bevent->button, bevent->time);
2552                         }
2553                         return TRUE;
2554                 } else {
2555                         if (bevent->button == 3 && !qlink) {
2556                                 g_object_set_data(
2557                                         G_OBJECT(textview->file_popup_menu),
2558                                         "menu_button", uri);
2559                                 gtk_menu_popup(GTK_MENU(textview->file_popup_menu), 
2560                                                NULL, NULL, NULL, NULL, 
2561                                                bevent->button, bevent->time);
2562                                 return TRUE;
2563                         }
2564                 }
2565         }
2566
2567         return FALSE;
2568 }
2569
2570 gchar *textview_get_visible_uri         (TextView       *textview, 
2571                                          ClickableText  *uri)
2572 {
2573         GtkTextBuffer *buffer;
2574         GtkTextIter start, end;
2575
2576         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview->text));
2577
2578         gtk_text_buffer_get_iter_at_offset(buffer, &start, uri->start);
2579         gtk_text_buffer_get_iter_at_offset(buffer, &end,   uri->end);
2580
2581         return gtk_text_buffer_get_text(buffer, &start, &end, FALSE);
2582 }
2583
2584 /*!
2585  *\brief    Check to see if a web URL has been disguised as a different
2586  *          URL (possible with HTML email).
2587  *
2588  *\param    uri The uri to check
2589  *
2590  *\param    textview The TextView the URL is contained in
2591  *
2592  *\return   gboolean TRUE if the URL is ok, or if the user chose to open
2593  *          it anyway, otherwise FALSE          
2594  */
2595 gboolean textview_uri_security_check(TextView *textview, ClickableText *uri)
2596 {
2597         gchar *visible_str;
2598         gboolean retval = TRUE;
2599
2600         if (is_uri_string(uri->uri) == FALSE)
2601                 return TRUE;
2602
2603         visible_str = textview_get_visible_uri(textview, uri);
2604         if (visible_str == NULL)
2605                 return TRUE;
2606
2607         if (strcmp(visible_str, uri->uri) != 0 && is_uri_string(visible_str)) {
2608                 gchar *uri_path;
2609                 gchar *visible_uri_path;
2610
2611                 uri_path = get_uri_path(uri->uri);
2612                 visible_uri_path = get_uri_path(visible_str);
2613                 if (path_cmp(uri_path, visible_uri_path) != 0)
2614                         retval = FALSE;
2615         }
2616
2617         if (retval == FALSE) {
2618                 gchar *msg;
2619                 AlertValue aval;
2620
2621                 msg = g_markup_printf_escaped(_("The real URL is different from "
2622                                                 "the displayed URL.\n"
2623                                                 "\n"
2624                                                 "<b>Displayed URL:</b> %s\n"
2625                                                 "\n"
2626                                                 "<b>Real URL:</b> %s\n"
2627                                                 "\n"
2628                                                 "Open it anyway?"),
2629                                                visible_str,uri->uri);
2630                 aval = alertpanel_full(_("Phishing attempt warning"), msg,
2631                                        GTK_STOCK_CANCEL, _("_Open URL"), NULL, FALSE,
2632                                        NULL, ALERT_WARNING, G_ALERTDEFAULT);
2633                 g_free(msg);
2634                 if (aval == G_ALERTALTERNATE)
2635                         retval = TRUE;
2636         }
2637
2638         g_free(visible_str);
2639
2640         return retval;
2641 }
2642
2643 static void textview_uri_list_remove_all(GSList *uri_list)
2644 {
2645         GSList *cur;
2646
2647         for (cur = uri_list; cur != NULL; cur = cur->next) {
2648                 if (cur->data) {
2649                         g_free(((ClickableText *)cur->data)->uri);
2650                         g_free(((ClickableText *)cur->data)->filename);
2651                         if (((ClickableText *)cur->data)->is_quote) {
2652                                 g_free(((ClickableText *)cur->data)->fg_color);
2653                                 g_free(((ClickableText *)cur->data)->data); 
2654                                 /* (only free data in quotes uris) */
2655                         }
2656                         g_free(cur->data);
2657                 }
2658         }
2659
2660         g_slist_free(uri_list);
2661 }
2662
2663 static void open_uri_cb (TextView *textview, guint action, void *data)
2664 {
2665         ClickableText *uri = g_object_get_data(G_OBJECT(textview->link_popup_menu),
2666                                            "menu_button");
2667         if (uri == NULL)
2668                 return;
2669
2670         if (textview_uri_security_check(textview, uri) == TRUE) 
2671                 open_uri(uri->uri,
2672                          prefs_common.uri_cmd);
2673         g_object_set_data(G_OBJECT(textview->link_popup_menu), "menu_button",
2674                           NULL);
2675 }
2676
2677 static void open_image_cb (TextView *textview, guint action, void *data)
2678 {
2679         ClickableText *uri = g_object_get_data(G_OBJECT(textview->file_popup_menu),
2680                                            "menu_button");
2681
2682         gchar *cmd = NULL;
2683         gchar buf[1024];
2684         const gchar *p;
2685         gchar *filename = NULL;
2686         gchar *tmp_filename = NULL;
2687
2688         if (uri == NULL)
2689                 return;
2690
2691         if (uri->filename == NULL)
2692                 return;
2693         
2694         filename = g_strdup(uri->filename);
2695         
2696         if (!g_utf8_validate(filename, -1, NULL)) {
2697                 gchar *tmp = conv_filename_to_utf8(filename);
2698                 g_free(filename);
2699                 filename = tmp;
2700         }
2701
2702         subst_for_filename(filename);
2703
2704         tmp_filename = g_filename_from_uri(uri->uri, NULL, NULL);
2705         copy_file(tmp_filename, filename, FALSE);
2706         g_free(tmp_filename);
2707
2708         cmd = mailcap_get_command_for_type("image/jpeg", filename);
2709         if (cmd == NULL) {
2710                 gboolean remember = FALSE;
2711                 cmd = input_dialog_combo_remember
2712                         (_("Open with"),
2713                          _("Enter the command line to open file:\n"
2714                            "('%s' will be replaced with file name)"),
2715                          prefs_common.mime_open_cmd,
2716                          prefs_common.mime_open_cmd_history,
2717                          TRUE, &remember);
2718                 if (cmd && remember) {
2719                         mailcap_update_default("image/jpeg", cmd);
2720                 }
2721         }
2722         if (cmd && (p = strchr(cmd, '%')) && *(p + 1) == 's' &&
2723             !strchr(p + 2, '%'))
2724                 g_snprintf(buf, sizeof(buf), cmd, filename);
2725         else {
2726                 g_warning("Image viewer command line is invalid: '%s'", cmd);
2727                 return;
2728         }
2729
2730         execute_command_line(buf, TRUE);
2731
2732         g_free(filename);
2733         g_free(cmd);
2734
2735         g_object_set_data(G_OBJECT(textview->file_popup_menu), "menu_button",
2736                           NULL);
2737 }
2738
2739 static void save_file_cb (TextView *textview, guint action, void *data)
2740 {
2741         ClickableText *uri = g_object_get_data(G_OBJECT(textview->file_popup_menu),
2742                                            "menu_button");
2743         gchar *filename = NULL;
2744         gchar *filepath = NULL;
2745         gchar *filedir = NULL;
2746         gchar *tmp_filename = NULL;
2747         if (uri == NULL)
2748                 return;
2749
2750         if (uri->filename == NULL)
2751                 return;
2752         
2753         filename = g_strdup(uri->filename);
2754         
2755         if (!g_utf8_validate(filename, -1, NULL)) {
2756                 gchar *tmp = conv_filename_to_utf8(filename);
2757                 g_free(filename);
2758                 filename = tmp;
2759         }
2760
2761         subst_for_filename(filename);
2762         
2763         if (prefs_common.attach_save_dir)
2764                 filepath = g_strconcat(prefs_common.attach_save_dir,
2765                                        G_DIR_SEPARATOR_S, filename, NULL);
2766         else
2767                 filepath = g_strdup(filename);
2768
2769         g_free(filename);
2770
2771         filename = filesel_select_file_save(_("Save as"), filepath);
2772         if (!filename) {
2773                 g_free(filepath);
2774                 return;
2775         }
2776
2777         if (is_file_exist(filename)) {
2778                 AlertValue aval;
2779                 gchar *res;
2780                 
2781                 res = g_strdup_printf(_("Overwrite existing file '%s'?"),
2782                                       filename);
2783                 aval = alertpanel(_("Overwrite"), res, GTK_STOCK_CANCEL, 
2784                                   GTK_STOCK_OK, NULL);
2785                 g_free(res);                                      
2786                 if (G_ALERTALTERNATE != aval)
2787                         return;
2788         }
2789
2790         tmp_filename = g_filename_from_uri(uri->uri, NULL, NULL);
2791         copy_file(tmp_filename, filename, FALSE);
2792         g_free(tmp_filename);
2793         
2794         filedir = g_path_get_dirname(filename);
2795         if (filedir && strcmp(filedir, ".")) {
2796                 g_free(prefs_common.attach_save_dir);
2797                 prefs_common.attach_save_dir = g_filename_to_utf8(filedir, -1, NULL, NULL, NULL);
2798         }
2799
2800         g_free(filedir);
2801         g_free(filepath);
2802
2803         g_object_set_data(G_OBJECT(textview->file_popup_menu), "menu_button",
2804                           NULL);
2805 }
2806
2807 static void copy_uri_cb (TextView *textview, guint action, void *data)
2808 {
2809         ClickableText *uri = g_object_get_data(G_OBJECT(textview->link_popup_menu),
2810                                            "menu_button");
2811         if (uri == NULL)
2812                 return;
2813
2814         gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), uri->uri, -1);
2815         gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), uri->uri, -1);
2816         g_object_set_data(G_OBJECT(textview->link_popup_menu), "menu_button",
2817                           NULL);
2818 }
2819
2820 static void add_uri_to_addrbook_cb (TextView *textview, guint action, void *data)
2821 {
2822         gchar *fromname, *fromaddress;
2823         ClickableText *uri = g_object_get_data(G_OBJECT(textview->mail_popup_menu),
2824                                            "menu_button");
2825         if (uri == NULL)
2826                 return;
2827
2828         /* extract url */
2829         fromaddress = g_strdup(uri->uri + 7);
2830         /* Hiroyuki: please put this function in utils.c! */
2831         fromname = procheader_get_fromname(fromaddress);
2832         extract_address(fromaddress);
2833
2834         /* Add to address book - Match */
2835         addressbook_add_contact( fromname, fromaddress, NULL );
2836
2837         g_free(fromaddress);
2838         g_free(fromname);
2839 }
2840
2841 static void mail_to_uri_cb (TextView *textview, guint action, void *data)
2842 {
2843         PrefsAccount *account = NULL;
2844         ClickableText *uri = g_object_get_data(G_OBJECT(textview->mail_popup_menu),
2845                                            "menu_button");
2846         if (uri == NULL)
2847                 return;
2848
2849         if (textview->messageview && textview->messageview->msginfo &&
2850             textview->messageview->msginfo->folder) {
2851                 FolderItem   *folder_item;
2852
2853                 folder_item = textview->messageview->msginfo->folder;
2854                 if (folder_item->prefs && folder_item->prefs->enable_default_account)
2855                         account = account_find_from_id(folder_item->prefs->default_account);
2856         }
2857         compose_new(account, uri->uri + 7, NULL);
2858 }
2859
2860 static void copy_mail_to_uri_cb (TextView *textview, guint action, void *data)
2861 {
2862         ClickableText *uri = g_object_get_data(G_OBJECT(textview->mail_popup_menu),
2863                                            "menu_button");
2864         if (uri == NULL)
2865                 return;
2866
2867         gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), uri->uri +7, -1);
2868         gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), uri->uri +7, -1);
2869         g_object_set_data(G_OBJECT(textview->mail_popup_menu), "menu_button",
2870                           NULL);
2871 }
2872
2873 void textview_get_selection_offsets(TextView *textview, gint *sel_start, gint *sel_end)
2874 {
2875                 GtkTextView *text = GTK_TEXT_VIEW(textview->text);
2876                 GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
2877                 GtkTextIter start, end;
2878                 if (gtk_text_buffer_get_selection_bounds(buffer, &start, &end)) {
2879                         if (sel_start)
2880                                 *sel_start = gtk_text_iter_get_offset(&start);
2881                         if (sel_end)
2882                                 *sel_end = gtk_text_iter_get_offset(&end);
2883                 } else {
2884                         if (sel_start)
2885                                 *sel_start = -1;
2886                         if (sel_end)
2887                                 *sel_end = -1;
2888                 }
2889 }