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