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