* src/filtering.[ch]
[claws.git] / src / action.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2003 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 <gtk/gtk.h>
28 #include <gdk/gdkkeysyms.h>
29 #include <gdk/gdkx.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <errno.h>
34 #include <sys/types.h>
35 #include <sys/wait.h>
36 #include <signal.h>
37 #include <unistd.h>
38
39 #include "intl.h"
40 #include "utils.h"
41 #include "gtkutils.h"
42 #include "manage_window.h"
43 #include "mainwindow.h"
44 #include "prefs_common.h"
45 #include "alertpanel.h"
46 #include "inputdialog.h"
47 #include "action.h"
48 #include "compose.h"
49 #include "procmsg.h"
50 #include "gtkstext.h"
51 #include "textview.h"
52
53 typedef struct _Children                Children;
54 typedef struct _ChildInfo               ChildInfo;
55 typedef struct _UserStringDialog        UserStringDialog;
56
57 struct _Children
58 {
59         GtkWidget       *dialog;
60         GtkWidget       *text;
61         GtkWidget       *input_entry;
62         GtkWidget       *input_hbox;
63         GtkWidget       *abort_btn;
64         GtkWidget       *close_btn;
65         GtkWidget       *scrolledwin;
66
67         gchar           *action;
68         ActionType       action_type;
69         GSList          *list;
70         gint             nb;
71         gint             open_in;
72         gboolean         output;
73
74         GtkWidget       *msg_text;
75         GdkFont         *msgfont;
76 };
77
78 struct _ChildInfo
79 {
80         Children        *children;
81         gchar           *cmd;
82         pid_t            pid;
83         gint             chld_in;
84         gint             chld_out;
85         gint             chld_err;
86         gint             chld_status;
87         gint             tag_in;
88         gint             tag_out;
89         gint             tag_err;
90         gint             tag_status;
91         gint             new_out;
92
93         GString         *output;
94 };
95
96 static void action_update_menu          (GtkItemFactory *ifactory,
97                                          gchar          *branch_path,
98                                          gpointer        callback,
99                                          gpointer        data);
100 static void compose_actions_execute_cb  (Compose        *compose,
101                                          guint           action_nb,
102                                          GtkWidget      *widget);
103 static void mainwin_actions_execute_cb  (MainWindow     *mainwin,
104                                          guint           action_nb,
105                                          GtkWidget      *widget);
106 static void msgview_actions_execute_cb  (MessageView    *msgview,
107                                          guint           action_nb,
108                                          GtkWidget      *widget);
109 static void message_actions_execute     (MessageView    *msgview,
110                                          guint           action_nb,
111                                          GSList         *msg_list);
112
113 static gboolean execute_actions         (gchar          *action, 
114                                          GSList         *msg_list, 
115                                          GtkWidget      *text,
116                                          GdkFont        *msgfont,
117                                          gint            body_pos,
118                                          MimeInfo       *partinfo);
119
120 static gchar *parse_action_cmd          (gchar          *action,
121                                          MsgInfo        *msginfo,
122                                          GSList         *msg_list,
123                                          MimeInfo       *partinfo,
124                                          const gchar    *user_str,
125                                          const gchar    *user_hidden_str,
126                                          const gchar    *sel_str);
127 static gboolean parse_append_filename   (GString        *cmd,
128                                          MsgInfo        *msginfo);
129
130 static gboolean parse_append_msgpart    (GString        *cmd,
131                                          MsgInfo        *msginfo,
132                                          MimeInfo       *partinfo);
133
134 static ChildInfo *fork_child            (gchar          *cmd,
135                                          const gchar    *msg_str,
136                                          Children       *children);
137
138 static gint wait_for_children           (Children       *children);
139
140 static void free_children               (Children       *children);
141
142 static void childinfo_close_pipes       (ChildInfo      *child_info);
143
144 static void create_io_dialog            (Children       *children);
145 static void update_io_dialog            (Children       *children);
146
147 static void hide_io_dialog_cb           (GtkWidget      *widget,
148                                          gpointer        data);
149 static gint io_dialog_key_pressed_cb    (GtkWidget      *widget,
150                                          GdkEventKey    *event,
151                                          gpointer        data);
152
153 static void catch_output                (gpointer                data,
154                                          gint                    source,
155                                          GdkInputCondition       cond);
156 static void catch_input                 (gpointer                data, 
157                                          gint                    source,
158                                          GdkInputCondition       cond);
159 static void catch_status                (gpointer                data,
160                                          gint                    source,
161                                          GdkInputCondition       cond);
162
163 static gchar *get_user_string           (const gchar    *action,
164                                          ActionType      type);
165
166
167 ActionType action_get_type(const gchar *action_str)
168 {
169         const gchar *p;
170         ActionType action_type = ACTION_NONE;
171
172         g_return_val_if_fail(action_str,  ACTION_ERROR);
173         g_return_val_if_fail(*action_str, ACTION_ERROR);
174
175         p = action_str;
176
177         if (p[0] == '|') {
178                 action_type |= ACTION_PIPE_IN;
179                 p++;
180         } else if (p[0] == '>') {
181                 action_type |= ACTION_USER_IN;
182                 p++;
183         } else if (p[0] == '*') {
184                 action_type |= ACTION_USER_HIDDEN_IN;
185                 p++;
186         }
187
188         if (p[0] == '\0')
189                 return ACTION_ERROR;
190
191         while (*p && action_type != ACTION_ERROR) {
192                 if (p[0] == '%') {
193                         switch (p[1]) {
194                         case 'f':
195                                 action_type |= ACTION_SINGLE;
196                                 break;
197                         case 'F':
198                                 action_type |= ACTION_MULTIPLE;
199                                 break;
200                         case 'p':
201                                 action_type |= ACTION_SINGLE;
202                                 break;
203                         case 's':
204                                 action_type |= ACTION_SELECTION_STR;
205                                 break;
206                         case 'u':
207                                 action_type |= ACTION_USER_STR;
208                                 break;
209                         case 'h':
210                                 action_type |= ACTION_USER_HIDDEN_STR;
211                                 break;
212                         default:
213                                 action_type = ACTION_ERROR;
214                                 break;
215                         }
216                 } else if (p[0] == '|') {
217                         if (p[1] == '\0')
218                                 action_type |= ACTION_PIPE_OUT;
219                 } else if (p[0] == '>') {
220                         if (p[1] == '\0')
221                                 action_type |= ACTION_INSERT;
222                 } else if (p[0] == '&') {
223                         if (p[1] == '\0')
224                                 action_type |= ACTION_ASYNC;
225                 }
226                 p++;
227         }
228
229         return action_type;
230 }
231
232 static gchar *parse_action_cmd(gchar *action, MsgInfo *msginfo,
233                                GSList *msg_list, MimeInfo *partinfo,
234                                const gchar *user_str,
235                                const gchar *user_hidden_str,
236                                const gchar *sel_str)
237 {
238         GString *cmd;
239         gchar *p;
240         GSList *cur;
241         
242         p = action;
243         
244         if (p[0] == '|' || p[0] == '>' || p[0] == '*')
245                 p++;
246
247         cmd = g_string_sized_new(strlen(action));
248
249         while (p[0] &&
250                !((p[0] == '|' || p[0] == '>' || p[0] == '&') && !p[1])) {
251                 if (p[0] == '%' && p[1]) {
252                         switch (p[1]) {
253                         case 'f':
254                                 if (!parse_append_filename(cmd, msginfo)) {
255                                         g_string_free(cmd, TRUE);
256                                         return NULL;
257                                 }
258                                 p++;
259                                 break;
260                         case 'F':
261                                 for (cur = msg_list; cur != NULL;
262                                      cur = cur->next) {
263                                         MsgInfo *msg = (MsgInfo *)cur->data;
264
265                                         if (!parse_append_filename(cmd, msg)) {
266                                                 g_string_free(cmd, TRUE);
267                                                 return NULL;
268                                         }
269                                         if (cur->next)
270                                                 g_string_append_c(cmd, ' ');
271                                 }
272                                 p++;
273                                 break;
274                         case 'p':
275                                 if (!parse_append_msgpart(cmd, msginfo,
276                                                           partinfo)) {
277                                         g_string_free(cmd, TRUE);
278                                         return NULL;
279                                 }
280                                 p++;
281                                 break;
282                         case 's':
283                                 if (sel_str)
284                                         g_string_append(cmd, sel_str);
285                                 p++;
286                                 break;
287                         case 'u':
288                                 if (user_str)
289                                         g_string_append(cmd, user_str);
290                                 p++;
291                                 break;
292                         case 'h':
293                                 if (user_hidden_str)
294                                         g_string_append(cmd, user_hidden_str);
295                                 p++;
296                                 break;
297                         default:
298                                 g_string_append_c(cmd, p[0]);
299                                 g_string_append_c(cmd, p[1]);
300                                 p++;
301                         }
302                 } else {
303                         g_string_append_c(cmd, p[0]);
304                 }
305                 p++;
306         }
307         if (cmd->len == 0) {
308                 g_string_free(cmd, TRUE);
309                 return NULL;
310         }
311
312         p = cmd->str;
313         g_string_free(cmd, FALSE);
314         return p;
315 }
316
317 static gboolean parse_append_filename(GString *cmd, MsgInfo *msginfo)
318 {
319         gchar *filename;
320
321         g_return_val_if_fail(msginfo, FALSE);
322
323         filename = procmsg_get_message_file(msginfo);
324
325         if (filename) {
326                 g_string_append(cmd, filename);
327                 g_free(filename);
328         } else {
329                 alertpanel_error(_("Could not get message file %d"),
330                                  msginfo->msgnum);
331                 return FALSE;
332         }
333
334         return TRUE;
335 }
336
337 static gboolean parse_append_msgpart(GString *cmd, MsgInfo *msginfo,
338                                      MimeInfo *partinfo)
339 {
340         gboolean single_part = FALSE;
341         gchar *filename;
342         gchar *part_filename;
343         gint ret;
344
345         if (!partinfo) {
346                 partinfo = procmime_scan_message(msginfo);
347                 if (!partinfo) {
348                         alertpanel_error(_("Could not get message part."));
349                         return FALSE;
350                 }
351
352                 single_part = TRUE;
353         }
354
355         filename = procmsg_get_message_file_path(msginfo);
356         part_filename = procmime_get_tmp_file_name(partinfo);
357
358         ret = procmime_get_part(part_filename, filename, partinfo); 
359
360         if (single_part)
361                 procmime_mimeinfo_free_all(partinfo);
362         g_free(filename);
363
364         if (ret < 0) {
365                 alertpanel_error(_("Can't get part of multipart message"));
366                 g_free(part_filename);
367                 return FALSE;
368         }
369
370         g_string_append(cmd, part_filename);
371
372         g_free(part_filename);
373
374         return TRUE;
375 }
376
377 void actions_execute(gpointer data, 
378                      guint action_nb,
379                      GtkWidget *widget,
380                      gint source)
381 {
382         if (source == TOOLBAR_MAIN) 
383                 mainwin_actions_execute_cb((MainWindow*)data, action_nb, widget);
384         else if (source == TOOLBAR_COMPOSE)
385                 compose_actions_execute_cb((Compose*)data, action_nb, widget);
386         else if (source == TOOLBAR_MSGVIEW)
387                 msgview_actions_execute_cb((MessageView*)data, action_nb, widget);      
388 }
389
390 void action_update_mainwin_menu(GtkItemFactory *ifactory, MainWindow *mainwin)
391 {
392         action_update_menu(ifactory, "/Tools/Actions",
393                            mainwin_actions_execute_cb, mainwin);
394 }
395
396 void action_update_msgview_menu(GtkItemFactory *ifactory, MessageView *msgview)
397 {
398         action_update_menu(ifactory, "/Tools/Actions",
399                            msgview_actions_execute_cb, msgview);
400 }
401
402 void action_update_compose_menu(GtkItemFactory *ifactory, Compose *compose)
403 {
404         action_update_menu(ifactory, "/Tools/Actions",
405                            compose_actions_execute_cb, compose);
406 }
407
408 static void action_update_menu(GtkItemFactory *ifactory, gchar *branch_path,
409                                gpointer callback, gpointer data)
410 {
411         GtkWidget *menuitem;
412         gchar *menu_path;
413         GSList *cur;
414         gchar *action, *action_p;
415         GList *amenu;
416         GtkItemFactoryEntry ifentry = {NULL, NULL, NULL, 0, "<Branch>"};
417
418         ifentry.path = branch_path;
419         menuitem = gtk_item_factory_get_widget(ifactory, branch_path);
420         g_return_if_fail(menuitem != NULL);
421
422         amenu = GTK_MENU_SHELL(menuitem)->children;
423         while (amenu != NULL) {
424                 GList *alist = amenu->next;
425                 gtk_widget_destroy(GTK_WIDGET(amenu->data));
426                 amenu = alist;
427         }
428
429         ifentry.accelerator     = NULL;
430         ifentry.callback_action = 0;
431         ifentry.callback        = callback;
432         ifentry.item_type       = NULL;
433
434         for (cur = prefs_common.actions_list; cur; cur = cur->next) {
435                 action   = g_strdup((gchar *)cur->data);
436                 action_p = strstr(action, ": ");
437                 if (action_p && action_p[2] &&
438                     action_get_type(&action_p[2]) != ACTION_ERROR) {
439                         action_p[0] = 0x00;
440                         menu_path = g_strdup_printf("%s/%s", branch_path,
441                                                     action);
442                         ifentry.path = menu_path;
443                         gtk_item_factory_create_item(ifactory, &ifentry, data,
444                                                      1);
445                         g_free(menu_path);
446                 }
447                 g_free(action);
448                 ifentry.callback_action++;
449         }
450 }
451
452 static void compose_actions_execute_cb(Compose *compose, guint action_nb,
453                                        GtkWidget *widget)
454 {
455         gchar *buf, *action;
456         ActionType action_type;
457
458         g_return_if_fail(action_nb < g_slist_length(prefs_common.actions_list));
459
460         buf = (gchar *)g_slist_nth_data(prefs_common.actions_list, action_nb);
461         g_return_if_fail(buf != NULL);
462         action = strstr(buf, ": ");
463         g_return_if_fail(action != NULL);
464
465         /* Point to the beginning of the command-line */
466         action += 2;
467
468         action_type = action_get_type(action);
469         if (action_type & (ACTION_SINGLE | ACTION_MULTIPLE)) {
470                 alertpanel_warning
471                         (_("The selected action cannot be used in the compose window\n"
472                            "because it contains %%f, %%F or %%p."));
473                 return;
474         }
475
476         execute_actions(action, NULL, compose->text, NULL, 0, NULL);
477 }
478
479 static void mainwin_actions_execute_cb(MainWindow *mainwin, guint action_nb,
480                                        GtkWidget *widget)
481 {
482         GSList *msg_list;
483
484         msg_list = summary_get_selected_msg_list(mainwin->summaryview);
485         message_actions_execute(mainwin->messageview, action_nb, msg_list);
486         g_slist_free(msg_list);
487 }
488
489 static void msgview_actions_execute_cb(MessageView *msgview, guint action_nb,
490                                        GtkWidget *widget)
491 {
492         GSList *msg_list = NULL;
493
494         if (msgview->msginfo)
495                 msg_list = g_slist_append(msg_list, msgview->msginfo);
496         message_actions_execute(msgview, action_nb, msg_list);
497         g_slist_free(msg_list);
498 }
499
500 static void message_actions_execute(MessageView *msgview, guint action_nb,
501                                     GSList *msg_list)
502 {
503         TextView *textview;
504         MimeInfo *partinfo;
505         gchar *buf;
506         gchar *action;
507         GtkWidget *text = NULL;
508         GdkFont *msgfont = NULL;
509         guint body_pos = 0;
510
511         g_return_if_fail(action_nb < g_slist_length(prefs_common.actions_list));
512
513         buf = (gchar *)g_slist_nth_data(prefs_common.actions_list, action_nb);
514
515         g_return_if_fail(buf);
516         g_return_if_fail(action = strstr(buf, ": "));
517
518         /* Point to the beginning of the command-line */
519         action += 2;
520
521         textview = messageview_get_current_textview(msgview);
522         if (textview) {
523                 text     = textview->text;
524                 msgfont  = textview->msgfont;
525                 body_pos = textview->body_pos;
526         }
527         partinfo = messageview_get_selected_mime_part(msgview);
528
529         execute_actions(action, msg_list, text, msgfont, body_pos, partinfo);
530 }
531
532 static gboolean execute_actions(gchar *action, GSList *msg_list,
533                                 GtkWidget *text, GdkFont *msgfont,
534                                 gint body_pos, MimeInfo *partinfo)
535 {
536         GSList *children_list = NULL;
537         gint is_ok  = TRUE;
538         gint msg_list_len;
539         Children *children;
540         ChildInfo *child_info;
541         ActionType action_type;
542         MsgInfo *msginfo;
543         gchar *cmd;
544         guint start = 0, end = 0;
545         gchar *sel_str = NULL;
546         gchar *msg_str = NULL;
547         gchar *user_str = NULL;
548         gchar *user_hidden_str = NULL;
549
550         g_return_val_if_fail(action && *action, FALSE);
551
552         action_type = action_get_type(action);
553
554         if (action_type == ACTION_ERROR)
555                 return FALSE;         /* ERR: syntax error */
556
557         if (action_type & (ACTION_SINGLE | ACTION_MULTIPLE) && !msg_list)
558                 return FALSE;         /* ERR: file command without selection */
559
560         msg_list_len = g_slist_length(msg_list);
561
562         if (action_type & (ACTION_PIPE_OUT | ACTION_PIPE_IN | ACTION_INSERT)) {
563                 if (msg_list_len > 1)
564                         return FALSE; /* ERR: pipe + multiple selection */
565                 if (!text)
566                         return FALSE; /* ERR: pipe and no displayed text */
567         }
568
569         if (action_type & ACTION_SELECTION_STR) {
570                 if (!text)
571                         return FALSE; /* ERR: selection string but no text */
572         }
573
574         if (text) {
575                 if (GTK_EDITABLE(text)->has_selection) {
576                         start = GTK_EDITABLE(text)->selection_start_pos;
577                         end   = GTK_EDITABLE(text)->selection_end_pos;
578                         if (start > end) {
579                                 guint tmp;
580                                 tmp = start;
581                                 start = end;
582                                 end = tmp;
583                         }
584
585                         if (start == end) {
586                                 start = body_pos;
587                                 end = gtk_stext_get_length(GTK_STEXT(text));
588                                 msg_str = gtk_editable_get_chars
589                                         (GTK_EDITABLE(text), start, end);
590                         } else {
591                                 sel_str = gtk_editable_get_chars
592                                         (GTK_EDITABLE(text), start, end);
593                                 msg_str = g_strdup(sel_str);
594                         }
595                 } else {
596                         start = body_pos;
597                         end = gtk_stext_get_length(GTK_STEXT(text));
598                         msg_str = gtk_editable_get_chars(GTK_EDITABLE(text),
599                                                          start, end);
600                 }
601         }
602
603         if (action_type & ACTION_USER_STR) {
604                 if (!(user_str = get_user_string(action, ACTION_USER_STR))) {
605                         g_free(msg_str);
606                         g_free(sel_str);
607                         return FALSE;
608                 }
609         }
610
611         if (action_type & ACTION_USER_HIDDEN_STR) {
612                 if (!(user_hidden_str =
613                         get_user_string(action, ACTION_USER_HIDDEN_STR))) {
614                         g_free(msg_str);
615                         g_free(sel_str);
616                         g_free(user_str);
617                         return FALSE;
618                 }
619         }
620
621         if (action_type & ACTION_PIPE_OUT) {
622                 gtk_stext_freeze(GTK_STEXT(text));
623                 gtk_stext_set_point(GTK_STEXT(text), start);
624                 gtk_stext_forward_delete(GTK_STEXT(text), end - start);
625                 gtk_stext_thaw(GTK_STEXT(text));
626         }
627
628         children = g_new0(Children, 1);
629
630         children->action      = g_strdup(action);
631         children->action_type = action_type;
632         children->msg_text    = text;
633         children->msgfont     = msgfont;
634
635         if ((action_type & (ACTION_USER_IN | ACTION_USER_HIDDEN_IN)) &&
636             ((action_type & ACTION_SINGLE) == 0 || msg_list_len == 1))
637                 children->open_in = 1;
638
639         if (action_type & ACTION_SINGLE) {
640                 GSList *cur;
641
642                 for (cur = msg_list; cur && is_ok == TRUE; cur = cur->next) {
643                         msginfo = (MsgInfo *)cur->data;
644                         if (!msginfo) {
645                                 is_ok  = FALSE; /* ERR: msginfo missing */
646                                 break;
647                         }
648                         cmd = parse_action_cmd(action, msginfo, msg_list,
649                                                partinfo, user_str,
650                                                user_hidden_str, sel_str);
651                         if (!cmd) {
652                                 debug_print("Action command error\n");
653                                 is_ok  = FALSE; /* ERR: incorrect command */
654                                 break;
655                         }
656                         if ((child_info = fork_child(cmd, msg_str, children))) {
657                                 children_list = g_slist_append(children_list,
658                                                                child_info);
659                         }
660                         g_free(cmd);
661                 }
662         } else {
663                 cmd = parse_action_cmd(action, NULL, msg_list, partinfo,
664                                        user_str, user_hidden_str, sel_str);
665                 if (cmd) {
666                         if ((child_info = fork_child(cmd, msg_str, children))) {
667                                 children_list = g_slist_append(children_list,
668                                                                child_info);
669                         }
670                         g_free(cmd);
671                 } else
672                         is_ok  = FALSE;         /* ERR: incorrect command */
673         }
674
675         g_free(msg_str);
676         g_free(sel_str);
677         g_free(user_str);
678         g_free(user_hidden_str);
679
680         if (!children_list) {
681                  /* If not waiting for children, return */
682                 free_children(children);
683         } else {
684                 GSList *cur;
685
686                 children->list        = children_list;
687                 children->nb          = g_slist_length(children_list);
688
689                 for (cur = children_list; cur; cur = cur->next) {
690                         child_info = (ChildInfo *) cur->data;
691                         child_info->tag_status = 
692                                 gdk_input_add(child_info->chld_status,
693                                               GDK_INPUT_READ,
694                                               catch_status, child_info);
695                 }
696
697                 create_io_dialog(children);
698         }
699
700         return is_ok;
701 }
702
703 static ChildInfo *fork_child(gchar *cmd, const gchar *msg_str,
704                              Children *children)
705 {
706         gint chld_in[2], chld_out[2], chld_err[2], chld_status[2];
707         gchar *cmdline[4];
708         pid_t pid, gch_pid;
709         ChildInfo *child_info;
710         gint sync;
711
712         sync = !(children->action_type & ACTION_ASYNC);
713
714         chld_in[0] = chld_in[1] = chld_out[0] = chld_out[1] = chld_err[0]
715                 = chld_err[1] = chld_status[0] = chld_status[1] = -1;
716
717         if (sync) {
718                 if (pipe(chld_status) || pipe(chld_in) || pipe(chld_out) ||
719                     pipe(chld_err)) {
720                         alertpanel_error(_("Command could not be started. "
721                                            "Pipe creation failed.\n%s"),
722                                         g_strerror(errno));
723                         /* Closing fd = -1 fails silently */
724                         close(chld_in[0]);
725                         close(chld_in[1]);
726                         close(chld_out[0]);
727                         close(chld_out[1]);
728                         close(chld_err[0]);
729                         close(chld_err[1]);
730                         close(chld_status[0]);
731                         close(chld_status[1]);
732                         return NULL; /* Pipe error */
733                 }
734         }
735
736         debug_print("Forking child and grandchild.\n");
737
738         pid = fork();
739         if (pid == 0) { /* Child */
740                 if (setpgid(0, 0))
741                         perror("setpgid");
742
743                 close(ConnectionNumber(gdk_display));
744
745                 gch_pid = fork();
746
747                 if (gch_pid == 0) {
748                         if (setpgid(0, getppid()))
749                                 perror("setpgid");
750
751                         if (sync) {
752                                 if (children->action_type &
753                                     (ACTION_PIPE_IN |
754                                      ACTION_USER_IN |
755                                      ACTION_USER_HIDDEN_IN)) {
756                                         close(fileno(stdin));
757                                         dup  (chld_in[0]);
758                                 }
759                                 close(chld_in[0]);
760                                 close(chld_in[1]);
761
762                                 close(fileno(stdout));
763                                 dup  (chld_out[1]);
764                                 close(chld_out[0]);
765                                 close(chld_out[1]);
766
767                                 close(fileno(stderr));
768                                 dup  (chld_err[1]);
769                                 close(chld_err[0]);
770                                 close(chld_err[1]);
771                         }
772
773                         cmdline[0] = "sh";
774                         cmdline[1] = "-c";
775                         cmdline[2] = cmd;
776                         cmdline[3] = 0;
777                         execvp("/bin/sh", cmdline);
778
779                         perror("execvp");
780                         _exit(1);
781                 } else if (gch_pid < (pid_t) 0) { /* Fork error */
782                         if (sync)
783                                 write(chld_status[1], "1\n", 2);
784                         perror("fork");
785                         _exit(1);
786                 } else { /* Child */
787                         if (sync) {
788                                 close(chld_in[0]);
789                                 close(chld_in[1]);
790                                 close(chld_out[0]);
791                                 close(chld_out[1]);
792                                 close(chld_err[0]);
793                                 close(chld_err[1]);
794                                 close(chld_status[0]);
795
796                                 debug_print("Child: Waiting for grandchild\n");
797                                 waitpid(gch_pid, NULL, 0);
798                                 debug_print("Child: grandchild ended\n");
799                                 write(chld_status[1], "0\n", 2);
800                                 close(chld_status[1]);
801                         }
802                         _exit(0);
803                 }
804         } else if (pid < 0) { /* Fork error */
805                 alertpanel_error(_("Could not fork to execute the following "
806                                    "command:\n%s\n%s"),
807                                  cmd, g_strerror(errno));
808                 return NULL; 
809         }
810
811         /* Parent */
812
813         if (!sync) {
814                 waitpid(pid, NULL, 0);
815                 return NULL;
816         }
817
818         close(chld_in[0]);
819         if (!(children->action_type &
820               (ACTION_PIPE_IN | ACTION_USER_IN | ACTION_USER_HIDDEN_IN)))
821                 close(chld_in[1]);
822         close(chld_out[1]);
823         close(chld_err[1]);
824         close(chld_status[1]);
825
826         child_info = g_new0(ChildInfo, 1);
827
828         child_info->children    = children;
829
830         child_info->pid         = pid;
831         child_info->cmd         = g_strdup(cmd);
832         child_info->new_out     = FALSE;
833         child_info->output      = g_string_new(NULL);
834         child_info->chld_in     =
835                 (children->action_type &
836                  (ACTION_PIPE_IN | ACTION_USER_IN | ACTION_USER_HIDDEN_IN))
837                         ? chld_in [1] : -1;
838         child_info->chld_out    = chld_out[0];
839         child_info->chld_err    = chld_err[0];
840         child_info->chld_status = chld_status[0];
841         child_info->tag_in      = -1;
842         child_info->tag_out     = gdk_input_add(chld_out[0], GDK_INPUT_READ,
843                                                 catch_output, child_info);
844         child_info->tag_err     = gdk_input_add(chld_err[0], GDK_INPUT_READ,
845                                                 catch_output, child_info);
846
847         if (!(children->action_type &
848               (ACTION_PIPE_IN | ACTION_PIPE_OUT | ACTION_INSERT)))
849                 return child_info;
850
851         if ((children->action_type & ACTION_PIPE_IN) && msg_str) {
852                 write(chld_in[1], msg_str, strlen(msg_str));
853                 if (!(children->action_type &
854                       (ACTION_USER_IN | ACTION_USER_HIDDEN_IN)))
855                         close(chld_in[1]);
856                 child_info->chld_in = -1; /* No more input */
857         }
858
859         return child_info;
860 }
861
862 static void kill_children_cb(GtkWidget *widget, gpointer data)
863 {
864         GSList *cur;
865         Children *children = (Children *) data;
866         ChildInfo *child_info;
867
868         for (cur = children->list; cur; cur = cur->next) {
869                 child_info = (ChildInfo *)(cur->data);
870                 debug_print("Killing child group id %d\n", child_info->pid);
871                 if (child_info->pid && kill(-child_info->pid, SIGTERM) < 0)
872                         perror("kill");
873         }
874 }
875
876 static gint wait_for_children(Children *children)
877 {
878         gboolean new_output;
879         ChildInfo *child_info;
880         GSList *cur;
881         gint nb = children->nb;
882
883         children->nb = 0;
884
885         cur = children->list;
886         new_output = FALSE;
887         while (cur) {
888                 child_info = (ChildInfo *)cur->data;
889                 if (child_info->pid)
890                         children->nb++;
891                 new_output |= child_info->new_out;
892                 cur = cur->next;
893         }
894
895         children->output |= new_output;
896
897         if (new_output || (children->dialog && (nb != children->nb)))
898                 update_io_dialog(children);
899
900         if (children->nb)
901                 return FALSE;
902
903         if (!children->dialog) {
904                 free_children(children);
905         } else if (!children->output) {
906                 gtk_widget_destroy(children->dialog);
907         }
908
909         return FALSE;
910 }
911
912 static void send_input(GtkWidget *w, gpointer data)
913 {
914         Children *children = (Children *) data;
915         ChildInfo *child_info = (ChildInfo *) children->list->data;
916
917         child_info->tag_in = gdk_input_add(child_info->chld_in,
918                                            GDK_INPUT_WRITE,
919                                            catch_input, children);
920         gtk_widget_set_sensitive(children->input_hbox, FALSE);
921 }
922
923 static gint delete_io_dialog_cb(GtkWidget *w, GdkEvent *e, gpointer data)
924 {
925         hide_io_dialog_cb(w, data);
926         return TRUE;
927 }
928
929 static void hide_io_dialog_cb(GtkWidget *w, gpointer data)
930 {
931
932         Children *children = (Children *)data;
933
934         if (!children->nb) {
935                 gtk_signal_disconnect_by_data(GTK_OBJECT(children->dialog),
936                                               children);
937                 gtk_widget_destroy(children->dialog);
938                 free_children(children);
939         }
940 }
941
942 static gint io_dialog_key_pressed_cb(GtkWidget *widget, GdkEventKey *event,
943                                      gpointer data)
944 {
945         if (event && event->keyval == GDK_Escape)
946                 hide_io_dialog_cb(widget, data);
947         return TRUE;
948 }
949
950 static void childinfo_close_pipes(ChildInfo *child_info)
951 {
952         if (child_info->tag_in > 0)
953                 gdk_input_remove(child_info->tag_in);
954         gdk_input_remove(child_info->tag_out);
955         gdk_input_remove(child_info->tag_err);
956
957         if (child_info->chld_in >= 0)
958                 close(child_info->chld_in);
959         close(child_info->chld_out);
960         close(child_info->chld_err);
961         close(child_info->chld_status);
962 }
963
964 static void free_children(Children *children)
965 {
966         ChildInfo *child_info;
967
968         debug_print("Freeing children data %p\n", children);
969
970         g_free(children->action);
971         while (children->list != NULL) {
972                 child_info = (ChildInfo *)children->list->data;
973                 g_free(child_info->cmd);
974                 g_string_free(child_info->output, TRUE);
975                 children->list = g_slist_remove(children->list, child_info);
976                 g_free(child_info);
977         }
978         g_free(children);
979 }
980
981 static void update_io_dialog(Children *children)
982 {
983         GSList *cur;
984
985         debug_print("Updating actions input/output dialog.\n");
986
987         if (!children->nb) {
988                 gtk_widget_set_sensitive(children->abort_btn, FALSE);
989                 gtk_widget_set_sensitive(children->close_btn, TRUE);
990                 if (children->input_hbox)
991                         gtk_widget_set_sensitive(children->input_hbox, FALSE);
992                 gtk_widget_grab_focus(children->close_btn);
993                 gtk_signal_connect(GTK_OBJECT(children->dialog),
994                                    "key_press_event",
995                                    GTK_SIGNAL_FUNC(io_dialog_key_pressed_cb),
996                                    children);
997         }
998
999         if (children->output) {
1000                 GtkWidget *text = children->text;
1001                 gchar *caption;
1002                 ChildInfo *child_info;
1003
1004                 gtk_widget_show(children->scrolledwin);
1005                 gtk_text_freeze(GTK_TEXT(text));
1006                 gtk_text_set_point(GTK_TEXT(text), 0);
1007                 gtk_text_forward_delete(GTK_TEXT(text), 
1008                                         gtk_text_get_length(GTK_TEXT(text)));
1009                 for (cur = children->list; cur; cur = cur->next) {
1010                         child_info = (ChildInfo *)cur->data;
1011                         if (child_info->pid)
1012                                 caption = g_strdup_printf
1013                                         (_("--- Running: %s\n"),
1014                                          child_info->cmd);
1015                         else
1016                                 caption = g_strdup_printf
1017                                         (_("--- Ended: %s\n"),
1018                                          child_info->cmd);
1019
1020                         gtk_text_insert(GTK_TEXT(text), NULL, NULL, NULL,
1021                                         caption, -1);
1022                         gtk_text_insert(GTK_TEXT(text), NULL, NULL, NULL,
1023                                         child_info->output->str, -1);
1024                         g_free(caption);
1025                         child_info->new_out = FALSE;
1026                 }
1027                 gtk_text_thaw(GTK_TEXT(text));
1028         }
1029 }
1030
1031 static void create_io_dialog(Children *children)
1032 {
1033         GtkWidget *dialog;
1034         GtkWidget *vbox;
1035         GtkWidget *entry = NULL;
1036         GtkWidget *input_hbox = NULL;
1037         GtkWidget *send_button;
1038         GtkWidget *label;
1039         GtkWidget *text;
1040         GtkWidget *scrolledwin;
1041         GtkWidget *hbox;
1042         GtkWidget *abort_button;
1043         GtkWidget *close_button;
1044
1045         debug_print("Creating action IO dialog\n");
1046
1047         dialog = gtk_dialog_new();
1048         gtk_container_set_border_width
1049                 (GTK_CONTAINER(GTK_DIALOG(dialog)->action_area), 5);
1050         gtk_window_set_position(GTK_WINDOW(dialog), GTK_WIN_POS_CENTER);
1051         gtk_window_set_title(GTK_WINDOW(dialog), _("Action's input/output"));
1052         gtk_window_set_modal(GTK_WINDOW(dialog), TRUE);
1053         manage_window_set_transient(GTK_WINDOW(dialog));
1054         gtk_signal_connect(GTK_OBJECT(dialog), "delete_event",
1055                         GTK_SIGNAL_FUNC(delete_io_dialog_cb), children);
1056         gtk_signal_connect(GTK_OBJECT(dialog), "destroy",
1057                         GTK_SIGNAL_FUNC(hide_io_dialog_cb),
1058                         children);
1059
1060         vbox = gtk_vbox_new(FALSE, 8);
1061         gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog)->vbox), vbox);
1062         gtk_container_set_border_width(GTK_CONTAINER(vbox), 8);
1063         gtk_widget_show(vbox);
1064
1065         label = gtk_label_new(children->action);
1066         gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 0);
1067         gtk_widget_show(label);
1068
1069         scrolledwin = gtk_scrolled_window_new(NULL, NULL);
1070         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledwin),
1071                                        GTK_POLICY_NEVER, GTK_POLICY_ALWAYS);
1072         gtk_box_pack_start(GTK_BOX(vbox), scrolledwin, TRUE, TRUE, 0);
1073         gtk_widget_set_usize(scrolledwin, 480, 200);
1074         gtk_widget_hide(scrolledwin);
1075
1076         text = gtk_text_new(gtk_scrolled_window_get_hadjustment
1077                             (GTK_SCROLLED_WINDOW(scrolledwin)),
1078                             gtk_scrolled_window_get_vadjustment
1079                             (GTK_SCROLLED_WINDOW(scrolledwin)));
1080         gtk_text_set_editable(GTK_TEXT(text), FALSE);
1081         gtk_container_add(GTK_CONTAINER(scrolledwin), text);
1082         gtk_widget_show(text);
1083
1084         if (children->open_in) {
1085                 input_hbox = gtk_hbox_new(FALSE, 8);
1086                 gtk_widget_show(input_hbox);
1087
1088                 entry = gtk_entry_new();
1089                 gtk_widget_set_usize(entry, 320, -1);
1090                 gtk_signal_connect(GTK_OBJECT(entry), "activate",
1091                                    GTK_SIGNAL_FUNC(send_input), children);
1092                 gtk_box_pack_start(GTK_BOX(input_hbox), entry, TRUE, TRUE, 0);
1093                 if (children->action_type & ACTION_USER_HIDDEN_IN)
1094                         gtk_entry_set_visibility(GTK_ENTRY(entry), FALSE);
1095                 gtk_widget_show(entry);
1096
1097                 send_button = gtk_button_new_with_label(_(" Send "));
1098                 gtk_signal_connect(GTK_OBJECT(send_button), "clicked",
1099                                    GTK_SIGNAL_FUNC(send_input), children);
1100                 gtk_box_pack_start(GTK_BOX(input_hbox), send_button, FALSE,
1101                                    FALSE, 0);
1102                 gtk_widget_show(send_button);
1103
1104                 gtk_box_pack_start(GTK_BOX(vbox), input_hbox, FALSE, FALSE, 0);
1105                 gtk_widget_grab_focus(entry);
1106         }
1107
1108         gtkut_button_set_create(&hbox, &abort_button, _("Abort"),
1109                                 &close_button, _("Close"), NULL, NULL);
1110         gtk_signal_connect(GTK_OBJECT(abort_button), "clicked",
1111                         GTK_SIGNAL_FUNC(kill_children_cb), children);
1112         gtk_signal_connect(GTK_OBJECT(close_button), "clicked",
1113                         GTK_SIGNAL_FUNC(hide_io_dialog_cb), children);
1114         gtk_widget_show(hbox);
1115
1116         if (children->nb)
1117                 gtk_widget_set_sensitive(close_button, FALSE);
1118
1119         gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog)->action_area), hbox);
1120
1121         children->dialog      = dialog;
1122         children->scrolledwin = scrolledwin;
1123         children->text        = text;
1124         children->input_hbox  = children->open_in ? input_hbox : NULL;
1125         children->input_entry = children->open_in ? entry : NULL;
1126         children->abort_btn   = abort_button;
1127         children->close_btn   = close_button;
1128
1129         gtk_widget_show(dialog);
1130 }
1131
1132 static void catch_status(gpointer data, gint source, GdkInputCondition cond)
1133 {
1134         ChildInfo *child_info = (ChildInfo *)data;
1135         gchar buf;
1136         gint c;
1137
1138         gdk_input_remove(child_info->tag_status);
1139
1140         c = read(source, &buf, 1);
1141         debug_print("Child returned %c\n", buf);
1142
1143         waitpid(-child_info->pid, NULL, 0);
1144         childinfo_close_pipes(child_info);
1145         child_info->pid = 0;
1146
1147         wait_for_children(child_info->children);
1148 }
1149         
1150 static void catch_input(gpointer data, gint source, GdkInputCondition cond)
1151 {
1152         Children *children = (Children *)data;
1153         ChildInfo *child_info = (ChildInfo *)children->list->data;
1154         gchar *input;
1155         gint c, count, len;
1156
1157         debug_print("Sending input to grand child.\n");
1158         if (!(cond && GDK_INPUT_WRITE))
1159                 return;
1160
1161         gdk_input_remove(child_info->tag_in);
1162         child_info->tag_in = -1;
1163
1164         input = gtk_editable_get_chars(GTK_EDITABLE(children->input_entry),
1165                                        0, -1);
1166         len = strlen(input);
1167         count = 0;
1168
1169         do {
1170                 c = write(child_info->chld_in, input + count, len - count);
1171                 if (c >= 0)
1172                         count += c;
1173         } while (c >= 0 && count < len);
1174
1175         if (c >= 0)
1176                 write(child_info->chld_in, "\n", 2);
1177
1178         g_free(input);
1179
1180         gtk_entry_set_text(GTK_ENTRY(children->input_entry), "");
1181         gtk_widget_set_sensitive(children->input_hbox, TRUE);
1182         close(child_info->chld_in);
1183         child_info->chld_in = -1;
1184         debug_print("Input to grand child sent.\n");
1185 }
1186
1187 static void catch_output(gpointer data, gint source, GdkInputCondition cond)
1188 {
1189         ChildInfo *child_info = (ChildInfo *)data;
1190         gint c, i;
1191         gchar buf[BUFFSIZE];
1192
1193         debug_print("Catching grand child's output.\n");
1194         if (child_info->children->action_type &
1195             (ACTION_PIPE_OUT | ACTION_INSERT)
1196             && source == child_info->chld_out) {
1197                 gboolean is_selection = FALSE;
1198                 GtkWidget *text = child_info->children->msg_text;
1199
1200                 if (GTK_EDITABLE(text)->has_selection)
1201                         is_selection = TRUE;
1202                 gtk_stext_freeze(GTK_STEXT(text));
1203                 while (TRUE) {
1204                         c = read(source, buf, sizeof(buf) - 1);
1205                         if (c == 0)
1206                                 break;
1207                         gtk_stext_insert(GTK_STEXT(text),
1208                                          child_info->children->msgfont,
1209                                          NULL, NULL, buf, c);
1210                 }
1211                 if (is_selection) {
1212                         /* Using the select_region draws things. Should not.
1213                          * so we just change selection position and 
1214                          * defere drawing when thawing. Hack?
1215                          */
1216                         GTK_EDITABLE(text)->selection_end_pos =
1217                                         gtk_stext_get_point(GTK_STEXT(text));
1218                 }
1219                 gtk_stext_thaw(GTK_STEXT(text));
1220         } else {
1221                 c = read(source, buf, sizeof(buf) - 1);
1222                 for (i = 0; i < c; i++)
1223                         g_string_append_c(child_info->output, buf[i]);
1224                 if (c > 0)
1225                         child_info->new_out = TRUE;
1226         }
1227         wait_for_children(child_info->children);
1228 }
1229
1230 static gchar *get_user_string(const gchar *action, ActionType type)
1231 {
1232         gchar *message;
1233         gchar *user_str = NULL;
1234
1235         switch (type) {
1236         case ACTION_USER_HIDDEN_STR:
1237                 message = g_strdup_printf
1238                         (_("Enter the argument for the following action:\n"
1239                            "(`%%h' will be replaced with the argument)\n"
1240                            "  %s"),
1241                          action);
1242                 user_str = input_dialog_with_invisible
1243                         (_("Action's hidden user argument"), message, NULL);
1244                 break;
1245         case ACTION_USER_STR:
1246                 message = g_strdup_printf
1247                         (_("Enter the argument for the following action:\n"
1248                            "(`%%u' will be replaced with the argument)\n"
1249                            "  %s"),
1250                          action);
1251                 user_str = input_dialog
1252                         (_("Action's user argument"), message, NULL);
1253                 break;
1254         default:
1255                 g_warning("Unsupported action type %d", type);
1256         }
1257
1258         return user_str;
1259 }