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