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