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