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