28dd069ca6ef7cce40f99f7d3adbe3d6ca7cdd6e
[claws.git] / src / mimeview.c
1 /*
2  * Claws Mail -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2015 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 #ifdef HAVE_CONFIG_H
20 #  include "config.h"
21 #include "claws-features.h"
22 #endif
23
24 #include "defs.h"
25
26 #ifdef G_OS_WIN32
27 #define UNICODE
28 #define _UNICODE
29 #endif
30
31 #include <glib.h>
32 #include <glib/gi18n.h>
33 #include <gdk/gdkkeysyms.h>
34 #include <gtk/gtk.h>
35 #include <stdio.h>
36 #include <sys/types.h>
37 #include <sys/stat.h>
38
39 #include "main.h"
40 #include "mimeview.h"
41 #include "textview.h"
42 #include "procmime.h"
43 #include "summaryview.h"
44 #include "menu.h"
45 #include "filesel.h"
46 #include "alertpanel.h"
47 #include "inputdialog.h"
48 #include "utils.h"
49 #include "gtkutils.h"
50 #include "prefs_common.h"
51 #include "procheader.h"
52 #include "stock_pixmap.h"
53 #include "gtk/gtkvscrollbutton.h"
54 #include "gtk/logwindow.h"
55 #include "timing.h"
56 #include "manage_window.h"
57 #include "privacy.h"
58 #include "file-utils.h"
59
60 typedef enum
61 {
62         COL_MIMETYPE = 0,
63         COL_SIZE     = 1,
64         COL_NAME     = 2,
65         COL_DATA     = 3,
66         N_MIMEVIEW_COLUMNS
67 } MimeViewColumnPos;
68
69 #define N_MIMEVIEW_COLS (N_MIMEVIEW_COLUMNS)
70
71 static void mimeview_set_multipart_tree         (MimeView       *mimeview,
72                                                  MimeInfo       *mimeinfo,
73                                                  GtkTreeIter    *parent);
74 static void mimeview_show_message_part          (MimeView       *mimeview,
75                                                  MimeInfo       *partinfo);
76 static void mimeview_change_view_type           (MimeView       *mimeview,
77                                                  MimeViewType    type);
78 static gchar *mimeview_get_filename_for_part    (MimeInfo       *partinfo,
79                                                  const gchar    *basedir,
80                                                  gint            number);
81 static gboolean mimeview_write_part             (const gchar    *filename,
82                                                  MimeInfo       *partinfo,
83                                                  gboolean        handle_error);
84
85 static void mimeview_selected           (GtkTreeSelection       *selection,
86                                          MimeView       *mimeview);
87 static gint mimeview_button_pressed     (GtkWidget      *widget,
88                                          GdkEventButton *event,
89                                          MimeView       *mimeview);
90 static gint mimeview_key_pressed        (GtkWidget      *widget,
91                                          GdkEventKey    *event,
92                                          MimeView       *mimeview);
93
94 static void mimeview_drag_data_get      (GtkWidget        *widget,
95                                          GdkDragContext   *drag_context,
96                                          GtkSelectionData *selection_data,
97                                          guint             info,
98                                          guint             time,
99                                          MimeView         *mimeview);
100
101 static gboolean mimeview_scrolled       (GtkWidget      *widget,
102                                          GdkEventScroll *event,
103                                          MimeView       *mimeview);
104
105 static void mimeview_save_all           (MimeView       *mimeview);
106 #ifndef G_OS_WIN32
107 static void mimeview_open_part_with     (MimeView       *mimeview,
108                                          MimeInfo       *partinfo,
109                                          gboolean        automatic);
110 #endif
111 static void mimeview_send_to            (MimeView       *mimeview,
112                                          MimeInfo       *partinfo);
113 static void mimeview_view_file          (const gchar    *filename,
114                                          MimeInfo       *partinfo,
115                                          const gchar    *cmd,
116                                          MimeView       *mimeview);
117 static gboolean icon_clicked_cb         (GtkWidget      *button, 
118                                          GdkEventButton *event, 
119                                          MimeView       *mimeview);
120 static void icon_selected               (MimeView       *mimeview, 
121                                          gint            num, 
122                                          MimeInfo       *partinfo);
123 static gint icon_key_pressed            (GtkWidget      *button, 
124                                          GdkEventKey    *event,
125                                          MimeView       *mimeview);
126 static void icon_list_append_icon       (MimeView       *mimeview, 
127                                          MimeInfo       *mimeinfo);
128 static void icon_list_create            (MimeView       *mimeview, 
129                                          MimeInfo       *mimeinfo);
130 static void icon_list_clear             (MimeView       *mimeview);
131 static void icon_list_toggle_by_mime_info (MimeView     *mimeview,
132                                            MimeInfo     *mimeinfo);
133 static void ctree_size_allocate_cb      (GtkWidget      *widget,
134                                          GtkAllocation  *allocation,
135                                          MimeView       *mimeview);
136 static gint mime_toggle_button_cb(GtkWidget *button, GdkEventButton *event,
137                                     MimeView *mimeview);
138 static gboolean part_button_pressed     (MimeView       *mimeview, 
139                                          GdkEventButton *event, 
140                                          MimeInfo       *partinfo);
141 static void icon_scroll_size_allocate_cb(GtkWidget      *widget, 
142                                          GtkAllocation  *layout_size, 
143                                          MimeView       *mimeview);
144 static MimeInfo *mimeview_get_part_to_use(MimeView *mimeview);
145 static const gchar *get_part_name(MimeInfo *partinfo);
146 static const gchar *get_part_description(MimeInfo *partinfo);
147
148 static void mimeview_launch_cb(GtkAction *action, gpointer data)
149 {
150         MimeView *mimeview = (MimeView *)data;
151         mimeview_launch(mimeview, mimeview_get_part_to_use(mimeview));
152 }
153
154 #ifndef G_OS_WIN32
155 static void mimeview_open_with_cb(GtkAction *action, gpointer data)
156 {
157         mimeview_open_with((MimeView *)data);
158 }
159 #endif
160
161 static void mimeview_copy_cb(GtkAction *action, gpointer data)
162 {
163         MimeView *mimeview = (MimeView *)data;
164         MimeInfo *mimeinfo = mimeview_get_part_to_use(mimeview);
165
166         if (mimeinfo == NULL)
167                 return;
168
169         if (mimeinfo->type == MIMETYPE_IMAGE) {
170                 GError *error = NULL;
171                 GdkPixbuf *pixbuf = procmime_get_part_as_pixbuf(mimeinfo, &error);
172                 if (error != NULL) {
173                         g_warning("could not copy: %s", error->message);
174                         g_error_free(error);
175                 } else {
176                         gtk_clipboard_set_image(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD),
177                                                 pixbuf);
178                 }
179                 g_object_unref(pixbuf);
180         } else {
181                 void *data = procmime_get_part_as_string(mimeinfo, FALSE);
182                 gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD),
183                                        data, mimeinfo->length);
184                 g_free(data);
185         }
186 }
187
188 static void mimeview_send_to_cb(GtkAction *action, gpointer data)
189 {
190         MimeView *mimeview = (MimeView *)data;  
191         mimeview_send_to(mimeview, mimeview_get_part_to_use(mimeview));
192 }
193
194 static void mimeview_display_as_text_cb(GtkAction *action, gpointer data)
195 {
196         mimeview_display_as_text((MimeView *)data);
197 }
198
199 static void mimeview_save_as_cb(GtkAction *action, gpointer data)
200 {
201         mimeview_save_as((MimeView *)data);
202 }
203
204 static void mimeview_save_all_cb(GtkAction *action, gpointer data)
205 {
206         mimeview_save_all((MimeView *)data);
207 }
208
209 static void mimeview_select_next_part_cb(GtkAction *action, gpointer data)
210 {
211         mimeview_select_next_part((MimeView *)data);
212 }
213
214 static void mimeview_select_prev_part_cb(GtkAction *action, gpointer data)
215 {
216         mimeview_select_prev_part((MimeView *)data);
217 }
218
219 static GtkActionEntry mimeview_menu_actions[] = {
220         { "MimeView", NULL, "MimeView", NULL, NULL, NULL },
221         { "MimeView/Open", NULL, N_("_Open"), NULL, "Open MIME part", G_CALLBACK(mimeview_launch_cb) },
222 #if (!defined G_OS_WIN32)
223         { "MimeView/OpenWith", NULL, N_("Open _with..."), NULL, "Open MIME part with...", G_CALLBACK(mimeview_open_with_cb) },
224 #endif
225         { "MimeView/Copy", NULL, N_("Copy"), NULL, "Copy", G_CALLBACK(mimeview_copy_cb) },
226         { "MimeView/SendTo", NULL, N_("Send to..."), NULL, "Send to", G_CALLBACK(mimeview_send_to_cb) },
227         { "MimeView/DisplayAsText", NULL, N_("_Display as text"), NULL, "Display as text", G_CALLBACK(mimeview_display_as_text_cb) },
228         { "MimeView/SaveAs", NULL, N_("_Save as..."), NULL, "Save as", G_CALLBACK(mimeview_save_as_cb) },
229         { "MimeView/SaveAll", NULL, N_("Save _all..."), NULL, "Save all parts", G_CALLBACK(mimeview_save_all_cb) },
230         { "MimeView/NextPart", NULL, N_("Next part"), NULL, "Next part", G_CALLBACK(mimeview_select_next_part_cb) },
231         { "MimeView/PrevPart", NULL, N_("Previous part"), NULL, "Previous part", G_CALLBACK(mimeview_select_prev_part_cb) }
232 };
233
234 static GtkTargetEntry mimeview_mime_types[] =
235 {
236         {"text/uri-list", 0, 0}
237 };
238
239 GSList *mimeviewer_factories;
240 GSList *mimeviews;
241
242 static GdkCursor *hand_cursor = NULL;
243
244 static gboolean mimeview_visi_notify(GtkWidget *widget,
245                                        GdkEventVisibility *event,
246                                        MimeView *mimeview)
247 {
248         gdk_window_set_cursor(gtk_widget_get_window(widget), hand_cursor);
249         return FALSE;
250 }
251
252 static gboolean mimeview_leave_notify(GtkWidget *widget,
253                                       GdkEventCrossing *event,
254                                       MimeView *mimeview)
255 {
256         gdk_window_set_cursor(gtk_widget_get_window(widget), NULL);
257         return FALSE;
258 }
259
260 static gboolean mimeview_enter_notify(GtkWidget *widget,
261                                       GdkEventCrossing *event,
262                                       MimeView *mimeview)
263 {
264         gdk_window_set_cursor(gtk_widget_get_window(widget), hand_cursor);
265         return FALSE;
266 }
267
268 MimeView *mimeview_create(MainWindow *mainwin)
269 {
270         MimeView *mimeview;
271
272         GtkWidget *paned;
273         GtkWidget *scrolledwin;
274         GtkWidget *ctree;
275         GtkWidget *mime_notebook;
276         GtkWidget *popupmenu;
277         GtkWidget *ctree_mainbox;
278         GtkWidget *vbox;
279         GtkWidget *mime_toggle;
280         GtkWidget *icon_mainbox;
281         GtkWidget *icon_scroll;
282         GtkWidget *icon_vbox;
283         GtkWidget *arrow;
284         GtkWidget *scrollbutton;
285         GtkWidget *hbox;
286         NoticeView *siginfoview;
287         GtkRequisition r;
288         GtkTreeStore *model;
289         GtkCellRenderer *renderer;
290         GtkTreeViewColumn *column;
291         GtkTreeSelection *selection;
292
293         gchar *titles[N_MIMEVIEW_COLS];
294         gint cols;
295
296         if (!hand_cursor)
297                 hand_cursor = gdk_cursor_new(GDK_HAND2);
298
299         debug_print("Creating MIME view...\n");
300         mimeview = g_new0(MimeView, 1);
301
302         titles[COL_MIMETYPE] = _("MIME Type");
303         titles[COL_SIZE]     = _("Size");
304         titles[COL_NAME]     = _("Name");
305
306         scrolledwin = gtk_scrolled_window_new(NULL, NULL);
307         gtk_widget_show(scrolledwin);
308         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledwin),
309                                        GTK_POLICY_AUTOMATIC,
310                                        GTK_POLICY_AUTOMATIC);
311                                        
312         model = gtk_tree_store_new(N_MIMEVIEW_COLS,
313                                    G_TYPE_STRING,
314                                    G_TYPE_STRING,
315                                    G_TYPE_STRING,
316                                    G_TYPE_POINTER);
317
318         ctree = gtk_tree_view_new_with_model(GTK_TREE_MODEL(model));
319         g_object_unref(model);
320         gtk_tree_view_set_enable_search(GTK_TREE_VIEW(ctree), FALSE);
321         gtk_tree_view_set_rules_hint(GTK_TREE_VIEW(ctree),
322                                         prefs_common.use_stripes_everywhere);
323         gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(ctree),
324                                         prefs_common.show_col_headers);
325
326         renderer = gtk_cell_renderer_text_new();
327         cols = gtk_tree_view_insert_column_with_attributes(GTK_TREE_VIEW(ctree),
328                                         -1, titles[COL_MIMETYPE],renderer,
329                                         "text", COL_MIMETYPE, NULL);
330         column = gtk_tree_view_get_column(GTK_TREE_VIEW(ctree), cols-1);
331                                                            
332         renderer = gtk_cell_renderer_text_new();
333         gtk_cell_renderer_set_alignment(renderer, 1, 0.5);
334         cols = gtk_tree_view_insert_column_with_attributes(GTK_TREE_VIEW(ctree),
335                                         -1, titles[COL_SIZE], renderer,
336                                         "text", COL_SIZE, NULL);
337         column = gtk_tree_view_get_column(GTK_TREE_VIEW(ctree), cols-1);
338         gtk_tree_view_column_set_alignment(GTK_TREE_VIEW_COLUMN(column), 1);
339         
340         renderer = gtk_cell_renderer_text_new();
341         cols = gtk_tree_view_insert_column_with_attributes(GTK_TREE_VIEW(ctree),
342                                         -1, titles[COL_NAME], renderer,
343                                         "text", COL_NAME, NULL);
344         column = gtk_tree_view_get_column(GTK_TREE_VIEW(ctree), cols-1);
345         gtk_tree_view_column_set_expand(GTK_TREE_VIEW_COLUMN(column), TRUE);
346
347         selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(ctree));
348         gtk_tree_selection_set_mode(selection, GTK_SELECTION_BROWSE);
349
350         gtk_widget_show(ctree);
351         gtk_container_add(GTK_CONTAINER(scrolledwin), ctree);
352         gtk_drag_source_set(ctree, GDK_BUTTON1_MASK|GDK_BUTTON3_MASK, 
353                             mimeview_mime_types, 1, GDK_ACTION_COPY);
354
355         g_signal_connect(G_OBJECT(selection), "changed",
356                          G_CALLBACK(mimeview_selected), mimeview);
357         g_signal_connect(G_OBJECT(ctree), "button_release_event",
358                          G_CALLBACK(mimeview_button_pressed), mimeview);
359         g_signal_connect(G_OBJECT(ctree), "key_press_event",
360                          G_CALLBACK(mimeview_key_pressed), mimeview);
361         g_signal_connect(G_OBJECT(ctree), "drag_data_get",
362                          G_CALLBACK(mimeview_drag_data_get), mimeview);
363
364         mime_notebook = gtk_notebook_new();
365         gtk_widget_show(mime_notebook);
366         gtk_widget_set_can_focus(mime_notebook, FALSE);
367         gtk_notebook_set_show_tabs(GTK_NOTEBOOK(mime_notebook), FALSE);
368         gtk_notebook_set_show_border(GTK_NOTEBOOK(mime_notebook), FALSE);
369         
370         icon_vbox = gtk_vbox_new(FALSE, 2);
371         gtk_widget_show(icon_vbox);
372         icon_scroll = gtk_layout_new(NULL, NULL);
373         gtk_widget_show(icon_scroll);
374         gtk_layout_put(GTK_LAYOUT(icon_scroll), icon_vbox, 0, 0);
375         scrollbutton = gtk_vscrollbutton_new(gtk_layout_get_vadjustment(GTK_LAYOUT(icon_scroll)));
376         gtk_widget_show(scrollbutton);
377
378         g_signal_connect(G_OBJECT(icon_scroll), "scroll_event",
379                          G_CALLBACK(mimeview_scrolled), mimeview);
380
381         mime_toggle = gtk_event_box_new();
382         gtk_event_box_set_visible_window(GTK_EVENT_BOX(mime_toggle), FALSE);
383
384         g_signal_connect(G_OBJECT(mime_toggle), "motion-notify-event",
385                          G_CALLBACK(mimeview_visi_notify), mimeview);
386         g_signal_connect(G_OBJECT(mime_toggle), "leave-notify-event",
387                          G_CALLBACK(mimeview_leave_notify), mimeview);
388         g_signal_connect(G_OBJECT(mime_toggle), "enter-notify-event",
389                          G_CALLBACK(mimeview_enter_notify), mimeview);
390
391         gtk_container_set_border_width(GTK_CONTAINER(mime_toggle), 2);
392         gtk_widget_show(mime_toggle);
393         mimeview->ctree_mode = FALSE;
394         arrow = gtk_arrow_new(GTK_ARROW_LEFT, GTK_SHADOW_NONE);
395         gtk_widget_show(arrow);
396         gtk_widget_size_request(arrow, &r);
397         gtk_container_add(GTK_CONTAINER(mime_toggle), arrow);
398         g_signal_connect(G_OBJECT(mime_toggle), "button_release_event", 
399                          G_CALLBACK(mime_toggle_button_cb), mimeview);
400
401         icon_mainbox = gtk_vbox_new(FALSE, 0);
402         gtk_widget_show(icon_mainbox);
403         gtk_widget_set_size_request(icon_mainbox, 32, -1);
404         gtk_box_pack_start(GTK_BOX(icon_mainbox), mime_toggle, FALSE, FALSE, 0);
405         gtk_box_pack_start(GTK_BOX(icon_mainbox), icon_scroll, TRUE, TRUE, 3);
406         gtk_box_pack_end(GTK_BOX(icon_mainbox), scrollbutton, FALSE, FALSE, 0);
407         g_signal_connect(G_OBJECT(icon_mainbox), "size_allocate", 
408                          G_CALLBACK(icon_scroll_size_allocate_cb), mimeview);
409         
410         ctree_mainbox = gtk_hbox_new(FALSE, 0); 
411         gtk_box_pack_start(GTK_BOX(ctree_mainbox), scrolledwin, TRUE, TRUE, 0);
412         g_signal_connect(G_OBJECT(ctree_mainbox), "size_allocate", 
413                          G_CALLBACK(ctree_size_allocate_cb), mimeview);
414
415         mimeview->ui_manager = gtk_ui_manager_new();
416         mimeview->action_group = cm_menu_create_action_group_full(mimeview->ui_manager,
417                         "MimeView", mimeview_menu_actions,
418                         G_N_ELEMENTS(mimeview_menu_actions), (gpointer)mimeview);
419
420         MENUITEM_ADDUI_MANAGER(mimeview->ui_manager, "/", "Menus", "Menus", GTK_UI_MANAGER_MENUBAR)
421         MENUITEM_ADDUI_MANAGER(mimeview->ui_manager, 
422                         "/Menus/", "MimeView", "MimeView", GTK_UI_MANAGER_MENU);
423         MENUITEM_ADDUI_MANAGER(mimeview->ui_manager, 
424                         "/Menus/MimeView/", "Open", "MimeView/Open",
425                         GTK_UI_MANAGER_MENUITEM);
426 #if (!defined G_OS_WIN32)
427         MENUITEM_ADDUI_MANAGER(mimeview->ui_manager, 
428                         "/Menus/MimeView/", "OpenWith", "MimeView/OpenWith",
429                         GTK_UI_MANAGER_MENUITEM);
430 #endif
431         MENUITEM_ADDUI_MANAGER(mimeview->ui_manager, 
432                         "/Menus/MimeView/", "Copy", "MimeView/Copy",
433                         GTK_UI_MANAGER_MENUITEM);
434         MENUITEM_ADDUI_MANAGER(mimeview->ui_manager,
435                         "/Menus/MimeView/", "SendTo", "MimeView/SendTo",
436                         GTK_UI_MANAGER_MENUITEM);
437         MENUITEM_ADDUI_MANAGER(mimeview->ui_manager, 
438                         "/Menus/MimeView/", "DisplayAsText", "MimeView/DisplayAsText",
439                         GTK_UI_MANAGER_MENUITEM);
440         MENUITEM_ADDUI_MANAGER(mimeview->ui_manager, 
441                         "/Menus/MimeView/", "SaveAs", "MimeView/SaveAs",
442                         GTK_UI_MANAGER_MENUITEM);
443         MENUITEM_ADDUI_MANAGER(mimeview->ui_manager, 
444                         "/Menus/MimeView/", "SaveAll", "MimeView/SaveAll",
445                         GTK_UI_MANAGER_MENUITEM);
446         MENUITEM_ADDUI_MANAGER(mimeview->ui_manager, 
447                         "/Menus/MimeView/", "NextPart", "MimeView/NextPart",
448                         GTK_UI_MANAGER_MENUITEM);
449         MENUITEM_ADDUI_MANAGER(mimeview->ui_manager, 
450                         "/Menus/MimeView/", "PrevPart", "MimeView/PrevPart",
451                         GTK_UI_MANAGER_MENUITEM);
452
453         popupmenu = gtk_menu_item_get_submenu(GTK_MENU_ITEM(
454                                 gtk_ui_manager_get_widget(mimeview->ui_manager, "/Menus/MimeView")) );
455
456
457         vbox = gtk_vbox_new(FALSE, 0);
458         gtk_widget_show(vbox);
459         siginfoview = noticeview_create(mainwin);
460         noticeview_hide(siginfoview);
461         noticeview_set_icon_clickable(siginfoview, TRUE);
462         gtk_box_pack_start(GTK_BOX(vbox), mime_notebook, TRUE, TRUE, 0);
463         gtk_box_pack_end(GTK_BOX(vbox), GTK_WIDGET_PTR(siginfoview), FALSE, FALSE, 0);
464
465         paned = gtk_vpaned_new();
466         gtk_widget_show(paned);
467         gtk_paned_pack1(GTK_PANED(paned), ctree_mainbox, FALSE, TRUE);
468         gtk_paned_pack2(GTK_PANED(paned), vbox, TRUE, TRUE);
469         
470         hbox = gtk_hbox_new(FALSE, 0);
471         gtk_box_pack_start(GTK_BOX(hbox), paned, TRUE, TRUE, 0);
472         gtk_box_pack_start(GTK_BOX(hbox), icon_mainbox, FALSE, FALSE, 0);
473
474         gtk_widget_show(hbox);
475         gtk_widget_hide(ctree_mainbox);
476 #ifdef GENERIC_UMPC
477         gtk_widget_set_size_request(mime_toggle, -1, r.height + 8);
478 #endif
479         mimeview->hbox          = hbox;
480         mimeview->paned         = paned;
481         mimeview->scrolledwin   = scrolledwin;
482         mimeview->ctree         = ctree;
483         mimeview->mime_notebook = mime_notebook;
484         mimeview->popupmenu     = popupmenu;
485         mimeview->type          = -1;
486         mimeview->ctree_mainbox = ctree_mainbox;
487         mimeview->icon_scroll   = icon_scroll;
488         mimeview->icon_vbox     = icon_vbox;
489         mimeview->icon_mainbox  = icon_mainbox;
490         mimeview->icon_count    = 0;
491         mimeview->mainwin       = mainwin;
492         mimeview->mime_toggle   = mime_toggle;
493         mimeview->siginfoview   = siginfoview;
494         mimeview->scrollbutton  = scrollbutton;
495         mimeview->target_list   = gtk_target_list_new(mimeview_mime_types, 1); 
496         
497         mimeviews = g_slist_prepend(mimeviews, mimeview);
498
499         return mimeview;
500 }
501
502 void mimeview_init(MimeView *mimeview)
503 {
504         textview_init(mimeview->textview);
505
506         gtk_container_add(GTK_CONTAINER(mimeview->mime_notebook),
507                 GTK_WIDGET_PTR(mimeview->textview));
508 }
509
510 static gboolean any_part_is_signed(MimeInfo *mimeinfo)
511 {
512         while (mimeinfo) {
513                 if (privacy_mimeinfo_is_signed(mimeinfo))
514                         return TRUE;
515                 mimeinfo = procmime_mimeinfo_next(mimeinfo);
516         }
517
518         return FALSE;
519 }
520
521 void mimeview_show_message(MimeView *mimeview, MimeInfo *mimeinfo,
522                            const gchar *file)
523 {
524         GtkTreeView *ctree = GTK_TREE_VIEW(mimeview->ctree);
525
526         mimeview_clear(mimeview);
527
528         cm_return_if_fail(file != NULL);
529         cm_return_if_fail(mimeinfo != NULL);
530
531         mimeview->mimeinfo = mimeinfo;
532
533         mimeview->file = g_strdup(file);
534
535         g_signal_handlers_block_by_func(G_OBJECT(ctree), mimeview_selected,
536                                         mimeview);
537
538         /* check if the mail's signed - it can change the mail structure */
539         
540         if (any_part_is_signed(mimeinfo))
541                 debug_print("signed mail\n");
542
543         mimeview_set_multipart_tree(mimeview, mimeinfo, NULL);
544         gtk_tree_view_expand_all(ctree);
545         icon_list_clear(mimeview);
546         icon_list_create(mimeview, mimeinfo);
547         
548         g_signal_handlers_unblock_by_func(G_OBJECT(ctree),
549                                           mimeview_selected, mimeview);
550 }
551
552 #ifdef USE_PTHREAD
553 static void mimeview_check_sig_cancel_now(MimeView *mimeview);
554 #endif
555
556 static void mimeview_free_mimeinfo(MimeView *mimeview)
557 {
558         gboolean defer = FALSE;
559 #ifdef USE_PTHREAD
560         defer = (mimeview->check_data != NULL);
561         if (defer)
562                 mimeview->check_data->free_after_use = TRUE;
563 #endif
564         if (mimeview->mimeinfo != NULL && !defer) {
565                 procmime_mimeinfo_free_all(&mimeview->mimeinfo);
566                 mimeview->mimeinfo = NULL;
567         } else if (defer) {
568 #ifdef USE_PTHREAD
569                 debug_print("deferring free(mimeinfo) and cancelling check\n");
570                 mimeview_check_sig_cancel_now(mimeview);
571 #endif
572         }
573 }
574
575 void mimeview_destroy(MimeView *mimeview)
576 {
577         GSList *cur;
578         
579         for (cur = mimeview->viewers; cur != NULL; cur = g_slist_next(cur)) {
580                 MimeViewer *viewer = (MimeViewer *) cur->data;
581                 viewer->destroy_viewer(viewer);
582         }
583         g_slist_free(mimeview->viewers);
584         gtk_target_list_unref(mimeview->target_list);
585
586 #ifdef USE_PTHREAD
587         if (mimeview->check_data) {
588                 mimeview->check_data->destroy_mimeview = TRUE;
589                 debug_print("deferring destroy\n");
590         } else 
591 #endif
592         {
593                 mimeview_free_mimeinfo(mimeview);
594                 gtk_tree_path_free(mimeview->opened);
595                 g_free(mimeview->file);
596                 g_free(mimeview);
597                 mimeviews = g_slist_remove(mimeviews, mimeview);
598         }
599         
600 }
601
602 MimeInfo *mimeview_get_selected_part(MimeView *mimeview)
603 {
604         return gtkut_tree_view_get_selected_pointer(
605                         GTK_TREE_VIEW(mimeview->ctree), COL_DATA,
606                         NULL, NULL, NULL);
607 }
608
609 MimeInfo *mimeview_get_node_part(MimeView *mimeview, GtkTreePath *path)
610 {
611         GtkTreeModel *model = gtk_tree_view_get_model(GTK_TREE_VIEW(mimeview->ctree));
612         GtkTreeIter iter;
613         MimeInfo *partinfo;
614         
615         gtk_tree_model_get_iter(model, &iter, path);
616         gtk_tree_model_get(model, &iter, COL_DATA, &partinfo, -1);
617         return partinfo;
618 }
619
620 gboolean mimeview_tree_is_empty(MimeView *mimeview)
621 {
622         GtkTreeModel *model = gtk_tree_view_get_model(GTK_TREE_VIEW(mimeview->ctree));
623         GtkTreeIter iter;
624         return !gtk_tree_model_get_iter_first(model, &iter);
625 }
626
627 static gboolean mimeview_tree_next(GtkTreeModel *model, GtkTreePath *path)
628 {
629         GtkTreeIter iter, parent;
630         gboolean has_parent;
631         
632         gtk_tree_model_get_iter(model, &iter, path);
633         
634         if (gtk_tree_model_iter_has_child(model, &iter)) {
635                 gtk_tree_path_down(path);
636                 return TRUE;
637         }
638
639         has_parent = gtk_tree_model_iter_parent(model, &parent, &iter);
640         
641         if (!gtk_tree_model_iter_next(model, &iter)) {
642                 while (has_parent) {
643                         GtkTreeIter saved_parent = parent;
644                         gtk_tree_path_up(path);
645                         if (gtk_tree_model_iter_next(model, &parent)) {
646                                 gtk_tree_path_next(path);
647                                 return TRUE;
648                         } else {
649                                 has_parent = gtk_tree_model_iter_parent(model, &parent, &saved_parent);
650                         }
651                 }
652                 
653         } else {
654                 gtk_tree_path_next(path);
655                 return TRUE;
656         }
657
658         return FALSE;
659 }
660
661 static gboolean mimeview_tree_prev(MimeView *mimeview, GtkTreePath *path)
662 {
663         GtkTreeModel *model = gtk_tree_view_get_model(GTK_TREE_VIEW(mimeview->ctree));
664         GtkTreeIter iter, child, parent;
665         gboolean has_parent;
666
667         gtk_tree_model_get_iter(model, &iter, path);    
668         has_parent = gtk_tree_model_iter_parent(model, &parent, &iter);
669
670         if (gtk_tree_path_prev(path)) {
671                 gtk_tree_model_get_iter(model, &iter, path);
672                 
673                 if (gtk_tree_model_iter_nth_child(model, &child, &iter, 0)) {
674                         gtk_tree_path_down(path);
675                         
676                         while (gtk_tree_model_iter_next(model, &child))
677                                 gtk_tree_path_next(path);
678                 }
679                 
680                 return TRUE;
681         }
682
683         if (has_parent) {
684                 gtk_tree_path_up(path);
685                 return TRUE;
686         }
687
688         return FALSE;
689 }
690
691 gint mimeview_get_selected_part_num(MimeView *mimeview)
692 {
693         GtkTreeModel *model = gtk_tree_view_get_model(GTK_TREE_VIEW(mimeview->ctree));
694         GtkTreeIter iter;
695         GtkTreePath *path;
696         gint i = 0;
697
698         if (!gtk_tree_model_get_iter_first(model, &iter))
699                 return -1;
700         path = gtk_tree_model_get_path(model, &iter);
701         
702         do {
703                 if (!gtk_tree_path_compare(mimeview->opened, path)) {
704                         gtk_tree_path_free(path);
705                         return i;
706                 }
707
708                 i++;
709         } while (mimeview_tree_next(model, path));
710
711         gtk_tree_path_free(path);
712
713         return -1;
714 }
715
716 void mimeview_select_part_num(MimeView *mimeview, gint i)
717 {
718         GtkTreeModel *model = gtk_tree_view_get_model(GTK_TREE_VIEW(mimeview->ctree));
719         GtkTreeIter iter;
720         GtkTreePath *path;
721         GtkTreeSelection *selection;
722         gint x = 0;
723         
724         if (i < 0)
725                 return;
726         
727         if (!gtk_tree_model_get_iter_first(model, &iter))
728                 return;
729         path = gtk_tree_model_get_path(model, &iter);
730         
731         while (x != i) {
732                 if (!mimeview_tree_next(model, path)) {
733                         gtk_tree_path_free(path);
734                         return;
735                 }
736                 x++;
737         }
738         
739         selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(mimeview->ctree));
740         gtk_tree_selection_select_path(selection, path);
741         gtk_tree_path_free(path);
742 }
743
744 static void mimeview_set_multipart_tree(MimeView *mimeview,
745                                         MimeInfo *mimeinfo,
746                                         GtkTreeIter *parent)
747 {
748         GtkTreeStore *model = GTK_TREE_STORE(gtk_tree_view_get_model(
749                                         GTK_TREE_VIEW(mimeview->ctree)));
750         GtkTreeIter iter;
751         gchar *content_type, *length, *name;
752
753         cm_return_if_fail(mimeinfo != NULL);
754
755         while (mimeinfo != NULL) {
756                 if (mimeinfo->type != MIMETYPE_UNKNOWN && mimeinfo->subtype)
757                         content_type = g_strdup_printf("%s/%s",
758                                         procmime_get_media_type_str(mimeinfo->type),
759                                         mimeinfo->subtype);
760                 else
761                         content_type = g_strdup("UNKNOWN");
762
763                 length = g_strdup(to_human_readable((goffset) mimeinfo->length));
764
765                 if (prefs_common.attach_desc)
766                         name = g_strdup(get_part_description(mimeinfo));
767                 else
768                         name = g_strdup(get_part_name(mimeinfo));
769
770                 gtk_tree_store_append(model, &iter, parent);
771                 gtk_tree_store_set(model, &iter,
772                                 COL_MIMETYPE, content_type,
773                                 COL_SIZE, length,
774                                 COL_NAME, name,
775                                 COL_DATA, mimeinfo, -1);
776                 g_free(content_type);
777                 g_free(length);
778                 g_free(name);
779
780                 if (mimeinfo->node->children)
781                         mimeview_set_multipart_tree(mimeview, 
782                                 (MimeInfo *) mimeinfo->node->children->data, &iter);
783                 mimeinfo = mimeinfo->node->next != NULL ? 
784                                 (MimeInfo *) mimeinfo->node->next->data : NULL;
785         }
786 }
787
788 static const gchar *get_real_part_name(MimeInfo *partinfo)
789 {
790         const gchar *name = NULL;
791
792         name = procmime_mimeinfo_get_parameter(partinfo, "filename");
793         if (name == NULL)
794                 name = procmime_mimeinfo_get_parameter(partinfo, "name");
795
796         return name;
797 }
798
799 static const gchar *get_part_name(MimeInfo *partinfo)
800 {
801         const gchar *name;
802
803         name = get_real_part_name(partinfo);
804         if (name == NULL)
805                 name = "";
806
807         return name;
808 }
809
810 static const gchar *get_part_description(MimeInfo *partinfo)
811 {
812         if (partinfo->description)
813                 return partinfo->description;
814         else
815                 return get_part_name(partinfo);
816 }
817
818 static void mimeview_show_message_part(MimeView *mimeview, MimeInfo *partinfo)
819 {
820         FILE *fp;
821         const gchar *fname;
822
823         if (!partinfo) return;
824
825         fname = mimeview->file;
826         if (!fname) return;
827
828         if ((fp = claws_fopen(fname, "rb")) == NULL) {
829                 FILE_OP_ERROR(fname, "claws_fopen");
830                 return;
831         }
832
833         if (fseek(fp, partinfo->offset, SEEK_SET) < 0) {
834                 FILE_OP_ERROR(mimeview->file, "fseek");
835                 claws_fclose(fp);
836                 return;
837         }
838
839         mimeview_change_view_type(mimeview, MIMEVIEW_TEXT);
840         textview_show_part(mimeview->textview, partinfo, fp);
841
842         claws_fclose(fp);
843 }
844
845 static MimeViewer *get_viewer_for_content_type(MimeView *mimeview, const gchar *content_type)
846 {
847         GSList *cur;
848         MimeViewerFactory *factory = NULL;
849         MimeViewer *viewer = NULL;
850         gchar *real_contenttype = NULL, *tmp;
851
852         real_contenttype = g_utf8_strdown((gchar *)content_type, -1);
853         
854         for (cur = mimeviewer_factories; cur != NULL; cur = g_slist_next(cur)) {
855                 MimeViewerFactory *curfactory = cur->data;
856                 gint i = 0;
857
858                 while (curfactory->content_types[i] != NULL) {
859                         tmp = g_utf8_strdown(curfactory->content_types[i], -1);
860                         if (g_pattern_match_simple(tmp, real_contenttype)) {
861                                 debug_print("%s\n", curfactory->content_types[i]);
862                                 factory = curfactory;
863                                 g_free(tmp);
864                                 break;
865                         }
866                         g_free(tmp);
867                         i++;
868                 }
869                 if (factory != NULL)
870                         break;
871         }
872         g_free(real_contenttype);
873         if (factory == NULL)
874                 return NULL;
875
876         for (cur = mimeview->viewers; cur != NULL; cur = g_slist_next(cur)) {
877                 MimeViewer *curviewer = cur->data;
878                 
879                 if (curviewer->factory == factory)
880                         return curviewer;
881         }
882         viewer = factory->create_viewer();
883         gtk_container_add(GTK_CONTAINER(mimeview->mime_notebook),
884                 GTK_WIDGET(viewer->get_widget(viewer)));
885                 
886         mimeview->viewers = g_slist_append(mimeview->viewers, viewer);
887
888         return viewer;
889 }
890
891 gboolean mimeview_has_viewer_for_content_type(MimeView *mimeview, const gchar *content_type)
892 {
893         return (get_viewer_for_content_type(mimeview, content_type) != NULL);
894 }
895
896 static MimeViewer *get_viewer_for_mimeinfo(MimeView *mimeview, MimeInfo *partinfo)
897 {
898         gchar *content_type = NULL;
899         MimeViewer *viewer = NULL;
900
901         if ((partinfo->type == MIMETYPE_APPLICATION) &&
902             (!g_ascii_strcasecmp(partinfo->subtype, "octet-stream"))) {
903                 const gchar *filename;
904
905                 filename = procmime_mimeinfo_get_parameter(partinfo, "filename");
906                 if (filename == NULL)
907                         filename = procmime_mimeinfo_get_parameter(partinfo, "name");
908                 if (filename != NULL)
909                         content_type = procmime_get_mime_type(filename);
910         } else {
911                 content_type = procmime_get_content_type_str(partinfo->type, partinfo->subtype);
912         }
913
914         if (content_type != NULL) {
915                 viewer = get_viewer_for_content_type(mimeview, content_type);
916                 g_free(content_type);
917         }
918
919         return viewer;
920 }
921
922 gboolean mimeview_show_part(MimeView *mimeview, MimeInfo *partinfo)
923 {
924         MimeViewer *viewer;
925         
926         if (mimeview->messageview->partial_display_shown) {
927                 noticeview_hide(mimeview->messageview->noticeview);
928                 mimeview->messageview->partial_display_shown = FALSE;
929         }
930
931         viewer = get_viewer_for_mimeinfo(mimeview, partinfo);
932         if (viewer == NULL) {
933                 if (mimeview->mimeviewer != NULL)
934                         mimeview->mimeviewer->clear_viewer(mimeview->mimeviewer);
935                 mimeview->mimeviewer = NULL;
936                 return FALSE;
937         }
938
939         if (mimeview->mimeviewer != NULL)
940                 mimeview->mimeviewer->clear_viewer(mimeview->mimeviewer);
941
942         if (mimeview->mimeviewer != viewer)
943                 mimeview->mimeviewer = viewer;
944
945         mimeview_change_view_type(mimeview, MIMEVIEW_VIEWER);
946         viewer->mimeview = mimeview;
947         viewer->show_mimepart(viewer, mimeview->file, partinfo);
948
949         return TRUE;
950 }
951
952 static void mimeview_change_view_type(MimeView *mimeview, MimeViewType type)
953 {
954         TextView  *textview  = mimeview->textview;
955         GtkWidget *focused = NULL;
956         
957         if (mainwindow_get_mainwindow())
958                 focused = gtkut_get_focused_child(
959                                 GTK_CONTAINER(mainwindow_get_mainwindow()->window));
960
961         if ((mimeview->type != MIMEVIEW_VIEWER) && 
962             (mimeview->type == type)) return;
963
964         switch (type) {
965         case MIMEVIEW_TEXT:
966                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mimeview->mime_notebook),
967                         gtk_notebook_page_num(GTK_NOTEBOOK(mimeview->mime_notebook), 
968                         GTK_WIDGET_PTR(textview)));
969                 break;
970         case MIMEVIEW_VIEWER:
971                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mimeview->mime_notebook),
972                         gtk_notebook_page_num(GTK_NOTEBOOK(mimeview->mime_notebook), 
973                         GTK_WIDGET(mimeview->mimeviewer->get_widget(mimeview->mimeviewer))));
974                 break;
975         default:
976                 return;
977         }
978         if (focused)
979                 gtk_widget_grab_focus(focused);
980         mimeview->type = type;
981 }
982
983 void mimeview_clear(MimeView *mimeview)
984 {
985         GtkTreeModel *model;
986         
987         if (!mimeview)
988                 return;
989
990         if (g_slist_find(mimeviews, mimeview) == NULL)
991                 return;
992         
993         noticeview_hide(mimeview->siginfoview);
994
995         model = gtk_tree_view_get_model(GTK_TREE_VIEW(mimeview->ctree));
996         gtk_tree_store_clear(GTK_TREE_STORE(model));
997
998         textview_clear(mimeview->textview);
999         if (mimeview->mimeviewer != NULL)
1000                 mimeview->mimeviewer->clear_viewer(mimeview->mimeviewer);
1001
1002         mimeview_free_mimeinfo(mimeview);
1003
1004         mimeview->mimeinfo = NULL;
1005
1006         gtk_tree_path_free(mimeview->opened);
1007         mimeview->opened = NULL;
1008
1009         g_free(mimeview->file);
1010         mimeview->file = NULL;
1011
1012         icon_list_clear(mimeview);
1013         mimeview_change_view_type(mimeview, MIMEVIEW_TEXT);
1014 }
1015
1016 gchar * get_message_check_signature_shortcut(MessageView *messageview) {
1017         GtkUIManager *ui_manager;
1018
1019         if (messageview->window != NULL)
1020                         ui_manager = messageview->ui_manager;
1021                 else
1022                         ui_manager = messageview->mainwin->ui_manager;
1023
1024         return cm_menu_item_get_shortcut(ui_manager, "Menu/Message/CheckSignature");
1025 }
1026
1027 static void check_signature_cb(GtkWidget *widget, gpointer user_data);
1028 static void display_full_info_cb(GtkWidget *widget, gpointer user_data);
1029
1030 static void update_signature_noticeview(MimeView *mimeview, MimeInfo *mimeinfo, 
1031                                         gboolean special, SignatureStatus code)
1032 {
1033         gchar *text = NULL, *button_text = NULL;
1034         void  *func = NULL;
1035         StockPixmap icon = STOCK_PIXMAP_PRIVACY_SIGNED;
1036         SignatureStatus mycode = SIGNATURE_UNCHECKED;
1037         
1038         cm_return_if_fail(mimeview != NULL);
1039         cm_return_if_fail(mimeinfo != NULL);
1040         
1041         if (special)
1042                 mycode = code;
1043         else 
1044                 mycode = privacy_mimeinfo_get_sig_status(mimeinfo);
1045
1046         switch (mycode) {
1047         case SIGNATURE_UNCHECKED:
1048                 button_text = _("Check signature");
1049                 func = check_signature_cb;
1050                 icon = STOCK_PIXMAP_PRIVACY_SIGNED;
1051                 break;
1052         case SIGNATURE_OK:
1053                 button_text = _("View full information");
1054                 func = display_full_info_cb;
1055                 icon = STOCK_PIXMAP_PRIVACY_PASSED;
1056                 break;
1057         case SIGNATURE_WARN:
1058                 button_text = _("View full information");
1059                 func = display_full_info_cb;
1060                 icon = STOCK_PIXMAP_PRIVACY_WARN;
1061                 break;
1062         case SIGNATURE_KEY_EXPIRED:
1063                 button_text = _("View full information");
1064                 func = display_full_info_cb;
1065                 icon = STOCK_PIXMAP_PRIVACY_EXPIRED;
1066                 break;
1067         case SIGNATURE_INVALID:
1068                 button_text = _("View full information");
1069                 func = display_full_info_cb;
1070                 icon = STOCK_PIXMAP_PRIVACY_FAILED;
1071                 break;
1072         case SIGNATURE_CHECK_FAILED:
1073         case SIGNATURE_CHECK_TIMEOUT:
1074                 button_text = _("Check again");
1075                 func = check_signature_cb;
1076                 icon = STOCK_PIXMAP_PRIVACY_UNKNOWN;
1077                 break;
1078         default:
1079                 break;
1080         }
1081         if (mycode == SIGNATURE_UNCHECKED) {
1082                 gchar *tmp = privacy_mimeinfo_sig_info_short(mimeinfo);
1083                 gchar *shortcut = get_message_check_signature_shortcut(mimeview->messageview);
1084
1085                 if (*shortcut == '\0')
1086                         text = g_strdup_printf(_("%s Click the icon to check it."), tmp);
1087                 else
1088                         text = g_strdup_printf(_("%s Click the icon or hit '%s' to check it."),
1089                                 tmp, shortcut);
1090                 g_free(tmp);
1091                 g_free(shortcut);
1092         } else if (mycode != SIGNATURE_CHECK_TIMEOUT) {
1093                 text = privacy_mimeinfo_sig_info_short(mimeinfo);
1094         } else if (mycode == SIGNATURE_CHECK_TIMEOUT) {
1095                 gchar *shortcut = get_message_check_signature_shortcut(mimeview->messageview);
1096
1097                 if (*shortcut == '\0')
1098                         text = g_strdup(_("Timeout checking the signature. Click the icon to try again."));
1099                 else
1100                         text = g_strdup_printf(_("Timeout checking the signature. Click the icon or hit '%s' to try again."), shortcut);
1101                 g_free(shortcut);
1102         }
1103
1104         noticeview_set_text(mimeview->siginfoview, text);
1105         gtk_label_set_selectable(GTK_LABEL(mimeview->siginfoview->text), TRUE);
1106
1107         g_free(text);
1108         noticeview_set_button_text(mimeview->siginfoview, NULL);
1109         noticeview_set_button_press_callback(
1110                 mimeview->siginfoview,
1111                 G_CALLBACK(func),
1112                 (gpointer) mimeview);
1113         noticeview_set_icon(mimeview->siginfoview, icon);
1114         noticeview_set_tooltip(mimeview->siginfoview, button_text);
1115
1116         icon_list_clear(mimeview);
1117         icon_list_create(mimeview, mimeview->mimeinfo);
1118 }
1119
1120 #ifdef USE_PTHREAD
1121
1122 /* reset all thread stuff, and do the cleanups we've been left to do */
1123 static void mimeview_check_data_reset(MimeView *mimeview)
1124 {
1125         gboolean must_free;
1126         gboolean must_destroy;
1127
1128         if (!mimeview->check_data)
1129                 return;
1130
1131         must_free = mimeview->check_data->free_after_use;
1132         must_destroy = mimeview->check_data->destroy_mimeview;
1133         
1134         if (mimeview->check_data->cancel_th_init) {
1135                 debug_print("killing canceller thread\n");
1136                 mimeview->check_data->cancel_th_init = FALSE;
1137                 pthread_cancel(mimeview->check_data->cancel_th);
1138         }
1139
1140         if (must_free) {
1141                 debug_print("freeing deferred mimeinfo\n");
1142                 procmime_mimeinfo_free_all(&mimeview->check_data->siginfo);
1143         }
1144
1145         g_free(mimeview->check_data);
1146         mimeview->check_data = NULL;
1147
1148         if (must_destroy) {
1149                 debug_print("freeing deferred mimeview\n");
1150                 mimeview_free_mimeinfo(mimeview);
1151                 gtk_tree_path_free(mimeview->opened);
1152                 g_free(mimeview->file);
1153                 g_free(mimeview);
1154                 mimeviews = g_slist_remove(mimeviews, mimeview);
1155         }
1156 }
1157
1158 /* GUI update once the checker thread is done or killed */
1159 static gboolean mimeview_check_sig_thread_cb(void *data)
1160 {
1161         MimeView *mimeview = (MimeView *) data;
1162         MimeInfo *mimeinfo = mimeview->siginfo;
1163
1164         debug_print("mimeview_check_sig_thread_cb\n");
1165         
1166         if (mimeinfo == NULL) {
1167                 /* message changed !? */
1168                 g_warning("no more siginfo!");
1169                 goto end;
1170         }
1171         
1172         if (!mimeview->check_data) {
1173                 g_warning("nothing to check");
1174                 return FALSE;
1175         }
1176
1177         if (mimeview->check_data->siginfo != mimeinfo) {
1178                 /* message changed !? */
1179                 g_warning("different siginfo!");
1180                 goto end;
1181         }
1182
1183         if (mimeview->check_data->destroy_mimeview ||
1184             mimeview->check_data->free_after_use) {
1185                 debug_print("not bothering, we're changing message\n"); 
1186                 goto end;
1187         }
1188         
1189         /* update status */
1190         if (mimeview->check_data->timeout) 
1191                 update_signature_noticeview(mimeview, mimeview->siginfo, 
1192                         TRUE, SIGNATURE_CHECK_TIMEOUT);
1193         else
1194                 update_signature_noticeview(mimeview, mimeview->siginfo, 
1195                         FALSE, 0);
1196
1197 end:
1198         mimeview_check_data_reset(mimeview);
1199         return FALSE;
1200 }
1201
1202 /* sig checker thread */
1203 static void *mimeview_check_sig_worker_thread(void *data)
1204 {
1205         MimeView *mimeview = (MimeView *)data;
1206         MimeInfo *mimeinfo = mimeview->siginfo;
1207         
1208         debug_print("checking...\n");
1209
1210         if (!mimeview->check_data)
1211                 return NULL;
1212
1213         if (mimeinfo && mimeinfo == mimeview->check_data->siginfo) {
1214                 privacy_mimeinfo_check_signature(mimeinfo);
1215                 if (mimeview->check_data && mimeview->check_data->cancel_th_init) {
1216                         mimeview->check_data->cancel_th_init = FALSE;
1217                         pthread_cancel(mimeview->check_data->cancel_th);
1218                 }
1219         } else {
1220                 /* that's strange! we changed message without 
1221                  * getting killed. */
1222                 g_warning("different siginfo!");
1223                 mimeview_check_data_reset(mimeview);
1224                 return NULL;
1225         }
1226
1227         /* use g_timeout so that GUI updates is done from the
1228          * correct thread */
1229         g_timeout_add(0,mimeview_check_sig_thread_cb,mimeview);
1230         
1231         return NULL;
1232 }
1233
1234 /* killer thread - acts when the checker didn't work fast
1235  * enough. */
1236 static void *mimeview_check_sig_cancel_thread(void *data)
1237 {
1238         MimeView *mimeview = (MimeView *)data;
1239         
1240         if (!mimeview->check_data)
1241                 return NULL; /* nothing to kill ! */
1242
1243         /* wait for a few seconds... */
1244         debug_print("waiting a while\n");
1245
1246         g_usleep(5 * 1000 * 1000);
1247         
1248         if (!mimeview->check_data)
1249                 return NULL; /* nothing to kill, it's done in time :) */
1250         
1251         /* too late, go away checker thread */
1252         debug_print("killing checker thread\n");
1253         if (mimeview->check_data->th_init) {
1254                 mimeview->check_data->th_init = FALSE;
1255                 pthread_cancel(mimeview->check_data->th);
1256         }
1257
1258         /* tell upstream it was a timeout */
1259         mimeview->check_data->timeout = TRUE;
1260         /* use g_timeout so that GUI updates is done from the
1261          * correct thread */
1262         g_timeout_add(0,mimeview_check_sig_thread_cb,mimeview);
1263
1264         return NULL;
1265 }
1266
1267 /* get rid of the checker thread right now - used when changing the
1268  * displayed message for example. */
1269 static void mimeview_check_sig_cancel_now(MimeView *mimeview)
1270 {
1271         if (!mimeview->check_data)
1272                 return;
1273         debug_print("killing checker thread NOW\n");
1274         if (mimeview->check_data->th_init) {
1275                 mimeview->check_data->th_init = FALSE;
1276                 pthread_cancel(mimeview->check_data->th);
1277         }
1278
1279         /* tell upstream it was a timeout */
1280         mimeview->check_data->timeout = TRUE;
1281         mimeview_check_sig_thread_cb(mimeview);
1282         return;
1283 }
1284
1285 /* creates a thread to check the signature, and a second one
1286  * to kill the first one after a timeout */
1287 static void mimeview_check_sig_in_thread(MimeView *mimeview)
1288 {
1289         pthread_t th, th2;
1290         pthread_attr_t detach, detach2;
1291         
1292         if (mimeview->check_data) {
1293                 g_warning("already checking it");
1294                 return;
1295         }
1296         
1297         mimeview->check_data = g_new0(SigCheckData, 1);
1298         mimeview->check_data->siginfo = mimeview->siginfo;
1299         debug_print("creating thread\n");
1300
1301         /* init thread attributes and create the checker thread */
1302         if (pthread_attr_init(&detach) != 0 ||
1303             pthread_attr_setdetachstate(&detach, PTHREAD_CREATE_DETACHED) != 0 ||
1304             pthread_attr_init(&detach2) != 0 ||
1305             pthread_attr_setdetachstate(&detach2, PTHREAD_CREATE_DETACHED) != 0 ||
1306             pthread_create(&th, &detach, 
1307                         mimeview_check_sig_worker_thread, 
1308                         mimeview) != 0) {
1309                 /* arh. We'll do it synchronously. */
1310                 g_warning("can't create checked thread");
1311                 g_free(mimeview->check_data);
1312                 mimeview->check_data = NULL;
1313                 return;
1314         } else {
1315                 mimeview->check_data->th = th;
1316                 mimeview->check_data->th_init = TRUE;
1317         }
1318
1319         /* create the killer thread */
1320         if (pthread_create(&th2, &detach2, 
1321                         mimeview_check_sig_cancel_thread, 
1322                         mimeview) != 0) {
1323                 g_warning("can't create killer thread");
1324                 g_free(mimeview->check_data);
1325                 mimeview->check_data = NULL;
1326                 return;
1327         } else {
1328                 mimeview->check_data->cancel_th = th2;
1329                 mimeview->check_data->cancel_th_init = TRUE;
1330         }
1331 }
1332 #endif
1333
1334 static void check_signature_cb(GtkWidget *widget, gpointer user_data)
1335 {
1336         MimeView *mimeview = (MimeView *) user_data;
1337         MimeInfo *mimeinfo = mimeview->siginfo;
1338         
1339         if (mimeinfo == NULL)
1340                 return;
1341 #ifdef USE_PTHREAD
1342         if (mimeview->check_data)
1343                 return;
1344 #endif
1345         noticeview_set_text(mimeview->siginfoview, _("Checking signature..."));
1346         GTK_EVENTS_FLUSH();
1347 #ifdef USE_PTHREAD
1348         /* let's do it non-blocking */
1349         mimeview_check_sig_in_thread(mimeview);
1350         if (!mimeview->check_data) /* let's check syncronously */
1351 #endif
1352         {
1353                 debug_print("checking without thread\n");
1354                 privacy_mimeinfo_check_signature(mimeinfo);
1355                 update_signature_noticeview(mimeview, mimeview->siginfo, FALSE, 0);
1356         }
1357 }
1358
1359 void mimeview_check_signature(MimeView *mimeview)
1360 {
1361         check_signature_cb(NULL, mimeview);     
1362 }
1363
1364 static void redisplay_email(GtkWidget *widget, gpointer user_data)
1365 {
1366         MimeView *mimeview = (MimeView *) user_data;
1367         gtk_tree_path_free(mimeview->opened);
1368         mimeview->opened = NULL;
1369         mimeview_selected(gtk_tree_view_get_selection(
1370                         GTK_TREE_VIEW(mimeview->ctree)), mimeview);
1371 }
1372
1373 static void display_full_info_cb(GtkWidget *widget, gpointer user_data)
1374 {
1375         MimeView *mimeview = (MimeView *) user_data;
1376         gchar *siginfo;
1377
1378         siginfo = privacy_mimeinfo_sig_info_full(mimeview->siginfo);
1379         textview_set_text(mimeview->textview, siginfo);
1380         g_free(siginfo);
1381         noticeview_set_button_text(mimeview->siginfoview, NULL);
1382         noticeview_set_button_press_callback(
1383                 mimeview->siginfoview,
1384                 G_CALLBACK(redisplay_email),
1385                 (gpointer) mimeview);
1386         noticeview_set_tooltip(mimeview->siginfoview, _("Go back to email"));
1387 }
1388
1389 static void update_signature_info(MimeView *mimeview, MimeInfo *selected)
1390 {
1391         MimeInfo *siginfo;
1392         MimeInfo *first_text;
1393         
1394         cm_return_if_fail(mimeview != NULL);
1395         cm_return_if_fail(selected != NULL);
1396         
1397         if (selected->type == MIMETYPE_MESSAGE 
1398         &&  !g_ascii_strcasecmp(selected->subtype, "rfc822")) {
1399                 /* if the first text part is signed, check that */
1400                 first_text = selected;
1401                 while (first_text && first_text->type != MIMETYPE_TEXT) {
1402                         first_text = procmime_mimeinfo_next(first_text);
1403                 }
1404                 if (first_text) {
1405                         update_signature_info(mimeview, first_text);
1406                         return;
1407                 }       
1408         }
1409
1410         siginfo = selected;
1411         while (siginfo != NULL) {
1412                 if (privacy_mimeinfo_is_signed(siginfo))
1413                         break;
1414                 siginfo = procmime_mimeinfo_parent(siginfo);
1415         }
1416         mimeview->siginfo = siginfo;
1417
1418         /* This shortcut boolean is there to correctly set the menu's
1419          * CheckSignature item sensitivity without killing performance
1420          * each time the menu sensitiveness is updated (a lot).
1421          */
1422         mimeview->signed_part = (siginfo != NULL);
1423
1424         if (siginfo == NULL) {
1425                 noticeview_hide(mimeview->siginfoview);
1426                 return;
1427         }
1428         
1429         update_signature_noticeview(mimeview, siginfo, FALSE, 0);
1430         noticeview_show(mimeview->siginfoview);
1431 }
1432
1433 void mimeview_show_part_as_text(MimeView *mimeview, MimeInfo *partinfo)
1434 {
1435         cm_return_if_fail(mimeview != NULL);
1436         cm_return_if_fail(partinfo != NULL);
1437
1438         mimeview_show_message_part(mimeview, partinfo);
1439 }
1440
1441 static void mimeview_selected(GtkTreeSelection *selection, MimeView *mimeview)
1442 {
1443         GtkTreeView *ctree = GTK_TREE_VIEW(mimeview->ctree);
1444         GtkTreeModel *model;
1445         GtkTreeIter iter;
1446         GtkTreePath *path;
1447         MimeInfo *partinfo;
1448         MainWindow *mainwin;
1449
1450         selection = gtk_tree_view_get_selection(ctree);
1451         if (!gtk_tree_selection_get_selected(selection, &model, &iter))
1452                 return;
1453
1454         path = gtk_tree_model_get_path(model, &iter);
1455
1456         if (mimeview->opened && !gtk_tree_path_compare(mimeview->opened, path)) {
1457                 gtk_tree_path_free(path);
1458                 return;
1459         }
1460         
1461         gtk_tree_path_free(mimeview->opened);
1462         mimeview->opened = path;
1463         mimeview->spec_part = NULL;
1464         gtk_tree_view_scroll_to_cell(ctree, path, NULL, TRUE, 0.5, 0);
1465
1466         partinfo = mimeview_get_node_part(mimeview, path);
1467         if (!partinfo) return;
1468
1469         /* ungrab the mouse event */
1470         if (gtk_widget_has_grab(GTK_WIDGET(ctree))) {
1471                 gtk_grab_remove(GTK_WIDGET(ctree));
1472                 if (gdk_pointer_is_grabbed())
1473                         gdk_pointer_ungrab(GDK_CURRENT_TIME);
1474         }
1475         
1476         mimeview->textview->default_text = FALSE;
1477
1478         update_signature_info(mimeview, partinfo);
1479
1480         if (!mimeview_show_part(mimeview, partinfo)) {
1481                 switch (partinfo->type) {
1482                 case MIMETYPE_TEXT:
1483                 case MIMETYPE_MESSAGE:
1484                 case MIMETYPE_MULTIPART:
1485                         mimeview_show_message_part(mimeview, partinfo);
1486                 
1487                         break;
1488                 default:
1489                         mimeview->textview->default_text = TRUE;
1490                         mimeview_change_view_type(mimeview, MIMEVIEW_TEXT);
1491                         textview_clear(mimeview->textview);
1492                         textview_show_mime_part(mimeview->textview, partinfo);
1493                         break;
1494                 }
1495         }
1496         mainwin = mainwindow_get_mainwindow();
1497         if (mainwin)
1498                 main_window_set_menu_sensitive(mainwin);
1499
1500         if (mimeview->siginfo && privacy_auto_check_signatures(mimeview->siginfo)
1501         &&  privacy_mimeinfo_get_sig_status(mimeview->siginfo) == SIGNATURE_UNCHECKED) {
1502                 mimeview_check_signature(mimeview);
1503         }
1504 }
1505
1506 static gint mimeview_button_pressed(GtkWidget *widget, GdkEventButton *event,
1507                                     MimeView *mimeview)
1508 {
1509         GtkTreeSelection *selection;
1510         GtkTreeIter iter;
1511
1512         if (!event) return FALSE;
1513
1514         if (event->button == 2 || event->button == 3) {
1515                 selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(widget));
1516                 if (!gtk_tree_selection_get_selected(selection, NULL, &iter))
1517                         return FALSE;
1518                 
1519                 gtk_tree_selection_select_iter(selection, &iter);
1520         }
1521         part_button_pressed(mimeview, event, mimeview_get_selected_part(mimeview));
1522
1523         return FALSE;
1524 }
1525
1526 static gboolean mimeview_scrolled(GtkWidget *widget, GdkEventScroll *event,
1527                                     MimeView *mimeview)
1528 {
1529         GtkVScrollbutton *scrollbutton = (GtkVScrollbutton *)mimeview->scrollbutton;
1530         if (event->direction == GDK_SCROLL_UP) {
1531                 scrollbutton->scroll_type = GTK_SCROLL_STEP_BACKWARD;
1532         } else {
1533                 scrollbutton->scroll_type = GTK_SCROLL_STEP_FORWARD;
1534         }
1535         gtk_vscrollbutton_scroll(scrollbutton);
1536         return TRUE;
1537 }
1538
1539 static gboolean part_button_pressed(MimeView *mimeview, GdkEventButton *event, 
1540                                     MimeInfo *partinfo)
1541 {
1542         static MimeInfo *lastinfo;
1543         static guint32 lasttime;
1544
1545         gint double_click_time;
1546         g_object_get(gtk_settings_get_default(), "gtk-double-click-time", &double_click_time, NULL);
1547
1548         if (event->button == 2 ||
1549             (event->button == 1 && (event->time - lasttime) < double_click_time && lastinfo == partinfo)) {
1550                 /* call external program for image, audio or html */
1551                 mimeview_launch(mimeview, partinfo);
1552                 return TRUE;
1553         } else if (event->button == 3) {
1554                 MainWindow *mainwin = mainwindow_get_mainwindow();
1555
1556                 if (partinfo && (partinfo->type == MIMETYPE_MESSAGE ||
1557                                  partinfo->type == MIMETYPE_IMAGE ||
1558                                  partinfo->type == MIMETYPE_MULTIPART))
1559                         cm_menu_set_sensitive_full(mimeview->ui_manager, "Menus/MimeView/DisplayAsText", FALSE);
1560                 else
1561                         cm_menu_set_sensitive_full(mimeview->ui_manager, "Menus/MimeView/DisplayAsText", TRUE);
1562
1563                 if (partinfo && (partinfo->type == MIMETYPE_MESSAGE ||
1564                                  partinfo->type == MIMETYPE_IMAGE ||
1565                                  partinfo->type == MIMETYPE_TEXT))
1566                         cm_menu_set_sensitive_full(mimeview->ui_manager, "Menus/MimeView/Copy", TRUE);
1567                 else
1568                         cm_menu_set_sensitive_full(mimeview->ui_manager, "Menus/MimeView/Copy", FALSE);
1569 #ifndef G_OS_WIN32
1570                 if (partinfo &&
1571                     partinfo->type == MIMETYPE_APPLICATION &&
1572                     !g_ascii_strcasecmp(partinfo->subtype, "octet-stream"))
1573                         cm_menu_set_sensitive_full(mimeview->ui_manager, "Menus/MimeView/Open", FALSE);
1574                 else
1575 #endif
1576                         cm_menu_set_sensitive_full(mimeview->ui_manager, "Menus/MimeView/Open", TRUE);
1577                 if (mainwin)
1578                         main_window_set_menu_sensitive(mainwin);
1579                 g_object_set_data(G_OBJECT(mimeview->popupmenu),
1580                                   "pop_partinfo", partinfo);
1581                                     
1582                 gtk_menu_popup(GTK_MENU(mimeview->popupmenu),
1583                                NULL, NULL, NULL, NULL,
1584                                event->button, event->time);
1585                 return TRUE;
1586         }
1587
1588         lastinfo = partinfo;
1589         lasttime = event->time;
1590         return FALSE;
1591 }
1592
1593
1594 gboolean mimeview_pass_key_press_event(MimeView *mimeview, GdkEventKey *event)
1595 {
1596         return mimeview_key_pressed(mimeview->ctree, event, mimeview);
1597 }
1598
1599 void mimeview_select_next_part(MimeView *mimeview)
1600 {
1601         GtkTreeView *ctree = GTK_TREE_VIEW(mimeview->ctree);
1602         GtkTreeModel *model = gtk_tree_view_get_model(ctree);
1603         GtkTreeSelection *selection;
1604         GtkTreeIter iter;
1605         GtkTreePath *path;
1606         MimeInfo *partinfo = NULL;
1607         gboolean has_next;
1608         
1609         if (!mimeview->opened) return;
1610
1611         gtk_tree_model_get_iter(model, &iter, mimeview->opened);
1612         path = gtk_tree_model_get_path(model, &iter);
1613 skip:
1614         has_next = mimeview_tree_next(model, path);
1615         if (!has_next) {
1616                 has_next = gtk_tree_model_get_iter_first(model, &iter);
1617                 gtk_tree_path_free(path);
1618                 path = gtk_tree_model_get_path(model, &iter);
1619         }
1620
1621         if (has_next) {
1622                 partinfo = mimeview_get_node_part(mimeview, path);
1623                 if (partinfo->type == MIMETYPE_MULTIPART ||
1624                     (!prefs_common.show_inline_attachments && partinfo->id))
1625                         goto skip;
1626                 selection = gtk_tree_view_get_selection(ctree);
1627                 gtk_tree_selection_select_path(selection, path);
1628                 icon_list_toggle_by_mime_info(mimeview, partinfo);
1629         }
1630         
1631         gtk_tree_path_free(path);
1632 }
1633
1634 void mimeview_select_prev_part(MimeView *mimeview)
1635 {
1636         GtkTreeView *ctree = GTK_TREE_VIEW(mimeview->ctree);
1637         GtkTreeModel *model = gtk_tree_view_get_model(ctree);
1638         GtkTreeSelection *selection;
1639         GtkTreeIter iter;
1640         GtkTreePath *path;
1641         MimeInfo *partinfo = NULL;
1642         gboolean has_prev;
1643         
1644         if (!mimeview->opened) return;
1645
1646         gtk_tree_model_get_iter(model, &iter, mimeview->opened);
1647         path = gtk_tree_model_get_path(model, &iter);
1648 skip:
1649         has_prev = mimeview_tree_prev(mimeview, path);
1650         if (!has_prev) {
1651                 while (mimeview_tree_next(model, path)) {}
1652                 has_prev = TRUE;
1653         }
1654
1655         if (has_prev) {
1656                 partinfo = mimeview_get_node_part(mimeview, path);
1657                 if (partinfo->type == MIMETYPE_MULTIPART ||
1658                     (!prefs_common.show_inline_attachments && partinfo->id))
1659                         goto skip;
1660                 selection = gtk_tree_view_get_selection(ctree);
1661                 gtk_tree_selection_select_path(selection, path);
1662                 icon_list_toggle_by_mime_info(mimeview, partinfo);
1663         }
1664         
1665         gtk_tree_path_free(path);
1666 }
1667
1668 #define BREAK_ON_MODIFIER_KEY() \
1669         if ((event->state & (GDK_MOD1_MASK|GDK_CONTROL_MASK)) != 0) break
1670
1671 static gint mimeview_key_pressed(GtkWidget *widget, GdkEventKey *event,
1672                                  MimeView *mimeview)
1673 {
1674         SummaryView *summaryview;
1675
1676         if (!event) return FALSE;
1677         if (!mimeview->opened) return FALSE;
1678
1679         summaryview = mimeview->messageview->mainwin->summaryview;
1680         
1681         if (summaryview && quicksearch_has_focus(summaryview->quicksearch))
1682                 return FALSE;
1683                 
1684         switch (event->keyval) {
1685         case GDK_KEY_Home:
1686         case GDK_KEY_End:
1687                 textview_scroll_max(mimeview->textview,
1688                                     (event->keyval == GDK_KEY_Home));
1689                 return TRUE;
1690         case GDK_KEY_Page_Down:
1691         case GDK_KEY_space:
1692                 if (mimeview_scroll_page(mimeview,
1693                                          (event->state & GDK_SHIFT_MASK) != 0))
1694                         return TRUE;
1695                         
1696                 if (!(event->state & GDK_SHIFT_MASK))
1697                         mimeview_select_next_part(mimeview);
1698                 return TRUE;
1699         case GDK_KEY_Page_Up:
1700         case GDK_KEY_BackSpace:
1701                 mimeview_scroll_page(mimeview, TRUE);
1702                 return TRUE;
1703         case GDK_KEY_Return:
1704         case GDK_KEY_KP_Enter:
1705                 mimeview_scroll_one_line(mimeview,
1706                                          (event->state & GDK_MOD1_MASK) != 0);
1707                 return TRUE;
1708         case GDK_KEY_Up:
1709         case GDK_KEY_Down:
1710                 mimeview_scroll_one_line(mimeview, (event->keyval == GDK_KEY_Up));
1711                 return TRUE;
1712         default:
1713                 break;
1714         }
1715
1716         if (mimeview->messageview->new_window) return FALSE;
1717
1718         return summary_pass_key_press_event(summaryview, event);
1719 }
1720
1721 static void mimeview_drag_data_get(GtkWidget        *widget,
1722                                    GdkDragContext   *drag_context,
1723                                    GtkSelectionData *selection_data,
1724                                    guint             info,
1725                                    guint             time,
1726                                    MimeView         *mimeview)
1727 {
1728         gchar *filename = NULL, *uriname, *tmp;
1729         MimeInfo *partinfo;
1730         gint err;
1731         gint count = 0;
1732
1733         if (!mimeview->opened) return;
1734         if (!mimeview->file) return;
1735
1736         partinfo = mimeview_get_selected_part(mimeview);
1737         if (!partinfo) return;
1738
1739         if (strlen(get_part_name(partinfo)) > 0) {
1740                 filename = g_path_get_basename(get_part_name(partinfo));
1741                 if (*filename == '\0') return;
1742         } else if (partinfo->type == MIMETYPE_MESSAGE 
1743                    && !g_ascii_strcasecmp(partinfo->subtype, "rfc822")) {
1744                 gchar *name = NULL;
1745                 GPtrArray *headers = NULL;
1746                 FILE *fp;
1747
1748                 fp = claws_fopen(partinfo->data.filename, "rb");
1749                 if (fp != NULL && fseek(fp, partinfo->offset, SEEK_SET) == 0) {
1750                         headers = procheader_get_header_array_asis(fp);
1751                         if (headers) {
1752                                 gint i;
1753                                 for (i = 0; i < headers->len; i++) {
1754                                         Header *header = g_ptr_array_index(headers, i);
1755                                         if (procheader_headername_equal(header->name, "Subject")) {
1756                                                 unfold_line(header->body);
1757                                                 name = g_strconcat(header->body, ".txt", NULL);
1758                                                 subst_for_filename(name);
1759                                         }
1760                                 }
1761                                 procheader_header_array_destroy(headers);
1762                         }
1763                 }
1764                 if (fp != NULL)
1765                         claws_fclose(fp);
1766                 if (name)
1767                         filename = g_path_get_basename(name);
1768                 g_free(name);
1769         }
1770         if (filename == NULL)
1771                 filename = g_path_get_basename("Unnamed part");
1772
1773         if (!g_utf8_validate(filename, -1, NULL))
1774                 tmp = conv_codeset_strdup(filename,
1775                                 conv_get_locale_charset_str(),
1776                                 CS_UTF_8);
1777         else
1778                 tmp = g_strdup(filename);
1779
1780         if (tmp == NULL) {
1781                 g_warning("filename not in UTF-8");
1782                 tmp = g_strdup("Unnamed part");
1783         }
1784         filename = g_strconcat(get_mime_tmp_dir(), G_DIR_SEPARATOR_S,
1785                                tmp, NULL);
1786
1787 check_new_file:
1788         if (is_file_exist(filename)) {
1789                 gchar *ext = NULL;
1790                 gchar *prefix = NULL;
1791                 gchar *new_name = NULL;
1792                 if (strrchr(tmp, '.')) {
1793                         prefix = g_strdup(tmp);
1794                         ext = g_strdup(strrchr(tmp, '.'));
1795                         *(strrchr(prefix, '.')) = '\0';
1796                 } else {
1797                         prefix = g_strdup(tmp);
1798                         ext = g_strdup("");
1799                 }
1800                 count++;
1801                 new_name = g_strdup_printf("%s.%d%s", prefix, count, ext);
1802                 g_free(prefix);
1803                 g_free(ext);
1804                 g_free(filename);
1805                 filename = g_strconcat(get_mime_tmp_dir(), G_DIR_SEPARATOR_S,
1806                                new_name, NULL);
1807                 g_free(new_name);
1808                 goto check_new_file;
1809         }
1810
1811         g_free(tmp);
1812
1813         if ((err = procmime_get_part(filename, partinfo)) < 0)
1814                 alertpanel_error
1815                         (_("Couldn't save the part of multipart message: %s"), 
1816                                 g_strerror(-err));
1817
1818         tmp = g_filename_to_uri(filename, NULL, NULL);
1819         uriname = g_strconcat(tmp, "\r\n", NULL);
1820         g_free(tmp);
1821
1822         gtk_selection_data_set(selection_data, 
1823                    gtk_selection_data_get_target(selection_data), 8,
1824                                (guchar *)uriname, strlen(uriname));
1825
1826         g_free(uriname);
1827         g_free(filename);
1828 }
1829
1830 /**
1831  * Returns a filename (with path) for an attachment
1832  * \param partinfo The attachment to save
1833  * \param basedir The target directory
1834  * \param number Used for dummy filename if attachment is unnamed
1835  */
1836 static gchar *mimeview_get_filename_for_part(MimeInfo *partinfo,
1837                                       const gchar *basedir,
1838                                       gint number)
1839 {
1840         gchar *fullname;
1841         gchar *filename;
1842
1843         filename = g_strdup(get_part_name(partinfo));
1844         if (!filename || !*filename) {
1845                 g_free(filename);
1846                 filename = g_strdup_printf("noname.%d", number);
1847         }
1848
1849         if (!g_utf8_validate(filename, -1, NULL)) {
1850                 gchar *tmp = conv_filename_to_utf8(filename);
1851                 g_free(filename);
1852                 filename = tmp;
1853         }
1854         
1855         subst_for_filename(filename);
1856
1857         fullname = g_strconcat
1858                 (basedir, G_DIR_SEPARATOR_S, (g_path_is_absolute(filename))
1859                  ? &filename[1] : filename, NULL);
1860
1861         g_free(filename);
1862         filename = conv_filename_from_utf8(fullname);
1863         g_free(fullname);
1864         return filename;
1865 }
1866
1867 /**
1868  * Write a single attachment to file
1869  * \param filename Filename with path
1870  * \param partinfo Attachment to save
1871  */
1872 static gboolean mimeview_write_part(const gchar *filename,
1873                                     MimeInfo *partinfo,
1874                                     gboolean handle_error)
1875 {
1876         gchar *dir;
1877         gint err;
1878
1879         dir= g_path_get_dirname(filename);
1880         if (!is_dir_exist(dir))
1881                 make_dir_hier(dir);
1882         g_free(dir);
1883
1884         if (is_file_exist(filename)) {
1885                 AlertValue aval;
1886                 gchar *res;
1887                 gchar *tmp;
1888                 
1889                 if (!g_utf8_validate(filename, -1, NULL))
1890                         tmp = conv_filename_to_utf8(filename);
1891                 else 
1892                         tmp = g_strdup(filename);
1893                 
1894                 res = g_strdup_printf(_("Overwrite existing file '%s'?"),
1895                                       tmp);
1896                 g_free(tmp);
1897                 aval = alertpanel(_("Overwrite"), res, GTK_STOCK_CANCEL,
1898                                   GTK_STOCK_OK, NULL, ALERTFOCUS_FIRST);
1899                 g_free(res);
1900                 if (G_ALERTALTERNATE != aval) return FALSE;
1901         }
1902
1903         if ((err = procmime_get_part(filename, partinfo)) < 0) {
1904                 debug_print("error saving MIME part: %d\n", err);
1905                 if (handle_error)
1906                         alertpanel_error
1907                                 (_("Couldn't save the part of multipart message: %s"),
1908                                  g_strerror(-err));
1909                 return FALSE;
1910         }
1911
1912         return TRUE;
1913 }
1914
1915 static AlertValue mimeview_save_all_error_ask(gint n)
1916 {
1917         gchar *message = g_strdup_printf(
1918                 _("An error has occurred while saving message part #%d. "
1919                 "Do you want to cancel operation or skip error and "
1920                 "continue?"), n);
1921         AlertValue av = alertpanel_full(_("Error saving all message parts"),
1922                 message, GTK_STOCK_CANCEL, _("Skip"), _("Skip all"),
1923                 ALERTFOCUS_FIRST, FALSE, NULL, ALERT_WARNING);
1924         g_free(message);
1925         return av;
1926 }
1927
1928 static void mimeview_save_all_info(gint errors, gint total)
1929 {
1930         if (!errors) {
1931                 gchar *msg = g_strdup_printf(
1932                                 ngettext("%d file saved successfully.",
1933                                         "%d files saved successfully.",
1934                                         total),
1935                                 total);
1936                 alertpanel_notice("%s", msg);
1937                 g_free(msg);
1938         } else {
1939                 gchar *msg1 = g_strdup_printf(
1940                                 ngettext("%d file saved successfully",
1941                                         "%d files saved successfully",
1942                                         total - errors),
1943                                 total - errors);
1944                 gchar *msg2 = g_strdup_printf(
1945                                 ngettext("%s, %d file failed.",
1946                                         "%s, %d files failed.",
1947                                         errors),
1948                                 msg1, errors);
1949                 alertpanel_warning("%s", msg2);
1950                 g_free(msg2);
1951                 g_free(msg1);
1952         }
1953 }
1954
1955 /**
1956  * Menu callback: Save all attached files
1957  * \param mimeview Current display
1958  */
1959 static void mimeview_save_all(MimeView *mimeview)
1960 {
1961         MimeInfo *partinfo;
1962         gchar *dirname;
1963         gchar *startdir = NULL;
1964         gint number = 1, errors = 0;
1965         gboolean skip_errors = FALSE;
1966
1967         if (!mimeview->opened) return;
1968         if (!mimeview->file) return;
1969         if (!mimeview->mimeinfo) return;
1970
1971         partinfo = mimeview->mimeinfo;
1972         if (prefs_common.attach_save_dir && *prefs_common.attach_save_dir)
1973                 startdir = g_strconcat(prefs_common.attach_save_dir, G_DIR_SEPARATOR_S, NULL);
1974         else
1975                 startdir = g_strdup(get_home_dir());
1976
1977         manage_window_focus_in(gtk_widget_get_ancestor(mimeview->hbox, GTK_TYPE_WINDOW), NULL, NULL);
1978         dirname = filesel_select_file_save_folder(_("Select destination folder"), startdir);
1979         if (!dirname) {
1980                 g_free(startdir);
1981                 return;
1982         }
1983
1984         if (!is_dir_exist (dirname)) {
1985                 alertpanel_error(_("'%s' is not a directory."), dirname);
1986                 g_free(startdir);
1987                 g_free(dirname);
1988                 return;
1989         }
1990
1991         if (dirname[strlen(dirname)-1] == G_DIR_SEPARATOR)
1992                 dirname[strlen(dirname)-1] = '\0';
1993
1994         /* Skip the first part, that is sometimes DISPOSITIONTYPE_UNKNOWN */
1995         if (partinfo && partinfo->type == MIMETYPE_MESSAGE)
1996                 partinfo = procmime_mimeinfo_next(partinfo);
1997         if (partinfo && partinfo->type == MIMETYPE_MULTIPART) {
1998                 partinfo = procmime_mimeinfo_next(partinfo);
1999                 if (partinfo && partinfo->type == MIMETYPE_TEXT)
2000                         partinfo = procmime_mimeinfo_next(partinfo);
2001         }
2002
2003         while (partinfo != NULL) {
2004                 if (partinfo->type != MIMETYPE_MESSAGE &&
2005                     partinfo->type != MIMETYPE_MULTIPART &&
2006                     (partinfo->disposition != DISPOSITIONTYPE_INLINE
2007                      || get_real_part_name(partinfo) != NULL)) {
2008                         gchar *filename = mimeview_get_filename_for_part(
2009                                 partinfo, dirname, number++);
2010
2011                         gboolean ok = mimeview_write_part(filename, partinfo, FALSE);
2012                         g_free(filename);
2013                         if (!ok) {
2014                                 ++errors;
2015                                 if (!skip_errors) {
2016                                         AlertValue av = mimeview_save_all_error_ask(number - 1);
2017                                         skip_errors = (av == G_ALERTOTHER);
2018                                         if (av == G_ALERTDEFAULT) /* cancel */
2019                                                 break;
2020                                 }
2021                         }
2022                 }
2023                 partinfo = procmime_mimeinfo_next(partinfo);
2024         }
2025
2026         g_free(prefs_common.attach_save_dir);
2027         g_free(startdir);
2028         prefs_common.attach_save_dir = g_filename_to_utf8(dirname,
2029                                         -1, NULL, NULL, NULL);
2030         g_free(dirname);
2031
2032         mimeview_save_all_info(errors, number - 1);
2033 }
2034
2035 static MimeInfo *mimeview_get_part_to_use(MimeView *mimeview)
2036 {
2037         MimeInfo *partinfo = NULL;
2038         if (mimeview->spec_part) {
2039                 partinfo = mimeview->spec_part;
2040                 mimeview->spec_part = NULL;
2041         } else {
2042                 partinfo = (MimeInfo *) g_object_get_data
2043                          (G_OBJECT(mimeview->popupmenu),
2044                          "pop_partinfo");
2045                 g_object_set_data(G_OBJECT(mimeview->popupmenu),
2046                                   "pop_partinfo", NULL);
2047                 if (!partinfo) { 
2048                         partinfo = mimeview_get_selected_part(mimeview);
2049                 }                        
2050         }
2051
2052         return partinfo;
2053 }
2054 /**
2055  * Menu callback: Save the selected attachment
2056  * \param mimeview Current display
2057  */
2058 void mimeview_save_as(MimeView *mimeview)
2059 {
2060         gchar *filename;
2061         gchar *filepath = NULL;
2062         gchar *filedir = NULL;
2063         MimeInfo *partinfo;
2064         gchar *partname = NULL;
2065
2066         if (!mimeview->opened) return;
2067         if (!mimeview->file) return;
2068
2069         partinfo = mimeview_get_part_to_use(mimeview);
2070
2071         cm_return_if_fail(partinfo != NULL);
2072         
2073         if (get_part_name(partinfo) == NULL) {
2074                 return;
2075         }
2076         partname = g_strdup(get_part_name(partinfo));
2077         
2078         if (!g_utf8_validate(partname, -1, NULL)) {
2079                 gchar *tmp = conv_filename_to_utf8(partname);
2080                 if (!tmp) {
2081                         tmp = conv_codeset_strdup(partname,
2082                                 conv_get_locale_charset_str(),
2083                                 CS_UTF_8);
2084                 }
2085                 if (tmp) {
2086                         g_free(partname);
2087                         partname = tmp;
2088                 }
2089         }
2090
2091         subst_for_filename(partname);
2092         
2093         if (prefs_common.attach_save_dir && *prefs_common.attach_save_dir)
2094                 filepath = g_strconcat(prefs_common.attach_save_dir,
2095                                        G_DIR_SEPARATOR_S, partname, NULL);
2096         else
2097                 filepath = g_strdup(partname);
2098
2099         g_free(partname);
2100
2101         manage_window_focus_in(gtk_widget_get_ancestor(mimeview->hbox, GTK_TYPE_WINDOW), NULL, NULL);
2102         filename = filesel_select_file_save(_("Save as"), filepath);
2103         if (!filename) {
2104                 g_free(filepath);
2105                 return;
2106         }
2107
2108         mimeview_write_part(filename, partinfo, TRUE);
2109
2110         filedir = g_path_get_dirname(filename);
2111         if (filedir && strcmp(filedir, ".")) {
2112                 g_free(prefs_common.attach_save_dir);
2113                 prefs_common.attach_save_dir = g_filename_to_utf8(filedir, -1, NULL, NULL, NULL);
2114         }
2115
2116         g_free(filedir);
2117         g_free(filepath);
2118 }
2119
2120 void mimeview_display_as_text(MimeView *mimeview)
2121 {
2122         MimeInfo *partinfo;
2123
2124         if (!mimeview->opened) return;
2125
2126         partinfo = mimeview_get_part_to_use(mimeview);
2127         mimeview_select_mimepart_icon(mimeview, partinfo);
2128         cm_return_if_fail(partinfo != NULL);
2129         mimeview_show_message_part(mimeview, partinfo);
2130 }
2131
2132 void mimeview_launch(MimeView *mimeview, MimeInfo *partinfo)
2133 {
2134         gchar *filename;
2135         gint err;
2136
2137         if (!mimeview->opened) return;
2138         if (!mimeview->file) return;
2139
2140         if (!partinfo)
2141                 partinfo = mimeview_get_part_to_use(mimeview);
2142
2143         cm_return_if_fail(partinfo != NULL);
2144
2145         filename = procmime_get_tmp_file_name(partinfo);
2146
2147         if ((err = procmime_get_part(filename, partinfo)) < 0)
2148                 alertpanel_error
2149                         (_("Couldn't save the part of multipart message: %s"), 
2150                                 g_strerror(-err));
2151         else
2152                 mimeview_view_file(filename, partinfo, NULL, mimeview);
2153
2154         g_free(filename);
2155 }
2156
2157 #ifndef G_OS_WIN32
2158 void mimeview_open_with(MimeView *mimeview)
2159 {
2160         MimeInfo *partinfo;
2161
2162         if (!mimeview) return;
2163         if (!mimeview->opened) return;
2164         if (!mimeview->file) return;
2165
2166         partinfo = mimeview_get_part_to_use(mimeview);
2167
2168         mimeview_open_part_with(mimeview, partinfo, FALSE);
2169 }
2170
2171 static void mimeview_open_part_with(MimeView *mimeview, MimeInfo *partinfo, gboolean automatic)
2172 {
2173         gchar *filename;
2174         gchar *cmd;
2175         gchar *mime_command = NULL;
2176         gchar *content_type = NULL;
2177         gint err;
2178
2179         cm_return_if_fail(partinfo != NULL);
2180
2181         filename = procmime_get_tmp_file_name(partinfo);
2182
2183         if ((err = procmime_get_part(filename, partinfo)) < 0) {
2184                 alertpanel_error
2185                         (_("Couldn't save the part of multipart message: %s"), 
2186                                 g_strerror(-err));
2187                 g_free(filename);
2188                 return;
2189         }
2190         
2191         if (!prefs_common.mime_open_cmd_history)
2192                 prefs_common.mime_open_cmd_history =
2193                         add_history(NULL, prefs_common.mime_open_cmd);
2194
2195         if ((partinfo->type == MIMETYPE_APPLICATION) &&
2196             (!g_ascii_strcasecmp(partinfo->subtype, "octet-stream"))) {
2197                 /* guess content-type from filename */
2198                 content_type = procmime_get_mime_type(filename);
2199         } 
2200         if (content_type == NULL) {
2201                 content_type = procmime_get_content_type_str(partinfo->type,
2202                         partinfo->subtype);
2203         }
2204         
2205         if ((partinfo->type == MIMETYPE_TEXT && !strcmp(partinfo->subtype, "html"))
2206         && prefs_common_get_uri_cmd() && prefs_common.uri_cmd[0]) {
2207                 mime_command = g_strdup(prefs_common_get_uri_cmd());
2208                 g_free(content_type);
2209                 content_type = NULL;
2210         } else if (partinfo->type != MIMETYPE_TEXT || !prefs_common_get_ext_editor_cmd()
2211         ||  !prefs_common_get_ext_editor_cmd()[0]) {
2212                 mime_command = mailcap_get_command_for_type(content_type, filename);
2213         } else {
2214                 mime_command = g_strdup(prefs_common_get_ext_editor_cmd());
2215                 g_free(content_type);
2216                 content_type = NULL;
2217         }
2218         if (mime_command == NULL) {
2219                 /* try with extension this time */
2220                 g_free(content_type);
2221                 content_type = procmime_get_mime_type(filename);
2222                 mime_command = mailcap_get_command_for_type(content_type, filename);
2223         }
2224
2225         if (mime_command == NULL)
2226                 automatic = FALSE;
2227         
2228         if (!automatic) {
2229                 gboolean remember = FALSE;
2230                 if (content_type != NULL)
2231                         cmd = input_dialog_combo_remember
2232                                 (_("Open with"),
2233                                  _("Enter the command-line to open file:\n"
2234                                    "('%s' will be replaced with file name)"),
2235                                  mime_command ? mime_command : prefs_common.mime_open_cmd,
2236                                  prefs_common.mime_open_cmd_history, &remember);
2237                 else
2238                         cmd = input_dialog_combo
2239                                 (_("Open with"),
2240                                  _("Enter the command-line to open file:\n"
2241                                    "('%s' will be replaced with file name)"),
2242                                  mime_command ? mime_command : prefs_common.mime_open_cmd,
2243                                  prefs_common.mime_open_cmd_history);
2244                 if (cmd && remember) {
2245                         mailcap_update_default(content_type, cmd);
2246                 }
2247                 g_free(mime_command);
2248         } else {
2249                 cmd = mime_command;
2250         }
2251         if (cmd) {
2252                 mimeview_view_file(filename, partinfo, cmd, mimeview);
2253                 g_free(prefs_common.mime_open_cmd);
2254                 prefs_common.mime_open_cmd = cmd;
2255                 prefs_common.mime_open_cmd_history =
2256                         add_history(prefs_common.mime_open_cmd_history, cmd);
2257         }
2258
2259         g_free(content_type);
2260         g_free(filename);
2261 }
2262 #endif
2263
2264 static void mimeview_send_to(MimeView *mimeview, MimeInfo *partinfo)
2265 {
2266         GList *attach_file = NULL;
2267         AttachInfo *ainfo = NULL;
2268         gchar *filename;
2269         gint err;
2270
2271         if (!mimeview->opened) return;
2272         if (!mimeview->file) return;
2273
2274         cm_return_if_fail(partinfo != NULL);
2275
2276         filename = procmime_get_tmp_file_name(partinfo);
2277
2278         if (!(err = procmime_get_part(filename, partinfo))) {
2279                 ainfo = g_new0(AttachInfo, 1);
2280                 ainfo->file = filename;
2281                 ainfo->name = g_strdup(get_part_name(partinfo));
2282                 ainfo->content_type = procmime_get_content_type_str(
2283                                         partinfo->type, partinfo->subtype);
2284                 ainfo->charset = g_strdup(procmime_mimeinfo_get_parameter(
2285                                         partinfo, "charset"));
2286                 attach_file = g_list_append(attach_file, ainfo);
2287                 
2288                 compose_new(NULL, NULL, attach_file);
2289                 
2290                 g_free(ainfo->name);
2291                 g_free(ainfo->content_type);
2292                 g_free(ainfo->charset);
2293                 g_free(ainfo);
2294                 g_list_free(attach_file);
2295         } else
2296                 alertpanel_error
2297                         (_("Couldn't save the part of multipart message: %s"), 
2298                                 g_strerror(-err));
2299         g_free(filename);
2300 }
2301
2302 static void mimeview_view_file(const gchar *filename, MimeInfo *partinfo,
2303                                const gchar *cmd, MimeView *mimeview)
2304 {
2305 #ifndef G_OS_WIN32
2306         gchar *p;
2307         gchar buf[BUFFSIZE];
2308
2309         if (cmd == NULL)
2310                 mimeview_open_part_with(mimeview, partinfo, TRUE);
2311         else {
2312                 if ((p = strchr(cmd, '%')) && *(p + 1) == 's' &&
2313                     !strchr(p + 2, '%')) {
2314                         g_snprintf(buf, sizeof(buf), cmd, filename);
2315                         if (!prefs_common.save_parts_readwrite)
2316                                 g_chmod(filename, S_IRUSR);
2317                         else
2318                                 g_chmod(filename, S_IRUSR|S_IWUSR);
2319                 } else {
2320                         g_warning("MIME viewer command-line is invalid: '%s'", cmd);
2321                         mimeview_open_part_with(mimeview, partinfo, FALSE);
2322                 }
2323                 if (execute_command_line(buf, TRUE, NULL) != 0) {
2324                         if (!prefs_common.save_parts_readwrite)
2325                                 g_chmod(filename, S_IRUSR|S_IWUSR);
2326                         mimeview_open_part_with(mimeview, partinfo, FALSE);
2327                 }
2328         }
2329 #else
2330         SHFILEINFO file_info;
2331         GError *error = NULL;
2332         gunichar2 *fn16 = g_utf8_to_utf16(filename, -1, NULL, NULL, &error);
2333
2334         if (error != NULL) {
2335                 alertpanel_error(_("Could not convert attachment name to UTF-16:\n\n%s"),
2336                                         error->message);
2337                 debug_print("filename '%s' conversion to UTF-16 failed\n", filename);
2338                 g_error_free(error);
2339                 return;
2340         }
2341
2342         if ((SHGetFileInfo((LPCWSTR)fn16, 0, &file_info, sizeof(SHFILEINFO), SHGFI_EXETYPE)) != 0) {
2343                 AlertValue val = alertpanel_full(_("Execute untrusted binary?"), 
2344                                       _("This attachment is an executable file. Executing "
2345                                         "untrusted binaries is dangerous and could compromise "
2346                                         "your computer.\n\n"
2347                                         "Do you want to run this file?"), GTK_STOCK_CANCEL, 
2348                                         _("Run binary"),
2349                                       NULL, ALERTFOCUS_FIRST, FALSE, NULL, ALERT_WARNING);
2350                 if (val == G_ALERTALTERNATE) {
2351                         debug_print("executing binary\n");
2352                         ShellExecute(NULL, L"open", (LPCWSTR)fn16, NULL, NULL, SW_SHOW);
2353                 }
2354         } else {
2355                 ShellExecute(NULL, L"open", (LPCWSTR)fn16, NULL, NULL, SW_SHOW);
2356         }
2357
2358         g_free(fn16);
2359         
2360 #endif
2361 }
2362
2363 void mimeview_register_viewer_factory(MimeViewerFactory *factory)
2364 {
2365         mimeviewer_factories = g_slist_append(mimeviewer_factories, factory);
2366 }
2367
2368 static gint cmp_viewer_by_factroy(gconstpointer a, gconstpointer b)
2369 {
2370         return ((MimeViewer *) a)->factory == (MimeViewerFactory *) b ? 0 : -1;
2371 }
2372
2373 void mimeview_unregister_viewer_factory(MimeViewerFactory *factory)
2374 {
2375         GSList *mimeview_list, *viewer_list;
2376
2377         for (mimeview_list = mimeviews; mimeview_list != NULL; mimeview_list = g_slist_next(mimeview_list)) {
2378                 MimeView *mimeview = (MimeView *) mimeview_list->data;
2379                 
2380                 if (mimeview->mimeviewer && mimeview->mimeviewer->factory == factory) {
2381                         mimeview_change_view_type(mimeview, MIMEVIEW_TEXT);
2382                         mimeview->mimeviewer = NULL;
2383                 }
2384
2385                 while ((viewer_list = g_slist_find_custom(mimeview->viewers, factory, cmp_viewer_by_factroy)) != NULL) {
2386                         MimeViewer *mimeviewer = (MimeViewer *) viewer_list->data;
2387
2388                         mimeviewer->destroy_viewer(mimeviewer);
2389                         mimeview->viewers = g_slist_remove(mimeview->viewers, mimeviewer);
2390                 }
2391         }
2392
2393         mimeviewer_factories = g_slist_remove(mimeviewer_factories, factory);
2394 }
2395
2396 static gboolean icon_clicked_cb (GtkWidget *button, GdkEventButton *event, MimeView *mimeview)
2397 {
2398         gint      num;
2399         MimeInfo *partinfo;
2400
2401         num      = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(button), "icon_number"));
2402         partinfo = g_object_get_data(G_OBJECT(button), "partinfo");
2403
2404         if (event->button == 1) {
2405                 icon_selected(mimeview, num, partinfo);
2406                 gtk_widget_grab_focus(button);
2407                 icon_list_toggle_by_mime_info(mimeview, partinfo);
2408         }
2409         part_button_pressed(mimeview, event, partinfo);
2410
2411         return FALSE;
2412 }
2413
2414 static void icon_selected (MimeView *mimeview, gint num, MimeInfo *partinfo)
2415 {
2416         GtkTreeModel *model = gtk_tree_view_get_model(GTK_TREE_VIEW(mimeview->ctree));
2417         GtkTreeIter iter;
2418         GtkTreePath *path;
2419         MimeInfo *curr = NULL;
2420         
2421         if (!gtk_tree_model_get_iter_first(model, &iter))
2422                 return;
2423         path = gtk_tree_model_get_path(model, &iter);
2424         
2425         do {
2426                 gtk_tree_model_get_iter(model, &iter, path);
2427                 gtk_tree_model_get(model, &iter, COL_DATA, &curr, -1);
2428                 if (curr == partinfo) {
2429                         GtkTreeSelection *sel = gtk_tree_view_get_selection(
2430                                                 GTK_TREE_VIEW(mimeview->ctree));
2431                         gtk_tree_selection_select_iter(sel, &iter);
2432                         gtk_tree_path_free(path);
2433                         return;
2434                 }
2435         } while (mimeview_tree_next(model, path));
2436         
2437         gtk_tree_path_free(path);
2438 }               
2439
2440 void mimeview_select_mimepart_icon(MimeView *mimeview, MimeInfo *partinfo)
2441 {
2442         icon_list_toggle_by_mime_info(mimeview, partinfo);
2443         icon_selected(mimeview, -1, partinfo);
2444 }
2445
2446 static gint icon_key_pressed(GtkWidget *button, GdkEventKey *event,
2447                              MimeView *mimeview)
2448 {
2449         SummaryView  *summaryview;
2450         
2451         if (!event) return FALSE;
2452
2453         switch (event->keyval) {
2454         case GDK_KEY_space:
2455                 if (mimeview_scroll_page(mimeview, FALSE))
2456                         return TRUE;
2457
2458                 mimeview_select_next_part(mimeview);
2459                 return TRUE;
2460
2461                 break;
2462         case GDK_KEY_BackSpace:
2463                 mimeview_scroll_page(mimeview, TRUE);
2464                 return TRUE;
2465         case GDK_KEY_Return:
2466         case GDK_KEY_KP_Enter:
2467                 mimeview_scroll_one_line(mimeview,
2468                                          (event->state & GDK_MOD1_MASK) != 0);
2469                 return TRUE;
2470         case GDK_KEY_y:
2471                 BREAK_ON_MODIFIER_KEY();
2472                 mimeview_save_as(mimeview);
2473                 return TRUE;
2474         case GDK_KEY_t:
2475                 BREAK_ON_MODIFIER_KEY();
2476                 mimeview_display_as_text(mimeview);
2477                 return TRUE;    
2478         case GDK_KEY_l:
2479                 BREAK_ON_MODIFIER_KEY();
2480                 mimeview_launch(mimeview, NULL);
2481                 return TRUE;
2482 #ifndef G_OS_WIN32
2483         case GDK_KEY_o:
2484                 BREAK_ON_MODIFIER_KEY();
2485                 mimeview_open_with(mimeview);
2486                 return TRUE;
2487 #endif
2488         case GDK_KEY_c:
2489                 BREAK_ON_MODIFIER_KEY();
2490                 mimeview_check_signature(mimeview);
2491                 return TRUE;
2492         case GDK_KEY_a:
2493                 BREAK_ON_MODIFIER_KEY();
2494                 mimeview_select_next_part(mimeview);
2495                 return TRUE;
2496         default:
2497                 break;
2498         }
2499
2500         if (!mimeview->messageview->mainwin) return FALSE;
2501         summaryview = mimeview->messageview->mainwin->summaryview;
2502         return summary_pass_key_press_event(summaryview, event);
2503 }
2504
2505 static gboolean icon_popup_menu(GtkWidget *widget, gpointer data)
2506 {
2507         MimeView *mimeview = (MimeView *)data;
2508         MimeInfo *partinfo = g_object_get_data(G_OBJECT(widget), "partinfo");
2509
2510         g_object_set_data(G_OBJECT(mimeview->popupmenu),
2511                           "pop_partinfo", partinfo);
2512         gtk_menu_popup(GTK_MENU(mimeview->popupmenu),
2513                        NULL, NULL, NULL, NULL,
2514                        0, gtk_get_current_event_time());
2515         return TRUE;
2516 }
2517
2518 static void icon_list_append_icon (MimeView *mimeview, MimeInfo *mimeinfo) 
2519 {
2520         GtkWidget *pixmap = NULL;
2521         GtkWidget *vbox;
2522         GtkWidget *button;
2523         gchar *tip;
2524         gchar *tiptmp;
2525         const gchar *desc = NULL; 
2526         gchar *sigshort = NULL;
2527         gchar *content_type;
2528         StockPixmap stockp;
2529         MimeInfo *partinfo;
2530         MimeInfo *siginfo = NULL;
2531         MimeInfo *encrypted = NULL;
2532 #ifdef GENERIC_UMPC
2533         GtkRequisition r;
2534 #endif
2535         
2536         if (!prefs_common.show_inline_attachments && mimeinfo->id)
2537                 return;
2538
2539         vbox = mimeview->icon_vbox;
2540         mimeview->icon_count++;
2541         button = gtk_event_box_new();
2542
2543         g_signal_connect(G_OBJECT(button), "motion-notify-event",
2544                          G_CALLBACK(mimeview_visi_notify), mimeview);
2545         g_signal_connect(G_OBJECT(button), "leave-notify-event",
2546                          G_CALLBACK(mimeview_leave_notify), mimeview);
2547         g_signal_connect(G_OBJECT(button), "enter-notify-event",
2548                          G_CALLBACK(mimeview_enter_notify), mimeview);
2549
2550         gtk_container_set_border_width(GTK_CONTAINER(button), 2);
2551         g_object_set_data(G_OBJECT(button), "icon_number", 
2552                           GINT_TO_POINTER(mimeview->icon_count));
2553         g_object_set_data(G_OBJECT(button), "partinfo", 
2554                           mimeinfo);
2555
2556         switch (mimeinfo->type) {
2557                 
2558         case MIMETYPE_TEXT:
2559                 if (mimeinfo->subtype && !g_ascii_strcasecmp(mimeinfo->subtype, "html"))
2560                         stockp = STOCK_PIXMAP_MIME_TEXT_HTML;
2561                 else if  (mimeinfo->subtype && !g_ascii_strcasecmp(mimeinfo->subtype, "enriched"))
2562                         stockp = STOCK_PIXMAP_MIME_TEXT_ENRICHED;
2563                 else if  (mimeinfo->subtype && !g_ascii_strcasecmp(mimeinfo->subtype, "calendar"))
2564                         stockp = STOCK_PIXMAP_MIME_TEXT_CALENDAR;
2565                 else if  (mimeinfo->subtype && (!g_ascii_strcasecmp(mimeinfo->subtype, "x-patch")
2566                                 || !g_ascii_strcasecmp(mimeinfo->subtype, "x-diff")))
2567                         stockp = STOCK_PIXMAP_MIME_TEXT_PATCH;
2568                 else
2569                         stockp = STOCK_PIXMAP_MIME_TEXT_PLAIN;
2570                 break;
2571         case MIMETYPE_MESSAGE:
2572                 stockp = STOCK_PIXMAP_MIME_MESSAGE;
2573                 break;
2574         case MIMETYPE_APPLICATION:
2575                 if (mimeinfo->subtype && (!g_ascii_strcasecmp(mimeinfo->subtype, "pgp-signature")
2576                     || !g_ascii_strcasecmp(mimeinfo->subtype, "x-pkcs7-signature")
2577                     || !g_ascii_strcasecmp(mimeinfo->subtype, "pkcs7-signature")))
2578                         stockp = STOCK_PIXMAP_MIME_PGP_SIG;
2579                 else if (mimeinfo->subtype && !g_ascii_strcasecmp(mimeinfo->subtype, "pdf"))
2580                         stockp = STOCK_PIXMAP_MIME_PDF;
2581                 else if  (mimeinfo->subtype && !g_ascii_strcasecmp(mimeinfo->subtype, "postscript"))
2582                         stockp = STOCK_PIXMAP_MIME_PS;
2583                 else
2584                         stockp = STOCK_PIXMAP_MIME_APPLICATION;
2585                 break;
2586         case MIMETYPE_IMAGE:
2587                 stockp = STOCK_PIXMAP_MIME_IMAGE;
2588                 break;
2589         case MIMETYPE_AUDIO:
2590                 stockp = STOCK_PIXMAP_MIME_AUDIO;
2591                 break;
2592         default:
2593                 stockp = STOCK_PIXMAP_MIME_UNKNOWN;
2594                 break;
2595         }
2596         
2597         partinfo = mimeinfo;
2598         while (partinfo != NULL) {
2599                 if (privacy_mimeinfo_is_signed(partinfo)) {
2600                         siginfo = partinfo;
2601                         break;
2602                 }
2603                 if (privacy_mimeinfo_is_encrypted(partinfo)) {
2604                         encrypted = partinfo;
2605                         break;
2606                 }
2607                 partinfo = procmime_mimeinfo_parent(partinfo);
2608         }       
2609
2610         if (siginfo != NULL) {
2611                 switch (privacy_mimeinfo_get_sig_status(siginfo)) {
2612                 case SIGNATURE_UNCHECKED:
2613                 case SIGNATURE_CHECK_FAILED:
2614                 case SIGNATURE_CHECK_TIMEOUT:
2615                         pixmap = stock_pixmap_widget_with_overlay(stockp,
2616                             STOCK_PIXMAP_PRIVACY_EMBLEM_SIGNED, OVERLAY_BOTTOM_RIGHT, 6, 3);
2617                         break;
2618                 case SIGNATURE_OK:
2619                         pixmap = stock_pixmap_widget_with_overlay(stockp,
2620                             STOCK_PIXMAP_PRIVACY_EMBLEM_PASSED, OVERLAY_BOTTOM_RIGHT, 6, 3);
2621                         break;
2622                 case SIGNATURE_WARN:
2623                 case SIGNATURE_KEY_EXPIRED:
2624                         pixmap = stock_pixmap_widget_with_overlay(stockp,
2625                             STOCK_PIXMAP_PRIVACY_EMBLEM_WARN, OVERLAY_BOTTOM_RIGHT, 6, 3);
2626                         break;
2627                 case SIGNATURE_INVALID:
2628                         pixmap = stock_pixmap_widget_with_overlay(stockp,
2629                             STOCK_PIXMAP_PRIVACY_EMBLEM_FAILED, OVERLAY_BOTTOM_RIGHT, 6, 3);
2630                         break;
2631                 }
2632                 sigshort = privacy_mimeinfo_sig_info_short(siginfo);
2633         } else if (encrypted != NULL) {
2634                         pixmap = stock_pixmap_widget_with_overlay(stockp,
2635                             STOCK_PIXMAP_PRIVACY_EMBLEM_ENCRYPTED, OVERLAY_BOTTOM_RIGHT, 6, 3);         
2636         } else {
2637                 pixmap = stock_pixmap_widget_with_overlay(stockp, 0,
2638                                                           OVERLAY_NONE, 6, 3);
2639         }
2640         gtk_container_add(GTK_CONTAINER(button), pixmap);
2641         if (!desc) {
2642                 if (prefs_common.attach_desc)
2643                         desc = get_part_description(mimeinfo);
2644                 else
2645                         desc = get_part_name(mimeinfo);
2646         }
2647
2648         content_type = procmime_get_content_type_str(mimeinfo->type,
2649                                                      mimeinfo->subtype);
2650
2651         tip = g_strconcat("<b>", _("Type:"), "  </b>", content_type,
2652                           "\n<b>", _("Size:"), " </b>",
2653                           to_human_readable((goffset)mimeinfo->length), NULL);
2654         g_free(content_type);
2655         if (desc && *desc) {
2656                 gchar *tmp = NULL, *escaped = NULL;
2657                 if (!g_utf8_validate(desc, -1, NULL)) {
2658                         tmp = conv_filename_to_utf8(desc);
2659                 } else {
2660                         tmp = g_strdup(desc);
2661                 }
2662                 escaped = g_markup_escape_text(tmp,-1);
2663                 
2664                 tiptmp = g_strconcat(tip, "\n<b>",
2665                                 prefs_common.attach_desc && mimeinfo->description ?
2666                                 _("Description:") : _("Filename:"),
2667                                 " </b>", escaped, NULL);
2668                 g_free(tip);
2669                 tip = tiptmp;
2670                 g_free(tmp);
2671                 g_free(escaped);
2672         }
2673         if (sigshort && *sigshort) {
2674                 gchar *sigshort_escaped =
2675                         g_markup_escape_text(sigshort, -1);
2676
2677                 tiptmp = g_strjoin("\n", tip, sigshort_escaped, NULL);
2678                 g_free(tip);
2679                 g_free(sigshort_escaped);
2680                 tip = tiptmp;
2681         }
2682         g_free(sigshort);
2683
2684         gtk_widget_set_tooltip_markup(button, tip);
2685         g_free(tip);
2686         gtk_widget_show_all(button);
2687         gtk_drag_source_set(button, GDK_BUTTON1_MASK|GDK_BUTTON3_MASK, 
2688                             mimeview_mime_types, 1, GDK_ACTION_COPY);
2689
2690         g_signal_connect(G_OBJECT(button), "popup-menu",
2691                          G_CALLBACK(icon_popup_menu), mimeview);
2692         g_signal_connect(G_OBJECT(button), "button_release_event", 
2693                          G_CALLBACK(icon_clicked_cb), mimeview);
2694         g_signal_connect(G_OBJECT(button), "key_press_event", 
2695                          G_CALLBACK(icon_key_pressed), mimeview);
2696         g_signal_connect(G_OBJECT(button), "drag_data_get",
2697                          G_CALLBACK(mimeview_drag_data_get), mimeview);
2698         gtk_box_pack_start(GTK_BOX(vbox), button, FALSE, FALSE, 0);
2699 #ifdef GENERIC_UMPC
2700         gtk_widget_size_request(pixmap, &r);
2701         gtk_widget_set_size_request(button, -1, r.height + 4);
2702 #endif
2703
2704 }
2705
2706 static void icon_list_clear (MimeView *mimeview)
2707 {
2708         GList     *child, *orig;
2709         GtkAdjustment *adj;
2710                 
2711         orig = gtk_container_get_children(GTK_CONTAINER(mimeview->icon_vbox));
2712         for (child = orig; child != NULL; child = g_list_next(child)) {
2713                 gtkut_container_remove(GTK_CONTAINER(mimeview->icon_vbox), 
2714                                        GTK_WIDGET(child->data));
2715         }
2716         g_list_free(orig);
2717         mimeview->icon_count = 0;
2718         adj  = gtk_layout_get_vadjustment(GTK_LAYOUT(mimeview->icon_scroll));
2719         gtk_adjustment_set_value(adj, gtk_adjustment_get_lower(adj));
2720         gtk_adjustment_changed(adj);
2721 }
2722
2723 /*!
2724  *\brief        Used to 'click' the next or previous icon.
2725  *
2726  *\return       true if the icon 'number' exists and was selected.
2727  */
2728 static void icon_scroll_size_allocate_cb(GtkWidget *widget, 
2729                                          GtkAllocation *size, MimeView *mimeview)
2730 {
2731         GtkAllocation vbox_size;
2732         GtkAllocation layout_size;
2733         GtkAdjustment *adj;
2734         guint width;
2735         guint height;
2736
2737         adj = gtk_layout_get_vadjustment(GTK_LAYOUT(mimeview->icon_scroll));
2738
2739         gtk_widget_get_allocation(mimeview->icon_vbox, &vbox_size);
2740         gtk_widget_get_allocation(mimeview->icon_scroll, &layout_size);
2741                 
2742         gtk_layout_get_size(GTK_LAYOUT(mimeview->icon_scroll), &width, &height);
2743         gtk_layout_set_size(GTK_LAYOUT(mimeview->icon_scroll), 
2744                             width, 
2745                             MAX(vbox_size.height, layout_size.height));
2746         gtk_adjustment_set_step_increment(adj, 10);
2747 }
2748
2749 static void icon_list_create(MimeView *mimeview, MimeInfo *mimeinfo)
2750 {
2751         GtkRequisition size;
2752         GtkRequisition requisition;
2753
2754         cm_return_if_fail(mimeinfo != NULL);
2755
2756         while (mimeinfo != NULL) {
2757                 if (mimeinfo->type != MIMETYPE_MULTIPART)
2758                         icon_list_append_icon(mimeview, mimeinfo);
2759                 if (mimeinfo->node->children != NULL)
2760                         icon_list_create(mimeview, 
2761                                 (MimeInfo *) mimeinfo->node->children->data);
2762                 mimeinfo = mimeinfo->node->next != NULL 
2763                          ? (MimeInfo *) mimeinfo->node->next->data 
2764                          : NULL;
2765         }
2766         gtk_widget_size_request(mimeview->icon_vbox, &size);
2767         gtk_widget_get_requisition(mimeview->icon_mainbox, &requisition);
2768         if (size.width > requisition.width) {
2769                 gtk_widget_set_size_request(mimeview->icon_mainbox, 
2770                                             size.width, -1);
2771         }
2772         if (mimeview->opened)
2773                 icon_list_toggle_by_mime_info(mimeview,
2774                         mimeview_get_node_part(mimeview, mimeview->opened));
2775 }
2776
2777 static void icon_list_toggle_by_mime_info (MimeView     *mimeview,
2778                                            MimeInfo     *mimeinfo)
2779 {
2780         GList *children, *child;
2781         
2782         children = gtk_container_get_children(GTK_CONTAINER(mimeview->icon_vbox));
2783         for (child = children; child != NULL; child = g_list_next(child)) {
2784                 gboolean *highlight = NULL;
2785                 GtkWidget *icon = gtk_bin_get_child(GTK_BIN(child->data));
2786
2787                 if (!GTK_IS_EVENT_BOX(child->data))
2788                         continue;
2789
2790                 highlight = g_object_get_data(G_OBJECT(icon), "highlight");
2791                 *highlight = (g_object_get_data(G_OBJECT(child->data),
2792                                       "partinfo") == (gpointer)mimeinfo);
2793
2794                 gtk_widget_queue_draw(icon);
2795         }
2796         g_list_free(children);
2797 }
2798
2799 static void ctree_size_allocate_cb(GtkWidget *widget, GtkAllocation *allocation,
2800                                     MimeView *mimeview)
2801 {
2802         prefs_common.mimeview_tree_height = allocation->height;
2803 }
2804
2805 static gint mime_toggle_button_cb(GtkWidget *button, GdkEventButton *event,
2806                                     MimeView *mimeview)
2807 {
2808         g_object_ref(button); 
2809
2810         mimeview_leave_notify(button, NULL, NULL);
2811
2812         mimeview->ctree_mode = !mimeview->ctree_mode;
2813         if (mimeview->ctree_mode) {
2814                 gtk_arrow_set(GTK_ARROW(gtk_bin_get_child(GTK_BIN((button)))), GTK_ARROW_RIGHT, 
2815                                         GTK_SHADOW_NONE);
2816                 gtk_widget_hide(mimeview->icon_mainbox);
2817                 gtk_widget_show(mimeview->ctree_mainbox);
2818                 gtk_paned_set_position(GTK_PANED(mimeview->paned),
2819                                         prefs_common.mimeview_tree_height);
2820
2821                 gtkut_container_remove(GTK_CONTAINER(mimeview->icon_mainbox), 
2822                                         button);
2823                 gtk_box_pack_end(GTK_BOX(mimeview->ctree_mainbox), 
2824                                    button, FALSE, FALSE, 0);
2825         } else {
2826                 gtk_arrow_set(GTK_ARROW(gtk_bin_get_child(GTK_BIN((button)))), GTK_ARROW_LEFT, 
2827                               GTK_SHADOW_NONE);
2828                 gtk_widget_hide(mimeview->ctree_mainbox);
2829                 gtk_widget_show(mimeview->icon_mainbox);
2830                 gtk_paned_set_position(GTK_PANED(mimeview->paned), 0);
2831
2832                 gtkut_container_remove(GTK_CONTAINER(mimeview->ctree_mainbox), 
2833                                         button);
2834                 gtk_box_pack_start(GTK_BOX(mimeview->icon_mainbox), 
2835                                    button, FALSE, FALSE, 0);
2836                 gtk_box_reorder_child(GTK_BOX(gtk_widget_get_parent(button)), button, 0);
2837                 if (mimeview->opened)
2838                         icon_list_toggle_by_mime_info(mimeview,
2839                                         mimeview_get_node_part(mimeview, mimeview->opened));
2840                 summary_grab_focus(mimeview->mainwin->summaryview);
2841         }
2842         g_object_unref(button);
2843         return TRUE;
2844 }
2845
2846 void mimeview_update (MimeView *mimeview)
2847 {
2848         if (mimeview && mimeview->mimeinfo) {
2849                 icon_list_clear(mimeview);
2850                 icon_list_create(mimeview, mimeview->mimeinfo);
2851         }
2852 }
2853
2854 void mimeview_handle_cmd(MimeView *mimeview, const gchar *cmd, GdkEventButton *event, gpointer data)
2855 {
2856         MessageView *msgview = NULL;
2857         MainWindow *mainwin = NULL;
2858         
2859         if (!cmd)
2860                 return;
2861         
2862         msgview = mimeview->messageview;
2863         if (!msgview)
2864                 return;
2865                 
2866         mainwin = msgview->mainwin;
2867         if (!mainwin)
2868                 return;
2869                 
2870         g_object_set_data(G_OBJECT(mimeview->popupmenu),
2871                           "pop_partinfo", NULL);
2872
2873         if (!strcmp(cmd, "sc://view_log"))
2874                 log_window_show(mainwin->logwin);
2875         else if (!strcmp(cmd, "sc://save_as"))
2876                 mimeview_save_as(mimeview);
2877         else if (!strcmp(cmd, "sc://display_as_text"))
2878                 mimeview_display_as_text(mimeview);
2879 #ifndef G_OS_WIN32
2880         else if (!strcmp(cmd, "sc://open_with"))
2881                 mimeview_open_with(mimeview);
2882 #endif
2883         else if (!strcmp(cmd, "sc://open"))
2884                 mimeview_launch(mimeview, NULL);
2885         else if (!strcmp(cmd, "sc://select_attachment") && data != NULL) {
2886                 icon_list_toggle_by_mime_info(mimeview, (MimeInfo *)data);
2887                 icon_selected(mimeview, -1, (MimeInfo *)data);
2888         } else if (!strcmp(cmd, "sc://open_attachment") && data != NULL) {
2889                 mimeview_launch(mimeview, (MimeInfo *)data);
2890         } else if (!strcmp(cmd, "sc://menu_attachment") && data != NULL) {
2891                 mimeview->spec_part = (MimeInfo *)data;
2892                 part_button_pressed(mimeview, event, (MimeInfo *)data);
2893         } else if (!strncmp(cmd, "sc://search_tags:", strlen("sc://search_tags:"))) {
2894                 const gchar *tagname = cmd + strlen("sc://search_tags:");
2895                 gchar *buf = g_strdup_printf("tag matchcase \"%s\"", tagname);
2896                 gtk_toggle_button_set_active(
2897                                 GTK_TOGGLE_BUTTON(mimeview->messageview->mainwin->summaryview->toggle_search), 
2898                                 TRUE);
2899                 quicksearch_set(mimeview->messageview->mainwin->summaryview->quicksearch, 
2900                                 ADVANCED_SEARCH_EXTENDED, buf);
2901                 g_free(buf);
2902         }
2903 }
2904
2905 gboolean mimeview_scroll_page(MimeView *mimeview, gboolean up)
2906 {
2907         if (mimeview->type == MIMEVIEW_TEXT)
2908                 return textview_scroll_page(mimeview->textview, up);
2909         else if (mimeview->mimeviewer) {
2910                 MimeViewer *mimeviewer = mimeview->mimeviewer;
2911                 if (mimeviewer->scroll_page)
2912                         return mimeviewer->scroll_page(mimeviewer, up);
2913         }
2914         return TRUE;
2915 }
2916
2917 void mimeview_scroll_one_line(MimeView *mimeview, gboolean up)
2918 {
2919         if (mimeview->type == MIMEVIEW_TEXT)
2920                 textview_scroll_one_line(mimeview->textview, up);
2921         else if (mimeview->mimeviewer) {
2922                 MimeViewer *mimeviewer = mimeview->mimeviewer;
2923                 if (mimeviewer->scroll_one_line)
2924                         mimeviewer->scroll_one_line(mimeviewer, up);
2925         }
2926 }