Remove deprecated define.
[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 static void mimeview_selected(GtkTreeSelection *selection, MimeView *mimeview)
1434 {
1435         GtkTreeView *ctree = GTK_TREE_VIEW(mimeview->ctree);
1436         GtkTreeModel *model;
1437         GtkTreeIter iter;
1438         GtkTreePath *path;
1439         MimeInfo *partinfo;
1440         MainWindow *mainwin;
1441
1442         selection = gtk_tree_view_get_selection(ctree);
1443         if (!gtk_tree_selection_get_selected(selection, &model, &iter))
1444                 return;
1445
1446         path = gtk_tree_model_get_path(model, &iter);
1447
1448         if (mimeview->opened && !gtk_tree_path_compare(mimeview->opened, path)) {
1449                 gtk_tree_path_free(path);
1450                 return;
1451         }
1452         
1453         gtk_tree_path_free(mimeview->opened);
1454         mimeview->opened = path;
1455         mimeview->spec_part = NULL;
1456         gtk_tree_view_scroll_to_cell(ctree, path, NULL, TRUE, 0.5, 0);
1457
1458         partinfo = mimeview_get_node_part(mimeview, path);
1459         if (!partinfo) return;
1460
1461         /* ungrab the mouse event */
1462         if (gtk_widget_has_grab(GTK_WIDGET(ctree))) {
1463                 gtk_grab_remove(GTK_WIDGET(ctree));
1464                 if (gdk_pointer_is_grabbed())
1465                         gdk_pointer_ungrab(GDK_CURRENT_TIME);
1466         }
1467         
1468         mimeview->textview->default_text = FALSE;
1469
1470         update_signature_info(mimeview, partinfo);
1471
1472         if (!mimeview_show_part(mimeview, partinfo)) {
1473                 switch (partinfo->type) {
1474                 case MIMETYPE_TEXT:
1475                 case MIMETYPE_MESSAGE:
1476                 case MIMETYPE_MULTIPART:
1477                         mimeview_show_message_part(mimeview, partinfo);
1478                 
1479                         break;
1480                 default:
1481                         mimeview->textview->default_text = TRUE;
1482                         mimeview_change_view_type(mimeview, MIMEVIEW_TEXT);
1483                         textview_clear(mimeview->textview);
1484                         textview_show_mime_part(mimeview->textview, partinfo);
1485                         break;
1486                 }
1487         }
1488         mainwin = mainwindow_get_mainwindow();
1489         if (mainwin)
1490                 main_window_set_menu_sensitive(mainwin);
1491
1492         if (mimeview->siginfo && privacy_auto_check_signatures(mimeview->siginfo)
1493         &&  privacy_mimeinfo_get_sig_status(mimeview->siginfo) == SIGNATURE_UNCHECKED) {
1494                 mimeview_check_signature(mimeview);
1495         }
1496 }
1497
1498 static gint mimeview_button_pressed(GtkWidget *widget, GdkEventButton *event,
1499                                     MimeView *mimeview)
1500 {
1501         GtkTreeSelection *selection;
1502         GtkTreeIter iter;
1503
1504         if (!event) return FALSE;
1505
1506         if (event->button == 2 || event->button == 3) {
1507                 selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(widget));
1508                 if (!gtk_tree_selection_get_selected(selection, NULL, &iter))
1509                         return FALSE;
1510                 
1511                 gtk_tree_selection_select_iter(selection, &iter);
1512         }
1513         part_button_pressed(mimeview, event, mimeview_get_selected_part(mimeview));
1514
1515         return FALSE;
1516 }
1517
1518 static gboolean mimeview_scrolled(GtkWidget *widget, GdkEventScroll *event,
1519                                     MimeView *mimeview)
1520 {
1521         GtkVScrollbutton *scrollbutton = (GtkVScrollbutton *)mimeview->scrollbutton;
1522         if (event->direction == GDK_SCROLL_UP) {
1523                 scrollbutton->scroll_type = GTK_SCROLL_STEP_BACKWARD;
1524         } else {
1525                 scrollbutton->scroll_type = GTK_SCROLL_STEP_FORWARD;
1526         }
1527         gtk_vscrollbutton_scroll(scrollbutton);
1528         return TRUE;
1529 }
1530
1531 static gboolean part_button_pressed(MimeView *mimeview, GdkEventButton *event, 
1532                                     MimeInfo *partinfo)
1533 {
1534         static MimeInfo *lastinfo;
1535         static guint32 lasttime;
1536
1537         gint double_click_time;
1538         g_object_get(gtk_settings_get_default(), "gtk-double-click-time", &double_click_time, NULL);
1539
1540         if (event->button == 2 ||
1541             (event->button == 1 && (event->time - lasttime) < double_click_time && lastinfo == partinfo)) {
1542                 /* call external program for image, audio or html */
1543                 mimeview_launch(mimeview, partinfo);
1544                 return TRUE;
1545         } else if (event->button == 3) {
1546                 MainWindow *mainwin = mainwindow_get_mainwindow();
1547
1548                 if (partinfo && (partinfo->type == MIMETYPE_MESSAGE ||
1549                                  partinfo->type == MIMETYPE_IMAGE ||
1550                                  partinfo->type == MIMETYPE_MULTIPART))
1551                         cm_menu_set_sensitive_full(mimeview->ui_manager, "Menus/MimeView/DisplayAsText", FALSE);
1552                 else
1553                         cm_menu_set_sensitive_full(mimeview->ui_manager, "Menus/MimeView/DisplayAsText", TRUE);
1554
1555                 if (partinfo && (partinfo->type == MIMETYPE_MESSAGE ||
1556                                  partinfo->type == MIMETYPE_IMAGE ||
1557                                  partinfo->type == MIMETYPE_TEXT))
1558                         cm_menu_set_sensitive_full(mimeview->ui_manager, "Menus/MimeView/Copy", TRUE);
1559                 else
1560                         cm_menu_set_sensitive_full(mimeview->ui_manager, "Menus/MimeView/Copy", FALSE);
1561 #ifndef G_OS_WIN32
1562                 if (partinfo &&
1563                     partinfo->type == MIMETYPE_APPLICATION &&
1564                     !g_ascii_strcasecmp(partinfo->subtype, "octet-stream"))
1565                         cm_menu_set_sensitive_full(mimeview->ui_manager, "Menus/MimeView/Open", FALSE);
1566                 else
1567 #endif
1568                         cm_menu_set_sensitive_full(mimeview->ui_manager, "Menus/MimeView/Open", TRUE);
1569                 if (mainwin)
1570                         main_window_set_menu_sensitive(mainwin);
1571                 g_object_set_data(G_OBJECT(mimeview->popupmenu),
1572                                   "pop_partinfo", partinfo);
1573                                     
1574                 gtk_menu_popup(GTK_MENU(mimeview->popupmenu),
1575                                NULL, NULL, NULL, NULL,
1576                                event->button, event->time);
1577                 return TRUE;
1578         }
1579
1580         lastinfo = partinfo;
1581         lasttime = event->time;
1582         return FALSE;
1583 }
1584
1585
1586 gboolean mimeview_pass_key_press_event(MimeView *mimeview, GdkEventKey *event)
1587 {
1588         return mimeview_key_pressed(mimeview->ctree, event, mimeview);
1589 }
1590
1591 void mimeview_select_next_part(MimeView *mimeview)
1592 {
1593         GtkTreeView *ctree = GTK_TREE_VIEW(mimeview->ctree);
1594         GtkTreeModel *model = gtk_tree_view_get_model(ctree);
1595         GtkTreeSelection *selection;
1596         GtkTreeIter iter;
1597         GtkTreePath *path;
1598         MimeInfo *partinfo = NULL;
1599         gboolean has_next;
1600         
1601         if (!mimeview->opened) return;
1602
1603         gtk_tree_model_get_iter(model, &iter, mimeview->opened);
1604         path = gtk_tree_model_get_path(model, &iter);
1605 skip:
1606         has_next = mimeview_tree_next(model, path);
1607         if (!has_next) {
1608                 has_next = gtk_tree_model_get_iter_first(model, &iter);
1609                 gtk_tree_path_free(path);
1610                 path = gtk_tree_model_get_path(model, &iter);
1611         }
1612
1613         if (has_next) {
1614                 partinfo = mimeview_get_node_part(mimeview, path);
1615                 if (partinfo->type == MIMETYPE_MULTIPART ||
1616                     (!prefs_common.show_inline_attachments && partinfo->id))
1617                         goto skip;
1618                 selection = gtk_tree_view_get_selection(ctree);
1619                 gtk_tree_selection_select_path(selection, path);
1620                 icon_list_toggle_by_mime_info(mimeview, partinfo);
1621         }
1622         
1623         gtk_tree_path_free(path);
1624 }
1625
1626 void mimeview_select_prev_part(MimeView *mimeview)
1627 {
1628         GtkTreeView *ctree = GTK_TREE_VIEW(mimeview->ctree);
1629         GtkTreeModel *model = gtk_tree_view_get_model(ctree);
1630         GtkTreeSelection *selection;
1631         GtkTreeIter iter;
1632         GtkTreePath *path;
1633         MimeInfo *partinfo = NULL;
1634         gboolean has_prev;
1635         
1636         if (!mimeview->opened) return;
1637
1638         gtk_tree_model_get_iter(model, &iter, mimeview->opened);
1639         path = gtk_tree_model_get_path(model, &iter);
1640 skip:
1641         has_prev = mimeview_tree_prev(mimeview, path);
1642         if (!has_prev) {
1643                 while (mimeview_tree_next(model, path)) {}
1644                 has_prev = TRUE;
1645         }
1646
1647         if (has_prev) {
1648                 partinfo = mimeview_get_node_part(mimeview, path);
1649                 if (partinfo->type == MIMETYPE_MULTIPART ||
1650                     (!prefs_common.show_inline_attachments && partinfo->id))
1651                         goto skip;
1652                 selection = gtk_tree_view_get_selection(ctree);
1653                 gtk_tree_selection_select_path(selection, path);
1654                 icon_list_toggle_by_mime_info(mimeview, partinfo);
1655         }
1656         
1657         gtk_tree_path_free(path);
1658 }
1659
1660 #define BREAK_ON_MODIFIER_KEY() \
1661         if ((event->state & (GDK_MOD1_MASK|GDK_CONTROL_MASK)) != 0) break
1662
1663 static gint mimeview_key_pressed(GtkWidget *widget, GdkEventKey *event,
1664                                  MimeView *mimeview)
1665 {
1666         SummaryView *summaryview;
1667
1668         if (!event) return FALSE;
1669         if (!mimeview->opened) return FALSE;
1670
1671         summaryview = mimeview->messageview->mainwin->summaryview;
1672         
1673         if (summaryview && quicksearch_has_focus(summaryview->quicksearch))
1674                 return FALSE;
1675                 
1676         switch (event->keyval) {
1677         case GDK_KEY_Home:
1678         case GDK_KEY_End:
1679                 textview_scroll_max(mimeview->textview,
1680                                     (event->keyval == GDK_KEY_Home));
1681                 return TRUE;
1682         case GDK_KEY_Page_Down:
1683         case GDK_KEY_space:
1684                 if (mimeview_scroll_page(mimeview,
1685                                          (event->state & GDK_SHIFT_MASK) != 0))
1686                         return TRUE;
1687                         
1688                 if (!(event->state & GDK_SHIFT_MASK))
1689                         mimeview_select_next_part(mimeview);
1690                 return TRUE;
1691         case GDK_KEY_Page_Up:
1692         case GDK_KEY_BackSpace:
1693                 mimeview_scroll_page(mimeview, TRUE);
1694                 return TRUE;
1695         case GDK_KEY_Return:
1696         case GDK_KEY_KP_Enter:
1697                 mimeview_scroll_one_line(mimeview,
1698                                          (event->state & GDK_MOD1_MASK) != 0);
1699                 return TRUE;
1700         case GDK_KEY_Up:
1701         case GDK_KEY_Down:
1702                 mimeview_scroll_one_line(mimeview, (event->keyval == GDK_KEY_Up));
1703                 return TRUE;
1704         default:
1705                 break;
1706         }
1707
1708         if (mimeview->messageview->new_window) return FALSE;
1709
1710         return summary_pass_key_press_event(summaryview, event);
1711 }
1712
1713 static void mimeview_drag_data_get(GtkWidget        *widget,
1714                                    GdkDragContext   *drag_context,
1715                                    GtkSelectionData *selection_data,
1716                                    guint             info,
1717                                    guint             time,
1718                                    MimeView         *mimeview)
1719 {
1720         gchar *filename = NULL, *uriname, *tmp;
1721         MimeInfo *partinfo;
1722         gint err;
1723         gint count = 0;
1724
1725         if (!mimeview->opened) return;
1726         if (!mimeview->file) return;
1727
1728         partinfo = mimeview_get_selected_part(mimeview);
1729         if (!partinfo) return;
1730
1731         if (strlen(get_part_name(partinfo)) > 0) {
1732                 filename = g_path_get_basename(get_part_name(partinfo));
1733                 if (*filename == '\0') return;
1734         } else if (partinfo->type == MIMETYPE_MESSAGE 
1735                    && !g_ascii_strcasecmp(partinfo->subtype, "rfc822")) {
1736                 gchar *name = NULL;
1737                 GPtrArray *headers = NULL;
1738                 FILE *fp;
1739
1740                 fp = claws_fopen(partinfo->data.filename, "rb");
1741                 if (fp != NULL && fseek(fp, partinfo->offset, SEEK_SET) == 0) {
1742                         headers = procheader_get_header_array_asis(fp);
1743                         if (headers) {
1744                                 gint i;
1745                                 for (i = 0; i < headers->len; i++) {
1746                                         Header *header = g_ptr_array_index(headers, i);
1747                                         if (procheader_headername_equal(header->name, "Subject")) {
1748                                                 unfold_line(header->body);
1749                                                 name = g_strconcat(header->body, ".txt", NULL);
1750                                                 subst_for_filename(name);
1751                                         }
1752                                 }
1753                                 procheader_header_array_destroy(headers);
1754                         }
1755                 }
1756                 if (fp != NULL)
1757                         claws_fclose(fp);
1758                 if (name)
1759                         filename = g_path_get_basename(name);
1760                 g_free(name);
1761         }
1762         if (filename == NULL)
1763                 filename = g_path_get_basename("Unnamed part");
1764
1765         if (!g_utf8_validate(filename, -1, NULL))
1766                 tmp = conv_codeset_strdup(filename,
1767                                 conv_get_locale_charset_str(),
1768                                 CS_UTF_8);
1769         else
1770                 tmp = g_strdup(filename);
1771
1772         if (tmp == NULL) {
1773                 g_warning("filename not in UTF-8");
1774                 tmp = g_strdup("Unnamed part");
1775         }
1776         filename = g_strconcat(get_mime_tmp_dir(), G_DIR_SEPARATOR_S,
1777                                tmp, NULL);
1778
1779 check_new_file:
1780         if (is_file_exist(filename)) {
1781                 gchar *ext = NULL;
1782                 gchar *prefix = NULL;
1783                 gchar *new_name = NULL;
1784                 if (strrchr(tmp, '.')) {
1785                         prefix = g_strdup(tmp);
1786                         ext = g_strdup(strrchr(tmp, '.'));
1787                         *(strrchr(prefix, '.')) = '\0';
1788                 } else {
1789                         prefix = g_strdup(tmp);
1790                         ext = g_strdup("");
1791                 }
1792                 count++;
1793                 new_name = g_strdup_printf("%s.%d%s", prefix, count, ext);
1794                 g_free(prefix);
1795                 g_free(ext);
1796                 g_free(filename);
1797                 filename = g_strconcat(get_mime_tmp_dir(), G_DIR_SEPARATOR_S,
1798                                new_name, NULL);
1799                 g_free(new_name);
1800                 goto check_new_file;
1801         }
1802
1803         g_free(tmp);
1804
1805         if ((err = procmime_get_part(filename, partinfo)) < 0)
1806                 alertpanel_error
1807                         (_("Couldn't save the part of multipart message: %s"), 
1808                                 g_strerror(-err));
1809
1810         tmp = g_filename_to_uri(filename, NULL, NULL);
1811         uriname = g_strconcat(tmp, "\r\n", NULL);
1812         g_free(tmp);
1813
1814         gtk_selection_data_set(selection_data, 
1815                    gtk_selection_data_get_target(selection_data), 8,
1816                                (guchar *)uriname, strlen(uriname));
1817
1818         g_free(uriname);
1819         g_free(filename);
1820 }
1821
1822 /**
1823  * Returns a filename (with path) for an attachment
1824  * \param partinfo The attachment to save
1825  * \param basedir The target directory
1826  * \param number Used for dummy filename if attachment is unnamed
1827  */
1828 static gchar *mimeview_get_filename_for_part(MimeInfo *partinfo,
1829                                       const gchar *basedir,
1830                                       gint number)
1831 {
1832         gchar *fullname;
1833         gchar *filename;
1834
1835         filename = g_strdup(get_part_name(partinfo));
1836         if (!filename || !*filename) {
1837                 g_free(filename);
1838                 filename = g_strdup_printf("noname.%d", number);
1839         }
1840
1841         if (!g_utf8_validate(filename, -1, NULL)) {
1842                 gchar *tmp = conv_filename_to_utf8(filename);
1843                 g_free(filename);
1844                 filename = tmp;
1845         }
1846         
1847         subst_for_filename(filename);
1848
1849         fullname = g_strconcat
1850                 (basedir, G_DIR_SEPARATOR_S, (g_path_is_absolute(filename))
1851                  ? &filename[1] : filename, NULL);
1852
1853         g_free(filename);
1854         filename = conv_filename_from_utf8(fullname);
1855         g_free(fullname);
1856         return filename;
1857 }
1858
1859 /**
1860  * Write a single attachment to file
1861  * \param filename Filename with path
1862  * \param partinfo Attachment to save
1863  */
1864 static gboolean mimeview_write_part(const gchar *filename,
1865                                     MimeInfo *partinfo,
1866                                     gboolean handle_error)
1867 {
1868         gchar *dir;
1869         gint err;
1870
1871         dir= g_path_get_dirname(filename);
1872         if (!is_dir_exist(dir))
1873                 make_dir_hier(dir);
1874         g_free(dir);
1875
1876         if (is_file_exist(filename)) {
1877                 AlertValue aval;
1878                 gchar *res;
1879                 gchar *tmp;
1880                 
1881                 if (!g_utf8_validate(filename, -1, NULL))
1882                         tmp = conv_filename_to_utf8(filename);
1883                 else 
1884                         tmp = g_strdup(filename);
1885                 
1886                 res = g_strdup_printf(_("Overwrite existing file '%s'?"),
1887                                       tmp);
1888                 g_free(tmp);
1889                 aval = alertpanel(_("Overwrite"), res, GTK_STOCK_CANCEL,
1890                                   GTK_STOCK_OK, NULL, ALERTFOCUS_FIRST);
1891                 g_free(res);
1892                 if (G_ALERTALTERNATE != aval) return FALSE;
1893         }
1894
1895         if ((err = procmime_get_part(filename, partinfo)) < 0) {
1896                 debug_print("error saving MIME part: %d\n", err);
1897                 if (handle_error)
1898                         alertpanel_error
1899                                 (_("Couldn't save the part of multipart message: %s"),
1900                                  g_strerror(-err));
1901                 return FALSE;
1902         }
1903
1904         return TRUE;
1905 }
1906
1907 static AlertValue mimeview_save_all_error_ask(gint n)
1908 {
1909         gchar *message = g_strdup_printf(
1910                 _("An error has occurred while saving message part #%d. "
1911                 "Do you want to cancel operation or skip error and "
1912                 "continue?"), n);
1913         AlertValue av = alertpanel_full(_("Error saving all message parts"),
1914                 message, GTK_STOCK_CANCEL, _("Skip"), _("Skip all"),
1915                 ALERTFOCUS_FIRST, FALSE, NULL, ALERT_WARNING);
1916         g_free(message);
1917         return av;
1918 }
1919
1920 static void mimeview_save_all_info(gint errors, gint total)
1921 {
1922         if (!errors) {
1923                 gchar *msg = g_strdup_printf(
1924                                 ngettext("%d file saved successfully.",
1925                                         "%d files saved successfully.",
1926                                         total),
1927                                 total);
1928                 alertpanel_notice("%s", msg);
1929                 g_free(msg);
1930         } else {
1931                 gchar *msg1 = g_strdup_printf(
1932                                 ngettext("%d file saved successfully",
1933                                         "%d files saved successfully",
1934                                         total - errors),
1935                                 total - errors);
1936                 gchar *msg2 = g_strdup_printf(
1937                                 ngettext("%s, %d file failed.",
1938                                         "%s, %d files failed.",
1939                                         errors),
1940                                 msg1, errors);
1941                 alertpanel_warning("%s", msg2);
1942                 g_free(msg2);
1943                 g_free(msg1);
1944         }
1945 }
1946
1947 /**
1948  * Menu callback: Save all attached files
1949  * \param mimeview Current display
1950  */
1951 static void mimeview_save_all(MimeView *mimeview)
1952 {
1953         MimeInfo *partinfo;
1954         gchar *dirname;
1955         gchar *startdir = NULL;
1956         gint number = 1, errors = 0;
1957         gboolean skip_errors = FALSE;
1958
1959         if (!mimeview->opened) return;
1960         if (!mimeview->file) return;
1961         if (!mimeview->mimeinfo) return;
1962
1963         partinfo = mimeview->mimeinfo;
1964         if (prefs_common.attach_save_dir && *prefs_common.attach_save_dir)
1965                 startdir = g_strconcat(prefs_common.attach_save_dir, G_DIR_SEPARATOR_S, NULL);
1966         else
1967                 startdir = g_strdup(get_home_dir());
1968
1969         manage_window_focus_in(gtk_widget_get_ancestor(mimeview->hbox, GTK_TYPE_WINDOW), NULL, NULL);
1970         dirname = filesel_select_file_save_folder(_("Select destination folder"), startdir);
1971         if (!dirname) {
1972                 g_free(startdir);
1973                 return;
1974         }
1975
1976         if (!is_dir_exist (dirname)) {
1977                 alertpanel_error(_("'%s' is not a directory."), dirname);
1978                 g_free(startdir);
1979                 g_free(dirname);
1980                 return;
1981         }
1982
1983         if (dirname[strlen(dirname)-1] == G_DIR_SEPARATOR)
1984                 dirname[strlen(dirname)-1] = '\0';
1985
1986         /* Skip the first part, that is sometimes DISPOSITIONTYPE_UNKNOWN */
1987         if (partinfo && partinfo->type == MIMETYPE_MESSAGE)
1988                 partinfo = procmime_mimeinfo_next(partinfo);
1989         if (partinfo && partinfo->type == MIMETYPE_MULTIPART) {
1990                 partinfo = procmime_mimeinfo_next(partinfo);
1991                 if (partinfo && partinfo->type == MIMETYPE_TEXT)
1992                         partinfo = procmime_mimeinfo_next(partinfo);
1993         }
1994
1995         while (partinfo != NULL) {
1996                 if (partinfo->type != MIMETYPE_MESSAGE &&
1997                     partinfo->type != MIMETYPE_MULTIPART &&
1998                     (partinfo->disposition != DISPOSITIONTYPE_INLINE
1999                      || get_real_part_name(partinfo) != NULL)) {
2000                         gchar *filename = mimeview_get_filename_for_part(
2001                                 partinfo, dirname, number++);
2002
2003                         gboolean ok = mimeview_write_part(filename, partinfo, FALSE);
2004                         g_free(filename);
2005                         if (!ok) {
2006                                 ++errors;
2007                                 if (!skip_errors) {
2008                                         AlertValue av = mimeview_save_all_error_ask(number - 1);
2009                                         skip_errors = (av == G_ALERTOTHER);
2010                                         if (av == G_ALERTDEFAULT) /* cancel */
2011                                                 break;
2012                                 }
2013                         }
2014                 }
2015                 partinfo = procmime_mimeinfo_next(partinfo);
2016         }
2017
2018         g_free(prefs_common.attach_save_dir);
2019         g_free(startdir);
2020         prefs_common.attach_save_dir = g_filename_to_utf8(dirname,
2021                                         -1, NULL, NULL, NULL);
2022         g_free(dirname);
2023
2024         mimeview_save_all_info(errors, number - 1);
2025 }
2026
2027 static MimeInfo *mimeview_get_part_to_use(MimeView *mimeview)
2028 {
2029         MimeInfo *partinfo = NULL;
2030         if (mimeview->spec_part) {
2031                 partinfo = mimeview->spec_part;
2032                 mimeview->spec_part = NULL;
2033         } else {
2034                 partinfo = (MimeInfo *) g_object_get_data
2035                          (G_OBJECT(mimeview->popupmenu),
2036                          "pop_partinfo");
2037                 g_object_set_data(G_OBJECT(mimeview->popupmenu),
2038                                   "pop_partinfo", NULL);
2039                 if (!partinfo) { 
2040                         partinfo = mimeview_get_selected_part(mimeview);
2041                 }                        
2042         }
2043
2044         return partinfo;
2045 }
2046 /**
2047  * Menu callback: Save the selected attachment
2048  * \param mimeview Current display
2049  */
2050 void mimeview_save_as(MimeView *mimeview)
2051 {
2052         gchar *filename;
2053         gchar *filepath = NULL;
2054         gchar *filedir = NULL;
2055         MimeInfo *partinfo;
2056         gchar *partname = NULL;
2057
2058         if (!mimeview->opened) return;
2059         if (!mimeview->file) return;
2060
2061         partinfo = mimeview_get_part_to_use(mimeview);
2062
2063         cm_return_if_fail(partinfo != NULL);
2064         
2065         if (get_part_name(partinfo) == NULL) {
2066                 return;
2067         }
2068         partname = g_strdup(get_part_name(partinfo));
2069         
2070         if (!g_utf8_validate(partname, -1, NULL)) {
2071                 gchar *tmp = conv_filename_to_utf8(partname);
2072                 if (!tmp) {
2073                         tmp = conv_codeset_strdup(partname,
2074                                 conv_get_locale_charset_str(),
2075                                 CS_UTF_8);
2076                 }
2077                 if (tmp) {
2078                         g_free(partname);
2079                         partname = tmp;
2080                 }
2081         }
2082
2083         subst_for_filename(partname);
2084         
2085         if (prefs_common.attach_save_dir && *prefs_common.attach_save_dir)
2086                 filepath = g_strconcat(prefs_common.attach_save_dir,
2087                                        G_DIR_SEPARATOR_S, partname, NULL);
2088         else
2089                 filepath = g_strdup(partname);
2090
2091         g_free(partname);
2092
2093         manage_window_focus_in(gtk_widget_get_ancestor(mimeview->hbox, GTK_TYPE_WINDOW), NULL, NULL);
2094         filename = filesel_select_file_save(_("Save as"), filepath);
2095         if (!filename) {
2096                 g_free(filepath);
2097                 return;
2098         }
2099
2100         mimeview_write_part(filename, partinfo, TRUE);
2101
2102         filedir = g_path_get_dirname(filename);
2103         if (filedir && strcmp(filedir, ".")) {
2104                 g_free(prefs_common.attach_save_dir);
2105                 prefs_common.attach_save_dir = g_filename_to_utf8(filedir, -1, NULL, NULL, NULL);
2106         }
2107
2108         g_free(filedir);
2109         g_free(filepath);
2110 }
2111
2112 void mimeview_display_as_text(MimeView *mimeview)
2113 {
2114         MimeInfo *partinfo;
2115
2116         if (!mimeview->opened) return;
2117
2118         partinfo = mimeview_get_part_to_use(mimeview);
2119         mimeview_select_mimepart_icon(mimeview, partinfo);
2120         cm_return_if_fail(partinfo != NULL);
2121         mimeview_show_message_part(mimeview, partinfo);
2122 }
2123
2124 void mimeview_launch(MimeView *mimeview, MimeInfo *partinfo)
2125 {
2126         gchar *filename;
2127         gint err;
2128
2129         if (!mimeview->opened) return;
2130         if (!mimeview->file) return;
2131
2132         if (!partinfo)
2133                 partinfo = mimeview_get_part_to_use(mimeview);
2134
2135         cm_return_if_fail(partinfo != NULL);
2136
2137         filename = procmime_get_tmp_file_name(partinfo);
2138
2139         if ((err = procmime_get_part(filename, partinfo)) < 0)
2140                 alertpanel_error
2141                         (_("Couldn't save the part of multipart message: %s"), 
2142                                 g_strerror(-err));
2143         else
2144                 mimeview_view_file(filename, partinfo, NULL, mimeview);
2145
2146         g_free(filename);
2147 }
2148
2149 #ifndef G_OS_WIN32
2150 void mimeview_open_with(MimeView *mimeview)
2151 {
2152         MimeInfo *partinfo;
2153
2154         if (!mimeview) return;
2155         if (!mimeview->opened) return;
2156         if (!mimeview->file) return;
2157
2158         partinfo = mimeview_get_part_to_use(mimeview);
2159
2160         mimeview_open_part_with(mimeview, partinfo, FALSE);
2161 }
2162
2163 static void mimeview_open_part_with(MimeView *mimeview, MimeInfo *partinfo, gboolean automatic)
2164 {
2165         gchar *filename;
2166         gchar *cmd;
2167         gchar *mime_command = NULL;
2168         gchar *content_type = NULL;
2169         gint err;
2170
2171         cm_return_if_fail(partinfo != NULL);
2172
2173         filename = procmime_get_tmp_file_name(partinfo);
2174
2175         if ((err = procmime_get_part(filename, partinfo)) < 0) {
2176                 alertpanel_error
2177                         (_("Couldn't save the part of multipart message: %s"), 
2178                                 g_strerror(-err));
2179                 g_free(filename);
2180                 return;
2181         }
2182         
2183         if (!prefs_common.mime_open_cmd_history)
2184                 prefs_common.mime_open_cmd_history =
2185                         add_history(NULL, prefs_common.mime_open_cmd);
2186
2187         if ((partinfo->type == MIMETYPE_APPLICATION) &&
2188             (!g_ascii_strcasecmp(partinfo->subtype, "octet-stream"))) {
2189                 /* guess content-type from filename */
2190                 content_type = procmime_get_mime_type(filename);
2191         } 
2192         if (content_type == NULL) {
2193                 content_type = procmime_get_content_type_str(partinfo->type,
2194                         partinfo->subtype);
2195         }
2196         
2197         if ((partinfo->type == MIMETYPE_TEXT && !strcmp(partinfo->subtype, "html"))
2198         && prefs_common_get_uri_cmd() && prefs_common.uri_cmd[0]) {
2199                 mime_command = g_strdup(prefs_common_get_uri_cmd());
2200                 g_free(content_type);
2201                 content_type = NULL;
2202         } else if (partinfo->type != MIMETYPE_TEXT || !prefs_common_get_ext_editor_cmd()
2203         ||  !prefs_common_get_ext_editor_cmd()[0]) {
2204                 mime_command = mailcap_get_command_for_type(content_type, filename);
2205         } else {
2206                 mime_command = g_strdup(prefs_common_get_ext_editor_cmd());
2207                 g_free(content_type);
2208                 content_type = NULL;
2209         }
2210         if (mime_command == NULL) {
2211                 /* try with extension this time */
2212                 g_free(content_type);
2213                 content_type = procmime_get_mime_type(filename);
2214                 mime_command = mailcap_get_command_for_type(content_type, filename);
2215         }
2216
2217         if (mime_command == NULL)
2218                 automatic = FALSE;
2219         
2220         if (!automatic) {
2221                 gboolean remember = FALSE;
2222                 if (content_type != NULL)
2223                         cmd = input_dialog_combo_remember
2224                                 (_("Open with"),
2225                                  _("Enter the command-line to open file:\n"
2226                                    "('%s' will be replaced with file name)"),
2227                                  mime_command ? mime_command : prefs_common.mime_open_cmd,
2228                                  prefs_common.mime_open_cmd_history, &remember);
2229                 else
2230                         cmd = input_dialog_combo
2231                                 (_("Open with"),
2232                                  _("Enter the command-line to open file:\n"
2233                                    "('%s' will be replaced with file name)"),
2234                                  mime_command ? mime_command : prefs_common.mime_open_cmd,
2235                                  prefs_common.mime_open_cmd_history);
2236                 if (cmd && remember) {
2237                         mailcap_update_default(content_type, cmd);
2238                 }
2239                 g_free(mime_command);
2240         } else {
2241                 cmd = mime_command;
2242         }
2243         if (cmd) {
2244                 mimeview_view_file(filename, partinfo, cmd, mimeview);
2245                 g_free(prefs_common.mime_open_cmd);
2246                 prefs_common.mime_open_cmd = cmd;
2247                 prefs_common.mime_open_cmd_history =
2248                         add_history(prefs_common.mime_open_cmd_history, cmd);
2249         }
2250
2251         g_free(content_type);
2252         g_free(filename);
2253 }
2254 #endif
2255
2256 static void mimeview_send_to(MimeView *mimeview, MimeInfo *partinfo)
2257 {
2258         GList *attach_file = NULL;
2259         AttachInfo *ainfo = NULL;
2260         gchar *filename;
2261         gint err;
2262
2263         if (!mimeview->opened) return;
2264         if (!mimeview->file) return;
2265
2266         cm_return_if_fail(partinfo != NULL);
2267
2268         filename = procmime_get_tmp_file_name(partinfo);
2269
2270         if (!(err = procmime_get_part(filename, partinfo))) {
2271                 ainfo = g_new0(AttachInfo, 1);
2272                 ainfo->file = filename;
2273                 ainfo->name = g_strdup(get_part_name(partinfo));
2274                 ainfo->content_type = procmime_get_content_type_str(
2275                                         partinfo->type, partinfo->subtype);
2276                 ainfo->charset = g_strdup(procmime_mimeinfo_get_parameter(
2277                                         partinfo, "charset"));
2278                 attach_file = g_list_append(attach_file, ainfo);
2279                 
2280                 compose_new(NULL, NULL, attach_file);
2281                 
2282                 g_free(ainfo->name);
2283                 g_free(ainfo->content_type);
2284                 g_free(ainfo->charset);
2285                 g_free(ainfo);
2286                 g_list_free(attach_file);
2287         } else
2288                 alertpanel_error
2289                         (_("Couldn't save the part of multipart message: %s"), 
2290                                 g_strerror(-err));
2291         g_free(filename);
2292 }
2293
2294 static void mimeview_view_file(const gchar *filename, MimeInfo *partinfo,
2295                                const gchar *cmd, MimeView *mimeview)
2296 {
2297 #ifndef G_OS_WIN32
2298         gchar *p;
2299         gchar buf[BUFFSIZE];
2300
2301         if (cmd == NULL)
2302                 mimeview_open_part_with(mimeview, partinfo, TRUE);
2303         else {
2304                 if ((p = strchr(cmd, '%')) && *(p + 1) == 's' &&
2305                     !strchr(p + 2, '%')) {
2306                         g_snprintf(buf, sizeof(buf), cmd, filename);
2307                         if (!prefs_common.save_parts_readwrite)
2308                                 g_chmod(filename, S_IRUSR);
2309                         else
2310                                 g_chmod(filename, S_IRUSR|S_IWUSR);
2311                 } else {
2312                         g_warning("MIME viewer command-line is invalid: '%s'", cmd);
2313                         mimeview_open_part_with(mimeview, partinfo, FALSE);
2314                 }
2315                 if (execute_command_line(buf, TRUE, NULL) != 0) {
2316                         if (!prefs_common.save_parts_readwrite)
2317                                 g_chmod(filename, S_IRUSR|S_IWUSR);
2318                         mimeview_open_part_with(mimeview, partinfo, FALSE);
2319                 }
2320         }
2321 #else
2322         SHFILEINFO file_info;
2323         GError *error = NULL;
2324         gunichar2 *fn16 = g_utf8_to_utf16(filename, -1, NULL, NULL, &error);
2325
2326         if (error != NULL) {
2327                 alertpanel_error(_("Could not convert attachment name to UTF-16:\n\n%s"),
2328                                         error->message);
2329                 debug_print("filename '%s' conversion to UTF-16 failed\n", filename);
2330                 g_error_free(error);
2331                 return;
2332         }
2333
2334         if ((SHGetFileInfo((LPCWSTR)fn16, 0, &file_info, sizeof(SHFILEINFO), SHGFI_EXETYPE)) != 0) {
2335                 AlertValue val = alertpanel_full(_("Execute untrusted binary?"), 
2336                                       _("This attachment is an executable file. Executing "
2337                                         "untrusted binaries is dangerous and could compromise "
2338                                         "your computer.\n\n"
2339                                         "Do you want to run this file?"), GTK_STOCK_CANCEL, 
2340                                         _("Run binary"),
2341                                       NULL, ALERTFOCUS_FIRST, FALSE, NULL, ALERT_WARNING);
2342                 if (val == G_ALERTALTERNATE) {
2343                         debug_print("executing binary\n");
2344                         ShellExecute(NULL, L"open", (LPCWSTR)fn16, NULL, NULL, SW_SHOW);
2345                 }
2346         } else {
2347                 ShellExecute(NULL, L"open", (LPCWSTR)fn16, NULL, NULL, SW_SHOW);
2348         }
2349
2350         g_free(fn16);
2351         
2352 #endif
2353 }
2354
2355 void mimeview_register_viewer_factory(MimeViewerFactory *factory)
2356 {
2357         mimeviewer_factories = g_slist_append(mimeviewer_factories, factory);
2358 }
2359
2360 static gint cmp_viewer_by_factroy(gconstpointer a, gconstpointer b)
2361 {
2362         return ((MimeViewer *) a)->factory == (MimeViewerFactory *) b ? 0 : -1;
2363 }
2364
2365 void mimeview_unregister_viewer_factory(MimeViewerFactory *factory)
2366 {
2367         GSList *mimeview_list, *viewer_list;
2368
2369         for (mimeview_list = mimeviews; mimeview_list != NULL; mimeview_list = g_slist_next(mimeview_list)) {
2370                 MimeView *mimeview = (MimeView *) mimeview_list->data;
2371                 
2372                 if (mimeview->mimeviewer && mimeview->mimeviewer->factory == factory) {
2373                         mimeview_change_view_type(mimeview, MIMEVIEW_TEXT);
2374                         mimeview->mimeviewer = NULL;
2375                 }
2376
2377                 while ((viewer_list = g_slist_find_custom(mimeview->viewers, factory, cmp_viewer_by_factroy)) != NULL) {
2378                         MimeViewer *mimeviewer = (MimeViewer *) viewer_list->data;
2379
2380                         mimeviewer->destroy_viewer(mimeviewer);
2381                         mimeview->viewers = g_slist_remove(mimeview->viewers, mimeviewer);
2382                 }
2383         }
2384
2385         mimeviewer_factories = g_slist_remove(mimeviewer_factories, factory);
2386 }
2387
2388 static gboolean icon_clicked_cb (GtkWidget *button, GdkEventButton *event, MimeView *mimeview)
2389 {
2390         gint      num;
2391         MimeInfo *partinfo;
2392
2393         num      = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(button), "icon_number"));
2394         partinfo = g_object_get_data(G_OBJECT(button), "partinfo");
2395
2396         if (event->button == 1) {
2397                 icon_selected(mimeview, num, partinfo);
2398                 gtk_widget_grab_focus(button);
2399                 icon_list_toggle_by_mime_info(mimeview, partinfo);
2400         }
2401         part_button_pressed(mimeview, event, partinfo);
2402
2403         return FALSE;
2404 }
2405
2406 static void icon_selected (MimeView *mimeview, gint num, MimeInfo *partinfo)
2407 {
2408         GtkTreeModel *model = gtk_tree_view_get_model(GTK_TREE_VIEW(mimeview->ctree));
2409         GtkTreeIter iter;
2410         GtkTreePath *path;
2411         MimeInfo *curr = NULL;
2412         
2413         if (!gtk_tree_model_get_iter_first(model, &iter))
2414                 return;
2415         path = gtk_tree_model_get_path(model, &iter);
2416         
2417         do {
2418                 gtk_tree_model_get_iter(model, &iter, path);
2419                 gtk_tree_model_get(model, &iter, COL_DATA, &curr, -1);
2420                 if (curr == partinfo) {
2421                         GtkTreeSelection *sel = gtk_tree_view_get_selection(
2422                                                 GTK_TREE_VIEW(mimeview->ctree));
2423                         gtk_tree_selection_select_iter(sel, &iter);
2424                         gtk_tree_path_free(path);
2425                         return;
2426                 }
2427         } while (mimeview_tree_next(model, path));
2428         
2429         gtk_tree_path_free(path);
2430 }               
2431
2432 void mimeview_select_mimepart_icon(MimeView *mimeview, MimeInfo *partinfo)
2433 {
2434         icon_list_toggle_by_mime_info(mimeview, partinfo);
2435         icon_selected(mimeview, -1, partinfo);
2436 }
2437
2438 static gint icon_key_pressed(GtkWidget *button, GdkEventKey *event,
2439                              MimeView *mimeview)
2440 {
2441         SummaryView  *summaryview;
2442         
2443         if (!event) return FALSE;
2444
2445         switch (event->keyval) {
2446         case GDK_KEY_space:
2447                 if (mimeview_scroll_page(mimeview, FALSE))
2448                         return TRUE;
2449
2450                 mimeview_select_next_part(mimeview);
2451                 return TRUE;
2452
2453                 break;
2454         case GDK_KEY_BackSpace:
2455                 mimeview_scroll_page(mimeview, TRUE);
2456                 return TRUE;
2457         case GDK_KEY_Return:
2458         case GDK_KEY_KP_Enter:
2459                 mimeview_scroll_one_line(mimeview,
2460                                          (event->state & GDK_MOD1_MASK) != 0);
2461                 return TRUE;
2462         case GDK_KEY_y:
2463                 BREAK_ON_MODIFIER_KEY();
2464                 mimeview_save_as(mimeview);
2465                 return TRUE;
2466         case GDK_KEY_t:
2467                 BREAK_ON_MODIFIER_KEY();
2468                 mimeview_display_as_text(mimeview);
2469                 return TRUE;    
2470         case GDK_KEY_l:
2471                 BREAK_ON_MODIFIER_KEY();
2472                 mimeview_launch(mimeview, NULL);
2473                 return TRUE;
2474 #ifndef G_OS_WIN32
2475         case GDK_KEY_o:
2476                 BREAK_ON_MODIFIER_KEY();
2477                 mimeview_open_with(mimeview);
2478                 return TRUE;
2479 #endif
2480         case GDK_KEY_c:
2481                 BREAK_ON_MODIFIER_KEY();
2482                 mimeview_check_signature(mimeview);
2483                 return TRUE;
2484         case GDK_KEY_a:
2485                 BREAK_ON_MODIFIER_KEY();
2486                 mimeview_select_next_part(mimeview);
2487                 return TRUE;
2488         default:
2489                 break;
2490         }
2491
2492         if (!mimeview->messageview->mainwin) return FALSE;
2493         summaryview = mimeview->messageview->mainwin->summaryview;
2494         return summary_pass_key_press_event(summaryview, event);
2495 }
2496
2497 static gboolean icon_popup_menu(GtkWidget *widget, gpointer data)
2498 {
2499         MimeView *mimeview = (MimeView *)data;
2500         MimeInfo *partinfo = g_object_get_data(G_OBJECT(widget), "partinfo");
2501
2502         g_object_set_data(G_OBJECT(mimeview->popupmenu),
2503                           "pop_partinfo", partinfo);
2504         gtk_menu_popup(GTK_MENU(mimeview->popupmenu),
2505                        NULL, NULL, NULL, NULL,
2506                        0, gtk_get_current_event_time());
2507         return TRUE;
2508 }
2509
2510 static void icon_list_append_icon (MimeView *mimeview, MimeInfo *mimeinfo) 
2511 {
2512         GtkWidget *pixmap = NULL;
2513         GtkWidget *vbox;
2514         GtkWidget *button;
2515         gchar *tip;
2516         gchar *tiptmp;
2517         const gchar *desc = NULL; 
2518         gchar *sigshort = NULL;
2519         gchar *content_type;
2520         StockPixmap stockp;
2521         MimeInfo *partinfo;
2522         MimeInfo *siginfo = NULL;
2523         MimeInfo *encrypted = NULL;
2524 #ifdef GENERIC_UMPC
2525         GtkRequisition r;
2526 #endif
2527         
2528         if (!prefs_common.show_inline_attachments && mimeinfo->id)
2529                 return;
2530
2531         vbox = mimeview->icon_vbox;
2532         mimeview->icon_count++;
2533         button = gtk_event_box_new();
2534
2535         g_signal_connect(G_OBJECT(button), "motion-notify-event",
2536                          G_CALLBACK(mimeview_visi_notify), mimeview);
2537         g_signal_connect(G_OBJECT(button), "leave-notify-event",
2538                          G_CALLBACK(mimeview_leave_notify), mimeview);
2539         g_signal_connect(G_OBJECT(button), "enter-notify-event",
2540                          G_CALLBACK(mimeview_enter_notify), mimeview);
2541
2542         gtk_container_set_border_width(GTK_CONTAINER(button), 2);
2543         g_object_set_data(G_OBJECT(button), "icon_number", 
2544                           GINT_TO_POINTER(mimeview->icon_count));
2545         g_object_set_data(G_OBJECT(button), "partinfo", 
2546                           mimeinfo);
2547
2548         switch (mimeinfo->type) {
2549                 
2550         case MIMETYPE_TEXT:
2551                 if (mimeinfo->subtype && !g_ascii_strcasecmp(mimeinfo->subtype, "html"))
2552                         stockp = STOCK_PIXMAP_MIME_TEXT_HTML;
2553                 else if  (mimeinfo->subtype && !g_ascii_strcasecmp(mimeinfo->subtype, "enriched"))
2554                         stockp = STOCK_PIXMAP_MIME_TEXT_ENRICHED;
2555                 else if  (mimeinfo->subtype && !g_ascii_strcasecmp(mimeinfo->subtype, "calendar"))
2556                         stockp = STOCK_PIXMAP_MIME_TEXT_CALENDAR;
2557                 else if  (mimeinfo->subtype && (!g_ascii_strcasecmp(mimeinfo->subtype, "x-patch")
2558                                 || !g_ascii_strcasecmp(mimeinfo->subtype, "x-diff")))
2559                         stockp = STOCK_PIXMAP_MIME_TEXT_PATCH;
2560                 else
2561                         stockp = STOCK_PIXMAP_MIME_TEXT_PLAIN;
2562                 break;
2563         case MIMETYPE_MESSAGE:
2564                 stockp = STOCK_PIXMAP_MIME_MESSAGE;
2565                 break;
2566         case MIMETYPE_APPLICATION:
2567                 if (mimeinfo->subtype && (!g_ascii_strcasecmp(mimeinfo->subtype, "pgp-signature")
2568                     || !g_ascii_strcasecmp(mimeinfo->subtype, "x-pkcs7-signature")
2569                     || !g_ascii_strcasecmp(mimeinfo->subtype, "pkcs7-signature")))
2570                         stockp = STOCK_PIXMAP_MIME_PGP_SIG;
2571                 else if (mimeinfo->subtype && !g_ascii_strcasecmp(mimeinfo->subtype, "pdf"))
2572                         stockp = STOCK_PIXMAP_MIME_PDF;
2573                 else if  (mimeinfo->subtype && !g_ascii_strcasecmp(mimeinfo->subtype, "postscript"))
2574                         stockp = STOCK_PIXMAP_MIME_PS;
2575                 else
2576                         stockp = STOCK_PIXMAP_MIME_APPLICATION;
2577                 break;
2578         case MIMETYPE_IMAGE:
2579                 stockp = STOCK_PIXMAP_MIME_IMAGE;
2580                 break;
2581         case MIMETYPE_AUDIO:
2582                 stockp = STOCK_PIXMAP_MIME_AUDIO;
2583                 break;
2584         default:
2585                 stockp = STOCK_PIXMAP_MIME_UNKNOWN;
2586                 break;
2587         }
2588         
2589         partinfo = mimeinfo;
2590         while (partinfo != NULL) {
2591                 if (privacy_mimeinfo_is_signed(partinfo)) {
2592                         siginfo = partinfo;
2593                         break;
2594                 }
2595                 if (privacy_mimeinfo_is_encrypted(partinfo)) {
2596                         encrypted = partinfo;
2597                         break;
2598                 }
2599                 partinfo = procmime_mimeinfo_parent(partinfo);
2600         }       
2601
2602         if (siginfo != NULL) {
2603                 switch (privacy_mimeinfo_get_sig_status(siginfo)) {
2604                 case SIGNATURE_UNCHECKED:
2605                 case SIGNATURE_CHECK_FAILED:
2606                 case SIGNATURE_CHECK_TIMEOUT:
2607                         pixmap = stock_pixmap_widget_with_overlay(stockp,
2608                             STOCK_PIXMAP_PRIVACY_EMBLEM_SIGNED, OVERLAY_BOTTOM_RIGHT, 6, 3);
2609                         break;
2610                 case SIGNATURE_OK:
2611                         pixmap = stock_pixmap_widget_with_overlay(stockp,
2612                             STOCK_PIXMAP_PRIVACY_EMBLEM_PASSED, OVERLAY_BOTTOM_RIGHT, 6, 3);
2613                         break;
2614                 case SIGNATURE_WARN:
2615                 case SIGNATURE_KEY_EXPIRED:
2616                         pixmap = stock_pixmap_widget_with_overlay(stockp,
2617                             STOCK_PIXMAP_PRIVACY_EMBLEM_WARN, OVERLAY_BOTTOM_RIGHT, 6, 3);
2618                         break;
2619                 case SIGNATURE_INVALID:
2620                         pixmap = stock_pixmap_widget_with_overlay(stockp,
2621                             STOCK_PIXMAP_PRIVACY_EMBLEM_FAILED, OVERLAY_BOTTOM_RIGHT, 6, 3);
2622                         break;
2623                 }
2624                 sigshort = privacy_mimeinfo_sig_info_short(siginfo);
2625         } else if (encrypted != NULL) {
2626                         pixmap = stock_pixmap_widget_with_overlay(stockp,
2627                             STOCK_PIXMAP_PRIVACY_EMBLEM_ENCRYPTED, OVERLAY_BOTTOM_RIGHT, 6, 3);         
2628         } else {
2629                 pixmap = stock_pixmap_widget_with_overlay(stockp, 0,
2630                                                           OVERLAY_NONE, 6, 3);
2631         }
2632         gtk_container_add(GTK_CONTAINER(button), pixmap);
2633         if (!desc) {
2634                 if (prefs_common.attach_desc)
2635                         desc = get_part_description(mimeinfo);
2636                 else
2637                         desc = get_part_name(mimeinfo);
2638         }
2639
2640         content_type = procmime_get_content_type_str(mimeinfo->type,
2641                                                      mimeinfo->subtype);
2642
2643         tip = g_strconcat("<b>", _("Type:"), "  </b>", content_type,
2644                           "\n<b>", _("Size:"), " </b>",
2645                           to_human_readable((goffset)mimeinfo->length), NULL);
2646         g_free(content_type);
2647         if (desc && *desc) {
2648                 gchar *tmp = NULL, *escaped = NULL;
2649                 if (!g_utf8_validate(desc, -1, NULL)) {
2650                         tmp = conv_filename_to_utf8(desc);
2651                 } else {
2652                         tmp = g_strdup(desc);
2653                 }
2654                 escaped = g_markup_escape_text(tmp,-1);
2655                 
2656                 tiptmp = g_strconcat(tip, "\n<b>",
2657                                 prefs_common.attach_desc && mimeinfo->description ?
2658                                 _("Description:") : _("Filename:"),
2659                                 " </b>", escaped, NULL);
2660                 g_free(tip);
2661                 tip = tiptmp;
2662                 g_free(tmp);
2663                 g_free(escaped);
2664         }
2665         if (sigshort && *sigshort) {
2666                 gchar *sigshort_escaped =
2667                         g_markup_escape_text(sigshort, -1);
2668
2669                 tiptmp = g_strjoin("\n", tip, sigshort_escaped, NULL);
2670                 g_free(tip);
2671                 g_free(sigshort_escaped);
2672                 tip = tiptmp;
2673         }
2674         g_free(sigshort);
2675
2676         gtk_widget_set_tooltip_markup(button, tip);
2677         g_free(tip);
2678         gtk_widget_show_all(button);
2679         gtk_drag_source_set(button, GDK_BUTTON1_MASK|GDK_BUTTON3_MASK, 
2680                             mimeview_mime_types, 1, GDK_ACTION_COPY);
2681
2682         g_signal_connect(G_OBJECT(button), "popup-menu",
2683                          G_CALLBACK(icon_popup_menu), mimeview);
2684         g_signal_connect(G_OBJECT(button), "button_release_event", 
2685                          G_CALLBACK(icon_clicked_cb), mimeview);
2686         g_signal_connect(G_OBJECT(button), "key_press_event", 
2687                          G_CALLBACK(icon_key_pressed), mimeview);
2688         g_signal_connect(G_OBJECT(button), "drag_data_get",
2689                          G_CALLBACK(mimeview_drag_data_get), mimeview);
2690         gtk_box_pack_start(GTK_BOX(vbox), button, FALSE, FALSE, 0);
2691 #ifdef GENERIC_UMPC
2692         gtk_widget_size_request(pixmap, &r);
2693         gtk_widget_set_size_request(button, -1, r.height + 4);
2694 #endif
2695
2696 }
2697
2698 static void icon_list_clear (MimeView *mimeview)
2699 {
2700         GList     *child, *orig;
2701         GtkAdjustment *adj;
2702                 
2703         orig = gtk_container_get_children(GTK_CONTAINER(mimeview->icon_vbox));
2704         for (child = orig; child != NULL; child = g_list_next(child)) {
2705                 gtkut_container_remove(GTK_CONTAINER(mimeview->icon_vbox), 
2706                                        GTK_WIDGET(child->data));
2707         }
2708         g_list_free(orig);
2709         mimeview->icon_count = 0;
2710         adj  = gtk_layout_get_vadjustment(GTK_LAYOUT(mimeview->icon_scroll));
2711         gtk_adjustment_set_value(adj, gtk_adjustment_get_lower(adj));
2712         gtk_adjustment_changed(adj);
2713 }
2714
2715 /*!
2716  *\brief        Used to 'click' the next or previous icon.
2717  *
2718  *\return       true if the icon 'number' exists and was selected.
2719  */
2720 static void icon_scroll_size_allocate_cb(GtkWidget *widget, 
2721                                          GtkAllocation *size, MimeView *mimeview)
2722 {
2723         GtkAllocation vbox_size;
2724         GtkAllocation layout_size;
2725         GtkAdjustment *adj;
2726         guint width;
2727         guint height;
2728
2729         adj = gtk_layout_get_vadjustment(GTK_LAYOUT(mimeview->icon_scroll));
2730
2731         gtk_widget_get_allocation(mimeview->icon_vbox, &vbox_size);
2732         gtk_widget_get_allocation(mimeview->icon_scroll, &layout_size);
2733                 
2734         gtk_layout_get_size(GTK_LAYOUT(mimeview->icon_scroll), &width, &height);
2735         gtk_layout_set_size(GTK_LAYOUT(mimeview->icon_scroll), 
2736                             width, 
2737                             MAX(vbox_size.height, layout_size.height));
2738         gtk_adjustment_set_step_increment(adj, 10);
2739 }
2740
2741 static void icon_list_create(MimeView *mimeview, MimeInfo *mimeinfo)
2742 {
2743         GtkRequisition size;
2744         GtkRequisition requisition;
2745
2746         cm_return_if_fail(mimeinfo != NULL);
2747
2748         while (mimeinfo != NULL) {
2749                 if (mimeinfo->type != MIMETYPE_MULTIPART)
2750                         icon_list_append_icon(mimeview, mimeinfo);
2751                 if (mimeinfo->node->children != NULL)
2752                         icon_list_create(mimeview, 
2753                                 (MimeInfo *) mimeinfo->node->children->data);
2754                 mimeinfo = mimeinfo->node->next != NULL 
2755                          ? (MimeInfo *) mimeinfo->node->next->data 
2756                          : NULL;
2757         }
2758         gtk_widget_size_request(mimeview->icon_vbox, &size);
2759         gtk_widget_get_requisition(mimeview->icon_mainbox, &requisition);
2760         if (size.width > requisition.width) {
2761                 gtk_widget_set_size_request(mimeview->icon_mainbox, 
2762                                             size.width, -1);
2763         }
2764         if (mimeview->opened)
2765                 icon_list_toggle_by_mime_info(mimeview,
2766                         mimeview_get_node_part(mimeview, mimeview->opened));
2767 }
2768
2769 static void icon_list_toggle_by_mime_info (MimeView     *mimeview,
2770                                            MimeInfo     *mimeinfo)
2771 {
2772         GList *children, *child;
2773         
2774         children = gtk_container_get_children(GTK_CONTAINER(mimeview->icon_vbox));
2775         for (child = children; child != NULL; child = g_list_next(child)) {
2776                 gboolean *highlight = NULL;
2777                 GtkWidget *icon = gtk_bin_get_child(GTK_BIN(child->data));
2778
2779                 if (!GTK_IS_EVENT_BOX(child->data))
2780                         continue;
2781
2782                 highlight = g_object_get_data(G_OBJECT(icon), "highlight");
2783                 *highlight = (g_object_get_data(G_OBJECT(child->data),
2784                                       "partinfo") == (gpointer)mimeinfo);
2785
2786                 gtk_widget_queue_draw(icon);
2787         }
2788         g_list_free(children);
2789 }
2790
2791 static void ctree_size_allocate_cb(GtkWidget *widget, GtkAllocation *allocation,
2792                                     MimeView *mimeview)
2793 {
2794         prefs_common.mimeview_tree_height = allocation->height;
2795 }
2796
2797 static gint mime_toggle_button_cb(GtkWidget *button, GdkEventButton *event,
2798                                     MimeView *mimeview)
2799 {
2800         g_object_ref(button); 
2801
2802         mimeview_leave_notify(button, NULL, NULL);
2803
2804         mimeview->ctree_mode = !mimeview->ctree_mode;
2805         if (mimeview->ctree_mode) {
2806                 gtk_arrow_set(GTK_ARROW(gtk_bin_get_child(GTK_BIN((button)))), GTK_ARROW_RIGHT, 
2807                                         GTK_SHADOW_NONE);
2808                 gtk_widget_hide(mimeview->icon_mainbox);
2809                 gtk_widget_show(mimeview->ctree_mainbox);
2810                 gtk_paned_set_position(GTK_PANED(mimeview->paned),
2811                                         prefs_common.mimeview_tree_height);
2812
2813                 gtkut_container_remove(GTK_CONTAINER(mimeview->icon_mainbox), 
2814                                         button);
2815                 gtk_box_pack_end(GTK_BOX(mimeview->ctree_mainbox), 
2816                                    button, FALSE, FALSE, 0);
2817         } else {
2818                 gtk_arrow_set(GTK_ARROW(gtk_bin_get_child(GTK_BIN((button)))), GTK_ARROW_LEFT, 
2819                               GTK_SHADOW_NONE);
2820                 gtk_widget_hide(mimeview->ctree_mainbox);
2821                 gtk_widget_show(mimeview->icon_mainbox);
2822                 gtk_paned_set_position(GTK_PANED(mimeview->paned), 0);
2823
2824                 gtkut_container_remove(GTK_CONTAINER(mimeview->ctree_mainbox), 
2825                                         button);
2826                 gtk_box_pack_start(GTK_BOX(mimeview->icon_mainbox), 
2827                                    button, FALSE, FALSE, 0);
2828                 gtk_box_reorder_child(GTK_BOX(gtk_widget_get_parent(button)), button, 0);
2829                 if (mimeview->opened)
2830                         icon_list_toggle_by_mime_info(mimeview,
2831                                         mimeview_get_node_part(mimeview, mimeview->opened));
2832                 summary_grab_focus(mimeview->mainwin->summaryview);
2833         }
2834         g_object_unref(button);
2835         return TRUE;
2836 }
2837
2838 void mimeview_update (MimeView *mimeview)
2839 {
2840         if (mimeview && mimeview->mimeinfo) {
2841                 icon_list_clear(mimeview);
2842                 icon_list_create(mimeview, mimeview->mimeinfo);
2843         }
2844 }
2845
2846 void mimeview_handle_cmd(MimeView *mimeview, const gchar *cmd, GdkEventButton *event, gpointer data)
2847 {
2848         MessageView *msgview = NULL;
2849         MainWindow *mainwin = NULL;
2850         
2851         if (!cmd)
2852                 return;
2853         
2854         msgview = mimeview->messageview;
2855         if (!msgview)
2856                 return;
2857                 
2858         mainwin = msgview->mainwin;
2859         if (!mainwin)
2860                 return;
2861                 
2862         g_object_set_data(G_OBJECT(mimeview->popupmenu),
2863                           "pop_partinfo", NULL);
2864
2865         if (!strcmp(cmd, "sc://view_log"))
2866                 log_window_show(mainwin->logwin);
2867         else if (!strcmp(cmd, "sc://save_as"))
2868                 mimeview_save_as(mimeview);
2869         else if (!strcmp(cmd, "sc://display_as_text"))
2870                 mimeview_display_as_text(mimeview);
2871 #ifndef G_OS_WIN32
2872         else if (!strcmp(cmd, "sc://open_with"))
2873                 mimeview_open_with(mimeview);
2874 #endif
2875         else if (!strcmp(cmd, "sc://open"))
2876                 mimeview_launch(mimeview, NULL);
2877         else if (!strcmp(cmd, "sc://select_attachment") && data != NULL) {
2878                 icon_list_toggle_by_mime_info(mimeview, (MimeInfo *)data);
2879                 icon_selected(mimeview, -1, (MimeInfo *)data);
2880         } else if (!strcmp(cmd, "sc://open_attachment") && data != NULL) {
2881                 mimeview_launch(mimeview, (MimeInfo *)data);
2882         } else if (!strcmp(cmd, "sc://menu_attachment") && data != NULL) {
2883                 mimeview->spec_part = (MimeInfo *)data;
2884                 part_button_pressed(mimeview, event, (MimeInfo *)data);
2885         } else if (!strncmp(cmd, "sc://search_tags:", strlen("sc://search_tags:"))) {
2886                 const gchar *tagname = cmd + strlen("sc://search_tags:");
2887                 gchar *buf = g_strdup_printf("tag matchcase \"%s\"", tagname);
2888                 gtk_toggle_button_set_active(
2889                                 GTK_TOGGLE_BUTTON(mimeview->messageview->mainwin->summaryview->toggle_search), 
2890                                 TRUE);
2891                 quicksearch_set(mimeview->messageview->mainwin->summaryview->quicksearch, 
2892                                 ADVANCED_SEARCH_EXTENDED, buf);
2893                 g_free(buf);
2894         }
2895 }
2896
2897 gboolean mimeview_scroll_page(MimeView *mimeview, gboolean up)
2898 {
2899         if (mimeview->type == MIMEVIEW_TEXT)
2900                 return textview_scroll_page(mimeview->textview, up);
2901         else if (mimeview->mimeviewer) {
2902                 MimeViewer *mimeviewer = mimeview->mimeviewer;
2903                 if (mimeviewer->scroll_page)
2904                         return mimeviewer->scroll_page(mimeviewer, up);
2905         }
2906         return TRUE;
2907 }
2908
2909 void mimeview_scroll_one_line(MimeView *mimeview, gboolean up)
2910 {
2911         if (mimeview->type == MIMEVIEW_TEXT)
2912                 textview_scroll_one_line(mimeview->textview, up);
2913         else if (mimeview->mimeviewer) {
2914                 MimeViewer *mimeviewer = mimeview->mimeviewer;
2915                 if (mimeviewer->scroll_one_line)
2916                         mimeviewer->scroll_one_line(mimeviewer, up);
2917         }
2918 }