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