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