2d772e648f36afab0c7be45a5495efbfab4c5e69
[claws.git] / src / action.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2012 Hiroyuki Yamamoto & The Claws Mail Team
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  * 
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #include "claws-features.h"
23 #endif
24
25 #include "defs.h"
26
27 #include <glib.h>
28 #include <glib/gi18n.h>
29 #include <gtk/gtk.h>
30 #include <gdk/gdkkeysyms.h>
31 #ifdef GDK_WINDOWING_X11
32 #  include <gdk/gdkx.h>
33 #endif /* GDK_WINDOWING_X11 */
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <errno.h>
38 #include <sys/types.h>
39 #if HAVE_SYS_WAIT_H
40 #  include <sys/wait.h>
41 #endif
42 #include <signal.h>
43 #include <unistd.h>
44
45 #include "utils.h"
46 #include "gtkutils.h"
47 #include "manage_window.h"
48 #include "mainwindow.h"
49 #include "prefs_common.h"
50 #include "alertpanel.h"
51 #include "inputdialog.h"
52 #include "action.h"
53 #include "compose.h"
54 #include "procmsg.h"
55 #include "msgcache.h"
56 #include "textview.h"
57 #include "matcher_parser.h" /* CLAWS */
58 #include "filtering.h"
59 #include "procheader.h"
60
61 typedef struct _Children                Children;
62 typedef struct _ChildInfo               ChildInfo;
63 typedef struct _UserStringDialog        UserStringDialog;
64
65 struct _Children
66 {
67         GtkWidget       *dialog;
68         GtkWidget       *text;
69         GtkWidget       *input_entry;
70         GtkWidget       *input_hbox;
71         GtkWidget       *progress_bar;
72         GtkWidget       *abort_btn;
73         GtkWidget       *close_btn;
74         GtkWidget       *scrolledwin;
75
76         gchar           *action;
77         ActionType       action_type;
78         GSList          *list;
79         gint             nb;
80         gint             initial_nb;
81         gint             open_in;
82         gboolean         output;
83
84         GtkWidget       *msg_text;
85
86         gboolean         is_selection;
87 };
88
89 struct _ChildInfo
90 {
91         Children        *children;
92         gchar           *cmd;
93         pid_t            pid;
94         gint             next_sig;
95         gint             chld_in;
96         gint             chld_out;
97         gint             chld_err;
98         gint             chld_status;
99         gint             tag_in;
100         gint             tag_out;
101         gint             tag_err;
102         gint             tag_status;
103         gint             new_out;
104
105         GString         *output;
106         void (*callback)(void *data);
107         void *data;
108
109         GSList          *msginfo_list;
110 };
111
112 static void action_update_menu          (GtkUIManager   *ui_manager,
113                                          const gchar    *accel_group,
114                                          gchar          *branch_path,
115                                          gpointer        callback,
116                                          gpointer        data);
117 static void compose_actions_execute_cb  (GtkWidget      *widget, 
118                                          gpointer        data);
119 static void compose_actions_execute     (Compose        *compose,
120                                          guint           action_nb,
121                                          GtkWidget      *widget);
122
123 static void mainwin_actions_execute_cb  (GtkWidget      *widget, 
124                                          gpointer        data);
125 static void mainwin_actions_execute     (MainWindow     *mainwin,
126                                          guint           action_nb,
127                                          GtkWidget      *widget);
128
129 static void msgview_actions_execute_cb  (GtkWidget      *widget, 
130                                          gpointer        data);
131 static void msgview_actions_execute     (MessageView    *msgview,
132                                          guint           action_nb,
133                                          GtkWidget      *widget);
134
135 static void message_actions_execute     (MessageView    *msgview,
136                                          guint           action_nb,
137                                          GSList         *msg_list);
138
139 static gboolean execute_filtering_actions(gchar         *action, 
140                                           GSList        *msglist);
141
142 static gboolean execute_actions         (gchar          *action, 
143                                          GSList         *msg_list, 
144                                          GtkWidget      *text,
145                                          gint            body_pos,
146                                          MimeInfo       *partinfo, 
147                                          void (*callback)(void *data),
148                                          void *data);
149
150 static gchar *parse_action_cmd          (gchar          *action,
151                                          MsgInfo        *msginfo,
152                                          GSList         *msg_list,
153                                          MimeInfo       *partinfo,
154                                          const gchar    *user_str,
155                                          const gchar    *user_hidden_str,
156                                          const gchar    *sel_str);
157 static gboolean parse_append_filename   (GString        *cmd,
158                                          MsgInfo        *msginfo);
159
160 static gboolean parse_append_msgpart    (GString        *cmd,
161                                          MsgInfo        *msginfo,
162                                          MimeInfo       *partinfo);
163
164 static ChildInfo *fork_child            (gchar          *cmd,
165                                          const gchar    *msg_str,
166                                          Children       *children);
167
168 static gint wait_for_children           (Children       *children);
169
170 static void free_children               (Children       *children);
171
172 static void childinfo_close_pipes       (ChildInfo      *child_info);
173
174 static void create_io_dialog            (Children       *children);
175 static void update_io_dialog            (Children       *children);
176
177 static void hide_io_dialog_cb           (GtkWidget      *widget,
178                                          gpointer        data);
179 static gint io_dialog_key_pressed_cb    (GtkWidget      *widget,
180                                          GdkEventKey    *event,
181                                          gpointer        data);
182
183 static void catch_output                (gpointer                data,
184                                          gint                    source,
185                                          GIOCondition            cond);
186 static void catch_input                 (gpointer                data, 
187                                          gint                    source,
188                                          GIOCondition            cond);
189 static void catch_status                (gpointer                data,
190                                          gint                    source,
191                                          GIOCondition            cond);
192
193 static gchar *get_user_string           (const gchar    *action,
194                                          ActionType      type);
195
196
197 ActionType action_get_type(const gchar *action_str)
198 {
199         const gchar *p;
200         gboolean in_filtering_action = FALSE;
201         ActionType action_type = ACTION_NONE;
202
203         cm_return_val_if_fail(action_str,  ACTION_ERROR);
204         cm_return_val_if_fail(*action_str, ACTION_ERROR);
205
206         p = action_str;
207
208         if (p[0] == '|') {
209                 action_type |= ACTION_PIPE_IN;
210                 p++;
211         } else if (p[0] == '>') {
212                 action_type |= ACTION_USER_IN;
213                 p++;
214         } else if (p[0] == '*') {
215                 action_type |= ACTION_USER_HIDDEN_IN;
216                 p++;
217         }
218
219         if (p[0] == '\0')
220                 return ACTION_ERROR;
221
222         while (*p && action_type != ACTION_ERROR) {
223                 if (!in_filtering_action) {
224                         if (p[0] == '%' && p[1]) {
225                                 switch (p[1]) {
226                                 case 'a':
227                                         /* CLAWS: filtering action is a mutually exclusive
228                                         * action. we can enable others if needed later. we
229                                         * add ACTION_SINGLE | ACTION_MULTIPLE so it will
230                                         * only be executed from the main window toolbar */
231                                         if (p[2] == 's')  /* source messages */
232                                                 action_type = ACTION_FILTERING_ACTION 
233                                                                 | ACTION_SINGLE 
234                                                                 | ACTION_MULTIPLE;
235                                         in_filtering_action = TRUE;
236                                         break;
237                                 case 'f':
238                                         action_type |= ACTION_SINGLE;
239                                         break;
240                                 case 'F':
241                                         action_type |= ACTION_MULTIPLE;
242                                         break;
243                                 case 'p':
244                                         action_type |= ACTION_SINGLE;
245                                         break;
246                                 case 's':
247                                         action_type |= ACTION_SELECTION_STR;
248                                         break;
249                                 case 'u':
250                                         action_type |= ACTION_USER_STR;
251                                         break;
252                                 case 'h':
253                                         action_type |= ACTION_USER_HIDDEN_STR;
254                                         break;
255                                 case '%':
256                                         /* literal '%' */
257                                         break;
258                                 default:
259                                         action_type = ACTION_ERROR;
260                                         break;
261                                 }
262                                 p++;
263                         } else if (p[0] == '|') {
264                                 if (p[1] == '\0')
265                                         action_type |= ACTION_PIPE_OUT;
266                         } else if (p[0] == '>') {
267                                 if (p[1] == '\0')
268                                         action_type |= ACTION_INSERT;
269                         } else if (p[0] == '&') {
270                                 if (p[1] == '\0')
271                                         action_type |= ACTION_ASYNC;
272                         } else if (p[0] == '}') {
273                                 in_filtering_action = FALSE;
274                         }
275                 }
276                         p++;
277         }
278
279         return action_type;
280 }
281
282 static gchar *parse_action_cmd(gchar *action, MsgInfo *msginfo,
283                                GSList *msg_list, MimeInfo *partinfo,
284                                const gchar *user_str,
285                                const gchar *user_hidden_str,
286                                const gchar *sel_str)
287 {
288         GString *cmd;
289         gchar *p;
290         GSList *cur;
291         
292         p = action;
293         
294         if (p[0] == '|' || p[0] == '>' || p[0] == '*')
295                 p++;
296
297         cmd = g_string_sized_new(strlen(action));
298
299         while (p[0] &&
300                !((p[0] == '|' || p[0] == '>' || p[0] == '&') && !p[1])) {
301                 if (p[0] == '%' && p[1]) {
302                         switch (p[1]) {
303                         case 'f':
304                                 if (!parse_append_filename(cmd, msginfo)) {
305                                         g_string_free(cmd, TRUE);
306                                         return NULL;
307                                 }
308                                 p++;
309                                 break;
310                         case 'F':
311                                 for (cur = msg_list; cur != NULL;
312                                      cur = cur->next) {
313                                         MsgInfo *msg = (MsgInfo *)cur->data;
314
315                                         if (!parse_append_filename(cmd, msg)) {
316                                                 g_string_free(cmd, TRUE);
317                                                 return NULL;
318                                         }
319                                         if (cur->next)
320                                                 g_string_append_c(cmd, ' ');
321                                 }
322                                 p++;
323                                 break;
324                         case 'p':
325                                 if (!parse_append_msgpart(cmd, msginfo,
326                                                           partinfo)) {
327                                         g_string_free(cmd, TRUE);
328                                         return NULL;
329                                 }
330                                 p++;
331                                 break;
332                         case 's':
333                                 if (sel_str)
334                                         g_string_append(cmd, sel_str);
335                                 p++;
336                                 break;
337                         case 'u':
338                                 if (user_str)
339                                         g_string_append(cmd, user_str);
340                                 p++;
341                                 break;
342                         case 'h':
343                                 if (user_hidden_str)
344                                         g_string_append(cmd, user_hidden_str);
345                                 p++;
346                                 break;
347                         case '%':
348                                 g_string_append_c(cmd, p[1]);
349                                 p++;
350                                 break;
351                         default:
352                                 g_string_append_c(cmd, p[0]);
353                                 g_string_append_c(cmd, p[1]);
354                                 p++;
355                         }
356                 } else {
357                         g_string_append_c(cmd, p[0]);
358                 }
359                 p++;
360         }
361         if (cmd->len == 0) {
362                 g_string_free(cmd, TRUE);
363                 return NULL;
364         }
365
366         p = cmd->str;
367         g_string_free(cmd, FALSE);
368         return p;
369 }
370
371 static gboolean parse_append_filename(GString *cmd, MsgInfo *msginfo)
372 {
373         gchar *filename;
374         gchar *p, *q;
375         gchar escape_ch[] = "\\ ";
376
377         cm_return_val_if_fail(msginfo, FALSE);
378
379         filename = procmsg_get_message_file(msginfo);
380
381         if (!filename) {
382                 alertpanel_error(_("Could not get message file %d"),
383                                  msginfo->msgnum);
384                 return FALSE;
385         }
386
387         p = filename;
388         while ((q = strpbrk(p, "$\"`'\\ \t*?[]&|;<>()!#~")) != NULL) {
389                 escape_ch[1] = *q;
390                 *q = '\0';
391                 g_string_append(cmd, p);
392                 g_string_append(cmd, escape_ch);
393                 p = q + 1;
394         }
395         g_string_append(cmd, p);
396
397         g_free(filename);
398
399         return TRUE;
400 }
401
402 static gboolean parse_append_msgpart(GString *cmd, MsgInfo *msginfo,
403                                      MimeInfo *partinfo)
404 {
405         gboolean single_part = FALSE;
406         gchar *filename;
407         gchar *part_filename;
408         gint ret;
409
410         if (!partinfo) {
411                 partinfo = procmime_scan_message(msginfo);
412                 if (!partinfo) {
413                         alertpanel_error(_("Could not get message part."));
414                         return FALSE;
415                 }
416
417                 single_part = TRUE;
418         }
419
420         filename = procmsg_get_message_file_path(msginfo);
421         part_filename = procmime_get_tmp_file_name(partinfo);
422
423         ret = procmime_get_part(part_filename, partinfo);
424
425         if (single_part)
426                 procmime_mimeinfo_free_all(partinfo);
427         g_free(filename);
428
429         if (ret < 0) {
430                 alertpanel_error(_("Can't get part of multipart message: %s"), strerror(-ret));
431                 g_free(part_filename);
432                 return FALSE;
433         }
434
435         g_string_append(cmd, part_filename);
436
437         g_free(part_filename);
438
439         return TRUE;
440 }
441
442 void actions_execute(gpointer data, 
443                      guint action_nb,
444                      GtkWidget *widget,
445                      gint source)
446 {
447         if (source == TOOLBAR_MAIN) 
448                 mainwin_actions_execute((MainWindow*)data, action_nb, widget);
449         else if (source == TOOLBAR_COMPOSE)
450                 compose_actions_execute((Compose*)data, action_nb, widget);
451         else if (source == TOOLBAR_MSGVIEW)
452                 msgview_actions_execute((MessageView*)data, action_nb, widget); 
453 }
454
455 void action_update_mainwin_menu(GtkUIManager *ui_manager,
456                                 gchar *branch_path,
457                                 MainWindow *mainwin)
458 {
459         action_update_menu(ui_manager, "<MainwinActions>", branch_path,
460                            mainwin_actions_execute_cb, mainwin);
461 }
462
463 void action_update_msgview_menu(GtkUIManager    *ui_manager,
464                                 gchar *branch_path,
465                                 MessageView *msgview)
466 {
467         action_update_menu(ui_manager, "<MsgviewActions>", branch_path,
468                            msgview_actions_execute_cb, msgview);
469 }
470
471 void action_update_compose_menu(GtkUIManager *ui_manager, 
472                                 gchar *branch_path,
473                                 Compose *compose)
474 {
475         action_update_menu(ui_manager, "<ComposeActions>", branch_path,
476                            compose_actions_execute_cb, compose);
477 }
478
479 static GtkWidget *find_item_in_menu(GtkWidget *menu, gchar *name)
480 {
481         GList *children = gtk_container_get_children(GTK_CONTAINER(GTK_MENU_SHELL(menu)));
482         GList *amenu = children;
483         const gchar *existing_name;
484         while (amenu) {
485                 GtkWidget *item = GTK_WIDGET(amenu->data);
486                 if ((existing_name = g_object_get_data(G_OBJECT(item), "s_name")) != NULL &&
487                     !strcmp2(name, existing_name))
488                 {
489                         g_list_free(children);
490                          return item;
491                 }
492                 amenu = amenu->next;
493         }
494
495         g_list_free(children);
496
497         return NULL;
498 }
499
500 static GtkWidget *create_submenus(GtkWidget *menu, const gchar *action)
501 {
502         gchar *submenu = g_strdup(action);
503         GtkWidget *new_menu = NULL;
504         
505         if (strchr(submenu, '/')) {
506                 const gchar *end = (strchr(submenu, '/')+1);
507                 GtkWidget *menu_item = NULL;
508                 if (end && *end) {
509                         *strchr(submenu, '/') = '\0';
510                         if ((menu_item = find_item_in_menu(menu, submenu)) == NULL) {
511                                 menu_item = gtk_menu_item_new_with_mnemonic(submenu);
512                                 g_object_set_data_full(G_OBJECT(menu_item), "s_name", g_strdup(submenu), g_free);
513                                 gtk_widget_show(menu_item);
514                                 gtk_menu_shell_append(GTK_MENU_SHELL(menu), menu_item);         
515                                 new_menu = gtk_menu_new();
516                                 gtk_widget_show(new_menu);
517                                 gtk_menu_item_set_submenu(GTK_MENU_ITEM(menu_item), new_menu);
518                         } else {
519                                 new_menu = gtk_menu_item_get_submenu(GTK_MENU_ITEM(menu_item));
520                         }
521                         new_menu = create_submenus(new_menu, end);
522                 }
523         }
524         g_free(submenu);
525         return new_menu ? new_menu : menu;
526 }
527
528 static void action_update_menu(GtkUIManager *ui_manager,
529                                const gchar *accel_group,
530                                gchar *branch_path,
531                                gpointer callback, gpointer data)
532 {
533         GSList *cur;
534         gchar *action, *action_p;
535         int callback_action = 0;
536         GtkWidget *menu = gtk_menu_new();
537         GtkWidget *item;
538
539         for (cur = prefs_common.actions_list; cur != NULL; cur = cur->next) {
540                 GtkWidget *cur_menu = menu;
541                 const gchar *action_name = NULL;
542                 action   = g_strdup((gchar *)cur->data);
543                 action_p = strstr(action, ": ");
544                 if (action_p && action_p[2] &&
545                     (action_get_type(&action_p[2]) != ACTION_ERROR) &&
546                     (action[0] != '/')) {
547                         gchar *accel_path = NULL;
548
549                         action_p[0] = '\0';
550                         if (strchr(action, '/')) {
551                                 cur_menu = create_submenus(cur_menu, action);
552                                 action_name = strrchr(action, '/')+1;
553                         } else {
554                                 action_name = action;
555                         }
556                         gtk_menu_set_accel_group (GTK_MENU (cur_menu), 
557                                 gtk_ui_manager_get_accel_group(ui_manager));
558                         item = gtk_menu_item_new_with_label(action_name);
559                         gtk_menu_shell_append(GTK_MENU_SHELL(cur_menu), item);
560                         g_signal_connect(G_OBJECT(item), "activate",
561                                          G_CALLBACK(callback), data);
562                         g_object_set_data(G_OBJECT(item), "action_num", GINT_TO_POINTER(callback_action));
563                         gtk_widget_show(item);
564                         accel_path = g_strconcat(accel_group,branch_path, "/", action, NULL);
565                         gtk_menu_item_set_accel_path(GTK_MENU_ITEM(item), accel_path);
566                         g_free(accel_path);
567
568                 }
569                 g_free(action);
570                 callback_action++;
571         }
572
573         gtk_widget_show(menu);
574         gtk_menu_item_set_submenu(GTK_MENU_ITEM(gtk_ui_manager_get_widget(ui_manager, branch_path)), menu);
575 }
576
577 static void compose_actions_execute_cb(GtkWidget *widget, gpointer data)
578 {
579         Compose *compose = (Compose *)data;
580         gint action_nb = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(widget), "action_num"));
581         compose_actions_execute(compose, action_nb, NULL);
582 }
583
584 static void compose_actions_execute(Compose *compose, guint action_nb, GtkWidget *widget)
585 {
586         gchar *buf, *action;
587         ActionType action_type;
588
589         cm_return_if_fail(action_nb < g_slist_length(prefs_common.actions_list));
590
591         buf = (gchar *)g_slist_nth_data(prefs_common.actions_list, action_nb);
592         cm_return_if_fail(buf != NULL);
593         action = strstr(buf, ": ");
594         cm_return_if_fail(action != NULL);
595
596         /* Point to the beginning of the command-line */
597         action += 2;
598
599         action_type = action_get_type(action);
600         if (action_type & (ACTION_SINGLE | ACTION_MULTIPLE)) {
601                 alertpanel_warning
602                         (_("The selected action cannot be used in the compose window\n"
603                            "because it contains %%f, %%F, %%as or %%p."));
604                 return;
605         }
606
607         execute_actions(action, NULL, compose->text, 0, NULL, 
608                 compose_action_cb, compose);
609 }
610
611 static void mainwin_actions_execute_cb(GtkWidget *widget, gpointer data)
612 {
613         MainWindow *mainwin = (MainWindow *)data;
614         gint action_nb = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(widget), "action_num"));
615         mainwin_actions_execute(mainwin, action_nb, NULL);
616 }
617
618 static void mainwin_actions_execute(MainWindow *mainwin, guint action_nb,
619                                        GtkWidget *widget)
620 {
621         GSList *msg_list;
622
623         msg_list = summary_get_selected_msg_list(mainwin->summaryview);
624         message_actions_execute(mainwin->messageview, action_nb, msg_list);
625         g_slist_free(msg_list);
626 }
627
628 static void msgview_actions_execute_cb(GtkWidget *widget, gpointer data)
629 {
630         MessageView *msgview = (MessageView *)data;
631         gint action_nb = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(widget), "action_num"));
632         msgview_actions_execute(msgview, action_nb, NULL);
633 }
634
635 static void msgview_actions_execute(MessageView *msgview, guint action_nb,
636                                        GtkWidget *widget)
637 {
638         GSList *msg_list = NULL;
639
640         if (msgview->msginfo)
641                 msg_list = g_slist_append(msg_list, msgview->msginfo);
642         message_actions_execute(msgview, action_nb, msg_list);
643         g_slist_free(msg_list);
644 }
645
646 static void message_actions_execute(MessageView *msgview, guint action_nb,
647                                     GSList *msg_list)
648 {
649         TextView *textview;
650         MimeInfo *partinfo;
651         gchar *buf;
652         gchar *action;
653         GtkWidget *text = NULL;
654         guint body_pos = 0;
655         ActionType action_type;
656         
657         cm_return_if_fail(action_nb < g_slist_length(prefs_common.actions_list));
658
659         buf = (gchar *)g_slist_nth_data(prefs_common.actions_list, action_nb);
660
661         cm_return_if_fail(buf);
662         cm_return_if_fail((action = strstr(buf, ": ")));
663
664         /* Point to the beginning of the command-line */
665         action += 2;
666
667         textview = messageview_get_current_textview(msgview);
668         if (textview) {
669                 text     = textview->text;
670                 body_pos = textview->body_pos;
671         }
672         partinfo = messageview_get_selected_mime_part(msgview);
673
674         /* this command will alter the message text */
675         action_type = action_get_type(action);
676         if (action_type & (ACTION_PIPE_OUT | ACTION_INSERT))
677                 msgview->filtered = TRUE;
678
679         if (action_type & ACTION_FILTERING_ACTION) 
680                 /* CLAWS: most of the above code is not necessary for applying
681                  * filtering */
682                 execute_filtering_actions(action, msg_list);
683         else
684                 execute_actions(action, msg_list, text, body_pos, partinfo,
685                         NULL, NULL);
686 }
687
688 static gboolean execute_filtering_actions(gchar *action, GSList *msglist)
689 {
690         GSList *action_list, *p;
691         const gchar *sbegin, *send;
692         gchar *action_string;
693         SummaryView *summaryview = NULL;
694         MainWindow *mainwin = NULL;
695
696         if (mainwindow_get_mainwindow()) {
697                 summaryview = mainwindow_get_mainwindow()->summaryview;
698                 mainwin = mainwindow_get_mainwindow();
699         }
700
701         if (NULL == (sbegin = strstr2(action, "%as{")))
702                 return FALSE;
703         sbegin += sizeof "%as{" - 1;
704         if (NULL == (send = strrchr(sbegin, '}')))
705                 return FALSE;
706         action_string = g_strndup(sbegin, send - sbegin);
707         
708         action_list = matcher_parser_get_action_list(action_string);
709         if (action_list == NULL) {
710                 gchar *tmp = g_strdup(action_string);
711
712                 g_strstrip(tmp);
713                 if (*tmp == '\0')
714                         alertpanel_error(_("There is no filtering action set"));
715                 else
716                         alertpanel_error(_("Invalid filtering action(s):\n%s"), tmp);
717                 g_free(action_string);
718                 g_free(tmp);
719                 return FALSE;
720         }
721         g_free(action_string);
722         
723         /* apply actions on each message info */
724         for (p = msglist; p && p->data; p = g_slist_next(p)) {
725                 filteringaction_apply_action_list(action_list, (MsgInfo *) p->data);
726         }
727
728         if (summaryview) {
729                 summary_lock(summaryview);                              
730                 main_window_cursor_wait(mainwin);               
731                 summary_freeze(summaryview);    
732                 folder_item_update_freeze();                            
733         }
734
735         filtering_move_and_copy_msgs(msglist);
736
737         if (summaryview) {
738                 folder_item_update_thaw();                              
739                 summary_thaw(summaryview);              
740                 main_window_cursor_normal(mainwin);     
741                 summary_unlock(summaryview);                            
742                 summary_show(summaryview, summaryview->folder_item);
743         }
744         for (p = action_list; p; p = g_slist_next(p))
745                 if (p->data) filteringaction_free(p->data);     
746         g_slist_free(action_list);              
747         return TRUE;    
748 }
749
750 static gboolean execute_actions(gchar *action, GSList *msg_list,
751                                 GtkWidget *text,
752                                 gint body_pos, MimeInfo *partinfo,
753                                 void (*callback)(void *data), void *data)
754 {
755         GSList *children_list = NULL;
756         gint is_ok  = TRUE;
757         gint msg_list_len;
758         Children *children;
759         ChildInfo *child_info;
760         ActionType action_type;
761         MsgInfo *msginfo;
762         gchar *cmd;
763         gchar *sel_str = NULL;
764         gchar *msg_str = NULL;
765         gchar *user_str = NULL;
766         gchar *user_hidden_str = NULL;
767         GtkTextIter start_iter, end_iter;
768         gboolean is_selection = FALSE;
769
770         cm_return_val_if_fail(action && *action, FALSE);
771
772         action_type = action_get_type(action);
773
774         if (action_type == ACTION_ERROR)
775                 return FALSE;         /* ERR: syntax error */
776
777         if (action_type & (ACTION_SINGLE | ACTION_MULTIPLE) && !msg_list)
778                 return FALSE;         /* ERR: file command without selection */
779
780         msg_list_len = g_slist_length(msg_list);
781
782         if (action_type & (ACTION_PIPE_OUT | ACTION_PIPE_IN | ACTION_INSERT)) {
783                 if (msg_list_len > 1)
784                         return FALSE; /* ERR: pipe + multiple selection */
785                 if (!text)
786                         return FALSE; /* ERR: pipe and no displayed text */
787         }
788
789         if (action_type & ACTION_SELECTION_STR) {
790                 if (!text)
791                         return FALSE; /* ERR: selection string but no text */
792         }
793
794         if (text) {
795                 GtkTextBuffer *textbuf;
796
797                 textbuf = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
798                 is_selection = gtk_text_buffer_get_selection_bounds
799                         (textbuf, &start_iter, &end_iter);
800                 if (!is_selection) {
801                         gtk_text_buffer_get_iter_at_offset
802                                 (textbuf, &start_iter, body_pos);
803                         gtk_text_buffer_get_end_iter(textbuf, &end_iter);
804                 }
805                 msg_str = gtk_text_buffer_get_text
806                         (textbuf, &start_iter, &end_iter, FALSE);
807                 if (is_selection)
808                         sel_str = g_strdup(msg_str);
809         }
810
811         if (action_type & ACTION_USER_STR) {
812                 if (!(user_str = get_user_string(action, ACTION_USER_STR))) {
813                         g_free(msg_str);
814                         g_free(sel_str);
815                         return FALSE;
816                 }
817         }
818
819         if (action_type & ACTION_USER_HIDDEN_STR) {
820                 if (!(user_hidden_str =
821                         get_user_string(action, ACTION_USER_HIDDEN_STR))) {
822                         g_free(msg_str);
823                         g_free(sel_str);
824                         g_free(user_str);
825                         return FALSE;
826                 }
827         }
828
829         if (text && (action_type & ACTION_PIPE_OUT)) {
830                 GtkTextBuffer *textbuf;
831                 textbuf = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
832                 gtk_text_buffer_delete(textbuf, &start_iter, &end_iter);
833         }
834
835         children = g_new0(Children, 1);
836
837         children->action      = g_strdup(action);
838         children->action_type = action_type;
839         children->msg_text    = text;
840         children->is_selection = is_selection;
841
842         if ((action_type & (ACTION_USER_IN | ACTION_USER_HIDDEN_IN)) &&
843             ((action_type & ACTION_SINGLE) == 0 || msg_list_len == 1))
844                 children->open_in = 1;
845
846         if (action_type & ACTION_SINGLE) {
847                 GSList *cur;
848
849                 for (cur = msg_list; cur && is_ok == TRUE; cur = cur->next) {
850                         msginfo = (MsgInfo *)cur->data;
851                         if (!msginfo) {
852                                 is_ok  = FALSE; /* ERR: msginfo missing */
853                                 break;
854                         }
855                         cmd = parse_action_cmd(action, msginfo, msg_list,
856                                                partinfo, user_str,
857                                                user_hidden_str, sel_str);
858                         if (!cmd) {
859                                 debug_print("Action command error\n");
860                                 is_ok  = FALSE; /* ERR: incorrect command */
861                                 break;
862                         }
863                         if ((child_info = fork_child(cmd, msg_str, children))) {
864                                 /* Pass msginfo to catch_status () */
865                                 if (!(action_type & (ACTION_PIPE_OUT | ACTION_INSERT)))
866                                         child_info->msginfo_list = 
867                                                 g_slist_append (NULL, msginfo);
868                                 children_list = g_slist_append(children_list,
869                                                                child_info);
870                         }
871                         g_free(cmd);
872                 }
873         } else {
874                 cmd = parse_action_cmd(action, NULL, msg_list, partinfo,
875                                        user_str, user_hidden_str, sel_str);
876                 if (cmd) {
877                         if ((child_info = fork_child(cmd, msg_str, children))) {
878                                 if (!(action_type & (ACTION_PIPE_OUT | ACTION_INSERT)))
879                                         child_info->msginfo_list = 
880                                                 g_slist_copy (msg_list);
881                                 children_list = g_slist_append(children_list,
882                                                                 child_info);
883                         }
884                         g_free(cmd);
885                 } else
886                         is_ok  = FALSE;         /* ERR: incorrect command */
887         }
888
889         g_free(msg_str);
890         g_free(sel_str);
891         g_free(user_str);
892         g_free(user_hidden_str);
893
894         if (!children_list) {
895                  /* If not waiting for children, return */
896                 free_children(children);
897         } else {
898                 GSList *cur;
899
900                 children->list        = children_list;
901                 children->nb          = g_slist_length(children_list);
902                 children->initial_nb  = children->nb;
903
904                 for (cur = children_list; cur; cur = cur->next) {
905                         child_info = (ChildInfo *) cur->data;
906                         child_info->callback = callback;
907                         child_info->data = data;
908                         child_info->tag_status = 
909                                 claws_input_add(child_info->chld_status,
910                                               G_IO_IN | G_IO_HUP | G_IO_ERR,
911                                               catch_status, child_info,
912                                               FALSE);
913                 }
914
915                 create_io_dialog(children);
916         }
917         return is_ok;
918 }
919
920 static ChildInfo *fork_child(gchar *cmd, const gchar *msg_str,
921                              Children *children)
922 {
923 #ifdef G_OS_UNIX
924         gint chld_in[2], chld_out[2], chld_err[2], chld_status[2];
925         gchar *cmdline[4], *ret_str;
926         pid_t pid, gch_pid;
927         ChildInfo *child_info;
928         gint sync;
929         gssize by_written = 0, by_read = 0;
930
931         sync = !(children->action_type & ACTION_ASYNC);
932
933         chld_in[0] = chld_in[1] = chld_out[0] = chld_out[1] = chld_err[0]
934                 = chld_err[1] = chld_status[0] = chld_status[1] = -1;
935
936         if (sync) {
937                 if (pipe(chld_status) || pipe(chld_in) || pipe(chld_out) ||
938                     pipe(chld_err)) {
939                         alertpanel_error(_("Command could not be started. "
940                                            "Pipe creation failed.\n%s"),
941                                         g_strerror(errno));
942                         /* Closing fd = -1 fails silently */
943                         (void)close(chld_in[0]);
944                         (void)close(chld_in[1]);
945                         (void)close(chld_out[0]);
946                         (void)close(chld_out[1]);
947                         (void)close(chld_err[0]);
948                         (void)close(chld_err[1]);
949                         (void)close(chld_status[0]);
950                         (void)close(chld_status[1]);
951                         return NULL; /* Pipe error */
952                 }
953         }
954
955         debug_print("Forking child and grandchild.\n");
956         debug_print("Executing: /bin/sh -c %s\n", cmd);
957
958         pid = fork();
959         if (pid == 0) { /* Child */
960                 int r = 0;
961                 if (setpgid(0, 0))
962                         perror("setpgid");
963
964                 gch_pid = fork();
965
966                 if (gch_pid == 0) {
967                         if (setpgid(0, getppid()))
968                                 perror("setpgid");
969
970                         if (sync) {
971                                 if (children->action_type &
972                                     (ACTION_PIPE_IN |
973                                      ACTION_USER_IN |
974                                      ACTION_USER_HIDDEN_IN)) {
975                                         r |= close(fileno(stdin));
976                                         (void) dup  (chld_in[0]);
977                                 }
978                                 r |= close(chld_in[0]);
979                                 r |= close(chld_in[1]);
980
981                                 r |= close(fileno(stdout));
982                                 (void) dup  (chld_out[1]);
983                                 r |= close(chld_out[0]);
984                                 r |= close(chld_out[1]);
985
986                                 r |= close(fileno(stderr));
987                                 (void) dup  (chld_err[1]);
988                                 r |= close(chld_err[0]);
989                                 r |= close(chld_err[1]);
990
991                                 if (r != 0)
992                                         debug_print("%s(%d)", strerror(errno), errno);
993                         }
994
995                         cmdline[0] = "sh";
996                         cmdline[1] = "-c";
997                         ret_str = g_locale_from_utf8(cmd, strlen(cmd),
998                                                      &by_read, &by_written,
999                                                      NULL);
1000                         if (ret_str && by_written)
1001                                 cmdline[2] = ret_str;
1002                         else
1003                                 cmdline[2] = cmd;
1004                         cmdline[3] = NULL;
1005                         execvp("/bin/sh", cmdline);
1006
1007                         perror("execvp");
1008                         g_free(ret_str);
1009                         _exit(1);
1010                 } else if (gch_pid < (pid_t) 0) { /* Fork error */
1011                         if (sync)
1012                                 r = write(chld_status[1], "1\n", 2);
1013                         if (r != 0)
1014                                 debug_print("%s(%d)", strerror(errno), errno);
1015                         perror("fork");
1016                         _exit(1);
1017                 } else { /* Child */
1018                         if (sync) {
1019                                 r |= close(chld_in[0]);
1020                                 r |= close(chld_in[1]);
1021                                 r |= close(chld_out[0]);
1022                                 r |= close(chld_out[1]);
1023                                 r |= close(chld_err[0]);
1024                                 r |= close(chld_err[1]);
1025                                 r |= close(chld_status[0]);
1026
1027                                 debug_print("Child: waiting for grandchild\n");
1028                                 r |= waitpid(gch_pid, NULL, 0);
1029                                 debug_print("Child: grandchild ended\n");
1030                                 r |= write(chld_status[1], "0\n", 2);
1031                                 r |= close(chld_status[1]);
1032
1033                                 if (r != 0)
1034                                         debug_print("%s(%d)", strerror(errno), errno);
1035                         }
1036                         _exit(0);
1037                 }
1038         } else if (pid < 0) { /* Fork error */
1039                 alertpanel_error(_("Could not fork to execute the following "
1040                                    "command:\n%s\n%s"),
1041                                  cmd, g_strerror(errno));
1042                 return NULL; 
1043         }
1044
1045         /* Parent */
1046
1047         if (!sync) {
1048                 waitpid(pid, NULL, 0);
1049                 return NULL;
1050         }
1051
1052         (void)close(chld_in[0]);
1053         if (!(children->action_type &
1054               (ACTION_PIPE_IN | ACTION_USER_IN | ACTION_USER_HIDDEN_IN)))
1055                 (void)close(chld_in[1]);
1056         (void)close(chld_out[1]);
1057         (void)close(chld_err[1]);
1058         (void)close(chld_status[1]);
1059
1060         child_info = g_new0(ChildInfo, 1);
1061
1062         child_info->children    = children;
1063
1064         child_info->pid         = pid;
1065         child_info->next_sig    = SIGTERM;
1066         child_info->cmd         = g_strdup(cmd);
1067         child_info->new_out     = FALSE;
1068         child_info->output      = g_string_new(NULL);
1069         child_info->chld_in     =
1070                 (children->action_type &
1071                  (ACTION_PIPE_IN | ACTION_USER_IN | ACTION_USER_HIDDEN_IN))
1072                         ? chld_in [1] : -1;
1073         child_info->chld_out    = chld_out[0];
1074         child_info->chld_err    = chld_err[0];
1075         child_info->chld_status = chld_status[0];
1076         child_info->tag_in      = -1;
1077         child_info->tag_out     = claws_input_add(chld_out[0], G_IO_IN | G_IO_HUP | G_IO_ERR,
1078                                                 catch_output, child_info, FALSE);
1079         child_info->tag_err     = claws_input_add(chld_err[0], G_IO_IN | G_IO_HUP | G_IO_ERR,
1080                                                 catch_output, child_info, FALSE);
1081
1082         if (!(children->action_type &
1083               (ACTION_PIPE_IN | ACTION_PIPE_OUT | ACTION_INSERT)))
1084                 return child_info;
1085
1086         if ((children->action_type & ACTION_PIPE_IN) && msg_str) {
1087                 int r;
1088                 ret_str = g_locale_from_utf8(msg_str, strlen(msg_str),
1089                                              &by_read, &by_written, NULL);
1090                 if (ret_str && by_written) {
1091                         r = write(chld_in[1], ret_str, strlen(ret_str));
1092                         g_free(ret_str);
1093                 } else
1094                         r = write(chld_in[1], msg_str, strlen(msg_str));
1095                 if (!(children->action_type &
1096                       (ACTION_USER_IN | ACTION_USER_HIDDEN_IN)))
1097                         r = close(chld_in[1]);
1098                 child_info->chld_in = -1; /* No more input */
1099                 if (r != 0)
1100                         debug_print("%s(%d)", strerror(errno), errno);
1101         }
1102
1103         return child_info;
1104 #else
1105         return NULL;
1106 #endif /* G_OS_UNIX */
1107 }
1108
1109 static void kill_children_cb(GtkWidget *widget, gpointer data)
1110 {
1111 #ifdef G_OS_UNIX
1112         GSList *cur;
1113         Children *children = (Children *) data;
1114         ChildInfo *child_info;
1115
1116         for (cur = children->list; cur; cur = cur->next) {
1117                 child_info = (ChildInfo *)(cur->data);
1118                 debug_print("Killing child group id %d\n", child_info->pid);
1119                 if (child_info->pid && kill(-child_info->pid, child_info->next_sig) < 0)
1120                         perror("kill");
1121                 child_info->next_sig = SIGKILL;
1122         }
1123 #endif /* G_OS_UNIX */
1124 }
1125
1126 static gint wait_for_children(Children *children)
1127 {
1128         gboolean new_output;
1129         ChildInfo *child_info;
1130         GSList *cur;
1131
1132         cur = children->list;
1133         new_output = FALSE;
1134         while (cur) {
1135                 child_info = (ChildInfo *)cur->data;
1136                 new_output |= child_info->new_out;
1137                 cur = cur->next;
1138         }
1139
1140         children->output |= new_output;
1141
1142         if (new_output || (children->dialog && (children->initial_nb != children->nb)))
1143                 update_io_dialog(children);
1144
1145         if (children->nb)
1146                 return FALSE;
1147
1148         if (!children->dialog) {
1149                 free_children(children);
1150         } else if (!children->output) {
1151                 gtk_widget_destroy(children->dialog);
1152         }
1153
1154         return FALSE;
1155 }
1156
1157 static void send_input(GtkWidget *w, gpointer data)
1158 {
1159         Children *children = (Children *) data;
1160         ChildInfo *child_info = (ChildInfo *) children->list->data;
1161
1162         child_info->tag_in = claws_input_add(child_info->chld_in,
1163                                            G_IO_OUT | G_IO_ERR,
1164                                            catch_input, children, FALSE);
1165 }
1166
1167 static gint delete_io_dialog_cb(GtkWidget *w, GdkEvent *e, gpointer data)
1168 {
1169         hide_io_dialog_cb(w, data);
1170         return TRUE;
1171 }
1172
1173 static void hide_io_dialog_cb(GtkWidget *w, gpointer data)
1174 {
1175
1176         Children *children = (Children *)data;
1177
1178         if (!children->nb) {
1179                 g_signal_handlers_disconnect_matched
1180                         (G_OBJECT(children->dialog), G_SIGNAL_MATCH_DATA,
1181                          0, 0, NULL, NULL, children);
1182                 gtk_widget_destroy(children->dialog);
1183                 free_children(children);
1184         }
1185 }
1186
1187 static gint io_dialog_key_pressed_cb(GtkWidget *widget, GdkEventKey *event,
1188                                      gpointer data)
1189 {
1190         if (event && (event->keyval == GDK_KEY_Escape ||
1191                       event->keyval == GDK_KEY_Return ||
1192                           event->keyval == GDK_KEY_KP_Enter))
1193                 hide_io_dialog_cb(widget, data);
1194         return TRUE;
1195 }
1196
1197 static void childinfo_close_pipes(ChildInfo *child_info)
1198 {
1199         /* stdout and stderr pipes are guaranteed to be removed by
1200          * their handler, but in case where we receive child exit notification
1201          * before grand-child's pipes closing signals, we check them and close
1202          * them if necessary
1203          */
1204         if (child_info->tag_in > 0)
1205                 g_source_remove(child_info->tag_in);
1206         if (child_info->tag_out > 0)
1207                 g_source_remove(child_info->tag_out);
1208         if (child_info->tag_err > 0)
1209                 g_source_remove(child_info->tag_err);
1210
1211         if (child_info->chld_in >= 0)
1212                 (void)close(child_info->chld_in);
1213         if (child_info->chld_out >= 0)
1214                 (void)close(child_info->chld_out);
1215         if (child_info->chld_err >= 0)
1216                 (void)close(child_info->chld_err);
1217
1218         (void)close(child_info->chld_status);
1219 }
1220
1221 static void free_children(Children *children)
1222 {
1223         ChildInfo *child_info;
1224         void (*callback)(void *data) = NULL;
1225         void *data = NULL;
1226
1227         debug_print("Freeing children data %p\n", children);
1228
1229         g_free(children->action);
1230         while (children->list != NULL) {
1231                 child_info = (ChildInfo *)children->list->data;
1232                 g_free(child_info->cmd);
1233                 g_string_free(child_info->output, TRUE);
1234                 children->list = g_slist_remove(children->list, child_info);
1235                 callback = child_info->callback;
1236                 data = child_info->data;
1237                 g_free(child_info);
1238         }
1239
1240         if (callback)
1241                 callback(data);
1242         
1243         g_free(children);
1244 }
1245
1246 static void update_io_dialog(Children *children)
1247 {
1248         GSList *cur;
1249
1250         debug_print("Updating actions input/output dialog.\n");
1251
1252         if (children->progress_bar) {
1253                 gchar *text;
1254 #ifdef GENERIC_UMPC
1255                 /* use a more compact format */
1256                 const gchar *format = "%s %d/%d";
1257 #else
1258                 const gchar *format = "%s %d / %d";
1259 #endif
1260                 
1261                 gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(children->progress_bar),
1262                                                   (children->initial_nb == 0) ? 0 :
1263                                               (gdouble) (children->initial_nb - children->nb) /
1264                                               (gdouble) children->initial_nb);
1265                 text = g_strdup_printf(format, _("Completed"), 
1266                                        children->initial_nb - children->nb,
1267                                        children->initial_nb);
1268                 gtk_progress_bar_set_text(GTK_PROGRESS_BAR(children->progress_bar), text);
1269                 g_free(text);
1270         }
1271
1272         if (!children->nb) {
1273                 gtk_widget_set_sensitive(children->abort_btn, FALSE);
1274                 gtk_widget_set_sensitive(children->close_btn, TRUE);
1275                 if (children->input_hbox)
1276                         gtk_widget_set_sensitive(children->input_hbox, FALSE);
1277                 gtk_widget_grab_focus(children->close_btn);
1278                 g_signal_connect(G_OBJECT(children->dialog),
1279                                  "key_press_event",
1280                                  G_CALLBACK(io_dialog_key_pressed_cb),
1281                                  children);
1282         }
1283
1284         if (children->output) {
1285                 GtkWidget *text = children->text;
1286                 GtkTextBuffer *textbuf;
1287                 GtkTextIter iter, start_iter, end_iter;
1288                 gchar *caption;
1289                 ChildInfo *child_info;
1290
1291                 gtk_widget_show(children->scrolledwin);
1292                 textbuf = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
1293                 gtk_text_buffer_get_bounds(textbuf, &start_iter, &end_iter);
1294                 gtk_text_buffer_delete(textbuf, &start_iter, &end_iter);
1295                 gtk_text_buffer_get_start_iter(textbuf, &iter);
1296
1297                 for (cur = children->list; cur; cur = cur->next) {
1298                         child_info = (ChildInfo *)cur->data;
1299                         if (child_info->pid)
1300                                 caption = g_strdup_printf
1301                                         (_("--- Running: %s\n"),
1302                                          child_info->cmd);
1303                         else
1304                                 caption = g_strdup_printf
1305                                         (_("--- Ended: %s\n"),
1306                                          child_info->cmd);
1307
1308                         gtk_text_buffer_insert(textbuf, &iter, caption, -1);
1309                         gtk_text_buffer_insert(textbuf, &iter,
1310                                                child_info->output->str, -1);
1311                         g_free(caption);
1312                         child_info->new_out = FALSE;
1313                 }
1314         }
1315 }
1316
1317 static void create_io_dialog(Children *children)
1318 {
1319         GtkWidget *dialog;
1320         GtkWidget *vbox;
1321         GtkWidget *entry = NULL;
1322         GtkWidget *input_hbox = NULL;
1323         GtkWidget *send_button;
1324         GtkWidget *label;
1325         GtkWidget *text;
1326         GtkWidget *scrolledwin;
1327         GtkWidget *hbox;
1328         GtkWidget *progress_bar = NULL;
1329         GtkWidget *abort_button;
1330         GtkWidget *close_button;
1331
1332         debug_print("Creating action IO dialog\n");
1333
1334         dialog = gtk_dialog_new();
1335         gtk_container_set_border_width
1336                 (GTK_CONTAINER(gtk_dialog_get_action_area(GTK_DIALOG(dialog))), 5);
1337         gtk_window_set_position(GTK_WINDOW(dialog), GTK_WIN_POS_CENTER);
1338         gtk_window_set_title(GTK_WINDOW(dialog), _("Action's input/output"));
1339         gtk_window_set_modal(GTK_WINDOW(dialog), TRUE);
1340         manage_window_set_transient(GTK_WINDOW(dialog));
1341         g_signal_connect(G_OBJECT(dialog), "delete_event",
1342                          G_CALLBACK(delete_io_dialog_cb), children);
1343         g_signal_connect(G_OBJECT(dialog), "destroy",
1344                          G_CALLBACK(hide_io_dialog_cb),
1345                          children);
1346
1347         vbox = gtk_vbox_new(FALSE, 8);
1348         gtk_container_add(GTK_CONTAINER(
1349                                 gtk_dialog_get_content_area(GTK_DIALOG(dialog))), vbox);
1350         gtk_container_set_border_width(GTK_CONTAINER(vbox), 8);
1351         gtk_widget_show(vbox);
1352
1353         label = gtk_label_new(children->action);
1354         gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 0);
1355         gtk_widget_show(label);
1356
1357         scrolledwin = gtk_scrolled_window_new(NULL, NULL);
1358         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledwin),
1359                                        GTK_POLICY_AUTOMATIC,
1360                                        GTK_POLICY_AUTOMATIC);
1361         gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scrolledwin),
1362                                             GTK_SHADOW_IN);
1363         gtk_box_pack_start(GTK_BOX(vbox), scrolledwin, TRUE, TRUE, 0);
1364         gtk_widget_set_size_request(scrolledwin, 560, 200);
1365         gtk_widget_hide(scrolledwin);
1366
1367         text = gtk_text_view_new();
1368
1369         if (prefs_common.textfont) {
1370                 PangoFontDescription *font_desc;
1371                 font_desc = pango_font_description_from_string
1372                         (prefs_common.textfont);
1373                 if (font_desc) {
1374                         gtk_widget_modify_font(text, font_desc);
1375                         pango_font_description_free(font_desc);
1376                 }
1377         }
1378
1379         gtk_text_view_set_editable(GTK_TEXT_VIEW(text), FALSE);
1380         gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(text), GTK_WRAP_WORD);
1381         gtk_text_view_set_left_margin(GTK_TEXT_VIEW(text), 6);
1382         gtk_text_view_set_right_margin(GTK_TEXT_VIEW(text), 6);
1383         gtk_container_add(GTK_CONTAINER(scrolledwin), text);
1384         gtk_widget_show(text);
1385
1386         if (children->open_in) {
1387                 input_hbox = gtk_hbox_new(FALSE, 8);
1388                 gtk_widget_show(input_hbox);
1389
1390                 entry = gtk_entry_new();
1391                 gtk_widget_set_size_request(entry, 320, -1);
1392                 g_signal_connect(G_OBJECT(entry), "activate",
1393                                  G_CALLBACK(send_input), children);
1394                 gtk_box_pack_start(GTK_BOX(input_hbox), entry, TRUE, TRUE, 0);
1395                 if (children->action_type & ACTION_USER_HIDDEN_IN) {
1396                         gtk_entry_set_visibility(GTK_ENTRY(entry), FALSE);
1397 #ifdef MAEMO
1398                         hildon_gtk_entry_set_input_mode(GTK_ENTRY(entry), 
1399                                 HILDON_GTK_INPUT_MODE_FULL | 
1400                                 HILDON_GTK_INPUT_MODE_INVISIBLE);
1401 #endif
1402                 }
1403                 gtk_widget_show(entry);
1404
1405                 send_button = gtk_button_new_from_stock(GTK_STOCK_EXECUTE);
1406                 g_signal_connect(G_OBJECT(send_button), "clicked",
1407                                  G_CALLBACK(send_input), children);
1408                 gtk_box_pack_start(GTK_BOX(input_hbox), send_button, FALSE,
1409                                    FALSE, 0);
1410                 gtk_widget_show(send_button);
1411
1412                 gtk_box_pack_start(GTK_BOX(vbox), input_hbox, FALSE, FALSE, 0);
1413                 gtk_widget_grab_focus(entry);
1414         }
1415
1416         if (children->initial_nb > 1) {
1417                 gchar *text;
1418 #ifdef GENERIC_UMPC
1419                 /* use a more compact format */
1420                 const gchar *format = "%s 0/%d\n";
1421 #else
1422                 const gchar *format = "%s 0 / %d\n";
1423 #endif
1424                 
1425                 progress_bar = gtk_progress_bar_new();
1426 #if !GTK_CHECK_VERSION(3, 0, 0)
1427                 gtk_progress_bar_set_orientation(GTK_PROGRESS_BAR(progress_bar),
1428                                 GTK_PROGRESS_LEFT_TO_RIGHT);
1429 #else
1430                 gtk_orientable_set_orientation(GTK_PROGRESS_BAR(progress_bar),
1431                                 GTK_ORIENTATION_HORIZONTAL);
1432                 gtk_progress_bar_set_inverted(GTK_PROGRESS_BAR(progress_bar),
1433                                 FALSE);
1434 #endif
1435                 text = g_strdup_printf(format, _("Completed"), 
1436                                        children->initial_nb);
1437                 gtk_progress_bar_set_text(GTK_PROGRESS_BAR(progress_bar),
1438                                           text);
1439                 g_free(text);
1440                 gtk_box_pack_start(GTK_BOX(vbox), progress_bar, FALSE, FALSE, 0);
1441                 gtk_widget_show(progress_bar);
1442         }
1443
1444         gtkut_stock_button_set_create(&hbox, &abort_button, GTK_STOCK_STOP,
1445                                       &close_button, GTK_STOCK_CLOSE, NULL, NULL);
1446         g_signal_connect(G_OBJECT(abort_button), "clicked",
1447                          G_CALLBACK(kill_children_cb), children);
1448         g_signal_connect(G_OBJECT(close_button), "clicked",
1449                          G_CALLBACK(hide_io_dialog_cb), children);
1450         gtk_widget_show(hbox);
1451
1452         if (children->nb)
1453                 gtk_widget_set_sensitive(close_button, FALSE);
1454
1455         gtk_container_add(GTK_CONTAINER(
1456                         gtk_dialog_get_action_area(GTK_DIALOG(dialog))), hbox);
1457
1458         children->dialog       = dialog;
1459         children->scrolledwin  = scrolledwin;
1460         children->text         = text;
1461         children->input_hbox   = children->open_in ? input_hbox : NULL;
1462         children->input_entry  = children->open_in ? entry : NULL;
1463         children->progress_bar = progress_bar;
1464         children->abort_btn    = abort_button;
1465         children->close_btn    = close_button;
1466
1467         gtk_widget_show(dialog);
1468 }
1469
1470 static void catch_status(gpointer data, gint source, GIOCondition cond)
1471 {
1472         ChildInfo *child_info = (ChildInfo *)data;
1473         gchar buf;
1474         gint c;
1475
1476         g_source_remove(child_info->tag_status);
1477
1478         c = read(source, &buf, 1);
1479         if (c != 1) {
1480                 g_message("error reading child return status\n");
1481         }
1482         debug_print("Child returned %c\n", buf);
1483
1484 #ifdef G_OS_UNIX
1485         waitpid(-child_info->pid, NULL, 0);
1486 #endif
1487         childinfo_close_pipes(child_info);
1488         child_info->pid = 0;
1489
1490         if (child_info->children->action_type & (ACTION_SINGLE | ACTION_MULTIPLE)
1491             && child_info->msginfo_list) {
1492                 /* Actions on message *files* might change size and
1493                 * time stamp, and thus invalidate the cache */
1494                 SummaryView *summaryview  = NULL;
1495                 GSList      *cur;
1496                 MsgInfo     *msginfo, *nmi;     /* newmsginfo */
1497                 char        *file;
1498                 gboolean     modified_something = FALSE;
1499                 FolderItem  *last_item = NULL;
1500                 if (mainwindow_get_mainwindow ())
1501                         summaryview = mainwindow_get_mainwindow ()->summaryview;
1502                 for (cur = child_info->msginfo_list; cur; cur = cur->next) {
1503                         msginfo = (MsgInfo *)cur->data;
1504                         if (!(msginfo && /* Stuff used valid? */
1505                             msginfo->folder && msginfo->folder->cache)) 
1506                                 continue;
1507                         file = procmsg_get_message_file_path (msginfo);
1508                         if (!file) 
1509                                 continue;
1510                         nmi = procheader_parse_file (file, msginfo->flags, TRUE, FALSE);
1511                         if (!nmi) 
1512                                 continue; /* Deleted? */
1513                         if (msginfo->mtime != nmi->mtime || msginfo->size != nmi->size) {
1514                                 nmi->folder = msginfo->folder;
1515                                 nmi->msgnum = msginfo->msgnum;
1516                                 msgcache_update_msg (msginfo->folder->cache, nmi);
1517                                 modified_something = TRUE;
1518                                 last_item = nmi->folder;
1519                         }
1520                         procmsg_msginfo_free (nmi);
1521                         if (summaryview && summaryview->displayed &&
1522                             summaryview->folder_item == msginfo->folder &&
1523                             summary_get_msgnum(summaryview, summaryview->displayed) == msginfo->msgnum)
1524                                 summary_redisplay_msg(summaryview);
1525                                         
1526                 }
1527                 if (modified_something && last_item && 
1528                     summaryview && summaryview->folder_item == last_item) {
1529                         summary_show (summaryview, summaryview->folder_item);
1530                 }
1531                 g_slist_free (child_info->msginfo_list);
1532                 child_info->msginfo_list = NULL;
1533         }
1534
1535         if (!child_info->pid)
1536                 child_info->children->nb--;
1537
1538         wait_for_children(child_info->children);
1539 }
1540         
1541 static void catch_input(gpointer data, gint source, GIOCondition cond)
1542 {
1543         Children *children = (Children *)data;
1544         ChildInfo *child_info = (ChildInfo *)children->list->data;
1545         gchar *input, *ret_str;
1546         gint c, count, len, r;
1547         gssize by_read = 0, by_written = 0;
1548
1549         debug_print("Sending input to grand child.\n");
1550         if (!(cond & (G_IO_OUT | G_IO_ERR)))
1551                 return;
1552
1553         gtk_widget_set_sensitive(children->input_hbox, FALSE);
1554         gtk_widget_grab_focus(children->abort_btn);
1555
1556         g_source_remove(child_info->tag_in);
1557         child_info->tag_in = -1;
1558
1559         input = gtk_editable_get_chars(GTK_EDITABLE(children->input_entry),
1560                                        0, -1);
1561         ret_str = g_locale_from_utf8(input, strlen(input), &by_read,
1562                                      &by_written, NULL);
1563         if (ret_str && by_written) {
1564                 g_free(input);
1565                 input = ret_str;
1566         }
1567
1568         len = strlen(input);
1569         count = 0;
1570
1571         do {
1572                 c = write(child_info->chld_in, input + count, len - count);
1573                 if (c >= 0)
1574                         count += c;
1575         } while (c >= 0 && count < len);
1576
1577         if (c >= 0)
1578                 r = write(child_info->chld_in, "\n", 2);
1579
1580         g_free(input);
1581
1582         r = close(child_info->chld_in);
1583         if (r != 0)
1584                 debug_print("%s(%d)", strerror(errno), errno);
1585         child_info->chld_in = -1;
1586         debug_print("Input to grand child sent.\n");
1587 }
1588
1589 static void catch_output(gpointer data, gint source, GIOCondition cond)
1590 {
1591         ChildInfo *child_info = (ChildInfo *)data;
1592         gint c;
1593         gchar buf[BUFFSIZE];
1594
1595         debug_print("Catching grand child's output.\n");
1596         if (child_info->children->action_type &
1597             (ACTION_PIPE_OUT | ACTION_INSERT)
1598             && source == child_info->chld_out) {
1599                 GtkTextView *text =
1600                         GTK_TEXT_VIEW(child_info->children->msg_text);
1601                 GtkTextBuffer *textbuf = gtk_text_view_get_buffer(text);
1602                 GtkTextIter iter;
1603                 GtkTextMark *mark;
1604                 gint ins_pos;
1605
1606                 mark = gtk_text_buffer_get_insert(textbuf);
1607                 gtk_text_buffer_get_iter_at_mark(textbuf, &iter, mark);
1608                 ins_pos = gtk_text_iter_get_offset(&iter);
1609
1610                 while (TRUE) {
1611                         gsize bytes_read = 0, bytes_written = 0;
1612                         gchar *ret_str;
1613
1614                         c = read(source, buf, sizeof(buf) - 1);
1615                         if (c == 0)
1616                                 break;
1617
1618                         ret_str = g_locale_to_utf8
1619                                 (buf, c, &bytes_read, &bytes_written, NULL);
1620                         if (ret_str && bytes_written > 0) {
1621                                 gtk_text_buffer_insert
1622                                         (textbuf, &iter, ret_str,
1623                                          -1);
1624                                 g_free(ret_str);
1625                         } else
1626                                 gtk_text_buffer_insert(textbuf, &iter, buf, c);
1627                 }
1628
1629                 if (child_info->children->is_selection) {
1630                         GtkTextIter ins;
1631
1632                         gtk_text_buffer_get_iter_at_offset
1633                                 (textbuf, &ins, ins_pos);
1634                         gtk_text_buffer_select_range(textbuf, &ins, &iter);
1635                 }
1636         } else {
1637                 c = read(source, buf, sizeof(buf) - 1);
1638                 if (c > 0) {
1639                         gsize bytes_read = 0, bytes_written = 0;
1640                         gchar *ret_str;
1641
1642                         ret_str = g_locale_to_utf8
1643                                 (buf, c, &bytes_read, &bytes_written, NULL);
1644                         if (ret_str && bytes_written > 0) {
1645                                 g_string_append_len
1646                                         (child_info->output, ret_str,
1647                                          bytes_written);
1648                                 g_free(ret_str);
1649                         } else
1650                                 g_string_append_len(child_info->output, buf, c);
1651
1652                         child_info->new_out = TRUE;
1653                 }
1654         }
1655         if (c == 0) {
1656                 if (source == child_info->chld_out) {
1657                         g_source_remove(child_info->tag_out);
1658                         child_info->tag_out = -1;
1659                         (void)close(child_info->chld_out);
1660                         child_info->chld_out = -1;
1661                 } else {
1662                         g_source_remove(child_info->tag_err);
1663                         child_info->tag_err = -1;
1664                         (void)close(child_info->chld_err);
1665                         child_info->chld_err = -1;
1666                 }
1667         }
1668         
1669         wait_for_children(child_info->children);
1670 }
1671
1672 static gchar *get_user_string(const gchar *action, ActionType type)
1673 {
1674         gchar *message;
1675         gchar *user_str = NULL;
1676
1677         switch (type) {
1678         case ACTION_USER_HIDDEN_STR:
1679                 message = g_strdup_printf
1680                         (_("Enter the argument for the following action:\n"
1681                            "('%%h' will be replaced with the argument)\n"
1682                            "  %s"),
1683                          action);
1684                 user_str = input_dialog_with_invisible
1685                         (_("Action's hidden user argument"), message, NULL);
1686                 break;
1687         case ACTION_USER_STR:
1688                 message = g_strdup_printf
1689                         (_("Enter the argument for the following action:\n"
1690                            "('%%u' will be replaced with the argument)\n"
1691                            "  %s"),
1692                          action);
1693                 user_str = input_dialog
1694                         (_("Action's user argument"), message, NULL);
1695                 break;
1696         default:
1697                 g_warning("Unsupported action type %d", type);
1698         }
1699
1700         return user_str;
1701 }