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