2007-04-18 [paul] 2.9.0cvs7
[claws.git] / src / mimeview.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2007 Hiroyuki Yamamoto and the Claws Mail team
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 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, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #include "defs.h"
25
26 #include <glib.h>
27 #include <glib/gi18n.h>
28 #include <gdk/gdkkeysyms.h>
29 #include <gtk/gtknotebook.h>
30 #include <gtk/gtkscrolledwindow.h>
31 #include <gtk/gtkctree.h>
32 #include <gtk/gtkvbox.h>
33 #include <gtk/gtkhbox.h>
34 #include <gtk/gtkvpaned.h>
35 #include <gtk/gtktext.h>
36 #include <gtk/gtksignal.h>
37 #include <gtk/gtkmenu.h>
38 #include <gtk/gtkdnd.h>
39 #include <gtk/gtkselection.h>
40 #include <gtk/gtktooltips.h>
41 #include <gtk/gtkcontainer.h>
42 #include <gtk/gtkbutton.h>
43 #include <stdio.h>
44
45 #ifndef HAVE_APACHE_FNMATCH
46 /* kludge: apache's fnmatch clashes with <regex.h>, don't include
47  * fnmatch.h */
48 #include <fnmatch.h>
49 #endif
50
51 #include "main.h"
52 #include "mimeview.h"
53 #include "textview.h"
54 #include "procmime.h"
55 #include "summaryview.h"
56 #include "menu.h"
57 #include "filesel.h"
58 #include "alertpanel.h"
59 #include "inputdialog.h"
60 #include "utils.h"
61 #include "gtkutils.h"
62 #include "prefs_common.h"
63 #include "procheader.h"
64 #include "stock_pixmap.h"
65 #include "gtk/gtkvscrollbutton.h"
66 #include "gtk/logwindow.h"
67 #include "timing.h"
68
69 typedef enum
70 {
71         COL_MIMETYPE = 0,
72         COL_SIZE     = 1,
73         COL_NAME     = 2
74 } MimeViewColumnPos;
75
76 #define N_MIMEVIEW_COLS 3
77
78 static void mimeview_set_multipart_tree         (MimeView       *mimeview,
79                                                  MimeInfo       *mimeinfo,
80                                                  GtkCTreeNode   *parent);
81 static GtkCTreeNode *mimeview_append_part       (MimeView       *mimeview,
82                                                  MimeInfo       *partinfo,
83                                                  GtkCTreeNode   *parent);
84 static void mimeview_show_message_part          (MimeView       *mimeview,
85                                                  MimeInfo       *partinfo);
86 static void mimeview_change_view_type           (MimeView       *mimeview,
87                                                  MimeViewType    type);
88 static gchar *mimeview_get_filename_for_part            (MimeInfo       *partinfo,
89                                                  const gchar    *basedir,
90                                                  gint            number);
91 static gboolean mimeview_write_part             (const gchar    *filename,
92                                                  MimeInfo       *partinfo);
93
94 static void mimeview_selected           (GtkCTree       *ctree,
95                                          GtkCTreeNode   *node,
96                                          gint            column,
97                                          MimeView       *mimeview);
98 static void mimeview_start_drag         (GtkWidget      *widget,
99                                          gint            button,
100                                          GdkEvent       *event,
101                                          MimeView       *mimeview);
102 static gint mimeview_button_pressed     (GtkWidget      *widget,
103                                          GdkEventButton *event,
104                                          MimeView       *mimeview);
105 static gint mimeview_key_pressed        (GtkWidget      *widget,
106                                          GdkEventKey    *event,
107                                          MimeView       *mimeview);
108
109 static void mimeview_drag_data_get      (GtkWidget        *widget,
110                                          GdkDragContext   *drag_context,
111                                          GtkSelectionData *selection_data,
112                                          guint             info,
113                                          guint             time,
114                                          MimeView         *mimeview);
115
116 static gboolean mimeview_scrolled       (GtkWidget      *widget,
117                                          GdkEventScroll *event,
118                                          MimeView       *mimeview);
119 static void mimeview_display_as_text    (MimeView       *mimeview);
120 static void mimeview_save_as            (MimeView       *mimeview);
121 static void mimeview_save_all           (MimeView       *mimeview);
122 static void mimeview_launch             (MimeView       *mimeview,
123                                          MimeInfo       *partinfo);
124 static void mimeview_open_with          (MimeView       *mimeview);
125 static void mimeview_open_part_with     (MimeView       *mimeview,
126                                          MimeInfo       *partinfo,
127                                          gboolean        automatic);
128 static void mimeview_view_file          (const gchar    *filename,
129                                          MimeInfo       *partinfo,
130                                          const gchar    *cmd,
131                                          MimeView       *mimeview);
132 static gboolean icon_clicked_cb         (GtkWidget      *button, 
133                                          GdkEventButton *event, 
134                                          MimeView       *mimeview);
135 static void icon_selected               (MimeView       *mimeview, 
136                                          gint            num, 
137                                          MimeInfo       *partinfo);
138 static gint icon_key_pressed            (GtkWidget      *button, 
139                                          GdkEventKey    *event,
140                                          MimeView       *mimeview);
141 static void toggle_icon                 (GtkToggleButton *button,
142                                          MimeView       *mimeview);
143 static void icon_list_append_icon       (MimeView       *mimeview, 
144                                          MimeInfo       *mimeinfo);
145 static void icon_list_create            (MimeView       *mimeview, 
146                                          MimeInfo       *mimeinfo);
147 static void icon_list_clear             (MimeView       *mimeview);
148 static void icon_list_toggle_by_mime_info (MimeView     *mimeview,
149                                            MimeInfo     *mimeinfo);
150 static gboolean icon_list_select_by_number(MimeView     *mimeview,
151                                            gint          number);
152 static void mime_toggle_button_cb       (GtkWidget      *button,
153                                          MimeView       *mimeview);
154 static gboolean part_button_pressed     (MimeView       *mimeview, 
155                                          GdkEventButton *event, 
156                                          MimeInfo       *partinfo);
157 static void icon_scroll_size_allocate_cb(GtkWidget      *widget, 
158                                          GtkAllocation  *layout_size, 
159                                          MimeView       *mimeview);
160 static MimeInfo *mimeview_get_part_to_use(MimeView *mimeview);
161
162 static void mimeview_launch_cb(MimeView *mimeview)
163 {
164         mimeview_launch(mimeview, mimeview_get_part_to_use(mimeview));
165 }
166 static GtkItemFactoryEntry mimeview_popup_entries[] =
167 {
168         {N_("/_Open"),            NULL, mimeview_launch_cb,       0, NULL},
169         {N_("/Open _with..."),    NULL, mimeview_open_with,       0, NULL},
170         {N_("/_Display as text"), NULL, mimeview_display_as_text, 0, NULL},
171         {N_("/_Save as..."),      NULL, mimeview_save_as,         0, NULL},
172         {N_("/Save _all..."),     NULL, mimeview_save_all,        0, NULL},
173 };
174
175 static GtkTargetEntry mimeview_mime_types[] =
176 {
177         {"text/uri-list", 0, 0}
178 };
179
180 GSList *mimeviewer_factories;
181 GSList *mimeviews;
182
183 MimeView *mimeview_create(MainWindow *mainwin)
184 {
185         MimeView *mimeview;
186
187         GtkWidget *paned;
188         GtkWidget *scrolledwin;
189         GtkWidget *ctree;
190         GtkWidget *mime_notebook;
191         GtkWidget *popupmenu;
192         GtkWidget *ctree_mainbox;
193         GtkWidget *vbox;
194         GtkWidget *mime_toggle;
195         GtkWidget *icon_mainbox;
196         GtkWidget *icon_scroll;
197         GtkWidget *icon_vbox;
198         GtkWidget *arrow;
199         GtkWidget *scrollbutton;
200         GtkWidget *hbox;
201         GtkTooltips *tooltips;
202         GtkItemFactory *popupfactory;
203         NoticeView *siginfoview;
204         gchar *titles[N_MIMEVIEW_COLS];
205         gint n_entries;
206         gint i;
207
208         debug_print("Creating MIME view...\n");
209         mimeview = g_new0(MimeView, 1);
210
211         titles[COL_MIMETYPE] = _("MIME Type");
212         titles[COL_SIZE]     = _("Size");
213         titles[COL_NAME]     = _("Name");
214
215         scrolledwin = gtk_scrolled_window_new(NULL, NULL);
216         gtk_widget_show(scrolledwin);
217         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledwin),
218                                        GTK_POLICY_AUTOMATIC,
219                                        GTK_POLICY_AUTOMATIC);
220
221         ctree = gtk_sctree_new_with_titles(N_MIMEVIEW_COLS, 0, titles);
222         gtk_widget_show(ctree);
223         gtk_clist_set_selection_mode(GTK_CLIST(ctree), GTK_SELECTION_BROWSE);
224         gtk_ctree_set_line_style(GTK_CTREE(ctree), GTK_CTREE_LINES_NONE);
225         gtk_clist_set_column_justification(GTK_CLIST(ctree), COL_SIZE,
226                                            GTK_JUSTIFY_RIGHT);
227         gtk_clist_set_column_width(GTK_CLIST(ctree), COL_MIMETYPE, 240);
228         gtk_clist_set_column_width(GTK_CLIST(ctree), COL_SIZE, 90);
229         for (i = 0; i < N_MIMEVIEW_COLS; i++)
230                 GTK_WIDGET_UNSET_FLAGS(GTK_CLIST(ctree)->column[i].button,
231                                        GTK_CAN_FOCUS);
232         gtk_container_add(GTK_CONTAINER(scrolledwin), ctree);
233
234         g_signal_connect(G_OBJECT(ctree), "tree_select_row",
235                          G_CALLBACK(mimeview_selected), mimeview);
236         g_signal_connect(G_OBJECT(ctree), "button_release_event",
237                          G_CALLBACK(mimeview_button_pressed), mimeview);
238         g_signal_connect(G_OBJECT(ctree), "key_press_event",
239                          G_CALLBACK(mimeview_key_pressed), mimeview);
240         g_signal_connect(G_OBJECT (ctree),"start_drag",
241                          G_CALLBACK (mimeview_start_drag), mimeview);
242         g_signal_connect(G_OBJECT(ctree), "drag_data_get",
243                          G_CALLBACK(mimeview_drag_data_get), mimeview);
244
245         mime_notebook = gtk_notebook_new();
246         gtk_widget_show(mime_notebook);
247         GTK_WIDGET_UNSET_FLAGS(mime_notebook, GTK_CAN_FOCUS);
248         gtk_notebook_set_show_tabs(GTK_NOTEBOOK(mime_notebook), FALSE);
249         gtk_notebook_set_show_border(GTK_NOTEBOOK(mime_notebook), FALSE);
250         
251         icon_vbox = gtk_vbox_new(FALSE, 2);
252         gtk_widget_show(icon_vbox);
253         icon_scroll = gtk_layout_new(NULL, NULL);
254         gtk_widget_show(icon_scroll);
255         gtk_layout_put(GTK_LAYOUT(icon_scroll), icon_vbox, 0, 0);
256         scrollbutton = gtk_vscrollbutton_new(gtk_layout_get_vadjustment(GTK_LAYOUT(icon_scroll)));
257         gtk_widget_show(scrollbutton);
258
259         g_signal_connect(G_OBJECT(icon_scroll), "scroll_event",
260                          G_CALLBACK(mimeview_scrolled), mimeview);
261
262         mime_toggle = gtk_toggle_button_new();
263         gtk_widget_show(mime_toggle);
264         arrow = gtk_arrow_new(GTK_ARROW_LEFT, GTK_SHADOW_NONE);
265         gtk_widget_show(arrow);
266         gtk_container_add(GTK_CONTAINER(mime_toggle), arrow);
267         g_signal_connect(G_OBJECT(mime_toggle), "toggled", 
268                          G_CALLBACK(mime_toggle_button_cb), mimeview);
269
270         icon_mainbox = gtk_vbox_new(FALSE, 0);
271         gtk_widget_show(icon_mainbox);
272         gtk_box_pack_start(GTK_BOX(icon_mainbox), mime_toggle, FALSE, FALSE, 0);
273         gtk_box_pack_start(GTK_BOX(icon_mainbox), icon_scroll, TRUE, TRUE, 3);
274         gtk_box_pack_end(GTK_BOX(icon_mainbox), scrollbutton, FALSE, FALSE, 0);
275         g_signal_connect(G_OBJECT(icon_mainbox), "size_allocate", 
276                          G_CALLBACK(icon_scroll_size_allocate_cb), mimeview);
277         
278         ctree_mainbox = gtk_hbox_new(FALSE, 0); 
279         gtk_box_pack_start(GTK_BOX(ctree_mainbox), scrolledwin, TRUE, TRUE, 0);
280
281         n_entries = sizeof(mimeview_popup_entries) /
282                 sizeof(mimeview_popup_entries[0]);
283         popupmenu = menu_create_items(mimeview_popup_entries, n_entries,
284                                       "<MimeView>", &popupfactory, mimeview);
285         tooltips = gtk_tooltips_new();
286
287         vbox = gtk_vbox_new(FALSE, 0);
288         gtk_widget_show(vbox);
289         siginfoview = noticeview_create(mainwin);
290         noticeview_hide(siginfoview);
291         noticeview_set_icon_clickable(siginfoview, TRUE);
292         gtk_box_pack_start(GTK_BOX(vbox), mime_notebook, TRUE, TRUE, 0);
293         gtk_box_pack_end(GTK_BOX(vbox), GTK_WIDGET_PTR(siginfoview), FALSE, FALSE, 0);
294
295         paned = gtk_vpaned_new();
296         gtk_widget_show(paned);
297         gtk_paned_set_gutter_size(GTK_PANED(paned), 0);
298         gtk_paned_pack1(GTK_PANED(paned), ctree_mainbox, FALSE, TRUE);
299         gtk_paned_pack2(GTK_PANED(paned), vbox, TRUE, TRUE);
300         
301         hbox = gtk_hbox_new(FALSE, 0);
302         gtk_box_pack_start(GTK_BOX(hbox), paned, TRUE, TRUE, 0);
303         gtk_box_pack_start(GTK_BOX(hbox), icon_mainbox, FALSE, FALSE, 0);
304
305         gtk_widget_show(hbox);
306         gtk_widget_hide(ctree_mainbox);
307
308         mimeview->hbox          = hbox;
309         mimeview->paned         = paned;
310         mimeview->scrolledwin   = scrolledwin;
311         mimeview->ctree         = ctree;
312         mimeview->mime_notebook = mime_notebook;
313         mimeview->popupmenu     = popupmenu;
314         mimeview->popupfactory  = popupfactory;
315         mimeview->type          = -1;
316         mimeview->ctree_mainbox = ctree_mainbox;
317         mimeview->icon_scroll   = icon_scroll;
318         mimeview->icon_vbox     = icon_vbox;
319         mimeview->icon_mainbox  = icon_mainbox;
320         mimeview->icon_count    = 0;
321         mimeview->mainwin       = mainwin;
322         mimeview->tooltips      = tooltips;
323         mimeview->oldsize       = 60;
324         mimeview->mime_toggle   = mime_toggle;
325         mimeview->siginfoview   = siginfoview;
326         mimeview->scrollbutton  = scrollbutton;
327         mimeview->target_list   = gtk_target_list_new(mimeview_mime_types, 1); 
328         
329         mimeviews = g_slist_prepend(mimeviews, mimeview);
330
331         return mimeview;
332 }
333
334 void mimeview_init(MimeView *mimeview)
335 {
336         textview_init(mimeview->textview);
337
338         gtk_container_add(GTK_CONTAINER(mimeview->mime_notebook),
339                 GTK_WIDGET_PTR(mimeview->textview));
340 }
341
342 static gboolean any_part_is_signed(MimeInfo *mimeinfo)
343 {
344         while (mimeinfo) {
345                 if (privacy_mimeinfo_is_signed(mimeinfo))
346                         return TRUE;
347                 mimeinfo = procmime_mimeinfo_next(mimeinfo);
348         }
349
350         return FALSE;
351 }
352
353 void mimeview_show_message(MimeView *mimeview, MimeInfo *mimeinfo,
354                            const gchar *file)
355 {
356         GtkCTree *ctree = GTK_CTREE(mimeview->ctree);
357         GtkCTreeNode *node;
358
359         mimeview_clear(mimeview);
360
361         g_return_if_fail(file != NULL);
362         g_return_if_fail(mimeinfo != NULL);
363
364         mimeview->mimeinfo = mimeinfo;
365
366         mimeview->file = g_strdup(file);
367
368         g_signal_handlers_block_by_func(G_OBJECT(ctree), mimeview_selected,
369                                         mimeview);
370
371         /* check if the mail's signed - it can change the mail structure */
372         
373         if (any_part_is_signed(mimeinfo))
374                 debug_print("signed mail\n");
375
376         mimeview_set_multipart_tree(mimeview, mimeinfo, NULL);
377         icon_list_clear(mimeview);
378         icon_list_create(mimeview, mimeinfo);
379
380         g_signal_handlers_unblock_by_func(G_OBJECT(ctree),
381                                           mimeview_selected, mimeview);
382
383         node = GTK_CTREE_NODE(GTK_CLIST(ctree)->row_list);
384         if (node) {
385                 gtk_ctree_select(ctree, node);
386                 icon_list_toggle_by_mime_info
387                         (mimeview, gtk_ctree_node_get_row_data(ctree, node));
388                 gtkut_ctree_set_focus_row(ctree, node);
389         }
390 }
391
392 #ifdef USE_PTHREAD
393 static void mimeview_check_sig_cancel_now(MimeView *mimeview);
394 #endif
395
396 static void mimeview_free_mimeinfo(MimeView *mimeview)
397 {
398         gboolean defer = FALSE;
399 #ifdef USE_PTHREAD
400         defer = (mimeview->check_data != NULL);
401         if (defer)
402                 mimeview->check_data->free_after_use = TRUE;
403 #endif
404         if (mimeview->mimeinfo != NULL && !defer) {
405                 procmime_mimeinfo_free_all(mimeview->mimeinfo);
406                 mimeview->mimeinfo = NULL;
407         } else if (defer) {
408 #ifdef USE_PTHREAD
409                 debug_print("deferring free(mimeinfo) and cancelling check\n");
410                 mimeview_check_sig_cancel_now(mimeview);
411 #endif
412         }
413 }
414
415 void mimeview_destroy(MimeView *mimeview)
416 {
417         GSList *cur;
418         
419         for (cur = mimeview->viewers; cur != NULL; cur = g_slist_next(cur)) {
420                 MimeViewer *viewer = (MimeViewer *) cur->data;
421                 viewer->destroy_viewer(viewer);
422         }
423         g_slist_free(mimeview->viewers);
424         gtk_target_list_unref(mimeview->target_list);
425
426         mimeview_free_mimeinfo(mimeview);
427 #ifdef USE_PTHREAD
428         if (mimeview->check_data) {
429                 mimeview->check_data->destroy_mimeview = TRUE;
430                 debug_print("deferring destroy\n");
431         } else 
432 #endif
433         {
434                 g_free(mimeview->file);
435                 g_free(mimeview);
436                 mimeviews = g_slist_remove(mimeviews, mimeview);
437         }
438         
439 }
440
441 MimeInfo *mimeview_get_selected_part(MimeView *mimeview)
442 {
443         return gtk_ctree_node_get_row_data
444                 (GTK_CTREE(mimeview->ctree), mimeview->opened);
445 }
446
447 gint mimeview_get_selected_part_num(MimeView *mimeview)
448 {
449         gint i = 0;
450         GList *rows = GTK_CLIST(mimeview->ctree)->row_list;
451         while (rows) {
452                 if (mimeview->opened == GTK_CTREE_NODE(rows))
453                         return i;
454                 i++;
455                 rows = rows->next;
456         }
457         return -1;
458 }
459
460 void mimeview_select_part_num(MimeView *mimeview, gint i)
461 {
462         if (i < 0)
463                 return;
464         gtk_clist_unselect_all(GTK_CLIST(mimeview->ctree));
465         gtk_clist_select_row(GTK_CLIST(mimeview->ctree), i, -1);
466         gtkut_clist_set_focus_row(GTK_CLIST(mimeview->ctree), i);
467 }
468
469 static void mimeview_set_multipart_tree(MimeView *mimeview,
470                                         MimeInfo *mimeinfo,
471                                         GtkCTreeNode *parent)
472 {
473         GtkCTreeNode *node;
474
475         g_return_if_fail(mimeinfo != NULL);
476
477         while (mimeinfo != NULL) {
478                 node = mimeview_append_part(mimeview, mimeinfo, parent);
479
480                 if (mimeinfo->node->children)
481                         mimeview_set_multipart_tree(mimeview, (MimeInfo *) mimeinfo->node->children->data, node);
482                 mimeinfo = mimeinfo->node->next != NULL ? (MimeInfo *) mimeinfo->node->next->data : NULL;
483         }
484 }
485
486 static const gchar *get_real_part_name(MimeInfo *partinfo)
487 {
488         const gchar *name = NULL;
489
490         name = procmime_mimeinfo_get_parameter(partinfo, "filename");
491         if (name == NULL)
492                 name = procmime_mimeinfo_get_parameter(partinfo, "name");
493
494         return name;
495 }
496
497 static const gchar *get_part_name(MimeInfo *partinfo)
498 {
499         const gchar *name;
500
501         name = get_real_part_name(partinfo);
502         if (name == NULL)
503                 name = "";
504
505         return name;
506 }
507
508 static const gchar *get_part_description(MimeInfo *partinfo)
509 {
510         if (partinfo->description)
511                 return partinfo->description;
512         else
513                 return get_part_name(partinfo);
514 }
515
516 static GtkCTreeNode *mimeview_append_part(MimeView *mimeview,
517                                           MimeInfo *partinfo,
518                                           GtkCTreeNode *parent)
519 {
520         GtkCTree *ctree = GTK_CTREE(mimeview->ctree);
521         GtkCTreeNode *node;
522         static gchar content_type[64];
523         gchar *str[N_MIMEVIEW_COLS];
524
525         if (partinfo->type != MIMETYPE_UNKNOWN && partinfo->subtype) {
526                 g_snprintf(content_type, 64, "%s/%s", procmime_get_media_type_str(partinfo->type), partinfo->subtype);
527         } else {
528                 g_snprintf(content_type, 64, "UNKNOWN");
529         }
530
531         str[COL_MIMETYPE] = content_type;
532         str[COL_SIZE] = to_human_readable(partinfo->length);
533         if (prefs_common.attach_desc)
534                 str[COL_NAME] = (gchar *) get_part_description(partinfo);
535         else
536                 str[COL_NAME] = (gchar *) get_part_name(partinfo);
537
538         node = gtk_sctree_insert_node(ctree, parent, NULL, str, 0,
539                                      NULL, NULL, NULL, NULL,
540                                      FALSE, TRUE);
541         gtk_ctree_node_set_row_data(ctree, node, partinfo);
542
543         return node;
544 }
545
546 static void mimeview_show_message_part(MimeView *mimeview, MimeInfo *partinfo)
547 {
548         FILE *fp;
549         const gchar *fname;
550
551         if (!partinfo) return;
552
553         fname = mimeview->file;
554         if (!fname) return;
555
556         if ((fp = g_fopen(fname, "rb")) == NULL) {
557                 FILE_OP_ERROR(fname, "fopen");
558                 return;
559         }
560
561         if (fseek(fp, partinfo->offset, SEEK_SET) < 0) {
562                 FILE_OP_ERROR(mimeview->file, "fseek");
563                 fclose(fp);
564                 return;
565         }
566
567         mimeview_change_view_type(mimeview, MIMEVIEW_TEXT);
568         textview_show_part(mimeview->textview, partinfo, fp);
569
570         fclose(fp);
571 }
572
573 static MimeViewer *get_viewer_for_content_type(MimeView *mimeview, const gchar *content_type)
574 {
575         GSList *cur;
576         MimeViewerFactory *factory = NULL;
577         MimeViewer *viewer = NULL;
578
579 /*
580  * FNM_CASEFOLD is a GNU extension
581  * if its not defined copy the string to the stack and
582  * convert the copy to lower case
583  */
584 #ifndef FNM_CASEFOLD
585 #define FNM_CASEFOLD 0
586         Xstrdup_a(content_type, content_type, return NULL);
587         g_strdown((gchar *)content_type);
588 #endif
589         
590         for (cur = mimeviewer_factories; cur != NULL; cur = g_slist_next(cur)) {
591                 MimeViewerFactory *curfactory = cur->data;
592                 gint i = 0;
593
594                 while (curfactory->content_types[i] != NULL) {
595                         if(!fnmatch(curfactory->content_types[i], content_type, FNM_CASEFOLD)) {
596                                 debug_print("%s\n", curfactory->content_types[i]);
597                                 factory = curfactory;
598                                 break;
599                         }
600                         i++;
601                 }
602                 if (factory != NULL)
603                         break;
604         }
605         if (factory == NULL)
606                 return NULL;
607
608         for (cur = mimeview->viewers; cur != NULL; cur = g_slist_next(cur)) {
609                 MimeViewer *curviewer = cur->data;
610                 
611                 if (curviewer->factory == factory)
612                         return curviewer;
613         }
614         viewer = factory->create_viewer();
615         gtk_container_add(GTK_CONTAINER(mimeview->mime_notebook),
616                 GTK_WIDGET(viewer->get_widget(viewer)));
617                 
618         mimeview->viewers = g_slist_append(mimeview->viewers, viewer);
619
620         return viewer;
621 }
622
623 static MimeViewer *get_viewer_for_mimeinfo(MimeView *mimeview, MimeInfo *partinfo)
624 {
625         gchar *content_type = NULL;
626         MimeViewer *viewer = NULL;
627
628         if ((partinfo->type == MIMETYPE_APPLICATION) &&
629             (!g_ascii_strcasecmp(partinfo->subtype, "octet-stream"))) {
630                 const gchar *filename;
631
632                 filename = procmime_mimeinfo_get_parameter(partinfo, "filename");
633                 if (filename == NULL)
634                         filename = procmime_mimeinfo_get_parameter(partinfo, "name");
635                 if (filename != NULL)
636                         content_type = procmime_get_mime_type(filename);
637         } else {
638                 content_type = procmime_get_content_type_str(partinfo->type, partinfo->subtype);
639         }
640
641         if (content_type != NULL) {
642                 viewer = get_viewer_for_content_type(mimeview, content_type);
643                 g_free(content_type);
644         }
645
646         return viewer;
647 }
648
649 gboolean mimeview_show_part(MimeView *mimeview, MimeInfo *partinfo)
650 {
651         MimeViewer *viewer;
652         
653         viewer = get_viewer_for_mimeinfo(mimeview, partinfo);
654         if (viewer == NULL) {
655                 if (mimeview->mimeviewer != NULL)
656                         mimeview->mimeviewer->clear_viewer(mimeview->mimeviewer);
657                 mimeview->mimeviewer = NULL;
658                 return FALSE;
659         }
660
661         if (mimeview->mimeviewer != NULL)
662                 mimeview->mimeviewer->clear_viewer(mimeview->mimeviewer);
663
664         if (mimeview->mimeviewer != viewer) {
665                 mimeview->mimeviewer = viewer;
666                 mimeview_change_view_type(mimeview, MIMEVIEW_VIEWER);
667         }
668         viewer->mimeview = mimeview;
669         viewer->show_mimepart(viewer, mimeview->file, partinfo);
670
671         return TRUE;
672 }
673
674 static void mimeview_change_view_type(MimeView *mimeview, MimeViewType type)
675 {
676         TextView  *textview  = mimeview->textview;
677         GtkWidget *focused = NULL;
678         
679         if (mainwindow_get_mainwindow())
680                 focused = gtkut_get_focused_child(
681                                 GTK_CONTAINER(mainwindow_get_mainwindow()->window));
682
683         if ((mimeview->type != MIMEVIEW_VIEWER) && 
684             (mimeview->type == type)) return;
685
686         switch (type) {
687         case MIMEVIEW_TEXT:
688                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mimeview->mime_notebook),
689                         gtk_notebook_page_num(GTK_NOTEBOOK(mimeview->mime_notebook), 
690                         GTK_WIDGET_PTR(textview)));
691                 break;
692         case MIMEVIEW_VIEWER:
693                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mimeview->mime_notebook),
694                         gtk_notebook_page_num(GTK_NOTEBOOK(mimeview->mime_notebook), 
695                         GTK_WIDGET(mimeview->mimeviewer->get_widget(mimeview->mimeviewer))));
696                 break;
697         default:
698                 return;
699         }
700         if (focused)
701                 gtk_widget_grab_focus(focused);
702         mimeview->type = type;
703 }
704
705 void mimeview_clear(MimeView *mimeview)
706 {
707         GtkCList *clist = NULL;
708         
709         if (!mimeview)
710                 return;
711
712         if (g_slist_find(mimeviews, mimeview) == NULL)
713                 return;
714         
715         clist = GTK_CLIST(mimeview->ctree);
716         
717         noticeview_hide(mimeview->siginfoview);
718
719         gtk_clist_clear(clist);
720         textview_clear(mimeview->textview);
721         if (mimeview->mimeviewer != NULL)
722                 mimeview->mimeviewer->clear_viewer(mimeview->mimeviewer);
723
724         mimeview_free_mimeinfo(mimeview);
725
726         mimeview->mimeinfo = NULL;
727
728         mimeview->opened = NULL;
729
730         g_free(mimeview->file);
731         mimeview->file = NULL;
732
733         icon_list_clear(mimeview);
734         mimeview_change_view_type(mimeview, MIMEVIEW_TEXT);
735 }
736
737 static void check_signature_cb(GtkWidget *widget, gpointer user_data);
738 void mimeview_check_signature(MimeView *mimeview);
739 static void display_full_info_cb(GtkWidget *widget, gpointer user_data);
740
741 static void update_signature_noticeview(MimeView *mimeview, MimeInfo *mimeinfo, 
742                                         gboolean special, SignatureStatus code)
743 {
744         gchar *text = NULL, *button_text = NULL;
745         void  *func = NULL;
746         StockPixmap icon = STOCK_PIXMAP_PRIVACY_SIGNED;
747         SignatureStatus mycode = SIGNATURE_UNCHECKED;
748         
749         g_return_if_fail(mimeview != NULL);
750         g_return_if_fail(mimeinfo != NULL);
751         
752         if (special)
753                 mycode = code;
754         else 
755                 mycode = privacy_mimeinfo_get_sig_status(mimeinfo);
756
757         switch (mycode) {
758         case SIGNATURE_UNCHECKED:
759                 button_text = _("Check signature");
760                 func = check_signature_cb;
761                 icon = STOCK_PIXMAP_PRIVACY_SIGNED;
762                 break;
763         case SIGNATURE_OK:
764                 button_text = _("View full information");
765                 func = display_full_info_cb;
766                 icon = STOCK_PIXMAP_PRIVACY_PASSED;
767                 break;
768         case SIGNATURE_WARN:
769                 button_text = _("View full information");
770                 func = display_full_info_cb;
771                 icon = STOCK_PIXMAP_PRIVACY_WARN;
772                 break;
773         case SIGNATURE_INVALID:
774                 button_text = _("View full information");
775                 func = display_full_info_cb;
776                 icon = STOCK_PIXMAP_PRIVACY_FAILED;
777                 break;
778         case SIGNATURE_CHECK_FAILED:
779                 button_text = _("Check again");
780                 func = check_signature_cb;
781                 icon = STOCK_PIXMAP_PRIVACY_UNKNOWN;
782         case SIGNATURE_CHECK_TIMEOUT:
783                 button_text = _("Check again");
784                 func = check_signature_cb;
785                 icon = STOCK_PIXMAP_PRIVACY_UNKNOWN;
786         default:
787                 break;
788         }
789         if (mycode == SIGNATURE_UNCHECKED) {
790                 gchar *tmp = privacy_mimeinfo_sig_info_short(mimeinfo);
791                 text = g_strdup_printf("%s %s",
792                         tmp, _("Click the icon or hit 'C' to check it."));
793                 g_free(tmp);
794         } else if (mycode != SIGNATURE_CHECK_TIMEOUT) {
795                 text = privacy_mimeinfo_sig_info_short(mimeinfo);
796         } else if (mycode == SIGNATURE_CHECK_TIMEOUT) {
797                 text = g_strdup(_("Timeout checking the signature. Click the icon or hit 'C' to try again."));
798         }
799
800         noticeview_set_text(mimeview->siginfoview, text);
801         gtk_label_set_selectable(GTK_LABEL(mimeview->siginfoview->text), TRUE);
802
803         g_free(text);
804         noticeview_set_button_text(mimeview->siginfoview, NULL);
805         noticeview_set_button_press_callback(
806                 mimeview->siginfoview,
807                 G_CALLBACK(func),
808                 (gpointer) mimeview);
809         noticeview_set_icon(mimeview->siginfoview, icon);
810         noticeview_set_tooltip(mimeview->siginfoview, button_text);
811 }
812
813 #ifdef USE_PTHREAD
814
815 /* reset all thread stuff, and do the cleanups we've been left to do */
816 static void mimeview_check_data_reset(MimeView *mimeview)
817 {
818         if (!mimeview->check_data)
819                 return;
820
821         if (mimeview->check_data->free_after_use) {
822                 debug_print("freeing deferred mimeinfo\n");
823                 procmime_mimeinfo_free_all(mimeview->check_data->siginfo);
824         }
825         if (mimeview->check_data->destroy_mimeview) {
826                 debug_print("freeing deferred mimeview\n");
827                 g_free(mimeview->file);
828                 g_free(mimeview);
829                 mimeviews = g_slist_remove(mimeviews, mimeview);
830         }
831
832         g_free(mimeview->check_data);
833         mimeview->check_data = NULL;
834 }
835
836 /* GUI update once the checker thread is done or killed */
837 static gboolean mimeview_check_sig_thread_cb(void *data)
838 {
839         MimeView *mimeview = (MimeView *) data;
840         MimeInfo *mimeinfo = mimeview->siginfo;
841
842         debug_print("mimeview_check_sig_thread_cb\n");
843         
844         if (mimeinfo == NULL) {
845                 /* message changed !? */
846                 g_warning("no more siginfo!\n");
847                 goto end;
848         }
849         
850         if (!mimeview->check_data) {
851                 g_warning("nothing to check\n");
852                 return FALSE;
853         }
854
855         if (mimeview->check_data->siginfo != mimeinfo) {
856                 /* message changed !? */
857                 g_warning("different siginfo!\n");
858                 goto end;
859         }
860
861         if (mimeview->check_data->destroy_mimeview ||
862             mimeview->check_data->free_after_use) {
863                 debug_print("not bothering, we're changing message\n"); 
864                 goto end;
865         }
866         
867         /* update status */
868         if (mimeview->check_data->timeout) 
869                 update_signature_noticeview(mimeview, mimeview->siginfo, 
870                         TRUE, SIGNATURE_CHECK_TIMEOUT);
871         else
872                 update_signature_noticeview(mimeview, mimeview->siginfo, 
873                         FALSE, 0);
874         icon_list_clear(mimeview);
875         icon_list_create(mimeview, mimeview->mimeinfo);
876         
877 end:
878         mimeview_check_data_reset(mimeview);
879         return FALSE;
880 }
881
882 /* sig checker thread */
883 static void *mimeview_check_sig_worker_thread(void *data)
884 {
885         MimeView *mimeview = (MimeView *)data;
886         MimeInfo *mimeinfo = mimeview->siginfo;
887         
888         debug_print("checking...\n");
889
890         if (!mimeview->check_data)
891                 return NULL;
892
893         if (mimeinfo && mimeinfo == mimeview->check_data->siginfo)
894                 privacy_mimeinfo_check_signature(mimeinfo);
895         else {
896                 /* that's strange! we changed message without 
897                  * getting killed. */
898                 g_warning("different siginfo!\n");
899                 mimeview_check_data_reset(mimeview);
900                 return NULL;
901         }
902
903         /* use g_timeout so that GUI updates is done from the
904          * correct thread */
905         g_timeout_add(0,mimeview_check_sig_thread_cb,mimeview);
906         
907         return NULL;
908 }
909
910 /* killer thread - acts when the checker didn't work fast
911  * enough. */
912 static void *mimeview_check_sig_cancel_thread(void *data)
913 {
914         MimeView *mimeview = (MimeView *)data;
915         
916         if (!mimeview->check_data)
917                 return NULL; /* nothing to kill ! */
918
919         /* wait for a few seconds... */
920         debug_print("waiting a while\n");
921
922         sleep(5);
923         
924         if (!mimeview->check_data)
925                 return NULL; /* nothing to kill, it's done in time :) */
926         
927         /* too late, go away checker thread */
928         debug_print("killing checker thread\n");
929         pthread_cancel(mimeview->check_data->th);
930         
931         /* tell upstream it was a timeout */
932         mimeview->check_data->timeout = TRUE;
933         /* use g_timeout so that GUI updates is done from the
934          * correct thread */
935         g_timeout_add(0,mimeview_check_sig_thread_cb,mimeview);
936
937         return NULL;
938 }
939
940 /* get rid of the checker thread right now - used when changing the
941  * displayed message for example. */
942 static void mimeview_check_sig_cancel_now(MimeView *mimeview)
943 {
944         if (!mimeview->check_data)
945                 return;
946         debug_print("killing checker thread NOW\n");
947         pthread_cancel(mimeview->check_data->th);
948
949         /* tell upstream it was a timeout */
950         mimeview->check_data->timeout = TRUE;
951         mimeview_check_sig_thread_cb(mimeview);
952         return;
953 }
954
955 /* creates a thread to check the signature, and a second one
956  * to kill the first one after a timeout */
957 static void mimeview_check_sig_in_thread(MimeView *mimeview)
958 {
959         pthread_t th, th2;
960         pthread_attr_t detach, detach2;
961         
962         if (mimeview->check_data) {
963                 g_warning("already checking it");
964                 return;
965         }
966         
967         mimeview->check_data = g_new0(SigCheckData, 1);
968         mimeview->check_data->siginfo = mimeview->siginfo;
969         debug_print("creating thread\n");
970
971         pthread_attr_init(&detach);
972         pthread_attr_setdetachstate(&detach, TRUE);
973
974         pthread_attr_init(&detach2);
975         pthread_attr_setdetachstate(&detach2, TRUE);
976
977         /* create the checker thread */
978         if (pthread_create(&th, &detach, 
979                         mimeview_check_sig_worker_thread, 
980                         mimeview) != 0) {
981                 /* arh. We'll do it synchronously. */
982                 g_warning("can't create thread");
983                 g_free(mimeview->check_data);
984                 mimeview->check_data = NULL;
985                 return;
986         } else 
987                 mimeview->check_data->th = th;
988
989         /* create the killer thread */
990         pthread_create(&th2, &detach2, 
991                         mimeview_check_sig_cancel_thread, 
992                         mimeview);
993 }
994 #endif
995
996 static void check_signature_cb(GtkWidget *widget, gpointer user_data)
997 {
998         MimeView *mimeview = (MimeView *) user_data;
999         MimeInfo *mimeinfo = mimeview->siginfo;
1000         
1001         if (mimeinfo == NULL)
1002                 return;
1003 #ifdef USE_PTHREAD
1004         if (mimeview->check_data)
1005                 return;
1006 #endif
1007         noticeview_set_text(mimeview->siginfoview, _("Checking signature..."));
1008         GTK_EVENTS_FLUSH();
1009 #if (defined USE_PTHREAD && defined __GLIBC__ && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)))
1010         /* let's do it non-blocking */
1011         mimeview_check_sig_in_thread(mimeview);
1012         if (!mimeview->check_data) /* let's check syncronously */
1013 #endif
1014         {
1015                 debug_print("checking without thread\n");
1016                 privacy_mimeinfo_check_signature(mimeinfo);
1017                 update_signature_noticeview(mimeview, mimeview->siginfo, FALSE, 0);
1018                 icon_list_clear(mimeview);
1019                 icon_list_create(mimeview, mimeview->mimeinfo);
1020         }
1021 }
1022
1023 void mimeview_check_signature(MimeView *mimeview)
1024 {
1025         check_signature_cb(NULL, mimeview);     
1026 }
1027
1028 static void redisplay_email(GtkWidget *widget, gpointer user_data)
1029 {
1030         MimeView *mimeview = (MimeView *) user_data;
1031         GtkCTreeNode *node = mimeview->opened;
1032         mimeview->opened = NULL;
1033         mimeview_selected(GTK_CTREE(mimeview->ctree), node, 0, mimeview);
1034 }
1035
1036 static void display_full_info_cb(GtkWidget *widget, gpointer user_data)
1037 {
1038         MimeView *mimeview = (MimeView *) user_data;
1039         gchar *siginfo;
1040
1041         siginfo = privacy_mimeinfo_sig_info_full(mimeview->siginfo);
1042         textview_set_text(mimeview->textview, siginfo);
1043         g_free(siginfo);
1044         noticeview_set_button_text(mimeview->siginfoview, NULL);
1045         noticeview_set_button_press_callback(
1046                 mimeview->siginfoview,
1047                 G_CALLBACK(redisplay_email),
1048                 (gpointer) mimeview);
1049         noticeview_set_tooltip(mimeview->siginfoview, _("Go back to email"));
1050 }
1051
1052 static void update_signature_info(MimeView *mimeview, MimeInfo *selected)
1053 {
1054         MimeInfo *siginfo;
1055         MimeInfo *first_text;
1056         
1057         g_return_if_fail(mimeview != NULL);
1058         g_return_if_fail(selected != NULL);
1059         
1060         if (selected->type == MIMETYPE_MESSAGE 
1061         &&  !g_ascii_strcasecmp(selected->subtype, "rfc822")) {
1062                 /* if the first text part is signed, check that */
1063                 first_text = selected;
1064                 while (first_text && first_text->type != MIMETYPE_TEXT) {
1065                         first_text = procmime_mimeinfo_next(first_text);
1066                 }
1067                 if (first_text) {
1068                         update_signature_info(mimeview, first_text);
1069                         return;
1070                 }       
1071         }
1072
1073         siginfo = selected;
1074         while (siginfo != NULL) {
1075                 if (privacy_mimeinfo_is_signed(siginfo))
1076                         break;
1077                 siginfo = procmime_mimeinfo_parent(siginfo);
1078         }
1079         mimeview->siginfo = siginfo;
1080         
1081         if (siginfo == NULL) {
1082                 noticeview_hide(mimeview->siginfoview);
1083                 return;
1084         }
1085         
1086         update_signature_noticeview(mimeview, siginfo, FALSE, 0);
1087         noticeview_show(mimeview->siginfoview);
1088 }
1089
1090 static void mimeview_selected(GtkCTree *ctree, GtkCTreeNode *node, gint column,
1091                               MimeView *mimeview)
1092 {
1093         MimeInfo *partinfo;
1094         if (mimeview->opened == node) return;
1095         mimeview->opened = node;
1096         mimeview->spec_part = NULL;
1097         gtk_ctree_node_moveto(ctree, node, -1, 0.5, 0);
1098
1099         partinfo = gtk_ctree_node_get_row_data(ctree, node);
1100         if (!partinfo) return;
1101
1102         /* ungrab the mouse event */
1103         if (GTK_WIDGET_HAS_GRAB(ctree)) {
1104                 gtk_grab_remove(GTK_WIDGET(ctree));
1105                 if (gdk_pointer_is_grabbed())
1106                         gdk_pointer_ungrab(GDK_CURRENT_TIME);
1107         }
1108         
1109         mimeview->textview->default_text = FALSE;
1110
1111         update_signature_info(mimeview, partinfo);
1112
1113         if (!mimeview_show_part(mimeview, partinfo)) {
1114                 switch (partinfo->type) {
1115                 case MIMETYPE_TEXT:
1116                 case MIMETYPE_MESSAGE:
1117                 case MIMETYPE_MULTIPART:
1118                         mimeview_show_message_part(mimeview, partinfo);
1119                 
1120                         break;
1121                 default:
1122                         mimeview->textview->default_text = TRUE;
1123                         mimeview_change_view_type(mimeview, MIMEVIEW_TEXT);
1124                         textview_clear(mimeview->textview);
1125                         textview_show_mime_part(mimeview->textview, partinfo);
1126                         break;
1127                 }
1128         }
1129 }
1130
1131 static void mimeview_start_drag(GtkWidget *widget, gint button,
1132                                 GdkEvent *event, MimeView *mimeview)
1133 {
1134         GdkDragContext *context;
1135         MimeInfo *partinfo;
1136
1137         g_return_if_fail(mimeview != NULL);
1138
1139         partinfo = mimeview_get_selected_part(mimeview);
1140         if (partinfo->disposition == DISPOSITIONTYPE_INLINE) return;
1141
1142         context = gtk_drag_begin(widget, mimeview->target_list,
1143                                  GDK_ACTION_COPY, button, event);
1144         gtk_drag_set_icon_default(context);
1145 }
1146
1147 static gint mimeview_button_pressed(GtkWidget *widget, GdkEventButton *event,
1148                                     MimeView *mimeview)
1149 {
1150         GtkCList *clist = GTK_CLIST(widget);
1151         gint row, column;
1152
1153         if (!event) return FALSE;
1154
1155         if (event->button == 2 || event->button == 3) {
1156                 if (!gtk_clist_get_selection_info(clist, event->x, event->y,
1157                                                   &row, &column))
1158                         return FALSE;
1159                 gtk_clist_unselect_all(clist);
1160                 gtk_clist_select_row(clist, row, column);
1161                 gtkut_clist_set_focus_row(clist, row);
1162         }
1163         part_button_pressed(mimeview, event, mimeview_get_selected_part(mimeview));
1164
1165         return FALSE;
1166 }
1167
1168 static gboolean mimeview_scrolled(GtkWidget *widget, GdkEventScroll *event,
1169                                     MimeView *mimeview)
1170 {
1171         GtkVScrollbutton *scrollbutton = (GtkVScrollbutton *)mimeview->scrollbutton;
1172         if (event->direction == GDK_SCROLL_UP) {
1173                 scrollbutton->scroll_type = GTK_SCROLL_STEP_BACKWARD;
1174         } else {
1175                 scrollbutton->scroll_type = GTK_SCROLL_STEP_FORWARD;
1176         }
1177         gtk_vscrollbutton_scroll(scrollbutton);
1178         return TRUE;
1179 }
1180
1181 /* from gdkevents.c */
1182 #define DOUBLE_CLICK_TIME 250
1183
1184 static gboolean part_button_pressed(MimeView *mimeview, GdkEventButton *event, 
1185                                     MimeInfo *partinfo)
1186 {
1187         static MimeInfo *lastinfo;
1188         static guint32 lasttime;
1189
1190         if (event->button == 2 ||
1191             (event->button == 1 && (event->time - lasttime) < DOUBLE_CLICK_TIME && lastinfo == partinfo)) {
1192                 /* call external program for image, audio or html */
1193                 mimeview_launch(mimeview, partinfo);
1194                 return TRUE;
1195         } else if (event->button == 3) {
1196                 if (partinfo && (partinfo->type == MIMETYPE_MESSAGE ||
1197                                  partinfo->type == MIMETYPE_IMAGE ||
1198                                  partinfo->type == MIMETYPE_MULTIPART))
1199                         menu_set_sensitive(mimeview->popupfactory,
1200                                            "/Display as text", FALSE);
1201                 else
1202                         menu_set_sensitive(mimeview->popupfactory,
1203                                            "/Display as text", TRUE);
1204                 if (partinfo &&
1205                     partinfo->type == MIMETYPE_APPLICATION &&
1206                     !g_ascii_strcasecmp(partinfo->subtype, "octet-stream"))
1207                         menu_set_sensitive(mimeview->popupfactory,
1208                                            "/Open", FALSE);
1209                 else
1210                         menu_set_sensitive(mimeview->popupfactory,
1211                                            "/Open", TRUE);
1212
1213                 g_object_set_data(G_OBJECT(mimeview->popupmenu),
1214                                   "pop_partinfo", partinfo);
1215                                     
1216                 gtk_menu_popup(GTK_MENU(mimeview->popupmenu),
1217                                NULL, NULL, NULL, NULL,
1218                                event->button, event->time);
1219                 return TRUE;
1220         }
1221
1222         lastinfo = partinfo;
1223         lasttime = event->time;
1224         return FALSE;
1225 }
1226
1227
1228 void mimeview_pass_key_press_event(MimeView *mimeview, GdkEventKey *event)
1229 {
1230         mimeview_key_pressed(mimeview->ctree, event, mimeview);
1231 }
1232
1233 #define BREAK_ON_MODIFIER_KEY() \
1234         if ((event->state & (GDK_MOD1_MASK|GDK_CONTROL_MASK)) != 0) break
1235
1236 #define KEY_PRESS_EVENT_STOP() \
1237         g_signal_stop_emission_by_name(G_OBJECT(ctree), \
1238                                        "key_press_event");
1239
1240 static gint mimeview_key_pressed(GtkWidget *widget, GdkEventKey *event,
1241                                  MimeView *mimeview)
1242 {
1243         SummaryView *summaryview;
1244         GtkCTree *ctree = GTK_CTREE(widget);
1245         GtkCTreeNode *node;
1246
1247         if (!event) return FALSE;
1248         if (!mimeview->opened) return FALSE;
1249
1250         summaryview = mimeview->messageview->mainwin->summaryview;
1251         
1252         if (summaryview && quicksearch_has_focus(summaryview->quicksearch))
1253                 return FALSE;
1254                 
1255         switch (event->keyval) {
1256         case GDK_space:
1257                 if (mimeview_scroll_page(mimeview, FALSE))
1258                         return TRUE;
1259
1260                 node = GTK_CTREE_NODE_NEXT(mimeview->opened);
1261                 if (node) {
1262                         gtk_sctree_unselect_all(GTK_SCTREE(ctree));
1263                         gtk_sctree_select(GTK_SCTREE(ctree), node);
1264                         return TRUE;
1265                 }
1266                 break;
1267         case GDK_BackSpace:
1268                 mimeview_scroll_page(mimeview, TRUE);
1269                 return TRUE;
1270         case GDK_Return:
1271                 mimeview_scroll_one_line(mimeview,
1272                                          (event->state & GDK_MOD1_MASK) != 0);
1273                 return TRUE;
1274         case GDK_n:
1275         case GDK_N:
1276                 BREAK_ON_MODIFIER_KEY();
1277                 if (!GTK_CTREE_NODE_NEXT(mimeview->opened)) break;
1278                 KEY_PRESS_EVENT_STOP();
1279                 g_signal_emit_by_name(G_OBJECT(ctree), "scroll_vertical",
1280                                         GTK_SCROLL_STEP_FORWARD, 0.0);
1281                 return TRUE;
1282         case GDK_p:
1283         case GDK_P:
1284                 BREAK_ON_MODIFIER_KEY();
1285                 if (!GTK_CTREE_NODE_PREV(mimeview->opened)) break;
1286                 KEY_PRESS_EVENT_STOP();
1287                 g_signal_emit_by_name(G_OBJECT(ctree), "scroll_vertical",
1288                                         GTK_SCROLL_STEP_BACKWARD, 0.0);
1289                 return TRUE;
1290         case GDK_y:
1291                 BREAK_ON_MODIFIER_KEY();
1292                 KEY_PRESS_EVENT_STOP();
1293                 mimeview_save_as(mimeview);
1294                 return TRUE;
1295         case GDK_t:
1296                 BREAK_ON_MODIFIER_KEY();
1297                 KEY_PRESS_EVENT_STOP();
1298                 mimeview_display_as_text(mimeview);
1299                 return TRUE;    
1300         case GDK_l:
1301                 BREAK_ON_MODIFIER_KEY();
1302                 KEY_PRESS_EVENT_STOP();
1303                 mimeview_launch(mimeview, NULL);
1304                 return TRUE;
1305         case GDK_o:
1306                 BREAK_ON_MODIFIER_KEY();
1307                 KEY_PRESS_EVENT_STOP();
1308                 mimeview_open_with(mimeview);
1309                 return TRUE;
1310         case GDK_c:
1311                 BREAK_ON_MODIFIER_KEY();
1312                 KEY_PRESS_EVENT_STOP();
1313                 mimeview_check_signature(mimeview);
1314                 return TRUE;
1315         default:
1316                 break;
1317         }
1318
1319         if (!mimeview->messageview->mainwin) return FALSE;
1320
1321         summary_pass_key_press_event(summaryview, event);
1322         return TRUE;
1323 }
1324
1325 static void mimeview_drag_data_get(GtkWidget        *widget,
1326                                    GdkDragContext   *drag_context,
1327                                    GtkSelectionData *selection_data,
1328                                    guint             info,
1329                                    guint             time,
1330                                    MimeView         *mimeview)
1331 {
1332         gchar *filename = NULL, *uriname, *tmp;
1333         MimeInfo *partinfo;
1334         gint err;
1335
1336         if (!mimeview->opened) return;
1337         if (!mimeview->file) return;
1338
1339         partinfo = mimeview_get_selected_part(mimeview);
1340         if (!partinfo) return;
1341
1342         if (strlen(get_part_name(partinfo)) > 0) {
1343                 filename = g_path_get_basename(get_part_name(partinfo));
1344                 if (*filename == '\0') return;
1345         } else if (partinfo->type == MIMETYPE_MESSAGE 
1346                    && !g_ascii_strcasecmp(partinfo->subtype, "rfc822")) {
1347                 gchar *name = NULL;
1348                 GPtrArray *headers = NULL;
1349                 FILE *fp;
1350
1351                 fp = g_fopen(partinfo->data.filename, "rb");
1352                 fseek(fp, partinfo->offset, SEEK_SET);
1353                 headers = procheader_get_header_array_asis(fp);
1354                 if (headers) {
1355                         gint i;
1356                         for (i = 0; i < headers->len; i++) {
1357                                 Header *header = g_ptr_array_index(headers, i);
1358                                 if (procheader_headername_equal(header->name, "Subject")) {
1359                                         unfold_line(header->body);
1360                                         name = g_strconcat(header->body, ".txt", NULL);
1361                                         subst_for_filename(name);
1362                                 }
1363                         }
1364                         procheader_header_array_destroy(headers);
1365                 }
1366                 fclose(fp);
1367                 if (name)
1368                         filename = g_path_get_basename(name);
1369                 g_free(name);
1370         }
1371         if (filename == NULL)
1372                 filename = g_path_get_basename("Unnamed part");
1373
1374         if (!g_utf8_validate(filename, -1, NULL))
1375                 tmp = conv_codeset_strdup(filename,
1376                                 conv_get_locale_charset_str(),
1377                                 CS_UTF_8);
1378         else
1379                 tmp = g_strdup(filename);
1380
1381         if (tmp == NULL) {
1382                 g_warning("filename not in UTF-8");
1383                 tmp = g_strdup("Unnamed part");
1384         }
1385         filename = g_strconcat(get_mime_tmp_dir(), G_DIR_SEPARATOR_S,
1386                                tmp, NULL);
1387
1388         g_free(tmp);
1389
1390         if ((err = procmime_get_part(filename, partinfo)) < 0)
1391                 alertpanel_error
1392                         (_("Couldn't save the part of multipart message: %s"), 
1393                                 strerror(-err));
1394
1395         uriname = g_strconcat("file://", filename, "\r\n", NULL);
1396
1397         gtk_selection_data_set(selection_data, selection_data->target, 8,
1398                                (guchar *)uriname, strlen(uriname));
1399
1400         g_free(uriname);
1401         g_free(filename);
1402 }
1403
1404 /**
1405  * Returns a filename (with path) for an attachment
1406  * \param partinfo The attachment to save
1407  * \param basedir The target directory
1408  * \param number Used for dummy filename if attachment is unnamed
1409  */
1410 static gchar *mimeview_get_filename_for_part(MimeInfo *partinfo,
1411                                       const gchar *basedir,
1412                                       gint number)
1413 {
1414         gchar *fullname;
1415         gchar *filename;
1416
1417         filename = g_strdup(get_part_name(partinfo));
1418         if (!filename || !*filename)
1419                 filename = g_strdup_printf("noname.%d", number);
1420
1421         if (!g_utf8_validate(filename, -1, NULL)) {
1422                 gchar *tmp = conv_filename_to_utf8(filename);
1423                 g_free(filename);
1424                 filename = tmp;
1425         }
1426         
1427         subst_for_filename(filename);
1428
1429         fullname = g_strconcat
1430                 (basedir, G_DIR_SEPARATOR_S, (filename[0] == G_DIR_SEPARATOR)
1431                  ? &filename[1] : filename, NULL);
1432
1433         g_free(filename);
1434         filename = conv_filename_from_utf8(fullname);
1435         g_free(fullname);
1436         return filename;
1437 }
1438
1439 /**
1440  * Write a single attachment to file
1441  * \param filename Filename with path
1442  * \param partinfo Attachment to save
1443  */
1444 static gboolean mimeview_write_part(const gchar *filename,
1445                                     MimeInfo *partinfo)
1446 {
1447         gchar *dir;
1448         gint err;
1449
1450         dir= g_path_get_dirname(filename);
1451         if (!is_dir_exist(dir))
1452                 make_dir_hier(dir);
1453         g_free(dir);
1454
1455         if (is_file_exist(filename)) {
1456                 AlertValue aval;
1457                 gchar *res;
1458                 gchar *tmp;
1459                 
1460                 if (!g_utf8_validate(filename, -1, NULL))
1461                         tmp = conv_filename_to_utf8(filename);
1462                 else 
1463                         tmp = g_strdup(filename);
1464                 
1465                 res = g_strdup_printf(_("Overwrite existing file '%s'?"),
1466                                       tmp);
1467                 g_free(tmp);
1468                 aval = alertpanel(_("Overwrite"), res, GTK_STOCK_CANCEL, 
1469                                   GTK_STOCK_OK, NULL);
1470                 g_free(res);                                      
1471                 if (G_ALERTALTERNATE != aval) return FALSE;
1472         }
1473
1474         if ((err = procmime_get_part(filename, partinfo)) < 0) {
1475                 alertpanel_error
1476                         (_("Couldn't save the part of multipart message: %s"), 
1477                                 strerror(-err));
1478                 return FALSE;
1479         }
1480
1481         return TRUE;
1482 }
1483
1484 /**
1485  * Menu callback: Save all attached files
1486  * \param mimeview Current display
1487  */
1488 static void mimeview_save_all(MimeView *mimeview)
1489 {
1490         MimeInfo *partinfo;
1491         gchar *dirname;
1492         gchar *startdir = NULL;
1493         gint number = 1;
1494
1495         if (!mimeview->opened) return;
1496         if (!mimeview->file) return;
1497         if (!mimeview->mimeinfo) return;
1498
1499         partinfo = mimeview->mimeinfo;
1500         if (prefs_common.attach_save_dir && *prefs_common.attach_save_dir)
1501                 startdir = g_strconcat(prefs_common.attach_save_dir,
1502                                        G_DIR_SEPARATOR_S, NULL);
1503         else
1504                 startdir = g_strdup(get_home_dir());
1505
1506         dirname = filesel_select_file_save_folder(_("Select destination folder"), startdir);
1507         if (!dirname) {
1508                 g_free(startdir);
1509                 return;
1510         }
1511
1512         if (!is_dir_exist (dirname)) {
1513                 alertpanel_error(_("'%s' is not a directory."),
1514                                  dirname);
1515                 g_free(startdir);
1516                 return;
1517         }
1518
1519         if (dirname[strlen(dirname)-1] == G_DIR_SEPARATOR)
1520                 dirname[strlen(dirname)-1] = '\0';
1521
1522         /* Skip the first part, that is sometimes DISPOSITIONTYPE_UNKNOWN */
1523         if (partinfo && partinfo->type == MIMETYPE_MESSAGE)
1524                 partinfo = procmime_mimeinfo_next(partinfo);
1525         if (partinfo && partinfo->type == MIMETYPE_MULTIPART) {
1526                 partinfo = procmime_mimeinfo_next(partinfo);
1527                 if (partinfo && partinfo->type == MIMETYPE_TEXT)
1528                         partinfo = procmime_mimeinfo_next(partinfo);
1529         }
1530                 
1531         while (partinfo != NULL) {
1532                 if (partinfo->type != MIMETYPE_MESSAGE &&
1533                     partinfo->type != MIMETYPE_MULTIPART &&
1534                     (partinfo->disposition != DISPOSITIONTYPE_INLINE
1535                      || get_real_part_name(partinfo) != NULL)) {
1536                         gchar *filename = mimeview_get_filename_for_part
1537                                 (partinfo, dirname, number++);
1538
1539                         mimeview_write_part(filename, partinfo);
1540                         g_free(filename);
1541                 }
1542                 partinfo = procmime_mimeinfo_next(partinfo);
1543         }
1544
1545         g_free(prefs_common.attach_save_dir);
1546         g_free(startdir);
1547         prefs_common.attach_save_dir = g_filename_to_utf8(dirname,
1548                                         -1, NULL, NULL, NULL);
1549 }
1550
1551 static MimeInfo *mimeview_get_part_to_use(MimeView *mimeview)
1552 {
1553         MimeInfo *partinfo = NULL;
1554         if (mimeview->spec_part) {
1555                 partinfo = mimeview->spec_part;
1556                 mimeview->spec_part = NULL;
1557         } else {
1558                 partinfo = (MimeInfo *) g_object_get_data
1559                          (G_OBJECT(mimeview->popupmenu),
1560                          "pop_partinfo");
1561                 g_object_set_data(G_OBJECT(mimeview->popupmenu),
1562                                   "pop_partinfo", NULL);
1563                 if (!partinfo) { 
1564                         partinfo = mimeview_get_selected_part(mimeview);
1565                 }                        
1566         }
1567
1568         return partinfo;
1569 }
1570 /**
1571  * Menu callback: Save the selected attachment
1572  * \param mimeview Current display
1573  */
1574 static void mimeview_save_as(MimeView *mimeview)
1575 {
1576         gchar *filename;
1577         gchar *filepath = NULL;
1578         gchar *filedir = NULL;
1579         MimeInfo *partinfo;
1580         gchar *partname = NULL;
1581
1582         if (!mimeview->opened) return;
1583         if (!mimeview->file) return;
1584
1585         partinfo = mimeview_get_part_to_use(mimeview);
1586
1587         g_return_if_fail(partinfo != NULL);
1588         
1589         if (get_part_name(partinfo) == NULL) {
1590                 return;
1591         }
1592         partname = g_strdup(get_part_name(partinfo));
1593         
1594         if (!g_utf8_validate(partname, -1, NULL)) {
1595                 gchar *tmp = conv_filename_to_utf8(partname);
1596                 if (!tmp) {
1597                         tmp = conv_codeset_strdup(partname,
1598                                 conv_get_locale_charset_str(),
1599                                 CS_UTF_8);
1600                 }
1601                 if (tmp) {
1602                         g_free(partname);
1603                         partname = tmp;
1604                 }
1605         }
1606
1607         subst_for_filename(partname);
1608         
1609         if (prefs_common.attach_save_dir)
1610                 filepath = g_strconcat(prefs_common.attach_save_dir,
1611                                        G_DIR_SEPARATOR_S, partname, NULL);
1612         else
1613                 filepath = g_strdup(partname);
1614
1615         g_free(partname);
1616
1617         filename = filesel_select_file_save(_("Save as"), filepath);
1618         if (!filename) {
1619                 g_free(filepath);
1620                 return;
1621         }
1622
1623         mimeview_write_part(filename, partinfo);
1624
1625         filedir = g_path_get_dirname(filename);
1626         if (filedir && strcmp(filedir, ".")) {
1627                 g_free(prefs_common.attach_save_dir);
1628                 prefs_common.attach_save_dir = g_filename_to_utf8(filedir, -1, NULL, NULL, NULL);
1629         }
1630
1631         g_free(filedir);
1632         g_free(filepath);
1633 }
1634
1635 static void mimeview_display_as_text(MimeView *mimeview)
1636 {
1637         MimeInfo *partinfo;
1638
1639         if (!mimeview->opened) return;
1640
1641         partinfo = mimeview_get_part_to_use(mimeview);
1642         mimeview_select_mimepart_icon(mimeview, partinfo);
1643         g_return_if_fail(partinfo != NULL);
1644         mimeview_show_message_part(mimeview, partinfo);
1645 }
1646
1647 static void mimeview_launch(MimeView *mimeview, MimeInfo *partinfo)
1648 {
1649         gchar *filename;
1650         gint err;
1651
1652         if (!mimeview->opened) return;
1653         if (!mimeview->file) return;
1654
1655         if (!partinfo)
1656                 partinfo = mimeview_get_part_to_use(mimeview);
1657
1658         g_return_if_fail(partinfo != NULL);
1659
1660         filename = procmime_get_tmp_file_name(partinfo);
1661
1662         if ((err = procmime_get_part(filename, partinfo)) < 0)
1663                 alertpanel_error
1664                         (_("Couldn't save the part of multipart message: %s"), 
1665                                 strerror(-err));
1666         else
1667                 mimeview_view_file(filename, partinfo, NULL, mimeview);
1668
1669         g_free(filename);
1670 }
1671
1672 static void mimeview_open_with(MimeView *mimeview)
1673 {
1674         MimeInfo *partinfo;
1675
1676         if (!mimeview) return;
1677         if (!mimeview->opened) return;
1678         if (!mimeview->file) return;
1679
1680         partinfo = mimeview_get_part_to_use(mimeview);
1681
1682         mimeview_open_part_with(mimeview, partinfo, FALSE);
1683 }
1684
1685 static void mimeview_open_part_with(MimeView *mimeview, MimeInfo *partinfo, gboolean automatic)
1686 {
1687         gchar *filename;
1688         gchar *cmd;
1689         gchar *mime_command = NULL;
1690         gchar *content_type = NULL;
1691         gint err;
1692         g_return_if_fail(partinfo != NULL);
1693
1694         filename = procmime_get_tmp_file_name(partinfo);
1695
1696         if ((err = procmime_get_part(filename, partinfo)) < 0) {
1697                 alertpanel_error
1698                         (_("Couldn't save the part of multipart message: %s"), 
1699                                 strerror(-err));
1700                 g_free(filename);
1701                 return;
1702         }
1703
1704         if (!prefs_common.mime_open_cmd_history)
1705                 prefs_common.mime_open_cmd_history =
1706                         add_history(NULL, prefs_common.mime_open_cmd);
1707
1708         if ((partinfo->type == MIMETYPE_APPLICATION) &&
1709             (!g_ascii_strcasecmp(partinfo->subtype, "octet-stream"))) {
1710                 /* guess content-type from filename */
1711                 content_type = procmime_get_mime_type(filename);
1712         } 
1713         if (content_type == NULL) {
1714                 content_type = procmime_get_content_type_str(partinfo->type,
1715                         partinfo->subtype);
1716         }
1717         
1718         if ((partinfo->type == MIMETYPE_TEXT && !strcmp(partinfo->subtype, "html"))
1719         && prefs_common.uri_cmd && prefs_common.uri_cmd[0]) {
1720                 mime_command = g_strdup(prefs_common.uri_cmd);
1721                 g_free(content_type);
1722                 content_type = NULL;
1723         } else if (partinfo->type != MIMETYPE_TEXT || !prefs_common.ext_editor_cmd
1724         ||  !prefs_common.ext_editor_cmd[0]) {
1725                 mime_command = mailcap_get_command_for_type(content_type, filename);
1726         } else {
1727                 mime_command = g_strdup(prefs_common.ext_editor_cmd);
1728                 g_free(content_type);
1729                 content_type = NULL;
1730         }
1731         if (mime_command == NULL) {
1732                 /* try with extension this time */
1733                 g_free(content_type);
1734                 content_type = procmime_get_mime_type(filename);
1735                 mime_command = mailcap_get_command_for_type(content_type, filename);
1736         }
1737
1738         if (mime_command == NULL)
1739                 automatic = FALSE;
1740         
1741         if (!automatic) {
1742                 gboolean remember = FALSE;
1743                 if (content_type != NULL)
1744                         cmd = input_dialog_combo_remember
1745                                 (_("Open with"),
1746                                  _("Enter the command line to open file:\n"
1747                                    "('%s' will be replaced with file name)"),
1748                                  mime_command ? mime_command : prefs_common.mime_open_cmd,
1749                                  prefs_common.mime_open_cmd_history,
1750                                  TRUE, &remember);
1751                 else
1752                         cmd = input_dialog_combo
1753                                 (_("Open with"),
1754                                  _("Enter the command line to open file:\n"
1755                                    "('%s' will be replaced with file name)"),
1756                                  mime_command ? mime_command : prefs_common.mime_open_cmd,
1757                                  prefs_common.mime_open_cmd_history,
1758                                  TRUE);
1759                 if (cmd && remember) {
1760                         mailcap_update_default(content_type, cmd);
1761                 }
1762                 g_free(mime_command);
1763         } else {
1764                 cmd = mime_command;
1765         }
1766         if (cmd) {
1767                 mimeview_view_file(filename, partinfo, cmd, mimeview);
1768                 g_free(prefs_common.mime_open_cmd);
1769                 prefs_common.mime_open_cmd = cmd;
1770                 prefs_common.mime_open_cmd_history =
1771                         add_history(prefs_common.mime_open_cmd_history, cmd);
1772         }
1773         g_free(content_type);
1774         g_free(filename);
1775 }
1776
1777 static void mimeview_view_file(const gchar *filename, MimeInfo *partinfo,
1778                                const gchar *cmd, MimeView *mimeview)
1779 {
1780         gchar *p;
1781         gchar buf[BUFFSIZE];
1782         if (cmd == NULL)
1783                 mimeview_open_part_with(mimeview, partinfo, TRUE);
1784         else {
1785                 if ((p = strchr(cmd, '%')) && *(p + 1) == 's' &&
1786                     !strchr(p + 2, '%'))
1787                         g_snprintf(buf, sizeof(buf), cmd, filename);
1788                 else {
1789                         g_warning("MIME viewer command line is invalid: '%s'", cmd);
1790                         mimeview_open_part_with(mimeview, partinfo, FALSE);
1791                 }
1792                 if (execute_command_line(buf, TRUE) != 0)
1793                         mimeview_open_part_with(mimeview, partinfo, FALSE);
1794         }
1795 }
1796
1797 void mimeview_register_viewer_factory(MimeViewerFactory *factory)
1798 {
1799         mimeviewer_factories = g_slist_append(mimeviewer_factories, factory);
1800 }
1801
1802 static gint cmp_viewer_by_factroy(gconstpointer a, gconstpointer b)
1803 {
1804         return ((MimeViewer *) a)->factory == (MimeViewerFactory *) b ? 0 : -1;
1805 }
1806
1807 void mimeview_unregister_viewer_factory(MimeViewerFactory *factory)
1808 {
1809         GSList *mimeview_list, *viewer_list;
1810
1811         for (mimeview_list = mimeviews; mimeview_list != NULL; mimeview_list = g_slist_next(mimeview_list)) {
1812                 MimeView *mimeview = (MimeView *) mimeview_list->data;
1813                 
1814                 if (mimeview->mimeviewer && mimeview->mimeviewer->factory == factory) {
1815                         mimeview_change_view_type(mimeview, MIMEVIEW_TEXT);
1816                         mimeview->mimeviewer = NULL;
1817                 }
1818
1819                 while ((viewer_list = g_slist_find_custom(mimeview->viewers, factory, cmp_viewer_by_factroy)) != NULL) {
1820                         MimeViewer *mimeviewer = (MimeViewer *) viewer_list->data;
1821
1822                         mimeviewer->destroy_viewer(mimeviewer);
1823                         mimeview->viewers = g_slist_remove(mimeview->viewers, mimeviewer);
1824                 }
1825         }
1826
1827         mimeviewer_factories = g_slist_remove(mimeviewer_factories, factory);
1828 }
1829
1830 static gboolean icon_clicked_cb (GtkWidget *button, GdkEventButton *event, MimeView *mimeview)
1831 {
1832         gint      num;
1833         MimeInfo *partinfo;
1834
1835         num      = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(button), "icon_number"));
1836         partinfo = g_object_get_data(G_OBJECT(button), "partinfo");
1837
1838         if (event->button == 1) {
1839                 icon_selected(mimeview, num, partinfo);
1840                 gtk_widget_grab_focus(button);
1841                 if (!gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(button))) {
1842                         toggle_icon(GTK_TOGGLE_BUTTON(button), mimeview);
1843                 }
1844         }
1845         part_button_pressed(mimeview, event, partinfo);
1846
1847         return FALSE;
1848 }
1849
1850 static void icon_selected (MimeView *mimeview, gint num, MimeInfo *partinfo)
1851 {
1852         GtkCTreeNode *node;
1853         node = gtk_ctree_find_by_row_data(GTK_CTREE(mimeview->ctree), NULL, partinfo);
1854
1855         if (node)
1856                 gtk_ctree_select(GTK_CTREE(mimeview->ctree), node);
1857 }               
1858
1859 void mimeview_select_mimepart_icon(MimeView *mimeview, MimeInfo *partinfo)
1860 {
1861         icon_list_toggle_by_mime_info(mimeview, partinfo);
1862         icon_selected(mimeview, -1, partinfo);
1863 }
1864
1865 #undef  KEY_PRESS_EVENT_STOP
1866 #define KEY_PRESS_EVENT_STOP() \
1867         g_signal_stop_emission_by_name(G_OBJECT(button), \
1868                                        "key_press_event");
1869
1870 static gint icon_key_pressed(GtkWidget *button, GdkEventKey *event,
1871                              MimeView *mimeview)
1872 {
1873         gint          num;
1874         MimeInfo     *partinfo;
1875         SummaryView  *summaryview;
1876         TextView     *textview;
1877
1878         num      = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(button), "icon_number"));
1879         partinfo = g_object_get_data(G_OBJECT(button), "partinfo");
1880         
1881         if (!event) return FALSE;
1882
1883         textview = mimeview->textview;
1884
1885         switch (event->keyval) {
1886         case GDK_space:
1887                 if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(button))) {
1888                         /* stop the button being untoggled */
1889                         KEY_PRESS_EVENT_STOP();
1890                         if (mimeview_scroll_page(mimeview, FALSE))
1891                                 return TRUE;
1892
1893                         if (icon_list_select_by_number(mimeview, num + 1))
1894                                 return TRUE;
1895                 } else {
1896                         icon_selected(mimeview, num, partinfo);
1897                         toggle_icon(GTK_TOGGLE_BUTTON(button), mimeview);
1898                         return TRUE;
1899                 }
1900
1901                 break;
1902         case GDK_BackSpace:
1903                 mimeview_scroll_page(mimeview, TRUE);
1904                 return TRUE;
1905         case GDK_Return:
1906                 if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(button))) {
1907                         KEY_PRESS_EVENT_STOP();
1908                         mimeview_scroll_one_line(mimeview,
1909                                                  (event->state & GDK_MOD1_MASK) != 0);
1910                         return TRUE;
1911                 } else {
1912                         icon_selected(mimeview, num, partinfo);
1913                         toggle_icon(GTK_TOGGLE_BUTTON(button), mimeview);
1914                         return TRUE;
1915                 }
1916
1917         case GDK_n:
1918         case GDK_N:
1919                 BREAK_ON_MODIFIER_KEY();
1920                 if (icon_list_select_by_number(mimeview, num + 1)) {
1921                         KEY_PRESS_EVENT_STOP();
1922                         return TRUE;
1923                 }
1924                 break;
1925                 
1926         case GDK_p:
1927         case GDK_P:
1928                 BREAK_ON_MODIFIER_KEY();
1929                 if (icon_list_select_by_number(mimeview, num - 1)) {
1930                         KEY_PRESS_EVENT_STOP();
1931                         return TRUE;
1932                 }
1933                 break;
1934
1935         case GDK_y:
1936                 BREAK_ON_MODIFIER_KEY();
1937                 KEY_PRESS_EVENT_STOP();
1938                 mimeview_save_as(mimeview);
1939                 return TRUE;
1940         case GDK_t:
1941                 BREAK_ON_MODIFIER_KEY();
1942                 KEY_PRESS_EVENT_STOP();
1943                 mimeview_display_as_text(mimeview);
1944                 return TRUE;    
1945         case GDK_l:
1946                 BREAK_ON_MODIFIER_KEY();
1947                 KEY_PRESS_EVENT_STOP();
1948                 mimeview_launch(mimeview, NULL);
1949                 return TRUE;
1950         case GDK_o:
1951                 BREAK_ON_MODIFIER_KEY();
1952                 KEY_PRESS_EVENT_STOP();
1953                 mimeview_open_with(mimeview);
1954                 return TRUE;
1955         case GDK_c:
1956                 BREAK_ON_MODIFIER_KEY();
1957                 KEY_PRESS_EVENT_STOP();
1958                 mimeview_check_signature(mimeview);
1959                 return TRUE;
1960         default:
1961                 break;
1962         }
1963
1964         if (!mimeview->messageview->mainwin) return FALSE;
1965         summaryview = mimeview->messageview->mainwin->summaryview;
1966         return summary_pass_key_press_event(summaryview, event);
1967 }
1968
1969 static void toggle_icon(GtkToggleButton *button, MimeView *mimeview)
1970 {
1971         GList *child;
1972         
1973         child = gtk_container_get_children(GTK_CONTAINER(mimeview->icon_vbox));
1974         for (; child != NULL; child = g_list_next(child)) {
1975                 if (GTK_IS_TOGGLE_BUTTON(child->data) && 
1976                     GTK_TOGGLE_BUTTON(child->data) != button &&
1977                     gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(child->data)))
1978                         gtk_toggle_button_set_active
1979                                 (GTK_TOGGLE_BUTTON(child->data),
1980                                  FALSE);
1981         }
1982 }
1983
1984 static gboolean icon_popup_menu(GtkWidget *widget, gpointer data)
1985 {
1986         MimeView *mimeview = (MimeView *)data;
1987         MimeInfo *partinfo = g_object_get_data(G_OBJECT(widget), "partinfo");
1988
1989         g_object_set_data(G_OBJECT(mimeview->popupmenu),
1990                           "pop_partinfo", partinfo);
1991         gtk_menu_popup(GTK_MENU(mimeview->popupmenu),
1992                        NULL, NULL, NULL, NULL,
1993                        0, gtk_get_current_event_time());
1994         return TRUE;
1995 }
1996
1997 static void icon_list_append_icon (MimeView *mimeview, MimeInfo *mimeinfo) 
1998 {
1999         GtkWidget *pixmap = NULL;
2000         GtkWidget *vbox;
2001         GtkWidget *button;
2002         gchar *tip;
2003         gchar *tiptmp;
2004         const gchar *desc = NULL; 
2005         gchar *sigshort = NULL;
2006         gchar *content_type;
2007         StockPixmap stockp;
2008         MimeInfo *partinfo;
2009         MimeInfo *siginfo = NULL;
2010         MimeInfo *encrypted = NULL;
2011         
2012         vbox = mimeview->icon_vbox;
2013         mimeview->icon_count++;
2014         button = gtk_toggle_button_new();
2015         gtk_button_set_relief(GTK_BUTTON(button), GTK_RELIEF_NONE);
2016         g_object_set_data(G_OBJECT(button), "icon_number", 
2017                           GINT_TO_POINTER(mimeview->icon_count));
2018         g_object_set_data(G_OBJECT(button), "partinfo", 
2019                           mimeinfo);
2020
2021         switch (mimeinfo->type) {
2022                 
2023         case MIMETYPE_TEXT:
2024                 if (mimeinfo->subtype && !g_ascii_strcasecmp(mimeinfo->subtype, "html"))
2025                         stockp = STOCK_PIXMAP_MIME_TEXT_HTML;
2026                 else if  (mimeinfo->subtype && !g_ascii_strcasecmp(mimeinfo->subtype, "enriched"))
2027                         stockp = STOCK_PIXMAP_MIME_TEXT_ENRICHED;
2028                 else if  (mimeinfo->subtype && !g_ascii_strcasecmp(mimeinfo->subtype, "calendar"))
2029                         stockp = STOCK_PIXMAP_MIME_TEXT_CALENDAR;
2030                 else
2031                         stockp = STOCK_PIXMAP_MIME_TEXT_PLAIN;
2032                 break;
2033         case MIMETYPE_MESSAGE:
2034                 stockp = STOCK_PIXMAP_MIME_MESSAGE;
2035                 break;
2036         case MIMETYPE_APPLICATION:
2037                 if (mimeinfo->subtype && !g_ascii_strcasecmp(mimeinfo->subtype, "pgp-signature"))
2038                         stockp = STOCK_PIXMAP_MIME_PGP_SIG;
2039                 else if (mimeinfo->subtype && !g_ascii_strcasecmp(mimeinfo->subtype, "pdf"))
2040                         stockp = STOCK_PIXMAP_MIME_PDF;
2041                 else if  (mimeinfo->subtype && !g_ascii_strcasecmp(mimeinfo->subtype, "postscript"))
2042                         stockp = STOCK_PIXMAP_MIME_PS;
2043                 else
2044                         stockp = STOCK_PIXMAP_MIME_APPLICATION;
2045                 break;
2046         case MIMETYPE_IMAGE:
2047                 stockp = STOCK_PIXMAP_MIME_IMAGE;
2048                 break;
2049         case MIMETYPE_AUDIO:
2050                 stockp = STOCK_PIXMAP_MIME_AUDIO;
2051                 break;
2052         default:
2053                 stockp = STOCK_PIXMAP_MIME_UNKNOWN;
2054                 break;
2055         }
2056         
2057         partinfo = mimeinfo;
2058         while (partinfo != NULL) {
2059                 if (privacy_mimeinfo_is_signed(partinfo)) {
2060                         siginfo = partinfo;
2061                         break;
2062                 }
2063                 if (privacy_mimeinfo_is_encrypted(partinfo)) {
2064                         encrypted = partinfo;
2065                         break;
2066                 }
2067                 partinfo = procmime_mimeinfo_parent(partinfo);
2068         }       
2069
2070         if (siginfo != NULL) {
2071                 switch (privacy_mimeinfo_get_sig_status(siginfo)) {
2072                 case SIGNATURE_UNCHECKED:
2073                 case SIGNATURE_CHECK_FAILED:
2074                 case SIGNATURE_CHECK_TIMEOUT:
2075                         pixmap = stock_pixmap_widget_with_overlay(mimeview->mainwin->window, stockp,
2076                             STOCK_PIXMAP_PRIVACY_EMBLEM_SIGNED, OVERLAY_BOTTOM_RIGHT, 6, 3);
2077                         break;
2078                 case SIGNATURE_OK:
2079                         pixmap = stock_pixmap_widget_with_overlay(mimeview->mainwin->window, stockp,
2080                             STOCK_PIXMAP_PRIVACY_EMBLEM_PASSED, OVERLAY_BOTTOM_RIGHT, 6, 3);
2081                         break;
2082                 case SIGNATURE_WARN:
2083                         pixmap = stock_pixmap_widget_with_overlay(mimeview->mainwin->window, stockp,
2084                             STOCK_PIXMAP_PRIVACY_EMBLEM_WARN, OVERLAY_BOTTOM_RIGHT, 6, 3);
2085                         break;
2086                 case SIGNATURE_INVALID:
2087                         pixmap = stock_pixmap_widget_with_overlay(mimeview->mainwin->window, stockp,
2088                             STOCK_PIXMAP_PRIVACY_EMBLEM_FAILED, OVERLAY_BOTTOM_RIGHT, 6, 3);
2089                         break;
2090                 }
2091                 sigshort = privacy_mimeinfo_sig_info_short(siginfo);
2092         } else if (encrypted != NULL) {
2093                         pixmap = stock_pixmap_widget_with_overlay(mimeview->mainwin->window, stockp,
2094                             STOCK_PIXMAP_PRIVACY_EMBLEM_ENCRYPTED, OVERLAY_BOTTOM_RIGHT, 6, 3);         
2095         } else {
2096                 pixmap = stock_pixmap_widget_with_overlay(mimeview->mainwin->window, stockp, 0,
2097                                                           OVERLAY_NONE, 6, 3);
2098         }
2099         gtk_container_add(GTK_CONTAINER(button), pixmap);
2100         
2101         if (!desc) {
2102                 if (prefs_common.attach_desc)
2103                         desc = get_part_description(mimeinfo);
2104                 else
2105                         desc = get_part_name(mimeinfo);
2106         }
2107
2108         content_type = procmime_get_content_type_str(mimeinfo->type,
2109                                                      mimeinfo->subtype);
2110
2111         tip = g_strjoin("\n", content_type,
2112                         to_human_readable(mimeinfo->length), NULL);
2113         g_free(content_type);
2114         if (desc && *desc) {
2115                 gchar *tmp = NULL;
2116                 if (!g_utf8_validate(desc, -1, NULL)) {
2117                         tmp = conv_filename_to_utf8(desc);
2118                 } else {
2119                         tmp = g_strdup(desc);
2120                 }
2121                 tiptmp = g_strjoin("\n", tmp, tip, NULL);
2122                 g_free(tip);
2123                 tip = tiptmp;
2124                 g_free(tmp);
2125         }
2126         if (sigshort && *sigshort) {
2127                 tiptmp = g_strjoin("\n", tip, sigshort, NULL);
2128                 g_free(tip);
2129                 tip = tiptmp;
2130         }
2131         g_free(sigshort);
2132
2133         gtk_tooltips_set_tip(mimeview->tooltips, button, tip, NULL);
2134         g_free(tip);
2135         gtk_widget_show_all(button);
2136         gtk_drag_source_set(button, GDK_BUTTON1_MASK|GDK_BUTTON3_MASK, 
2137                             mimeview_mime_types, 1, GDK_ACTION_COPY);
2138 #ifndef MAEMO
2139         g_signal_connect(G_OBJECT(button), "popup-menu",
2140                          G_CALLBACK(icon_popup_menu), mimeview);
2141 #else
2142         gtk_widget_tap_and_hold_setup(GTK_WIDGET(button), NULL, NULL,
2143                         GTK_TAP_AND_HOLD_NONE | GTK_TAP_AND_HOLD_NO_INTERNALS);
2144         g_signal_connect(G_OBJECT(button), "tap-and-hold",
2145                          G_CALLBACK(icon_popup_menu), mimeview);
2146 #endif
2147         g_signal_connect(G_OBJECT(button), "button_release_event", 
2148                          G_CALLBACK(icon_clicked_cb), mimeview);
2149         g_signal_connect(G_OBJECT(button), "key_press_event", 
2150                          G_CALLBACK(icon_key_pressed), mimeview);
2151         g_signal_connect(G_OBJECT(button), "drag_data_get",
2152                          G_CALLBACK(mimeview_drag_data_get), mimeview);
2153         gtk_box_pack_start(GTK_BOX(vbox), button, FALSE, FALSE, 0);
2154
2155 }
2156
2157 static void icon_list_clear (MimeView *mimeview)
2158 {
2159         GList     *child;
2160         GtkAdjustment *adj;
2161                 
2162         child = gtk_container_children(GTK_CONTAINER(mimeview->icon_vbox));
2163         for (; child != NULL; child = g_list_next(child)) {
2164                 gtkut_container_remove(GTK_CONTAINER(mimeview->icon_vbox), 
2165                                        GTK_WIDGET(child->data));
2166                 gtk_widget_destroy(GTK_WIDGET(child->data));
2167         }
2168         g_list_free(child);
2169         mimeview->icon_count = 0;
2170         adj  = gtk_layout_get_vadjustment(GTK_LAYOUT(mimeview->icon_scroll));
2171         gtk_adjustment_set_value(adj, adj->lower);
2172 }
2173
2174 static void icon_list_toggle_by_mime_info(MimeView      *mimeview,
2175                                           MimeInfo      *mimeinfo)
2176 {
2177         GList *child;
2178         
2179         child = gtk_container_children(GTK_CONTAINER(mimeview->icon_vbox));
2180         for (; child != NULL; child = g_list_next(child)) {
2181                 if (GTK_IS_TOGGLE_BUTTON(child->data) &&  
2182                     g_object_get_data(G_OBJECT(child->data),
2183                                       "partinfo") == (gpointer)mimeinfo) {
2184                         toggle_icon(GTK_TOGGLE_BUTTON(child->data), mimeview);
2185                         gtk_toggle_button_set_active
2186                                 (GTK_TOGGLE_BUTTON(child->data), TRUE);
2187                 }                                
2188         }
2189 }
2190
2191 /*!
2192  *\brief        Used to 'click' the next or previous icon.
2193  *
2194  *\return       true if the icon 'number' exists and was selected.
2195  */
2196 static gboolean icon_list_select_by_number(MimeView     *mimeview,
2197                                            gint          number)
2198 {
2199         GList *child;
2200
2201         if (number == 0) return FALSE;
2202         child = gtk_container_children(GTK_CONTAINER(mimeview->icon_vbox));
2203         for (; child != NULL; child = g_list_next(child)) {
2204                 if (GTK_IS_TOGGLE_BUTTON(child->data) &&  
2205                     GPOINTER_TO_INT(g_object_get_data(G_OBJECT(child->data),
2206                                         "icon_number")) == number) {
2207                         icon_selected(mimeview, number,
2208                                       (MimeInfo*)g_object_get_data(G_OBJECT(child->data),
2209                                                                    "partinfo"));
2210                         toggle_icon(GTK_TOGGLE_BUTTON(child->data), mimeview);
2211                         gtk_toggle_button_set_active
2212                                 (GTK_TOGGLE_BUTTON(child->data), TRUE);
2213                         gtk_widget_grab_focus(GTK_WIDGET(child->data));
2214                 
2215                         return TRUE;
2216                 }                                
2217         }
2218         return FALSE;
2219 }
2220
2221 static void icon_scroll_size_allocate_cb(GtkWidget *widget, 
2222                                          GtkAllocation *size, MimeView *mimeview)
2223 {
2224         GtkAllocation *mainbox_size;
2225         GtkAllocation *vbox_size;
2226         GtkAllocation *layout_size;
2227         GtkAdjustment *adj;
2228         
2229         adj = gtk_layout_get_vadjustment(GTK_LAYOUT(mimeview->icon_scroll));
2230
2231         mainbox_size = &mimeview->icon_mainbox->allocation;
2232         vbox_size = &mimeview->icon_vbox->allocation;
2233         layout_size = &mimeview->icon_scroll->allocation;
2234                 
2235         gtk_layout_set_size(GTK_LAYOUT(mimeview->icon_scroll), 
2236                             GTK_LAYOUT(mimeview->icon_scroll)->width, 
2237                             MAX(vbox_size->height, layout_size->height));
2238         adj->step_increment = 10;
2239 }
2240
2241 static void icon_list_create(MimeView *mimeview, MimeInfo *mimeinfo)
2242 {
2243         GtkRequisition size;
2244
2245         g_return_if_fail(mimeinfo != NULL);
2246
2247         while (mimeinfo != NULL) {
2248                 if (mimeinfo->type != MIMETYPE_MULTIPART)
2249                         icon_list_append_icon(mimeview, mimeinfo);
2250                 if (mimeinfo->node->children != NULL)
2251                         icon_list_create(mimeview, 
2252                                 (MimeInfo *) mimeinfo->node->children->data);
2253                 mimeinfo = mimeinfo->node->next != NULL 
2254                          ? (MimeInfo *) mimeinfo->node->next->data 
2255                          : NULL;
2256         }
2257         gtk_widget_size_request(mimeview->icon_vbox, &size);
2258         if (size.width > mimeview->icon_mainbox->requisition.width) {
2259                 gtk_widget_set_size_request(mimeview->icon_mainbox, 
2260                                             size.width, -1);
2261         }
2262
2263 }
2264
2265 static void mime_toggle_button_cb (GtkWidget *button, MimeView *mimeview) 
2266 {
2267         gtk_widget_ref(button); 
2268
2269         if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(button))) {
2270                 gtk_arrow_set(GTK_ARROW(GTK_BIN(button)->child), GTK_ARROW_RIGHT, 
2271                                         GTK_SHADOW_NONE);
2272                 gtk_widget_hide(mimeview->icon_mainbox);
2273                 gtk_widget_show(mimeview->ctree_mainbox);
2274                 gtk_paned_set_position(GTK_PANED(mimeview->paned), mimeview->oldsize);
2275
2276                 gtkut_container_remove(GTK_CONTAINER(mimeview->icon_mainbox), 
2277                                         button);
2278                 gtk_box_pack_end(GTK_BOX(mimeview->ctree_mainbox), 
2279                                    button, FALSE, FALSE, 0);
2280                 gtk_paned_set_gutter_size(GTK_PANED(mimeview->paned), 6);
2281         } else {
2282                 gtk_arrow_set(GTK_ARROW(GTK_BIN(button)->child), GTK_ARROW_LEFT, 
2283                               GTK_SHADOW_NONE);
2284                 mimeview->oldsize = mimeview->ctree_mainbox->allocation.height;
2285                 gtk_widget_hide(mimeview->ctree_mainbox);
2286                 gtk_widget_show(mimeview->icon_mainbox);
2287                 gtk_paned_set_position(GTK_PANED(mimeview->paned), 0);
2288
2289                 gtkut_container_remove(GTK_CONTAINER(mimeview->ctree_mainbox), 
2290                                         button);
2291                 gtk_box_pack_start(GTK_BOX(mimeview->icon_mainbox), 
2292                                    button, FALSE, FALSE, 0);
2293                 gtk_box_reorder_child(GTK_BOX(button->parent), button, 0);
2294                 if (mimeview->opened)
2295                         icon_list_toggle_by_mime_info
2296                                 (mimeview, gtk_ctree_node_get_row_data(GTK_CTREE(mimeview->ctree), 
2297                                                                        mimeview->opened));
2298
2299                 gtk_paned_set_gutter_size(GTK_PANED(mimeview->paned), 0);
2300         }
2301         gtk_widget_grab_focus(button);
2302         gtk_widget_unref(button);
2303
2304 }
2305
2306 void mimeview_update (MimeView *mimeview) {
2307         if (mimeview && mimeview->mimeinfo) {
2308                 icon_list_clear(mimeview);
2309                 icon_list_create(mimeview, mimeview->mimeinfo);
2310         }
2311 }
2312
2313 void mimeview_handle_cmd(MimeView *mimeview, const gchar *cmd, GdkEventButton *event, gpointer data)
2314 {
2315         MessageView *msgview = NULL;
2316         MainWindow *mainwin = NULL;
2317         
2318         if (!cmd)
2319                 return;
2320         
2321         msgview = mimeview->messageview;
2322         if (!msgview)
2323                 return;
2324                 
2325         mainwin = msgview->mainwin;
2326         if (!mainwin)
2327                 return;
2328                 
2329         g_object_set_data(G_OBJECT(mimeview->popupmenu),
2330                           "pop_partinfo", NULL);
2331
2332         if (!strcmp(cmd, "sc://view_log"))
2333                 log_window_show(mainwin->logwin);
2334         else if (!strcmp(cmd, "sc://save_as"))
2335                 mimeview_save_as(mimeview);
2336         else if (!strcmp(cmd, "sc://display_as_text"))
2337                 mimeview_display_as_text(mimeview);
2338         else if (!strcmp(cmd, "sc://open_with"))
2339                 mimeview_open_with(mimeview);
2340         else if (!strcmp(cmd, "sc://open"))
2341                 mimeview_launch(mimeview, NULL);
2342         else if (!strcmp(cmd, "sc://select_attachment") && data != NULL) {
2343                 icon_list_toggle_by_mime_info(mimeview, (MimeInfo *)data);
2344                 icon_selected(mimeview, -1, (MimeInfo *)data);
2345         } else if (!strcmp(cmd, "sc://open_attachment") && data != NULL) {
2346                 mimeview_launch(mimeview, (MimeInfo *)data);
2347         } else if (!strcmp(cmd, "sc://menu_attachment") && data != NULL) {
2348                 mimeview->spec_part = (MimeInfo *)data;
2349                 part_button_pressed(mimeview, event, (MimeInfo *)data);
2350         }
2351 }
2352
2353 gboolean mimeview_scroll_page(MimeView *mimeview, gboolean up)
2354 {
2355         if (mimeview->type == MIMEVIEW_TEXT)
2356                 return textview_scroll_page(mimeview->textview, up);
2357         else if (mimeview->mimeviewer) {
2358                 MimeViewer *mimeviewer = mimeview->mimeviewer;
2359                 if (mimeviewer->scroll_page)
2360                         return mimeviewer->scroll_page(mimeviewer, up);
2361         }
2362         return TRUE;
2363 }
2364
2365 void mimeview_scroll_one_line(MimeView *mimeview, gboolean up)
2366 {
2367         if (mimeview->type == MIMEVIEW_TEXT)
2368                 textview_scroll_one_line(mimeview->textview, up);
2369         else if (mimeview->mimeviewer) {
2370                 MimeViewer *mimeviewer = mimeview->mimeviewer;
2371                 if (mimeviewer->scroll_one_line)
2372                         mimeviewer->scroll_one_line(mimeviewer, up);
2373         }
2374 }