Fix SSL certificate list not shown; Fix clicks in mimetree
[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, MainWindow *mainwin)
409 {
410         action_update_menu(ifactory, "/Tools/Actions",
411                            mainwin_actions_execute_cb, mainwin);
412 }
413
414 void action_update_msgview_menu(GtkItemFactory *ifactory, MessageView *msgview)
415 {
416         action_update_menu(ifactory, "/Tools/Actions",
417                            msgview_actions_execute_cb, msgview);
418 }
419
420 void action_update_compose_menu(GtkItemFactory *ifactory, Compose *compose)
421 {
422         action_update_menu(ifactory, "/Tools/Actions",
423                            compose_actions_execute_cb, compose);
424 }
425
426 static void action_update_menu(GtkItemFactory *ifactory, gchar *branch_path,
427                                gpointer callback, gpointer data)
428 {
429         GtkWidget *menuitem;
430         gchar *menu_path;
431         GSList *cur;
432         gchar *action, *action_p;
433         GList *amenu;
434         GtkItemFactoryEntry ifentry = {NULL, NULL, NULL, 0, "<Branch>"};
435
436         ifentry.path = branch_path;
437         menuitem = gtk_item_factory_get_widget(ifactory, branch_path);
438         g_return_if_fail(menuitem != NULL);
439
440         amenu = GTK_MENU_SHELL(menuitem)->children;
441         while (amenu != NULL) {
442                 GList *alist = amenu->next;
443                 gtk_widget_destroy(GTK_WIDGET(amenu->data));
444                 amenu = alist;
445         }
446
447         ifentry.accelerator     = NULL;
448         ifentry.callback_action = 0;
449         ifentry.callback        = callback;
450         ifentry.item_type       = NULL;
451
452         for (cur = prefs_common.actions_list; cur; cur = cur->next) {
453                 action   = g_strdup((gchar *)cur->data);
454                 action_p = strstr(action, ": ");
455                 if (action_p && action_p[2] &&
456                     action_get_type(&action_p[2]) != ACTION_ERROR) {
457                         action_p[0] = 0x00;
458                         menu_path = g_strdup_printf("%s/%s", branch_path,
459                                                     action);
460                         ifentry.path = menu_path;
461                         gtk_item_factory_create_item(ifactory, &ifentry, data,
462                                                      1);
463                         g_free(menu_path);
464                 }
465                 g_free(action);
466                 ifentry.callback_action++;
467         }
468 }
469
470 static void compose_actions_execute_cb(Compose *compose, guint action_nb,
471                                        GtkWidget *widget)
472 {
473         gchar *buf, *action;
474         ActionType action_type;
475
476         g_return_if_fail(action_nb < g_slist_length(prefs_common.actions_list));
477
478         buf = (gchar *)g_slist_nth_data(prefs_common.actions_list, action_nb);
479         g_return_if_fail(buf != NULL);
480         action = strstr(buf, ": ");
481         g_return_if_fail(action != NULL);
482
483         /* Point to the beginning of the command-line */
484         action += 2;
485
486         action_type = action_get_type(action);
487         if (action_type & (ACTION_SINGLE | ACTION_MULTIPLE)) {
488                 alertpanel_warning
489                         (_("The selected action cannot be used in the compose window\n"
490                            "because it contains %%f, %%F, %%as or %%p."));
491                 return;
492         }
493
494         execute_actions(action, NULL, compose->text, 0, NULL);
495 }
496
497 static void mainwin_actions_execute_cb(MainWindow *mainwin, guint action_nb,
498                                        GtkWidget *widget)
499 {
500         GSList *msg_list;
501
502         msg_list = summary_get_selected_msg_list(mainwin->summaryview);
503         message_actions_execute(mainwin->messageview, action_nb, msg_list);
504         g_slist_free(msg_list);
505 }
506
507 static void msgview_actions_execute_cb(MessageView *msgview, guint action_nb,
508                                        GtkWidget *widget)
509 {
510         GSList *msg_list = NULL;
511
512         if (msgview->msginfo)
513                 msg_list = g_slist_append(msg_list, msgview->msginfo);
514         message_actions_execute(msgview, action_nb, msg_list);
515         g_slist_free(msg_list);
516 }
517
518 static void message_actions_execute(MessageView *msgview, guint action_nb,
519                                     GSList *msg_list)
520 {
521         TextView *textview;
522         MimeInfo *partinfo;
523         gchar *buf;
524         gchar *action;
525         GtkWidget *text = NULL;
526         guint body_pos = 0;
527         ActionType action_type;
528         
529         g_return_if_fail(action_nb < g_slist_length(prefs_common.actions_list));
530
531         buf = (gchar *)g_slist_nth_data(prefs_common.actions_list, action_nb);
532
533         g_return_if_fail(buf);
534         g_return_if_fail((action = strstr(buf, ": ")));
535
536         /* Point to the beginning of the command-line */
537         action += 2;
538
539         textview = messageview_get_current_textview(msgview);
540         if (textview) {
541                 text     = textview->text;
542                 body_pos = textview->body_pos;
543         }
544         partinfo = messageview_get_selected_mime_part(msgview);
545
546         /* this command will alter the message text */
547         action_type = action_get_type(action);
548         if (action_type & (ACTION_PIPE_OUT | ACTION_INSERT))
549                 msgview->filtered = TRUE;
550
551         if (action_type & ACTION_FILTERING_ACTION) 
552                 /* CLAWS: most of the above code is not necessary for applying
553                  * filtering */
554                 execute_filtering_actions(action, msg_list);
555         else
556                 execute_actions(action, msg_list, text, body_pos, partinfo);
557 }
558
559 static gboolean execute_filtering_actions(gchar *action, GSList *msglist)
560 {
561         GSList *action_list, *p;
562         const gchar *sbegin, *send;
563         gchar *action_string;
564         
565         if (NULL == (sbegin = strstr2(action, "%as{")))
566                 return FALSE;
567         sbegin += sizeof "%as{" - 1;
568         if (NULL == (send = strrchr(sbegin, '}')))
569                 return FALSE;
570         action_string = g_strndup(sbegin, send - sbegin);
571         
572         action_list = matcher_parser_get_action_list(action_string);
573         g_free(action_string);
574         if (action_list == NULL) return FALSE;
575         
576         /* apply actions on each message info */
577         for (p = msglist; p && p->data; p = g_slist_next(p))
578                 filteringaction_apply_action_list(action_list, (MsgInfo *) p->data);
579                 
580         for (p = action_list; p; p = g_slist_next(p))
581                 if (p->data) filteringaction_free(p->data);     
582         g_slist_free(action_list);              
583         return TRUE;    
584 }
585
586 static gboolean execute_actions(gchar *action, GSList *msg_list,
587                                 GtkWidget *text,
588                                 gint body_pos, MimeInfo *partinfo)
589 {
590         GSList *children_list = NULL;
591         gint is_ok  = TRUE;
592         gint msg_list_len;
593         Children *children;
594         ChildInfo *child_info;
595         ActionType action_type;
596         MsgInfo *msginfo;
597         gchar *cmd;
598         gchar *sel_str = NULL;
599         gchar *msg_str = NULL;
600         gchar *user_str = NULL;
601         gchar *user_hidden_str = NULL;
602         GtkTextIter start_iter, end_iter;
603         gboolean is_selection = FALSE;
604
605         g_return_val_if_fail(action && *action, FALSE);
606
607         action_type = action_get_type(action);
608
609         if (action_type == ACTION_ERROR)
610                 return FALSE;         /* ERR: syntax error */
611
612         if (action_type & (ACTION_SINGLE | ACTION_MULTIPLE) && !msg_list)
613                 return FALSE;         /* ERR: file command without selection */
614
615         msg_list_len = g_slist_length(msg_list);
616
617         if (action_type & (ACTION_PIPE_OUT | ACTION_PIPE_IN | ACTION_INSERT)) {
618                 if (msg_list_len > 1)
619                         return FALSE; /* ERR: pipe + multiple selection */
620                 if (!text)
621                         return FALSE; /* ERR: pipe and no displayed text */
622         }
623
624         if (action_type & ACTION_SELECTION_STR) {
625                 if (!text)
626                         return FALSE; /* ERR: selection string but no text */
627         }
628
629         if (text) {
630                 GtkTextBuffer *textbuf;
631
632                 textbuf = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
633                 is_selection = gtk_text_buffer_get_selection_bounds(textbuf,
634                                                                     &start_iter,
635                                                                     &end_iter);
636                 if (!is_selection) {
637                         gtk_text_buffer_get_start_iter(textbuf, &start_iter);
638                         gtk_text_buffer_get_end_iter(textbuf, &end_iter);
639                 }
640                 msg_str = gtk_text_buffer_get_text(textbuf,
641                                                    &start_iter, &end_iter,
642                                                    FALSE);
643                 if (is_selection)
644                         sel_str = g_strdup (msg_str);
645         }
646
647         if (action_type & ACTION_USER_STR) {
648                 if (!(user_str = get_user_string(action, ACTION_USER_STR))) {
649                         g_free(msg_str);
650                         g_free(sel_str);
651                         return FALSE;
652                 }
653         }
654
655         if (action_type & ACTION_USER_HIDDEN_STR) {
656                 if (!(user_hidden_str =
657                         get_user_string(action, ACTION_USER_HIDDEN_STR))) {
658                         g_free(msg_str);
659                         g_free(sel_str);
660                         g_free(user_str);
661                         return FALSE;
662                 }
663         }
664
665         if (text && (action_type & ACTION_PIPE_OUT)) {
666                 GtkTextBuffer *textbuf;
667                 textbuf = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
668                 gtk_text_buffer_delete(textbuf, &start_iter, &end_iter);
669         }
670
671         children = g_new0(Children, 1);
672
673         children->action      = g_strdup(action);
674         children->action_type = action_type;
675         children->msg_text    = text;
676         children->is_selection = is_selection;
677
678         if ((action_type & (ACTION_USER_IN | ACTION_USER_HIDDEN_IN)) &&
679             ((action_type & ACTION_SINGLE) == 0 || msg_list_len == 1))
680                 children->open_in = 1;
681
682         if (action_type & ACTION_SINGLE) {
683                 GSList *cur;
684
685                 for (cur = msg_list; cur && is_ok == TRUE; cur = cur->next) {
686                         msginfo = (MsgInfo *)cur->data;
687                         if (!msginfo) {
688                                 is_ok  = FALSE; /* ERR: msginfo missing */
689                                 break;
690                         }
691                         cmd = parse_action_cmd(action, msginfo, msg_list,
692                                                partinfo, user_str,
693                                                user_hidden_str, sel_str);
694                         if (!cmd) {
695                                 debug_print("Action command error\n");
696                                 is_ok  = FALSE; /* ERR: incorrect command */
697                                 break;
698                         }
699                         if ((child_info = fork_child(cmd, msg_str, children))) {
700                                 children_list = g_slist_append(children_list,
701                                                                child_info);
702                         }
703                         g_free(cmd);
704                 }
705         } else {
706                 cmd = parse_action_cmd(action, NULL, msg_list, partinfo,
707                                        user_str, user_hidden_str, sel_str);
708                 if (cmd) {
709                         if ((child_info = fork_child(cmd, msg_str, children))) {
710                                 children_list = g_slist_append(children_list,
711                                                                child_info);
712                         }
713                         g_free(cmd);
714                 } else
715                         is_ok  = FALSE;         /* ERR: incorrect command */
716         }
717
718         g_free(msg_str);
719         g_free(sel_str);
720         g_free(user_str);
721         g_free(user_hidden_str);
722
723         if (!children_list) {
724                  /* If not waiting for children, return */
725                 free_children(children);
726         } else {
727                 GSList *cur;
728
729                 children->list        = children_list;
730                 children->nb          = g_slist_length(children_list);
731                 children->initial_nb  = children->nb;
732
733                 for (cur = children_list; cur; cur = cur->next) {
734                         child_info = (ChildInfo *) cur->data;
735                         child_info->tag_status = 
736                                 gdk_input_add(child_info->chld_status,
737                                               GDK_INPUT_READ,
738                                               catch_status, child_info);
739                 }
740
741                 create_io_dialog(children);
742         }
743
744         return is_ok;
745 }
746
747 static ChildInfo *fork_child(gchar *cmd, const gchar *msg_str,
748                              Children *children)
749 {
750         gint chld_in[2], chld_out[2], chld_err[2], chld_status[2];
751         gchar *cmdline[4];
752         pid_t pid, gch_pid;
753         ChildInfo *child_info;
754         gint sync;
755
756         sync = !(children->action_type & ACTION_ASYNC);
757
758         chld_in[0] = chld_in[1] = chld_out[0] = chld_out[1] = chld_err[0]
759                 = chld_err[1] = chld_status[0] = chld_status[1] = -1;
760
761         if (sync) {
762                 if (pipe(chld_status) || pipe(chld_in) || pipe(chld_out) ||
763                     pipe(chld_err)) {
764                         alertpanel_error(_("Command could not be started. "
765                                            "Pipe creation failed.\n%s"),
766                                         g_strerror(errno));
767                         /* Closing fd = -1 fails silently */
768                         close(chld_in[0]);
769                         close(chld_in[1]);
770                         close(chld_out[0]);
771                         close(chld_out[1]);
772                         close(chld_err[0]);
773                         close(chld_err[1]);
774                         close(chld_status[0]);
775                         close(chld_status[1]);
776                         return NULL; /* Pipe error */
777                 }
778         }
779
780         debug_print("Forking child and grandchild.\n");
781
782         pid = fork();
783         if (pid == 0) { /* Child */
784                 if (setpgid(0, 0))
785                         perror("setpgid");
786
787 #ifdef GDK_WINDOWING_X11
788                 close(ConnectionNumber(gdk_display));
789 #endif /* GDK_WINDOWING_X11 */
790
791                 gch_pid = fork();
792
793                 if (gch_pid == 0) {
794                         if (setpgid(0, getppid()))
795                                 perror("setpgid");
796
797                         if (sync) {
798                                 if (children->action_type &
799                                     (ACTION_PIPE_IN |
800                                      ACTION_USER_IN |
801                                      ACTION_USER_HIDDEN_IN)) {
802                                         close(fileno(stdin));
803                                         dup  (chld_in[0]);
804                                 }
805                                 close(chld_in[0]);
806                                 close(chld_in[1]);
807
808                                 close(fileno(stdout));
809                                 dup  (chld_out[1]);
810                                 close(chld_out[0]);
811                                 close(chld_out[1]);
812
813                                 close(fileno(stderr));
814                                 dup  (chld_err[1]);
815                                 close(chld_err[0]);
816                                 close(chld_err[1]);
817                         }
818
819                         cmdline[0] = "sh";
820                         cmdline[1] = "-c";
821                         cmdline[2] = cmd;
822                         cmdline[3] = 0;
823                         execvp("/bin/sh", cmdline);
824
825                         perror("execvp");
826                         _exit(1);
827                 } else if (gch_pid < (pid_t) 0) { /* Fork error */
828                         if (sync)
829                                 write(chld_status[1], "1\n", 2);
830                         perror("fork");
831                         _exit(1);
832                 } else { /* Child */
833                         if (sync) {
834                                 close(chld_in[0]);
835                                 close(chld_in[1]);
836                                 close(chld_out[0]);
837                                 close(chld_out[1]);
838                                 close(chld_err[0]);
839                                 close(chld_err[1]);
840                                 close(chld_status[0]);
841
842                                 debug_print("Child: Waiting for grandchild\n");
843                                 waitpid(gch_pid, NULL, 0);
844                                 debug_print("Child: grandchild ended\n");
845                                 write(chld_status[1], "0\n", 2);
846                                 close(chld_status[1]);
847                         }
848                         _exit(0);
849                 }
850         } else if (pid < 0) { /* Fork error */
851                 alertpanel_error(_("Could not fork to execute the following "
852                                    "command:\n%s\n%s"),
853                                  cmd, g_strerror(errno));
854                 return NULL; 
855         }
856
857         /* Parent */
858
859         if (!sync) {
860                 waitpid(pid, NULL, 0);
861                 return NULL;
862         }
863
864         close(chld_in[0]);
865         if (!(children->action_type &
866               (ACTION_PIPE_IN | ACTION_USER_IN | ACTION_USER_HIDDEN_IN)))
867                 close(chld_in[1]);
868         close(chld_out[1]);
869         close(chld_err[1]);
870         close(chld_status[1]);
871
872         child_info = g_new0(ChildInfo, 1);
873
874         child_info->children    = children;
875
876         child_info->pid         = pid;
877         child_info->cmd         = g_strdup(cmd);
878         child_info->new_out     = FALSE;
879         child_info->output      = g_string_new(NULL);
880         child_info->chld_in     =
881                 (children->action_type &
882                  (ACTION_PIPE_IN | ACTION_USER_IN | ACTION_USER_HIDDEN_IN))
883                         ? chld_in [1] : -1;
884         child_info->chld_out    = chld_out[0];
885         child_info->chld_err    = chld_err[0];
886         child_info->chld_status = chld_status[0];
887         child_info->tag_in      = -1;
888         child_info->tag_out     = gdk_input_add(chld_out[0], GDK_INPUT_READ,
889                                                 catch_output, child_info);
890         child_info->tag_err     = gdk_input_add(chld_err[0], GDK_INPUT_READ,
891                                                 catch_output, child_info);
892
893         if (!(children->action_type &
894               (ACTION_PIPE_IN | ACTION_PIPE_OUT | ACTION_INSERT)))
895                 return child_info;
896
897         if ((children->action_type & ACTION_PIPE_IN) && msg_str) {
898                 write(chld_in[1], msg_str, strlen(msg_str));
899                 if (!(children->action_type &
900                       (ACTION_USER_IN | ACTION_USER_HIDDEN_IN)))
901                         close(chld_in[1]);
902                 child_info->chld_in = -1; /* No more input */
903         }
904
905         return child_info;
906 }
907
908 static void kill_children_cb(GtkWidget *widget, gpointer data)
909 {
910         GSList *cur;
911         Children *children = (Children *) data;
912         ChildInfo *child_info;
913
914         for (cur = children->list; cur; cur = cur->next) {
915                 child_info = (ChildInfo *)(cur->data);
916                 debug_print("Killing child group id %d\n", child_info->pid);
917                 if (child_info->pid && kill(-child_info->pid, SIGTERM) < 0)
918                         perror("kill");
919         }
920 }
921
922 static gint wait_for_children(Children *children)
923 {
924         gboolean new_output;
925         ChildInfo *child_info;
926         GSList *cur;
927         gint nb = children->nb;
928
929         children->nb = 0;
930
931         cur = children->list;
932         new_output = FALSE;
933         while (cur) {
934                 child_info = (ChildInfo *)cur->data;
935                 if (child_info->pid)
936                         children->nb++;
937                 new_output |= child_info->new_out;
938                 cur = cur->next;
939         }
940
941         children->output |= new_output;
942
943         if (new_output || (children->dialog && (nb != children->nb)))
944                 update_io_dialog(children);
945
946         if (children->nb)
947                 return FALSE;
948
949         if (!children->dialog) {
950                 free_children(children);
951         } else if (!children->output) {
952                 gtk_widget_destroy(children->dialog);
953         }
954
955         return FALSE;
956 }
957
958 static void send_input(GtkWidget *w, gpointer data)
959 {
960         Children *children = (Children *) data;
961         ChildInfo *child_info = (ChildInfo *) children->list->data;
962
963         child_info->tag_in = gdk_input_add(child_info->chld_in,
964                                            GDK_INPUT_WRITE,
965                                            catch_input, children);
966         gtk_widget_set_sensitive(children->input_hbox, FALSE);
967 }
968
969 static gint delete_io_dialog_cb(GtkWidget *w, GdkEvent *e, gpointer data)
970 {
971         hide_io_dialog_cb(w, data);
972         return TRUE;
973 }
974
975 static void hide_io_dialog_cb(GtkWidget *w, gpointer data)
976 {
977
978         Children *children = (Children *)data;
979
980         if (!children->nb) {
981                 gtk_signal_disconnect_by_data(GTK_OBJECT(children->dialog),
982                                               children);
983                 gtk_widget_destroy(children->dialog);
984                 free_children(children);
985         }
986 }
987
988 static gint io_dialog_key_pressed_cb(GtkWidget *widget, GdkEventKey *event,
989                                      gpointer data)
990 {
991         if (event && event->keyval == GDK_Escape)
992                 hide_io_dialog_cb(widget, data);
993         return TRUE;
994 }
995
996 static void childinfo_close_pipes(ChildInfo *child_info)
997 {
998         /* stdout and stderr pipes are guaranteed to be removed by
999          * their handler, but in case where we receive child exit notification
1000          * before grand-child's pipes closing signals, we check them and close
1001          * them if necessary
1002          */
1003         if (child_info->tag_in > 0)
1004                 gdk_input_remove(child_info->tag_in);
1005         if (child_info->tag_out > 0)
1006                 gdk_input_remove(child_info->tag_out);
1007         if (child_info->tag_err > 0)
1008                 gdk_input_remove(child_info->tag_err);
1009
1010         if (child_info->chld_in >= 0)
1011                 close(child_info->chld_in);
1012         if (child_info->chld_out >= 0)
1013                 close(child_info->chld_out);
1014         if (child_info->chld_err >= 0)
1015                 close(child_info->chld_err);
1016
1017         close(child_info->chld_status);
1018 }
1019
1020 static void free_children(Children *children)
1021 {
1022         ChildInfo *child_info;
1023
1024         debug_print("Freeing children data %p\n", children);
1025
1026         g_free(children->action);
1027         while (children->list != NULL) {
1028                 child_info = (ChildInfo *)children->list->data;
1029                 g_free(child_info->cmd);
1030                 g_string_free(child_info->output, TRUE);
1031                 children->list = g_slist_remove(children->list, child_info);
1032                 g_free(child_info);
1033         }
1034         g_free(children);
1035 }
1036
1037 static void update_io_dialog(Children *children)
1038 {
1039         GSList *cur;
1040
1041         debug_print("Updating actions input/output dialog.\n");
1042
1043         if (children->progress_bar) {
1044                 gtk_progress_configure(GTK_PROGRESS(children->progress_bar),
1045                                 children->initial_nb -children->nb,
1046                                 0.0, children->initial_nb);
1047         }
1048
1049         if (!children->nb) {
1050                 gtk_widget_set_sensitive(children->abort_btn, FALSE);
1051                 gtk_widget_set_sensitive(children->close_btn, TRUE);
1052                 if (children->input_hbox)
1053                         gtk_widget_set_sensitive(children->input_hbox, FALSE);
1054                 gtk_widget_grab_focus(children->close_btn);
1055                 g_signal_connect(G_OBJECT(children->dialog),
1056                                  "key_press_event",
1057                                  G_CALLBACK(io_dialog_key_pressed_cb),
1058                                  children);
1059         }
1060
1061         if (children->output) {
1062                 GtkWidget *text = children->text;
1063                 gchar *caption;
1064                 ChildInfo *child_info;
1065                 GtkTextBuffer *textbuf;
1066                 GtkTextIter iter, start_iter, end_iter;
1067                 GdkFont *font;
1068
1069                 font = gtk_object_get_data(GTK_OBJECT(children->dialog), 
1070                                            "s_txtfont");
1071                 gtk_widget_show(children->scrolledwin);
1072                 textbuf = gtk_text_view_get_buffer (GTK_TEXT_VIEW(text));
1073                 gtk_text_buffer_get_start_iter (textbuf, &start_iter);
1074                 gtk_text_buffer_get_end_iter (textbuf, &end_iter);
1075                 iter = start_iter;
1076                 for (cur = children->list; cur; cur = cur->next) {
1077                         child_info = (ChildInfo *)cur->data;
1078                         if (child_info->pid)
1079                                 caption = g_strdup_printf
1080                                         (_("--- Running: %s\n"),
1081                                          child_info->cmd);
1082                         else
1083                                 caption = g_strdup_printf
1084                                         (_("--- Ended: %s\n"),
1085                                          child_info->cmd);
1086
1087                         gtk_text_buffer_insert(textbuf, &iter,
1088                                                caption, -1);
1089                         gtk_text_buffer_insert(textbuf, &iter,
1090                                                child_info->output->str, -1);
1091                         g_free(caption);
1092                         child_info->new_out = FALSE;
1093                 }
1094         }
1095 }
1096
1097 static void create_io_dialog(Children *children)
1098 {
1099         GtkWidget *dialog;
1100         GtkWidget *vbox;
1101         GtkWidget *entry = NULL;
1102         GtkWidget *input_hbox = NULL;
1103         GtkWidget *send_button;
1104         GtkWidget *label;
1105         GtkWidget *text;
1106         GtkWidget *scrolledwin;
1107         GtkWidget *hbox;
1108         GtkWidget *progress_bar = NULL;
1109         GtkWidget *abort_button;
1110         GtkWidget *close_button;
1111         GdkFont   *output_font;
1112
1113         debug_print("Creating action IO dialog\n");
1114
1115         dialog = gtk_dialog_new();
1116         gtk_container_set_border_width
1117                 (GTK_CONTAINER(GTK_DIALOG(dialog)->action_area), 5);
1118         gtk_window_set_position(GTK_WINDOW(dialog), GTK_WIN_POS_CENTER);
1119         gtk_window_set_title(GTK_WINDOW(dialog), _("Action's input/output"));
1120         gtk_window_set_modal(GTK_WINDOW(dialog), TRUE);
1121         manage_window_set_transient(GTK_WINDOW(dialog));
1122         g_signal_connect(G_OBJECT(dialog), "delete_event",
1123                          G_CALLBACK(delete_io_dialog_cb), children);
1124         g_signal_connect(G_OBJECT(dialog), "destroy",
1125                          G_CALLBACK(hide_io_dialog_cb),
1126                          children);
1127
1128         vbox = gtk_vbox_new(FALSE, 8);
1129         gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog)->vbox), vbox);
1130         gtk_container_set_border_width(GTK_CONTAINER(vbox), 8);
1131         gtk_widget_show(vbox);
1132
1133         label = gtk_label_new(children->action);
1134         gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 0);
1135         gtk_widget_show(label);
1136
1137         scrolledwin = gtk_scrolled_window_new(NULL, NULL);
1138         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledwin),
1139                                        GTK_POLICY_NEVER, GTK_POLICY_ALWAYS);
1140         gtk_box_pack_start(GTK_BOX(vbox), scrolledwin, TRUE, TRUE, 0);
1141         gtk_widget_set_size_request(scrolledwin, 480, 200);
1142         gtk_widget_hide(scrolledwin);
1143
1144         text = gtk_text_view_new();
1145         gtk_text_view_set_editable(GTK_TEXT_VIEW(text), FALSE);
1146         gtk_container_add(GTK_CONTAINER(scrolledwin), text);
1147         gtk_widget_show(text);
1148
1149         if (children->open_in) {
1150                 input_hbox = gtk_hbox_new(FALSE, 8);
1151                 gtk_widget_show(input_hbox);
1152
1153                 entry = gtk_entry_new();
1154                 gtk_widget_set_size_request(entry, 320, -1);
1155                 g_signal_connect(G_OBJECT(entry), "activate",
1156                                  G_CALLBACK(send_input), children);
1157                 gtk_box_pack_start(GTK_BOX(input_hbox), entry, TRUE, TRUE, 0);
1158                 if (children->action_type & ACTION_USER_HIDDEN_IN)
1159                         gtk_entry_set_visibility(GTK_ENTRY(entry), FALSE);
1160                 gtk_widget_show(entry);
1161
1162                 send_button = gtk_button_new_with_label(_(" Send "));
1163                 g_signal_connect(G_OBJECT(send_button), "clicked",
1164                                  G_CALLBACK(send_input), children);
1165                 gtk_box_pack_start(GTK_BOX(input_hbox), send_button, FALSE,
1166                                    FALSE, 0);
1167                 gtk_widget_show(send_button);
1168
1169                 gtk_box_pack_start(GTK_BOX(vbox), input_hbox, FALSE, FALSE, 0);
1170                 gtk_widget_grab_focus(entry);
1171         }
1172
1173         if (children->initial_nb > 1) {
1174                 progress_bar = gtk_progress_bar_new();
1175                 gtk_progress_bar_set_bar_style(GTK_PROGRESS_BAR(progress_bar),
1176                                 GTK_PROGRESS_CONTINUOUS);
1177                 gtk_progress_bar_set_orientation(GTK_PROGRESS_BAR(progress_bar),
1178                                 GTK_PROGRESS_LEFT_TO_RIGHT);
1179                 gtk_progress_set_activity_mode(GTK_PROGRESS(progress_bar), 
1180                                 FALSE);
1181                 gtk_progress_set_format_string(GTK_PROGRESS(progress_bar),
1182                                 _("Completed %v/%u"));
1183                 gtk_progress_set_show_text(GTK_PROGRESS(progress_bar), TRUE);
1184                 gtk_progress_configure(GTK_PROGRESS(progress_bar),
1185                                 children->initial_nb -children->nb,
1186                                 0.0, children->initial_nb);
1187
1188                 gtk_box_pack_start(GTK_BOX(vbox), progress_bar, FALSE, FALSE, 0);
1189                 gtk_widget_show(progress_bar);
1190         }
1191
1192         gtkut_button_set_create(&hbox, &abort_button, _("Abort"),
1193                                 &close_button, _("Close"), NULL, NULL);
1194         g_signal_connect(G_OBJECT(abort_button), "clicked",
1195                          G_CALLBACK(kill_children_cb), children);
1196         g_signal_connect(G_OBJECT(close_button), "clicked",
1197                          G_CALLBACK(hide_io_dialog_cb), children);
1198         gtk_widget_show(hbox);
1199
1200         if (children->nb)
1201                 gtk_widget_set_sensitive(close_button, FALSE);
1202
1203         gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog)->action_area), hbox);
1204
1205         children->dialog       = dialog;
1206         children->scrolledwin  = scrolledwin;
1207         children->text         = text;
1208         children->input_hbox   = children->open_in ? input_hbox : NULL;
1209         children->input_entry  = children->open_in ? entry : NULL;
1210         children->progress_bar = progress_bar;
1211         children->abort_btn    = abort_button;
1212         children->close_btn    = close_button;
1213
1214 #warning FIXME_GTK2 convert to Pango / FontDesc?
1215 #if 0
1216         output_font = gtkut_font_load_from_fontset(prefs_common.textfont);
1217         gtk_object_set_data_full(GTK_OBJECT(dialog), "s_txtfont",
1218                                  output_font, 
1219                                  (GtkDestroyNotify)gdk_font_unref); 
1220 #endif
1221         gtk_widget_show(dialog);
1222 }
1223
1224 static void catch_status(gpointer data, gint source, GdkInputCondition cond)
1225 {
1226         ChildInfo *child_info = (ChildInfo *)data;
1227         gchar buf;
1228         gint c;
1229
1230         gdk_input_remove(child_info->tag_status);
1231
1232         c = read(source, &buf, 1);
1233         debug_print("Child returned %c\n", buf);
1234
1235         waitpid(-child_info->pid, NULL, 0);
1236         childinfo_close_pipes(child_info);
1237         child_info->pid = 0;
1238
1239         wait_for_children(child_info->children);
1240 }
1241         
1242 static void catch_input(gpointer data, gint source, GdkInputCondition cond)
1243 {
1244         Children *children = (Children *)data;
1245         ChildInfo *child_info = (ChildInfo *)children->list->data;
1246         gchar *input;
1247         gint c, count, len;
1248
1249         debug_print("Sending input to grand child.\n");
1250         if (!(cond && GDK_INPUT_WRITE))
1251                 return;
1252
1253         gdk_input_remove(child_info->tag_in);
1254         child_info->tag_in = -1;
1255
1256         input = gtk_editable_get_chars(GTK_EDITABLE(children->input_entry),
1257                                        0, -1);
1258         len = strlen(input);
1259         count = 0;
1260
1261         do {
1262                 c = write(child_info->chld_in, input + count, len - count);
1263                 if (c >= 0)
1264                         count += c;
1265         } while (c >= 0 && count < len);
1266
1267         if (c >= 0)
1268                 write(child_info->chld_in, "\n", 2);
1269
1270         g_free(input);
1271
1272         gtk_entry_set_text(GTK_ENTRY(children->input_entry), "");
1273         gtk_widget_set_sensitive(children->input_hbox, TRUE);
1274         close(child_info->chld_in);
1275         child_info->chld_in = -1;
1276         debug_print("Input to grand child sent.\n");
1277 }
1278
1279 static void catch_output(gpointer data, gint source, GdkInputCondition cond)
1280 {
1281         ChildInfo *child_info = (ChildInfo *)data;
1282         gint c, i;
1283         gchar buf[BUFFSIZE];
1284
1285         debug_print("Catching grand child's output.\n");
1286         if (child_info->children->action_type &
1287             (ACTION_PIPE_OUT | ACTION_INSERT)
1288             && source == child_info->chld_out) {
1289                 GtkTextView *text = GTK_TEXT_VIEW(child_info->children->msg_text);
1290                 GtkTextBuffer *textbuf = gtk_text_view_get_buffer(text);
1291                 GtkTextIter iter1, iter2;
1292                 GtkTextMark *mark;
1293  
1294                 mark = gtk_text_buffer_get_insert(textbuf);
1295                 gtk_text_buffer_get_iter_at_mark(textbuf, &iter1, mark);
1296                 gtk_text_buffer_get_iter_at_mark(textbuf, &iter2, mark);
1297
1298                 while (TRUE) {
1299                         c = read(source, buf, sizeof(buf) - 1);
1300                         if (c == 0)
1301                                 break;
1302                         gtk_text_buffer_insert(textbuf, &iter2, buf, c);
1303                 }
1304                 if (child_info->children->is_selection) {
1305                         gtk_text_buffer_place_cursor(textbuf, &iter1);
1306                         gtk_text_buffer_move_mark_by_name
1307                                 (textbuf, "selection_bound", &iter2);
1308                 }
1309         } else {
1310                 c = read(source, buf, sizeof(buf) - 1);
1311                 for (i = 0; i < c; i++)
1312                         g_string_append_c(child_info->output, buf[i]);
1313                 if (c > 0)
1314                         child_info->new_out = TRUE;
1315         }
1316         if (c == 0) {
1317                 if (source == child_info->chld_out) {
1318                         gdk_input_remove(child_info->tag_out);
1319                         child_info->tag_out = -1;
1320                         close(child_info->chld_out);
1321                         child_info->chld_out = -1;
1322                 } else {
1323                         gdk_input_remove(child_info->tag_err);
1324                         child_info->tag_err = -1;
1325                         close(child_info->chld_err);
1326                         child_info->chld_err = -1;
1327                 }
1328         }
1329         
1330         wait_for_children(child_info->children);
1331 }
1332
1333 static gchar *get_user_string(const gchar *action, ActionType type)
1334 {
1335         gchar *message;
1336         gchar *user_str = NULL;
1337
1338         switch (type) {
1339         case ACTION_USER_HIDDEN_STR:
1340                 message = g_strdup_printf
1341                         (_("Enter the argument for the following action:\n"
1342                            "(`%%h' will be replaced with the argument)\n"
1343                            "  %s"),
1344                          action);
1345                 user_str = input_dialog_with_invisible
1346                         (_("Action's hidden user argument"), message, NULL);
1347                 break;
1348         case ACTION_USER_STR:
1349                 message = g_strdup_printf
1350                         (_("Enter the argument for the following action:\n"
1351                            "(`%%u' will be replaced with the argument)\n"
1352                            "  %s"),
1353                          action);
1354                 user_str = input_dialog
1355                         (_("Action's user argument"), message, NULL);
1356                 break;
1357         default:
1358                 g_warning("Unsupported action type %d", type);
1359         }
1360
1361         return user_str;
1362 }