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