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