P. <- Pawel
[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         ActionType action_type;
511         
512         g_return_if_fail(action_nb < g_slist_length(prefs_common.actions_list));
513
514         buf = (gchar *)g_slist_nth_data(prefs_common.actions_list, action_nb);
515
516         g_return_if_fail(buf);
517         g_return_if_fail(action = strstr(buf, ": "));
518
519         /* Point to the beginning of the command-line */
520         action += 2;
521
522         textview = messageview_get_current_textview(msgview);
523         if (textview) {
524                 text     = textview->text;
525                 msgfont  = textview->msgfont;
526                 body_pos = textview->body_pos;
527         }
528         partinfo = messageview_get_selected_mime_part(msgview);
529
530         /* this command will alter the message text */
531         action_type = action_get_type(action);
532         if (action_type & (ACTION_PIPE_OUT | ACTION_INSERT))
533                 msgview->filtered = TRUE;
534
535         execute_actions(action, msg_list, text, msgfont, body_pos, partinfo);
536 }
537
538 static gboolean execute_actions(gchar *action, GSList *msg_list,
539                                 GtkWidget *text, GdkFont *msgfont,
540                                 gint body_pos, MimeInfo *partinfo)
541 {
542         GSList *children_list = NULL;
543         gint is_ok  = TRUE;
544         gint msg_list_len;
545         Children *children;
546         ChildInfo *child_info;
547         ActionType action_type;
548         MsgInfo *msginfo;
549         gchar *cmd;
550         guint start = 0, end = 0;
551         gchar *sel_str = NULL;
552         gchar *msg_str = NULL;
553         gchar *user_str = NULL;
554         gchar *user_hidden_str = NULL;
555
556         g_return_val_if_fail(action && *action, FALSE);
557
558         action_type = action_get_type(action);
559
560         if (action_type == ACTION_ERROR)
561                 return FALSE;         /* ERR: syntax error */
562
563         if (action_type & (ACTION_SINGLE | ACTION_MULTIPLE) && !msg_list)
564                 return FALSE;         /* ERR: file command without selection */
565
566         msg_list_len = g_slist_length(msg_list);
567
568         if (action_type & (ACTION_PIPE_OUT | ACTION_PIPE_IN | ACTION_INSERT)) {
569                 if (msg_list_len > 1)
570                         return FALSE; /* ERR: pipe + multiple selection */
571                 if (!text)
572                         return FALSE; /* ERR: pipe and no displayed text */
573         }
574
575         if (action_type & ACTION_SELECTION_STR) {
576                 if (!text)
577                         return FALSE; /* ERR: selection string but no text */
578         }
579
580         if (text) {
581                 if (GTK_EDITABLE(text)->has_selection) {
582                         start = GTK_EDITABLE(text)->selection_start_pos;
583                         end   = GTK_EDITABLE(text)->selection_end_pos;
584                         if (start > end) {
585                                 guint tmp;
586                                 tmp = start;
587                                 start = end;
588                                 end = tmp;
589                         }
590
591                         if (start == end) {
592                                 start = body_pos;
593                                 end = gtk_stext_get_length(GTK_STEXT(text));
594                                 msg_str = gtk_editable_get_chars
595                                         (GTK_EDITABLE(text), start, end);
596                         } else {
597                                 sel_str = gtk_editable_get_chars
598                                         (GTK_EDITABLE(text), start, end);
599                                 msg_str = g_strdup(sel_str);
600                         }
601                 } else {
602                         start = body_pos;
603                         end = gtk_stext_get_length(GTK_STEXT(text));
604                         msg_str = gtk_editable_get_chars(GTK_EDITABLE(text),
605                                                          start, end);
606                 }
607         }
608
609         if (action_type & ACTION_USER_STR) {
610                 if (!(user_str = get_user_string(action, ACTION_USER_STR))) {
611                         g_free(msg_str);
612                         g_free(sel_str);
613                         return FALSE;
614                 }
615         }
616
617         if (action_type & ACTION_USER_HIDDEN_STR) {
618                 if (!(user_hidden_str =
619                         get_user_string(action, ACTION_USER_HIDDEN_STR))) {
620                         g_free(msg_str);
621                         g_free(sel_str);
622                         g_free(user_str);
623                         return FALSE;
624                 }
625         }
626
627         if (action_type & ACTION_PIPE_OUT) {
628                 gtk_stext_freeze(GTK_STEXT(text));
629                 gtk_stext_set_point(GTK_STEXT(text), start);
630                 gtk_stext_forward_delete(GTK_STEXT(text), end - start);
631                 gtk_stext_thaw(GTK_STEXT(text));
632         }
633
634         children = g_new0(Children, 1);
635
636         children->action      = g_strdup(action);
637         children->action_type = action_type;
638         children->msg_text    = text;
639         children->msgfont     = msgfont;
640
641         if ((action_type & (ACTION_USER_IN | ACTION_USER_HIDDEN_IN)) &&
642             ((action_type & ACTION_SINGLE) == 0 || msg_list_len == 1))
643                 children->open_in = 1;
644
645         if (action_type & ACTION_SINGLE) {
646                 GSList *cur;
647
648                 for (cur = msg_list; cur && is_ok == TRUE; cur = cur->next) {
649                         msginfo = (MsgInfo *)cur->data;
650                         if (!msginfo) {
651                                 is_ok  = FALSE; /* ERR: msginfo missing */
652                                 break;
653                         }
654                         cmd = parse_action_cmd(action, msginfo, msg_list,
655                                                partinfo, user_str,
656                                                user_hidden_str, sel_str);
657                         if (!cmd) {
658                                 debug_print("Action command error\n");
659                                 is_ok  = FALSE; /* ERR: incorrect command */
660                                 break;
661                         }
662                         if ((child_info = fork_child(cmd, msg_str, children))) {
663                                 children_list = g_slist_append(children_list,
664                                                                child_info);
665                         }
666                         g_free(cmd);
667                 }
668         } else {
669                 cmd = parse_action_cmd(action, NULL, msg_list, partinfo,
670                                        user_str, user_hidden_str, sel_str);
671                 if (cmd) {
672                         if ((child_info = fork_child(cmd, msg_str, children))) {
673                                 children_list = g_slist_append(children_list,
674                                                                child_info);
675                         }
676                         g_free(cmd);
677                 } else
678                         is_ok  = FALSE;         /* ERR: incorrect command */
679         }
680
681         g_free(msg_str);
682         g_free(sel_str);
683         g_free(user_str);
684         g_free(user_hidden_str);
685
686         if (!children_list) {
687                  /* If not waiting for children, return */
688                 free_children(children);
689         } else {
690                 GSList *cur;
691
692                 children->list        = children_list;
693                 children->nb          = g_slist_length(children_list);
694
695                 for (cur = children_list; cur; cur = cur->next) {
696                         child_info = (ChildInfo *) cur->data;
697                         child_info->tag_status = 
698                                 gdk_input_add(child_info->chld_status,
699                                               GDK_INPUT_READ,
700                                               catch_status, child_info);
701                 }
702
703                 create_io_dialog(children);
704         }
705
706         return is_ok;
707 }
708
709 static ChildInfo *fork_child(gchar *cmd, const gchar *msg_str,
710                              Children *children)
711 {
712         gint chld_in[2], chld_out[2], chld_err[2], chld_status[2];
713         gchar *cmdline[4];
714         pid_t pid, gch_pid;
715         ChildInfo *child_info;
716         gint sync;
717
718         sync = !(children->action_type & ACTION_ASYNC);
719
720         chld_in[0] = chld_in[1] = chld_out[0] = chld_out[1] = chld_err[0]
721                 = chld_err[1] = chld_status[0] = chld_status[1] = -1;
722
723         if (sync) {
724                 if (pipe(chld_status) || pipe(chld_in) || pipe(chld_out) ||
725                     pipe(chld_err)) {
726                         alertpanel_error(_("Command could not be started. "
727                                            "Pipe creation failed.\n%s"),
728                                         g_strerror(errno));
729                         /* Closing fd = -1 fails silently */
730                         close(chld_in[0]);
731                         close(chld_in[1]);
732                         close(chld_out[0]);
733                         close(chld_out[1]);
734                         close(chld_err[0]);
735                         close(chld_err[1]);
736                         close(chld_status[0]);
737                         close(chld_status[1]);
738                         return NULL; /* Pipe error */
739                 }
740         }
741
742         debug_print("Forking child and grandchild.\n");
743
744         pid = fork();
745         if (pid == 0) { /* Child */
746                 if (setpgid(0, 0))
747                         perror("setpgid");
748
749                 close(ConnectionNumber(gdk_display));
750
751                 gch_pid = fork();
752
753                 if (gch_pid == 0) {
754                         if (setpgid(0, getppid()))
755                                 perror("setpgid");
756
757                         if (sync) {
758                                 if (children->action_type &
759                                     (ACTION_PIPE_IN |
760                                      ACTION_USER_IN |
761                                      ACTION_USER_HIDDEN_IN)) {
762                                         close(fileno(stdin));
763                                         dup  (chld_in[0]);
764                                 }
765                                 close(chld_in[0]);
766                                 close(chld_in[1]);
767
768                                 close(fileno(stdout));
769                                 dup  (chld_out[1]);
770                                 close(chld_out[0]);
771                                 close(chld_out[1]);
772
773                                 close(fileno(stderr));
774                                 dup  (chld_err[1]);
775                                 close(chld_err[0]);
776                                 close(chld_err[1]);
777                         }
778
779                         cmdline[0] = "sh";
780                         cmdline[1] = "-c";
781                         cmdline[2] = cmd;
782                         cmdline[3] = 0;
783                         execvp("/bin/sh", cmdline);
784
785                         perror("execvp");
786                         _exit(1);
787                 } else if (gch_pid < (pid_t) 0) { /* Fork error */
788                         if (sync)
789                                 write(chld_status[1], "1\n", 2);
790                         perror("fork");
791                         _exit(1);
792                 } else { /* Child */
793                         if (sync) {
794                                 close(chld_in[0]);
795                                 close(chld_in[1]);
796                                 close(chld_out[0]);
797                                 close(chld_out[1]);
798                                 close(chld_err[0]);
799                                 close(chld_err[1]);
800                                 close(chld_status[0]);
801
802                                 debug_print("Child: Waiting for grandchild\n");
803                                 waitpid(gch_pid, NULL, 0);
804                                 debug_print("Child: grandchild ended\n");
805                                 write(chld_status[1], "0\n", 2);
806                                 close(chld_status[1]);
807                         }
808                         _exit(0);
809                 }
810         } else if (pid < 0) { /* Fork error */
811                 alertpanel_error(_("Could not fork to execute the following "
812                                    "command:\n%s\n%s"),
813                                  cmd, g_strerror(errno));
814                 return NULL; 
815         }
816
817         /* Parent */
818
819         if (!sync) {
820                 waitpid(pid, NULL, 0);
821                 return NULL;
822         }
823
824         close(chld_in[0]);
825         if (!(children->action_type &
826               (ACTION_PIPE_IN | ACTION_USER_IN | ACTION_USER_HIDDEN_IN)))
827                 close(chld_in[1]);
828         close(chld_out[1]);
829         close(chld_err[1]);
830         close(chld_status[1]);
831
832         child_info = g_new0(ChildInfo, 1);
833
834         child_info->children    = children;
835
836         child_info->pid         = pid;
837         child_info->cmd         = g_strdup(cmd);
838         child_info->new_out     = FALSE;
839         child_info->output      = g_string_new(NULL);
840         child_info->chld_in     =
841                 (children->action_type &
842                  (ACTION_PIPE_IN | ACTION_USER_IN | ACTION_USER_HIDDEN_IN))
843                         ? chld_in [1] : -1;
844         child_info->chld_out    = chld_out[0];
845         child_info->chld_err    = chld_err[0];
846         child_info->chld_status = chld_status[0];
847         child_info->tag_in      = -1;
848         child_info->tag_out     = gdk_input_add(chld_out[0], GDK_INPUT_READ,
849                                                 catch_output, child_info);
850         child_info->tag_err     = gdk_input_add(chld_err[0], GDK_INPUT_READ,
851                                                 catch_output, child_info);
852
853         if (!(children->action_type &
854               (ACTION_PIPE_IN | ACTION_PIPE_OUT | ACTION_INSERT)))
855                 return child_info;
856
857         if ((children->action_type & ACTION_PIPE_IN) && msg_str) {
858                 write(chld_in[1], msg_str, strlen(msg_str));
859                 if (!(children->action_type &
860                       (ACTION_USER_IN | ACTION_USER_HIDDEN_IN)))
861                         close(chld_in[1]);
862                 child_info->chld_in = -1; /* No more input */
863         }
864
865         return child_info;
866 }
867
868 static void kill_children_cb(GtkWidget *widget, gpointer data)
869 {
870         GSList *cur;
871         Children *children = (Children *) data;
872         ChildInfo *child_info;
873
874         for (cur = children->list; cur; cur = cur->next) {
875                 child_info = (ChildInfo *)(cur->data);
876                 debug_print("Killing child group id %d\n", child_info->pid);
877                 if (child_info->pid && kill(-child_info->pid, SIGTERM) < 0)
878                         perror("kill");
879         }
880 }
881
882 static gint wait_for_children(Children *children)
883 {
884         gboolean new_output;
885         ChildInfo *child_info;
886         GSList *cur;
887         gint nb = children->nb;
888
889         children->nb = 0;
890
891         cur = children->list;
892         new_output = FALSE;
893         while (cur) {
894                 child_info = (ChildInfo *)cur->data;
895                 if (child_info->pid)
896                         children->nb++;
897                 new_output |= child_info->new_out;
898                 cur = cur->next;
899         }
900
901         children->output |= new_output;
902
903         if (new_output || (children->dialog && (nb != children->nb)))
904                 update_io_dialog(children);
905
906         if (children->nb)
907                 return FALSE;
908
909         if (!children->dialog) {
910                 free_children(children);
911         } else if (!children->output) {
912                 gtk_widget_destroy(children->dialog);
913         }
914
915         return FALSE;
916 }
917
918 static void send_input(GtkWidget *w, gpointer data)
919 {
920         Children *children = (Children *) data;
921         ChildInfo *child_info = (ChildInfo *) children->list->data;
922
923         child_info->tag_in = gdk_input_add(child_info->chld_in,
924                                            GDK_INPUT_WRITE,
925                                            catch_input, children);
926         gtk_widget_set_sensitive(children->input_hbox, FALSE);
927 }
928
929 static gint delete_io_dialog_cb(GtkWidget *w, GdkEvent *e, gpointer data)
930 {
931         hide_io_dialog_cb(w, data);
932         return TRUE;
933 }
934
935 static void hide_io_dialog_cb(GtkWidget *w, gpointer data)
936 {
937
938         Children *children = (Children *)data;
939
940         if (!children->nb) {
941                 gtk_signal_disconnect_by_data(GTK_OBJECT(children->dialog),
942                                               children);
943                 gtk_widget_destroy(children->dialog);
944                 free_children(children);
945         }
946 }
947
948 static gint io_dialog_key_pressed_cb(GtkWidget *widget, GdkEventKey *event,
949                                      gpointer data)
950 {
951         if (event && event->keyval == GDK_Escape)
952                 hide_io_dialog_cb(widget, data);
953         return TRUE;
954 }
955
956 static void childinfo_close_pipes(ChildInfo *child_info)
957 {
958         if (child_info->tag_in > 0)
959                 gdk_input_remove(child_info->tag_in);
960         gdk_input_remove(child_info->tag_out);
961         gdk_input_remove(child_info->tag_err);
962
963         if (child_info->chld_in >= 0)
964                 close(child_info->chld_in);
965         close(child_info->chld_out);
966         close(child_info->chld_err);
967         close(child_info->chld_status);
968 }
969
970 static void free_children(Children *children)
971 {
972         ChildInfo *child_info;
973
974         debug_print("Freeing children data %p\n", children);
975
976         g_free(children->action);
977         while (children->list != NULL) {
978                 child_info = (ChildInfo *)children->list->data;
979                 g_free(child_info->cmd);
980                 g_string_free(child_info->output, TRUE);
981                 children->list = g_slist_remove(children->list, child_info);
982                 g_free(child_info);
983         }
984         g_free(children);
985 }
986
987 static void update_io_dialog(Children *children)
988 {
989         GSList *cur;
990
991         debug_print("Updating actions input/output dialog.\n");
992
993         if (!children->nb) {
994                 gtk_widget_set_sensitive(children->abort_btn, FALSE);
995                 gtk_widget_set_sensitive(children->close_btn, TRUE);
996                 if (children->input_hbox)
997                         gtk_widget_set_sensitive(children->input_hbox, FALSE);
998                 gtk_widget_grab_focus(children->close_btn);
999                 gtk_signal_connect(GTK_OBJECT(children->dialog),
1000                                    "key_press_event",
1001                                    GTK_SIGNAL_FUNC(io_dialog_key_pressed_cb),
1002                                    children);
1003         }
1004
1005         if (children->output) {
1006                 GtkWidget *text = children->text;
1007                 gchar *caption;
1008                 ChildInfo *child_info;
1009
1010                 gtk_widget_show(children->scrolledwin);
1011                 gtk_text_freeze(GTK_TEXT(text));
1012                 gtk_text_set_point(GTK_TEXT(text), 0);
1013                 gtk_text_forward_delete(GTK_TEXT(text), 
1014                                         gtk_text_get_length(GTK_TEXT(text)));
1015                 for (cur = children->list; cur; cur = cur->next) {
1016                         child_info = (ChildInfo *)cur->data;
1017                         if (child_info->pid)
1018                                 caption = g_strdup_printf
1019                                         (_("--- Running: %s\n"),
1020                                          child_info->cmd);
1021                         else
1022                                 caption = g_strdup_printf
1023                                         (_("--- Ended: %s\n"),
1024                                          child_info->cmd);
1025
1026                         gtk_text_insert(GTK_TEXT(text), NULL, NULL, NULL,
1027                                         caption, -1);
1028                         gtk_text_insert(GTK_TEXT(text), NULL, NULL, NULL,
1029                                         child_info->output->str, -1);
1030                         g_free(caption);
1031                         child_info->new_out = FALSE;
1032                 }
1033                 gtk_text_thaw(GTK_TEXT(text));
1034         }
1035 }
1036
1037 static void create_io_dialog(Children *children)
1038 {
1039         GtkWidget *dialog;
1040         GtkWidget *vbox;
1041         GtkWidget *entry = NULL;
1042         GtkWidget *input_hbox = NULL;
1043         GtkWidget *send_button;
1044         GtkWidget *label;
1045         GtkWidget *text;
1046         GtkWidget *scrolledwin;
1047         GtkWidget *hbox;
1048         GtkWidget *abort_button;
1049         GtkWidget *close_button;
1050
1051         debug_print("Creating action IO dialog\n");
1052
1053         dialog = gtk_dialog_new();
1054         gtk_container_set_border_width
1055                 (GTK_CONTAINER(GTK_DIALOG(dialog)->action_area), 5);
1056         gtk_window_set_position(GTK_WINDOW(dialog), GTK_WIN_POS_CENTER);
1057         gtk_window_set_title(GTK_WINDOW(dialog), _("Action's input/output"));
1058         gtk_window_set_modal(GTK_WINDOW(dialog), TRUE);
1059         manage_window_set_transient(GTK_WINDOW(dialog));
1060         gtk_signal_connect(GTK_OBJECT(dialog), "delete_event",
1061                         GTK_SIGNAL_FUNC(delete_io_dialog_cb), children);
1062         gtk_signal_connect(GTK_OBJECT(dialog), "destroy",
1063                         GTK_SIGNAL_FUNC(hide_io_dialog_cb),
1064                         children);
1065
1066         vbox = gtk_vbox_new(FALSE, 8);
1067         gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog)->vbox), vbox);
1068         gtk_container_set_border_width(GTK_CONTAINER(vbox), 8);
1069         gtk_widget_show(vbox);
1070
1071         label = gtk_label_new(children->action);
1072         gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 0);
1073         gtk_widget_show(label);
1074
1075         scrolledwin = gtk_scrolled_window_new(NULL, NULL);
1076         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledwin),
1077                                        GTK_POLICY_NEVER, GTK_POLICY_ALWAYS);
1078         gtk_box_pack_start(GTK_BOX(vbox), scrolledwin, TRUE, TRUE, 0);
1079         gtk_widget_set_usize(scrolledwin, 480, 200);
1080         gtk_widget_hide(scrolledwin);
1081
1082         text = gtk_text_new(gtk_scrolled_window_get_hadjustment
1083                             (GTK_SCROLLED_WINDOW(scrolledwin)),
1084                             gtk_scrolled_window_get_vadjustment
1085                             (GTK_SCROLLED_WINDOW(scrolledwin)));
1086         gtk_text_set_editable(GTK_TEXT(text), FALSE);
1087         gtk_container_add(GTK_CONTAINER(scrolledwin), text);
1088         gtk_widget_show(text);
1089
1090         if (children->open_in) {
1091                 input_hbox = gtk_hbox_new(FALSE, 8);
1092                 gtk_widget_show(input_hbox);
1093
1094                 entry = gtk_entry_new();
1095                 gtk_widget_set_usize(entry, 320, -1);
1096                 gtk_signal_connect(GTK_OBJECT(entry), "activate",
1097                                    GTK_SIGNAL_FUNC(send_input), children);
1098                 gtk_box_pack_start(GTK_BOX(input_hbox), entry, TRUE, TRUE, 0);
1099                 if (children->action_type & ACTION_USER_HIDDEN_IN)
1100                         gtk_entry_set_visibility(GTK_ENTRY(entry), FALSE);
1101                 gtk_widget_show(entry);
1102
1103                 send_button = gtk_button_new_with_label(_(" Send "));
1104                 gtk_signal_connect(GTK_OBJECT(send_button), "clicked",
1105                                    GTK_SIGNAL_FUNC(send_input), children);
1106                 gtk_box_pack_start(GTK_BOX(input_hbox), send_button, FALSE,
1107                                    FALSE, 0);
1108                 gtk_widget_show(send_button);
1109
1110                 gtk_box_pack_start(GTK_BOX(vbox), input_hbox, FALSE, FALSE, 0);
1111                 gtk_widget_grab_focus(entry);
1112         }
1113
1114         gtkut_button_set_create(&hbox, &abort_button, _("Abort"),
1115                                 &close_button, _("Close"), NULL, NULL);
1116         gtk_signal_connect(GTK_OBJECT(abort_button), "clicked",
1117                         GTK_SIGNAL_FUNC(kill_children_cb), children);
1118         gtk_signal_connect(GTK_OBJECT(close_button), "clicked",
1119                         GTK_SIGNAL_FUNC(hide_io_dialog_cb), children);
1120         gtk_widget_show(hbox);
1121
1122         if (children->nb)
1123                 gtk_widget_set_sensitive(close_button, FALSE);
1124
1125         gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog)->action_area), hbox);
1126
1127         children->dialog      = dialog;
1128         children->scrolledwin = scrolledwin;
1129         children->text        = text;
1130         children->input_hbox  = children->open_in ? input_hbox : NULL;
1131         children->input_entry = children->open_in ? entry : NULL;
1132         children->abort_btn   = abort_button;
1133         children->close_btn   = close_button;
1134
1135         gtk_widget_show(dialog);
1136 }
1137
1138 static void catch_status(gpointer data, gint source, GdkInputCondition cond)
1139 {
1140         ChildInfo *child_info = (ChildInfo *)data;
1141         gchar buf;
1142         gint c;
1143
1144         gdk_input_remove(child_info->tag_status);
1145
1146         c = read(source, &buf, 1);
1147         debug_print("Child returned %c\n", buf);
1148
1149         waitpid(-child_info->pid, NULL, 0);
1150         childinfo_close_pipes(child_info);
1151         child_info->pid = 0;
1152
1153         wait_for_children(child_info->children);
1154 }
1155         
1156 static void catch_input(gpointer data, gint source, GdkInputCondition cond)
1157 {
1158         Children *children = (Children *)data;
1159         ChildInfo *child_info = (ChildInfo *)children->list->data;
1160         gchar *input;
1161         gint c, count, len;
1162
1163         debug_print("Sending input to grand child.\n");
1164         if (!(cond && GDK_INPUT_WRITE))
1165                 return;
1166
1167         gdk_input_remove(child_info->tag_in);
1168         child_info->tag_in = -1;
1169
1170         input = gtk_editable_get_chars(GTK_EDITABLE(children->input_entry),
1171                                        0, -1);
1172         len = strlen(input);
1173         count = 0;
1174
1175         do {
1176                 c = write(child_info->chld_in, input + count, len - count);
1177                 if (c >= 0)
1178                         count += c;
1179         } while (c >= 0 && count < len);
1180
1181         if (c >= 0)
1182                 write(child_info->chld_in, "\n", 2);
1183
1184         g_free(input);
1185
1186         gtk_entry_set_text(GTK_ENTRY(children->input_entry), "");
1187         gtk_widget_set_sensitive(children->input_hbox, TRUE);
1188         close(child_info->chld_in);
1189         child_info->chld_in = -1;
1190         debug_print("Input to grand child sent.\n");
1191 }
1192
1193 static void catch_output(gpointer data, gint source, GdkInputCondition cond)
1194 {
1195         ChildInfo *child_info = (ChildInfo *)data;
1196         gint c, i;
1197         gchar buf[BUFFSIZE];
1198
1199         debug_print("Catching grand child's output.\n");
1200         if (child_info->children->action_type &
1201             (ACTION_PIPE_OUT | ACTION_INSERT)
1202             && source == child_info->chld_out) {
1203                 gboolean is_selection = FALSE;
1204                 GtkWidget *text = child_info->children->msg_text;
1205
1206                 if (GTK_EDITABLE(text)->has_selection)
1207                         is_selection = TRUE;
1208                 gtk_stext_freeze(GTK_STEXT(text));
1209                 while (TRUE) {
1210                         c = read(source, buf, sizeof(buf) - 1);
1211                         if (c == 0)
1212                                 break;
1213                         gtk_stext_insert(GTK_STEXT(text),
1214                                          child_info->children->msgfont,
1215                                          NULL, NULL, buf, c);
1216                 }
1217                 if (is_selection) {
1218                         /* Using the select_region draws things. Should not.
1219                          * so we just change selection position and 
1220                          * defere drawing when thawing. Hack?
1221                          */
1222                         GTK_EDITABLE(text)->selection_end_pos =
1223                                         gtk_stext_get_point(GTK_STEXT(text));
1224                 }
1225                 gtk_stext_thaw(GTK_STEXT(text));
1226         } else {
1227                 c = read(source, buf, sizeof(buf) - 1);
1228                 for (i = 0; i < c; i++)
1229                         g_string_append_c(child_info->output, buf[i]);
1230                 if (c > 0)
1231                         child_info->new_out = TRUE;
1232         }
1233         wait_for_children(child_info->children);
1234 }
1235
1236 static gchar *get_user_string(const gchar *action, ActionType type)
1237 {
1238         gchar *message;
1239         gchar *user_str = NULL;
1240
1241         switch (type) {
1242         case ACTION_USER_HIDDEN_STR:
1243                 message = g_strdup_printf
1244                         (_("Enter the argument for the following action:\n"
1245                            "(`%%h' will be replaced with the argument)\n"
1246                            "  %s"),
1247                          action);
1248                 user_str = input_dialog_with_invisible
1249                         (_("Action's hidden user argument"), message, NULL);
1250                 break;
1251         case ACTION_USER_STR:
1252                 message = g_strdup_printf
1253                         (_("Enter the argument for the following action:\n"
1254                            "(`%%u' will be replaced with the argument)\n"
1255                            "  %s"),
1256                          action);
1257                 user_str = input_dialog
1258                         (_("Action's user argument"), message, NULL);
1259                 break;
1260         default:
1261                 g_warning("Unsupported action type %d", type);
1262         }
1263
1264         return user_str;
1265 }