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