2007-06-15 [colin] 2.9.2cvs61
[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 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: %s"), strerror(-ret));
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         if (action_list == NULL) {
611                 gchar *tmp = g_strdup(action_string);
612
613                 g_strstrip(tmp);
614                 if (*tmp == '\0')
615                         alertpanel_error(_("There is no filtering action set"));
616                 else
617                         alertpanel_error(_("Invalid filtering action(s):\n%s"), tmp);
618                 g_free(action_string);
619                 g_free(tmp);
620                 return FALSE;
621         }
622         g_free(action_string);
623         
624         /* apply actions on each message info */
625         for (p = msglist; p && p->data; p = g_slist_next(p)) {
626                 filteringaction_apply_action_list(action_list, (MsgInfo *) p->data);
627         }
628
629         if (summaryview) {
630                 summary_lock(summaryview);                              
631                 main_window_cursor_wait(mainwin);               
632                 summary_freeze(summaryview);    
633                 folder_item_update_freeze();                            
634         }
635
636         filtering_move_and_copy_msgs(msglist);
637
638         if (summaryview) {
639                 folder_item_update_thaw();                              
640                 summary_thaw(summaryview);              
641                 main_window_cursor_normal(mainwin);     
642                 summary_unlock(summaryview);                            
643                 summary_show(summaryview, summaryview->folder_item);
644         }
645         for (p = action_list; p; p = g_slist_next(p))
646                 if (p->data) filteringaction_free(p->data);     
647         g_slist_free(action_list);              
648         return TRUE;    
649 }
650
651 static gboolean execute_actions(gchar *action, GSList *msg_list,
652                                 GtkWidget *text,
653                                 gint body_pos, MimeInfo *partinfo,
654                                 void (*callback)(void *data), void *data)
655 {
656         GSList *children_list = NULL;
657         gint is_ok  = TRUE;
658         gint msg_list_len;
659         Children *children;
660         ChildInfo *child_info;
661         ActionType action_type;
662         MsgInfo *msginfo;
663         gchar *cmd;
664         gchar *sel_str = NULL;
665         gchar *msg_str = NULL;
666         gchar *user_str = NULL;
667         gchar *user_hidden_str = NULL;
668         GtkTextIter start_iter, end_iter;
669         gboolean is_selection = FALSE;
670
671         g_return_val_if_fail(action && *action, FALSE);
672
673         action_type = action_get_type(action);
674
675         if (action_type == ACTION_ERROR)
676                 return FALSE;         /* ERR: syntax error */
677
678         if (action_type & (ACTION_SINGLE | ACTION_MULTIPLE) && !msg_list)
679                 return FALSE;         /* ERR: file command without selection */
680
681         msg_list_len = g_slist_length(msg_list);
682
683         if (action_type & (ACTION_PIPE_OUT | ACTION_PIPE_IN | ACTION_INSERT)) {
684                 if (msg_list_len > 1)
685                         return FALSE; /* ERR: pipe + multiple selection */
686                 if (!text)
687                         return FALSE; /* ERR: pipe and no displayed text */
688         }
689
690         if (action_type & ACTION_SELECTION_STR) {
691                 if (!text)
692                         return FALSE; /* ERR: selection string but no text */
693         }
694
695         if (text) {
696                 GtkTextBuffer *textbuf;
697
698                 textbuf = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
699                 is_selection = gtk_text_buffer_get_selection_bounds
700                         (textbuf, &start_iter, &end_iter);
701                 if (!is_selection) {
702                         gtk_text_buffer_get_iter_at_offset
703                                 (textbuf, &start_iter, body_pos);
704                         gtk_text_buffer_get_end_iter(textbuf, &end_iter);
705                 }
706                 msg_str = gtk_text_buffer_get_text
707                         (textbuf, &start_iter, &end_iter, FALSE);
708                 if (is_selection)
709                         sel_str = g_strdup(msg_str);
710         }
711
712         if (action_type & ACTION_USER_STR) {
713                 if (!(user_str = get_user_string(action, ACTION_USER_STR))) {
714                         g_free(msg_str);
715                         g_free(sel_str);
716                         return FALSE;
717                 }
718         }
719
720         if (action_type & ACTION_USER_HIDDEN_STR) {
721                 if (!(user_hidden_str =
722                         get_user_string(action, ACTION_USER_HIDDEN_STR))) {
723                         g_free(msg_str);
724                         g_free(sel_str);
725                         g_free(user_str);
726                         return FALSE;
727                 }
728         }
729
730         if (text && (action_type & ACTION_PIPE_OUT)) {
731                 GtkTextBuffer *textbuf;
732                 textbuf = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
733                 gtk_text_buffer_delete(textbuf, &start_iter, &end_iter);
734         }
735
736         children = g_new0(Children, 1);
737
738         children->action      = g_strdup(action);
739         children->action_type = action_type;
740         children->msg_text    = text;
741         children->is_selection = is_selection;
742
743         if ((action_type & (ACTION_USER_IN | ACTION_USER_HIDDEN_IN)) &&
744             ((action_type & ACTION_SINGLE) == 0 || msg_list_len == 1))
745                 children->open_in = 1;
746
747         if (action_type & ACTION_SINGLE) {
748                 GSList *cur;
749
750                 for (cur = msg_list; cur && is_ok == TRUE; cur = cur->next) {
751                         msginfo = (MsgInfo *)cur->data;
752                         if (!msginfo) {
753                                 is_ok  = FALSE; /* ERR: msginfo missing */
754                                 break;
755                         }
756                         cmd = parse_action_cmd(action, msginfo, msg_list,
757                                                partinfo, user_str,
758                                                user_hidden_str, sel_str);
759                         if (!cmd) {
760                                 debug_print("Action command error\n");
761                                 is_ok  = FALSE; /* ERR: incorrect command */
762                                 break;
763                         }
764                         if ((child_info = fork_child(cmd, msg_str, children))) {
765                                 /* Pass msginfo to catch_status () */
766                                 if (!(action_type & (ACTION_PIPE_OUT | ACTION_INSERT)))
767                                         child_info->msginfo_list = 
768                                                 g_slist_append (NULL, msginfo);
769                                 children_list = g_slist_append(children_list,
770                                                                child_info);
771                         }
772                         g_free(cmd);
773                 }
774         } else {
775                 cmd = parse_action_cmd(action, NULL, msg_list, partinfo,
776                                        user_str, user_hidden_str, sel_str);
777                 if (cmd) {
778                         if ((child_info = fork_child(cmd, msg_str, children))) {
779                                 if (!(action_type & (ACTION_PIPE_OUT | ACTION_INSERT)))
780                                         child_info->msginfo_list = 
781                                                 g_slist_copy (msg_list);
782                                 children_list = g_slist_append(children_list,
783                                                                 child_info);
784                         }
785                         g_free(cmd);
786                 } else
787                         is_ok  = FALSE;         /* ERR: incorrect command */
788         }
789
790         g_free(msg_str);
791         g_free(sel_str);
792         g_free(user_str);
793         g_free(user_hidden_str);
794
795         if (!children_list) {
796                  /* If not waiting for children, return */
797                 free_children(children);
798         } else {
799                 GSList *cur;
800
801                 children->list        = children_list;
802                 children->nb          = g_slist_length(children_list);
803                 children->initial_nb  = children->nb;
804
805                 for (cur = children_list; cur; cur = cur->next) {
806                         child_info = (ChildInfo *) cur->data;
807                         child_info->callback = callback;
808                         child_info->data = data;
809                         child_info->tag_status = 
810                                 gdk_input_add(child_info->chld_status,
811                                               GDK_INPUT_READ,
812                                               catch_status, child_info);
813                 }
814
815                 create_io_dialog(children);
816         }
817         return is_ok;
818 }
819
820 static ChildInfo *fork_child(gchar *cmd, const gchar *msg_str,
821                              Children *children)
822 {
823 #ifdef G_OS_UNIX
824         gint chld_in[2], chld_out[2], chld_err[2], chld_status[2];
825         gchar *cmdline[4], *ret_str;
826         pid_t pid, gch_pid;
827         ChildInfo *child_info;
828         gint sync;
829         gssize by_written = 0, by_read = 0;
830
831         sync = !(children->action_type & ACTION_ASYNC);
832
833         chld_in[0] = chld_in[1] = chld_out[0] = chld_out[1] = chld_err[0]
834                 = chld_err[1] = chld_status[0] = chld_status[1] = -1;
835
836         if (sync) {
837                 if (pipe(chld_status) || pipe(chld_in) || pipe(chld_out) ||
838                     pipe(chld_err)) {
839                         alertpanel_error(_("Command could not be started. "
840                                            "Pipe creation failed.\n%s"),
841                                         g_strerror(errno));
842                         /* Closing fd = -1 fails silently */
843                         close(chld_in[0]);
844                         close(chld_in[1]);
845                         close(chld_out[0]);
846                         close(chld_out[1]);
847                         close(chld_err[0]);
848                         close(chld_err[1]);
849                         close(chld_status[0]);
850                         close(chld_status[1]);
851                         return NULL; /* Pipe error */
852                 }
853         }
854
855         debug_print("Forking child and grandchild.\n");
856         debug_print("Executing: /bin/sh -c %s\n", cmd);
857
858         pid = fork();
859         if (pid == 0) { /* Child */
860                 if (setpgid(0, 0))
861                         perror("setpgid");
862
863 #ifdef GDK_WINDOWING_X11
864                 close(ConnectionNumber(gdk_display));
865 #endif /* GDK_WINDOWING_X11 */
866
867                 gch_pid = fork();
868
869                 if (gch_pid == 0) {
870                         if (setpgid(0, getppid()))
871                                 perror("setpgid");
872
873                         if (sync) {
874                                 if (children->action_type &
875                                     (ACTION_PIPE_IN |
876                                      ACTION_USER_IN |
877                                      ACTION_USER_HIDDEN_IN)) {
878                                         close(fileno(stdin));
879                                         dup  (chld_in[0]);
880                                 }
881                                 close(chld_in[0]);
882                                 close(chld_in[1]);
883
884                                 close(fileno(stdout));
885                                 dup  (chld_out[1]);
886                                 close(chld_out[0]);
887                                 close(chld_out[1]);
888
889                                 close(fileno(stderr));
890                                 dup  (chld_err[1]);
891                                 close(chld_err[0]);
892                                 close(chld_err[1]);
893                         }
894
895                         cmdline[0] = "sh";
896                         cmdline[1] = "-c";
897                         ret_str = g_locale_from_utf8(cmd, strlen(cmd),
898                                                      &by_read, &by_written,
899                                                      NULL);
900                         if (ret_str && by_written)
901                                 cmdline[2] = ret_str;
902                         else
903                                 cmdline[2] = cmd;
904                         cmdline[3] = NULL;
905                         execvp("/bin/sh", cmdline);
906
907                         perror("execvp");
908                         g_free(ret_str);
909                         _exit(1);
910                 } else if (gch_pid < (pid_t) 0) { /* Fork error */
911                         if (sync)
912                                 write(chld_status[1], "1\n", 2);
913                         perror("fork");
914                         _exit(1);
915                 } else { /* Child */
916                         if (sync) {
917                                 close(chld_in[0]);
918                                 close(chld_in[1]);
919                                 close(chld_out[0]);
920                                 close(chld_out[1]);
921                                 close(chld_err[0]);
922                                 close(chld_err[1]);
923                                 close(chld_status[0]);
924
925                                 debug_print("Child: waiting for grandchild\n");
926                                 waitpid(gch_pid, NULL, 0);
927                                 debug_print("Child: grandchild ended\n");
928                                 write(chld_status[1], "0\n", 2);
929                                 close(chld_status[1]);
930                         }
931                         _exit(0);
932                 }
933         } else if (pid < 0) { /* Fork error */
934                 alertpanel_error(_("Could not fork to execute the following "
935                                    "command:\n%s\n%s"),
936                                  cmd, g_strerror(errno));
937                 return NULL; 
938         }
939
940         /* Parent */
941
942         if (!sync) {
943                 waitpid(pid, NULL, 0);
944                 return NULL;
945         }
946
947         close(chld_in[0]);
948         if (!(children->action_type &
949               (ACTION_PIPE_IN | ACTION_USER_IN | ACTION_USER_HIDDEN_IN)))
950                 close(chld_in[1]);
951         close(chld_out[1]);
952         close(chld_err[1]);
953         close(chld_status[1]);
954
955         child_info = g_new0(ChildInfo, 1);
956
957         child_info->children    = children;
958
959         child_info->pid         = pid;
960         child_info->cmd         = g_strdup(cmd);
961         child_info->new_out     = FALSE;
962         child_info->output      = g_string_new(NULL);
963         child_info->chld_in     =
964                 (children->action_type &
965                  (ACTION_PIPE_IN | ACTION_USER_IN | ACTION_USER_HIDDEN_IN))
966                         ? chld_in [1] : -1;
967         child_info->chld_out    = chld_out[0];
968         child_info->chld_err    = chld_err[0];
969         child_info->chld_status = chld_status[0];
970         child_info->tag_in      = -1;
971         child_info->tag_out     = gdk_input_add(chld_out[0], GDK_INPUT_READ,
972                                                 catch_output, child_info);
973         child_info->tag_err     = gdk_input_add(chld_err[0], GDK_INPUT_READ,
974                                                 catch_output, child_info);
975
976         if (!(children->action_type &
977               (ACTION_PIPE_IN | ACTION_PIPE_OUT | ACTION_INSERT)))
978                 return child_info;
979
980         if ((children->action_type & ACTION_PIPE_IN) && msg_str) {
981                 ret_str = g_locale_from_utf8(msg_str, strlen(msg_str),
982                                              &by_read, &by_written, NULL);
983                 if (ret_str && by_written) {
984                         write(chld_in[1], ret_str, strlen(ret_str));
985                         g_free(ret_str);
986                 } else
987                         write(chld_in[1], msg_str, strlen(msg_str));
988                 if (!(children->action_type &
989                       (ACTION_USER_IN | ACTION_USER_HIDDEN_IN)))
990                         close(chld_in[1]);
991                 child_info->chld_in = -1; /* No more input */
992         }
993
994         return child_info;
995 #else
996         return NULL;
997 #endif /* G_OS_UNIX */
998 }
999
1000 static void kill_children_cb(GtkWidget *widget, gpointer data)
1001 {
1002 #ifdef G_OS_UNIX
1003         GSList *cur;
1004         Children *children = (Children *) data;
1005         ChildInfo *child_info;
1006
1007         for (cur = children->list; cur; cur = cur->next) {
1008                 child_info = (ChildInfo *)(cur->data);
1009                 debug_print("Killing child group id %d\n", child_info->pid);
1010                 if (child_info->pid && kill(-child_info->pid, SIGTERM) < 0)
1011                         perror("kill");
1012         }
1013 #endif /* G_OS_UNIX */
1014 }
1015
1016 static gint wait_for_children(Children *children)
1017 {
1018         gboolean new_output;
1019         ChildInfo *child_info;
1020         GSList *cur;
1021         gint nb = children->nb;
1022
1023         children->nb = 0;
1024
1025         cur = children->list;
1026         new_output = FALSE;
1027         while (cur) {
1028                 child_info = (ChildInfo *)cur->data;
1029                 if (child_info->pid)
1030                         children->nb++;
1031                 new_output |= child_info->new_out;
1032                 cur = cur->next;
1033         }
1034
1035         children->output |= new_output;
1036
1037         if (new_output || (children->dialog && (nb != children->nb)))
1038                 update_io_dialog(children);
1039
1040         if (children->nb)
1041                 return FALSE;
1042
1043         if (!children->dialog) {
1044                 free_children(children);
1045         } else if (!children->output) {
1046                 gtk_widget_destroy(children->dialog);
1047         }
1048
1049         return FALSE;
1050 }
1051
1052 static void send_input(GtkWidget *w, gpointer data)
1053 {
1054         Children *children = (Children *) data;
1055         ChildInfo *child_info = (ChildInfo *) children->list->data;
1056
1057         child_info->tag_in = gdk_input_add(child_info->chld_in,
1058                                            GDK_INPUT_WRITE,
1059                                            catch_input, children);
1060 }
1061
1062 static gint delete_io_dialog_cb(GtkWidget *w, GdkEvent *e, gpointer data)
1063 {
1064         hide_io_dialog_cb(w, data);
1065         return TRUE;
1066 }
1067
1068 static void hide_io_dialog_cb(GtkWidget *w, gpointer data)
1069 {
1070
1071         Children *children = (Children *)data;
1072
1073         if (!children->nb) {
1074                 g_signal_handlers_disconnect_matched
1075                         (G_OBJECT(children->dialog), G_SIGNAL_MATCH_DATA,
1076                          0, 0, NULL, NULL, children);
1077                 gtk_widget_destroy(children->dialog);
1078                 free_children(children);
1079         }
1080 }
1081
1082 static gint io_dialog_key_pressed_cb(GtkWidget *widget, GdkEventKey *event,
1083                                      gpointer data)
1084 {
1085         if (event && (event->keyval == GDK_Escape ||
1086                       event->keyval == GDK_Return ||
1087                           event->keyval == GDK_KP_Enter))
1088                 hide_io_dialog_cb(widget, data);
1089         return TRUE;
1090 }
1091
1092 static void childinfo_close_pipes(ChildInfo *child_info)
1093 {
1094         /* stdout and stderr pipes are guaranteed to be removed by
1095          * their handler, but in case where we receive child exit notification
1096          * before grand-child's pipes closing signals, we check them and close
1097          * them if necessary
1098          */
1099         if (child_info->tag_in > 0)
1100                 gdk_input_remove(child_info->tag_in);
1101         if (child_info->tag_out > 0)
1102                 gdk_input_remove(child_info->tag_out);
1103         if (child_info->tag_err > 0)
1104                 gdk_input_remove(child_info->tag_err);
1105
1106         if (child_info->chld_in >= 0)
1107                 close(child_info->chld_in);
1108         if (child_info->chld_out >= 0)
1109                 close(child_info->chld_out);
1110         if (child_info->chld_err >= 0)
1111                 close(child_info->chld_err);
1112
1113         close(child_info->chld_status);
1114 }
1115
1116 static void free_children(Children *children)
1117 {
1118         ChildInfo *child_info;
1119         void (*callback)(void *data) = NULL;
1120         void *data = NULL;
1121
1122         debug_print("Freeing children data %p\n", children);
1123
1124         g_free(children->action);
1125         while (children->list != NULL) {
1126                 child_info = (ChildInfo *)children->list->data;
1127                 g_free(child_info->cmd);
1128                 g_string_free(child_info->output, TRUE);
1129                 children->list = g_slist_remove(children->list, child_info);
1130                 callback = child_info->callback;
1131                 data = child_info->data;
1132                 g_free(child_info);
1133         }
1134
1135         if (callback)
1136                 callback(data);
1137         
1138         g_free(children);
1139 }
1140
1141 static void update_io_dialog(Children *children)
1142 {
1143         GSList *cur;
1144
1145         debug_print("Updating actions input/output dialog.\n");
1146
1147         if (children->progress_bar) {
1148                 gchar *text;
1149                 
1150                 gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(children->progress_bar),
1151                                                   (children->initial_nb == 0) ? 0 :
1152                                               (gdouble) (children->initial_nb - children->nb) /
1153                                               (gdouble) children->initial_nb);
1154                 text = g_strdup_printf("%s %d/%d", _("Completed"), 
1155                                        children->initial_nb - children->nb,
1156                                        children->initial_nb);
1157                 gtk_progress_bar_set_text(GTK_PROGRESS_BAR(children->progress_bar), text);
1158                 g_free(text);
1159         }                                             
1160
1161         if (!children->nb) {
1162                 gtk_widget_set_sensitive(children->abort_btn, FALSE);
1163                 gtk_widget_set_sensitive(children->close_btn, TRUE);
1164                 if (children->input_hbox)
1165                         gtk_widget_set_sensitive(children->input_hbox, FALSE);
1166                 gtk_widget_grab_focus(children->close_btn);
1167                 g_signal_connect(G_OBJECT(children->dialog),
1168                                  "key_press_event",
1169                                  G_CALLBACK(io_dialog_key_pressed_cb),
1170                                  children);
1171         }
1172
1173         if (children->output) {
1174                 GtkWidget *text = children->text;
1175                 GtkTextBuffer *textbuf;
1176                 GtkTextIter iter, start_iter, end_iter;
1177                 gchar *caption;
1178                 ChildInfo *child_info;
1179
1180                 gtk_widget_show(children->scrolledwin);
1181                 textbuf = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
1182                 gtk_text_buffer_get_bounds(textbuf, &start_iter, &end_iter);
1183                 gtk_text_buffer_delete(textbuf, &start_iter, &end_iter);
1184                 gtk_text_buffer_get_start_iter(textbuf, &iter);
1185
1186                 for (cur = children->list; cur; cur = cur->next) {
1187                         child_info = (ChildInfo *)cur->data;
1188                         if (child_info->pid)
1189                                 caption = g_strdup_printf
1190                                         (_("--- Running: %s\n"),
1191                                          child_info->cmd);
1192                         else
1193                                 caption = g_strdup_printf
1194                                         (_("--- Ended: %s\n"),
1195                                          child_info->cmd);
1196
1197                         gtk_text_buffer_insert(textbuf, &iter, caption, -1);
1198                         gtk_text_buffer_insert(textbuf, &iter,
1199                                                child_info->output->str, -1);
1200                         g_free(caption);
1201                         child_info->new_out = FALSE;
1202                 }
1203         }
1204 }
1205
1206 static void create_io_dialog(Children *children)
1207 {
1208         GtkWidget *dialog;
1209         GtkWidget *vbox;
1210         GtkWidget *entry = NULL;
1211         GtkWidget *input_hbox = NULL;
1212         GtkWidget *send_button;
1213         GtkWidget *label;
1214         GtkWidget *text;
1215         GtkWidget *scrolledwin;
1216         GtkWidget *hbox;
1217         GtkWidget *progress_bar = NULL;
1218         GtkWidget *abort_button;
1219         GtkWidget *close_button;
1220
1221         debug_print("Creating action IO dialog\n");
1222
1223         dialog = gtk_dialog_new();
1224         gtk_container_set_border_width
1225                 (GTK_CONTAINER(GTK_DIALOG(dialog)->action_area), 5);
1226         gtk_window_set_position(GTK_WINDOW(dialog), GTK_WIN_POS_CENTER);
1227         gtk_window_set_title(GTK_WINDOW(dialog), _("Action's input/output"));
1228         gtk_window_set_modal(GTK_WINDOW(dialog), TRUE);
1229         manage_window_set_transient(GTK_WINDOW(dialog));
1230         g_signal_connect(G_OBJECT(dialog), "delete_event",
1231                          G_CALLBACK(delete_io_dialog_cb), children);
1232         g_signal_connect(G_OBJECT(dialog), "destroy",
1233                          G_CALLBACK(hide_io_dialog_cb),
1234                          children);
1235
1236         vbox = gtk_vbox_new(FALSE, 8);
1237         gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog)->vbox), vbox);
1238         gtk_container_set_border_width(GTK_CONTAINER(vbox), 8);
1239         gtk_widget_show(vbox);
1240
1241         label = gtk_label_new(children->action);
1242         gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 0);
1243         gtk_widget_show(label);
1244
1245         scrolledwin = gtk_scrolled_window_new(NULL, NULL);
1246         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledwin),
1247                                        GTK_POLICY_AUTOMATIC,
1248                                        GTK_POLICY_AUTOMATIC);
1249         gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scrolledwin),
1250                                             GTK_SHADOW_IN);
1251         gtk_box_pack_start(GTK_BOX(vbox), scrolledwin, TRUE, TRUE, 0);
1252         gtk_widget_set_size_request(scrolledwin, 560, 200);
1253         gtk_widget_hide(scrolledwin);
1254
1255         text = gtk_text_view_new();
1256
1257         if (prefs_common.textfont) {
1258                 PangoFontDescription *font_desc;
1259                 font_desc = pango_font_description_from_string
1260                         (prefs_common.textfont);
1261                 if (font_desc) {
1262                         gtk_widget_modify_font(text, font_desc);
1263                         pango_font_description_free(font_desc);
1264                 }
1265         }
1266
1267         gtk_text_view_set_editable(GTK_TEXT_VIEW(text), FALSE);
1268         gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(text), GTK_WRAP_WORD);
1269         gtk_text_view_set_left_margin(GTK_TEXT_VIEW(text), 6);
1270         gtk_text_view_set_right_margin(GTK_TEXT_VIEW(text), 6);
1271         gtk_container_add(GTK_CONTAINER(scrolledwin), text);
1272         gtk_widget_show(text);
1273
1274         if (children->open_in) {
1275                 input_hbox = gtk_hbox_new(FALSE, 8);
1276                 gtk_widget_show(input_hbox);
1277
1278                 entry = gtk_entry_new();
1279                 gtk_widget_set_size_request(entry, 320, -1);
1280                 g_signal_connect(G_OBJECT(entry), "activate",
1281                                  G_CALLBACK(send_input), children);
1282                 gtk_box_pack_start(GTK_BOX(input_hbox), entry, TRUE, TRUE, 0);
1283                 if (children->action_type & ACTION_USER_HIDDEN_IN)
1284                         gtk_entry_set_visibility(GTK_ENTRY(entry), FALSE);
1285                 gtk_widget_show(entry);
1286
1287                 send_button = gtk_button_new_from_stock(GTK_STOCK_EXECUTE);
1288                 g_signal_connect(G_OBJECT(send_button), "clicked",
1289                                  G_CALLBACK(send_input), children);
1290                 gtk_box_pack_start(GTK_BOX(input_hbox), send_button, FALSE,
1291                                    FALSE, 0);
1292                 gtk_widget_show(send_button);
1293
1294                 gtk_box_pack_start(GTK_BOX(vbox), input_hbox, FALSE, FALSE, 0);
1295                 gtk_widget_grab_focus(entry);
1296         }
1297
1298         if (children->initial_nb > 1) {
1299                 gchar * text;
1300                 
1301                 progress_bar = gtk_progress_bar_new();
1302                 gtk_progress_bar_set_orientation(GTK_PROGRESS_BAR(progress_bar),
1303                                 GTK_PROGRESS_LEFT_TO_RIGHT);
1304                 text = g_strdup_printf("%s 0/%d\n", _("Completed"), 
1305                                        children->initial_nb);
1306                 gtk_progress_bar_set_text(GTK_PROGRESS_BAR(progress_bar),
1307                                           text);
1308                 g_free(text);
1309                 gtk_box_pack_start(GTK_BOX(vbox), progress_bar, FALSE, FALSE, 0);
1310                 gtk_widget_show(progress_bar);
1311         }
1312
1313         gtkut_stock_button_set_create(&hbox, &abort_button, GTK_STOCK_STOP,
1314                                       &close_button, GTK_STOCK_CLOSE, NULL, NULL);
1315         g_signal_connect(G_OBJECT(abort_button), "clicked",
1316                          G_CALLBACK(kill_children_cb), children);
1317         g_signal_connect(G_OBJECT(close_button), "clicked",
1318                          G_CALLBACK(hide_io_dialog_cb), children);
1319         gtk_widget_show(hbox);
1320
1321         if (children->nb)
1322                 gtk_widget_set_sensitive(close_button, FALSE);
1323
1324         gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog)->action_area), hbox);
1325
1326         children->dialog       = dialog;
1327         children->scrolledwin  = scrolledwin;
1328         children->text         = text;
1329         children->input_hbox   = children->open_in ? input_hbox : NULL;
1330         children->input_entry  = children->open_in ? entry : NULL;
1331         children->progress_bar = progress_bar;
1332         children->abort_btn    = abort_button;
1333         children->close_btn    = close_button;
1334
1335         gtk_widget_show(dialog);
1336 }
1337
1338 static void catch_status(gpointer data, gint source, GdkInputCondition cond)
1339 {
1340         ChildInfo *child_info = (ChildInfo *)data;
1341         gchar buf;
1342         gint c;
1343
1344         gdk_input_remove(child_info->tag_status);
1345
1346         c = read(source, &buf, 1);
1347         debug_print("Child returned %c\n", buf);
1348
1349 #ifdef G_OS_UNIX
1350         waitpid(-child_info->pid, NULL, 0);
1351 #endif
1352         childinfo_close_pipes(child_info);
1353         child_info->pid = 0;
1354
1355         if (child_info->children->action_type & (ACTION_SINGLE | ACTION_MULTIPLE)
1356             && child_info->msginfo_list) {
1357                 /* Actions on message *files* might change size and
1358                 * time stamp, and thus invalidate the cache */
1359                 SummaryView *summaryview  = NULL;
1360                 GSList      *cur;
1361                 MsgInfo     *msginfo, *nmi;     /* newmsginfo */
1362                 char        *file;
1363                 gboolean     modified_something = FALSE;
1364                 FolderItem  *last_item = NULL;
1365                 if (mainwindow_get_mainwindow ())
1366                         summaryview = mainwindow_get_mainwindow ()->summaryview;
1367                 for (cur = child_info->msginfo_list; cur; cur = cur->next) {
1368                         msginfo = (MsgInfo *)cur->data;
1369                         if (!(msginfo && /* Stuff used valid? */
1370                             msginfo->folder && msginfo->folder->cache)) 
1371                                 continue;
1372                         file = procmsg_get_message_file_path (msginfo);
1373                         if (!file) 
1374                                 continue;
1375                         nmi = procheader_parse_file (file, msginfo->flags, TRUE, FALSE);
1376                         if (!nmi) 
1377                                 continue; /* Deleted? */
1378                         if (msginfo->mtime != nmi->mtime || msginfo->size != nmi->size) {
1379                                 nmi->folder = msginfo->folder;
1380                                 nmi->msgnum = msginfo->msgnum;
1381                                 msgcache_update_msg (msginfo->folder->cache, nmi);
1382                                 modified_something = TRUE;
1383                                 last_item = nmi->folder;
1384                         }
1385                         procmsg_msginfo_free (nmi);
1386                         if (summaryview && summaryview->displayed &&
1387                             summaryview->folder_item == msginfo->folder &&
1388                             summary_get_msgnum(summaryview, summaryview->displayed) == msginfo->msgnum)
1389                                 summary_redisplay_msg(summaryview);
1390                                         
1391                 }
1392                 if (modified_something && last_item && 
1393                     summaryview && summaryview->folder_item == last_item) {
1394                         summary_show (summaryview, summaryview->folder_item);
1395                 }
1396                 g_slist_free (child_info->msginfo_list);
1397                 child_info->msginfo_list = NULL;
1398         }
1399
1400         wait_for_children(child_info->children);
1401 }
1402         
1403 static void catch_input(gpointer data, gint source, GdkInputCondition cond)
1404 {
1405         Children *children = (Children *)data;
1406         ChildInfo *child_info = (ChildInfo *)children->list->data;
1407         gchar *input, *ret_str;
1408         gint c, count, len;
1409         gssize by_read = 0, by_written = 0;
1410
1411         debug_print("Sending input to grand child.\n");
1412         if (!(cond && GDK_INPUT_WRITE))
1413                 return;
1414
1415         gtk_widget_set_sensitive(children->input_hbox, FALSE);
1416         gtk_widget_grab_focus(children->abort_btn);
1417
1418         gdk_input_remove(child_info->tag_in);
1419         child_info->tag_in = -1;
1420
1421         input = gtk_editable_get_chars(GTK_EDITABLE(children->input_entry),
1422                                        0, -1);
1423         ret_str = g_locale_from_utf8(input, strlen(input), &by_read,
1424                                      &by_written, NULL);
1425         if (ret_str && by_written) {
1426                 g_free(input);
1427                 input = ret_str;
1428         }
1429
1430         len = strlen(input);
1431         count = 0;
1432
1433         do {
1434                 c = write(child_info->chld_in, input + count, len - count);
1435                 if (c >= 0)
1436                         count += c;
1437         } while (c >= 0 && count < len);
1438
1439         if (c >= 0)
1440                 write(child_info->chld_in, "\n", 2);
1441
1442         g_free(input);
1443
1444         close(child_info->chld_in);
1445         child_info->chld_in = -1;
1446         debug_print("Input to grand child sent.\n");
1447 }
1448
1449 static void catch_output(gpointer data, gint source, GdkInputCondition cond)
1450 {
1451         ChildInfo *child_info = (ChildInfo *)data;
1452         gint c;
1453         gchar buf[BUFFSIZE];
1454
1455         debug_print("Catching grand child's output.\n");
1456         if (child_info->children->action_type &
1457             (ACTION_PIPE_OUT | ACTION_INSERT)
1458             && source == child_info->chld_out) {
1459                 GtkTextView *text =
1460                         GTK_TEXT_VIEW(child_info->children->msg_text);
1461                 GtkTextBuffer *textbuf = gtk_text_view_get_buffer(text);
1462                 GtkTextIter iter;
1463                 GtkTextMark *mark;
1464                 gint ins_pos;
1465
1466                 mark = gtk_text_buffer_get_insert(textbuf);
1467                 gtk_text_buffer_get_iter_at_mark(textbuf, &iter, mark);
1468                 ins_pos = gtk_text_iter_get_offset(&iter);
1469
1470                 while (TRUE) {
1471                         gsize bytes_read = 0, bytes_written = 0;
1472                         gchar *ret_str;
1473
1474                         c = read(source, buf, sizeof(buf) - 1);
1475                         if (c == 0)
1476                                 break;
1477
1478                         ret_str = g_locale_to_utf8
1479                                 (buf, c, &bytes_read, &bytes_written, NULL);
1480                         if (ret_str && bytes_written > 0) {
1481                                 gtk_text_buffer_insert
1482                                         (textbuf, &iter, ret_str,
1483                                          -1);
1484                                 g_free(ret_str);
1485                         } else
1486                                 gtk_text_buffer_insert(textbuf, &iter, buf, c);
1487                 }
1488
1489                 if (child_info->children->is_selection) {
1490                         GtkTextIter ins;
1491
1492                         gtk_text_buffer_get_iter_at_offset
1493                                 (textbuf, &ins, ins_pos);
1494                         gtk_text_buffer_select_range(textbuf, &ins, &iter);
1495                 }
1496         } else {
1497                 c = read(source, buf, sizeof(buf) - 1);
1498                 if (c > 0) {
1499                         gsize bytes_read = 0, bytes_written = 0;
1500                         gchar *ret_str;
1501
1502                         ret_str = g_locale_to_utf8
1503                                 (buf, c, &bytes_read, &bytes_written, NULL);
1504                         if (ret_str && bytes_written > 0) {
1505                                 g_string_append_len
1506                                         (child_info->output, ret_str,
1507                                          bytes_written);
1508                                 g_free(ret_str);
1509                         } else
1510                                 g_string_append_len(child_info->output, buf, c);
1511
1512                         child_info->new_out = TRUE;
1513                 }
1514         }
1515         if (c == 0) {
1516                 if (source == child_info->chld_out) {
1517                         gdk_input_remove(child_info->tag_out);
1518                         child_info->tag_out = -1;
1519                         close(child_info->chld_out);
1520                         child_info->chld_out = -1;
1521                 } else {
1522                         gdk_input_remove(child_info->tag_err);
1523                         child_info->tag_err = -1;
1524                         close(child_info->chld_err);
1525                         child_info->chld_err = -1;
1526                 }
1527         }
1528         
1529         wait_for_children(child_info->children);
1530 }
1531
1532 static gchar *get_user_string(const gchar *action, ActionType type)
1533 {
1534         gchar *message;
1535         gchar *user_str = NULL;
1536
1537         switch (type) {
1538         case ACTION_USER_HIDDEN_STR:
1539                 message = g_strdup_printf
1540                         (_("Enter the argument for the following action:\n"
1541                            "('%%h' will be replaced with the argument)\n"
1542                            "  %s"),
1543                          action);
1544                 user_str = input_dialog_with_invisible
1545                         (_("Action's hidden user argument"), message, NULL);
1546                 break;
1547         case ACTION_USER_STR:
1548                 message = g_strdup_printf
1549                         (_("Enter the argument for the following action:\n"
1550                            "('%%u' will be replaced with the argument)\n"
1551                            "  %s"),
1552                          action);
1553                 user_str = input_dialog
1554                         (_("Action's user argument"), message, NULL);
1555                 break;
1556         default:
1557                 g_warning("Unsupported action type %d", type);
1558         }
1559
1560         return user_str;
1561 }