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