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