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