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