0.8.7claws8
[claws.git] / src / prefs_actions.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2002 Hiroyuki Yamamoto
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #include "defs.h"
25
26 #include <glib.h>
27 #include <gtk/gtk.h>
28 #include <gdk/gdkkeysyms.h>
29 #include <gdk/gdkx.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <errno.h>
34 #include <sys/types.h>
35 #include <sys/wait.h>
36 #include <signal.h>
37 #include <unistd.h>
38
39 #include "intl.h"
40 #include "prefs_gtk.h"
41 #include "inc.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 "prefs_actions.h"
49 #include "compose.h"
50 #include "procmsg.h"
51 #include "gtkstext.h"
52 #include "mimeview.h"
53 #include "textview.h"
54
55 typedef enum
56 {
57         ACTION_NONE     = 1 << 0,
58         ACTION_PIPE_IN  = 1 << 1,
59         ACTION_PIPE_OUT = 1 << 2,
60         ACTION_SINGLE   = 1 << 3,
61         ACTION_MULTIPLE = 1 << 4,
62         ACTION_ASYNC    = 1 << 5,
63         ACTION_OPEN_IN  = 1 << 6,
64         ACTION_HIDE_IN  = 1 << 7,
65         ACTION_INSERT   = 1 << 8,
66         ACTION_ERROR    = 1 << 9,
67 } ActionType;
68
69 static struct Actions
70 {
71         GtkWidget *window;
72
73         GtkWidget *ok_btn;
74
75         GtkWidget *name_entry;
76         GtkWidget *cmd_entry;
77
78         GtkWidget *actions_clist;
79 } actions;
80
81 typedef struct _Children Children;
82 typedef struct _ChildInfo ChildInfo;
83
84 struct _Children
85 {
86         GtkWidget       *window;
87         GtkWidget       *dialog;
88         GtkWidget       *text;
89         GtkWidget       *input_entry;
90         GtkWidget       *input_hbox;
91         GtkWidget       *abort_btn;
92         GtkWidget       *close_btn;
93         GtkWidget       *scrolledwin;
94
95         gchar           *action;
96         GSList          *list;
97         gint             nb;
98         gint             open_in;
99         gboolean         output;
100 };
101
102 struct _ChildInfo
103 {
104         Children        *children;
105         gchar           *cmd;
106         guint            type;
107         pid_t            pid;
108         gint             chld_in;
109         gint             chld_out;
110         gint             chld_err;
111         gint             chld_status;
112         gint             tag_in;
113         gint             tag_out;
114         gint             tag_err;
115         gint             tag_status;
116         gint             new_out;
117         GString         *output;
118         GtkWidget       *text;
119         GdkFont         *msgfont;
120 };
121
122 /* widget creating functions */
123 static void prefs_actions_create        (MainWindow *mainwin);
124 static void prefs_actions_set_dialog    (void);
125 static gint prefs_actions_clist_set_row (gint row);
126
127 /* callback functions */
128 static void prefs_actions_help_cb       (GtkWidget      *w,
129                                          gpointer        data);
130 static void prefs_actions_register_cb   (GtkWidget      *w,
131                                          gpointer        data);
132 static void prefs_actions_substitute_cb (GtkWidget      *w,
133                                          gpointer        data);
134 static void prefs_actions_delete_cb     (GtkWidget      *w,
135                                          gpointer        data);
136 static void prefs_actions_up            (GtkWidget      *w,
137                                          gpointer        data);
138 static void prefs_actions_down          (GtkWidget      *w,
139                                          gpointer        data);
140 static void prefs_actions_select        (GtkCList       *clist,
141                                          gint            row,
142                                          gint            column,
143                                          GdkEvent       *event);
144 static void prefs_actions_row_move      (GtkCList       *clist,
145                                          gint            source_row,
146                                          gint            dest_row);
147 static gint prefs_actions_deleted       (GtkWidget      *widget,
148                                          GdkEventAny    *event,
149                                          gpointer       *data);
150 static void prefs_actions_key_pressed   (GtkWidget      *widget,
151                                          GdkEventKey    *event,
152                                          gpointer        data);
153 static void prefs_actions_cancel        (GtkWidget      *w,
154                                          gpointer        data);
155 static void prefs_actions_ok            (GtkWidget      *w,
156                                          gpointer        data);
157 static void update_actions_menu         (GtkItemFactory *ifactory,
158                                          gchar          *branch_path,
159                                          gpointer        callback,
160                                          gpointer        data);
161 static void mainwin_actions_execute_cb  (MainWindow     *mainwin,
162                                          guint           action_nb,
163                                          GtkWidget      *widget);
164 static void compose_actions_execute_cb  (Compose        *compose,
165                                          guint           action_nb,
166                                          GtkWidget      *widget);
167 static guint get_action_type            (gchar          *action);
168
169 static gboolean execute_actions         (gchar          *action, 
170                                          GtkWidget      *window,
171                                          GtkCTree       *ctree, 
172                                          GtkWidget      *text,
173                                          GdkFont        *msgfont,
174                                          gint            body_pos,
175                                          MimeView       *mimeview);
176
177 static gchar *parse_action_cmd          (gchar          *action,
178                                          MsgInfo        *msginfo,
179                                          GtkCTree       *ctree,
180                                          MimeView       *mimeview);
181 static gboolean parse_append_filename   (GString        **cmd,
182                                          MsgInfo        *msginfo);
183
184 static gboolean parse_append_msgpart    (GString        **cmd,
185                                          MsgInfo        *msginfo,
186                                          MimeView       *mimeview);
187
188 ChildInfo *fork_child                   (gchar          *cmd,
189                                          gint            action_type,
190                                          GtkWidget      *text,
191                                          GdkFont        *msgfont,
192                                          gint            body_pos,
193                                          Children       *children);
194
195 static gint wait_for_children           (gpointer        data);
196
197 static void free_children               (Children       *children);
198
199 static void childinfo_close_pipes       (ChildInfo      *child_info);
200
201 static void create_io_dialog            (Children       *children);
202 static void update_io_dialog            (Children       *children);
203
204 static void hide_io_dialog_cb           (GtkWidget      *widget,
205                                          gpointer        data);
206
207 static void catch_output                (gpointer                data,
208                                          gint                    source,
209                                          GdkInputCondition       cond);
210 static void catch_input                 (gpointer                data, 
211                                          gint                    source,
212                                          GdkInputCondition       cond);
213 static void catch_status                (gpointer                data,
214                                          gint                    source,
215                                          GdkInputCondition       cond);
216
217 void prefs_actions_open(MainWindow *mainwin)
218 {
219 #if 0
220         if (prefs_rc_is_readonly(ACTIONS_RC))
221                 return;
222 #endif
223         inc_lock();
224
225         if (!actions.window)
226                 prefs_actions_create(mainwin);
227
228         manage_window_set_transient(GTK_WINDOW(actions.window));
229         gtk_widget_grab_focus(actions.ok_btn);
230
231         prefs_actions_set_dialog();
232
233         gtk_widget_show(actions.window);
234 }
235
236 static void prefs_actions_create(MainWindow *mainwin)
237 {
238         GtkWidget *window;
239         GtkWidget *vbox;
240         GtkWidget *ok_btn;
241         GtkWidget *cancel_btn;
242         GtkWidget *confirm_area;
243
244         GtkWidget *vbox1;
245
246         GtkWidget *entry_vbox;
247         GtkWidget *hbox;
248         GtkWidget *name_label;
249         GtkWidget *name_entry;
250         GtkWidget *cmd_label;
251         GtkWidget *cmd_entry;
252
253         GtkWidget *reg_hbox;
254         GtkWidget *btn_hbox;
255         GtkWidget *arrow;
256         GtkWidget *reg_btn;
257         GtkWidget *subst_btn;
258         GtkWidget *del_btn;
259
260         GtkWidget *cond_hbox;
261         GtkWidget *cond_scrolledwin;
262         GtkWidget *cond_clist;
263
264         GtkWidget *help_vbox;
265         GtkWidget *help_label;
266         GtkWidget *help_toggle;
267
268         GtkWidget *btn_vbox;
269         GtkWidget *up_btn;
270         GtkWidget *down_btn;
271
272         gchar *title[1];
273
274         debug_print("Creating actions configuration window...\n");
275
276         window = gtk_window_new (GTK_WINDOW_DIALOG);
277
278         gtk_container_set_border_width(GTK_CONTAINER (window), 8);
279         gtk_window_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
280         gtk_window_set_modal(GTK_WINDOW(window), TRUE);
281         gtk_window_set_policy(GTK_WINDOW(window), FALSE, TRUE, TRUE);
282         gtk_window_set_default_size(GTK_WINDOW(window), 400, -1);
283
284         vbox = gtk_vbox_new(FALSE, 6);
285         gtk_widget_show(vbox);
286         gtk_container_add(GTK_CONTAINER(window), vbox);
287
288         gtkut_button_set_create(&confirm_area, &ok_btn, _("OK"),
289                                 &cancel_btn, _("Cancel"), NULL, NULL);
290         gtk_widget_show(confirm_area);
291         gtk_box_pack_end(GTK_BOX(vbox), confirm_area, FALSE, FALSE, 0);
292         gtk_widget_grab_default(ok_btn);
293
294         gtk_window_set_title(GTK_WINDOW(window), _("Actions configuration"));
295         gtk_signal_connect(GTK_OBJECT(window), "delete_event",
296                            GTK_SIGNAL_FUNC(prefs_actions_deleted), NULL);
297         gtk_signal_connect(GTK_OBJECT(window), "key_press_event",
298                            GTK_SIGNAL_FUNC(prefs_actions_key_pressed), NULL);
299         MANAGE_WINDOW_SIGNALS_CONNECT(window);
300         gtk_signal_connect(GTK_OBJECT(ok_btn), "clicked",
301                            GTK_SIGNAL_FUNC(prefs_actions_ok), mainwin);
302         gtk_signal_connect(GTK_OBJECT(cancel_btn), "clicked",
303                            GTK_SIGNAL_FUNC(prefs_actions_cancel), NULL);
304
305         vbox1 = gtk_vbox_new(FALSE, 8);
306         gtk_widget_show(vbox1);
307         gtk_box_pack_start(GTK_BOX(vbox), vbox1, TRUE, TRUE, 0);
308         gtk_container_set_border_width(GTK_CONTAINER(vbox1), 2);
309
310         entry_vbox = gtk_vbox_new(FALSE, 4);
311         gtk_box_pack_start(GTK_BOX(vbox1), entry_vbox, FALSE, FALSE, 0);
312
313         hbox = gtk_hbox_new(FALSE, 8);
314         gtk_box_pack_start(GTK_BOX(entry_vbox), hbox, FALSE, FALSE, 0);
315
316         name_label = gtk_label_new(_("Menu name:"));
317         gtk_box_pack_start(GTK_BOX(hbox), name_label, FALSE, FALSE, 0);
318
319         name_entry = gtk_entry_new();
320         gtk_box_pack_start(GTK_BOX(hbox), name_entry, TRUE, TRUE, 0);
321
322         hbox = gtk_hbox_new(FALSE, 8);
323         gtk_box_pack_start(GTK_BOX(entry_vbox), hbox, TRUE, TRUE, 0);
324
325         cmd_label = gtk_label_new(_("Command line:"));
326         gtk_box_pack_start(GTK_BOX(hbox), cmd_label, FALSE, FALSE, 0);
327
328         cmd_entry = gtk_entry_new();
329         gtk_box_pack_start(GTK_BOX(hbox), cmd_entry, TRUE, TRUE, 0);
330
331         gtk_widget_show_all(entry_vbox);
332
333         help_vbox = gtk_vbox_new(FALSE, 8);
334         gtk_box_pack_start(GTK_BOX(vbox1), help_vbox, FALSE, FALSE, 0);
335
336         help_label = gtk_label_new
337                 (_("Menu name:\n"
338                    " Use / in menu name to make submenus.\n"
339                    "Command line:\n"
340                    " Begin with:\n"
341                    "   | to send message body or selection to command\n"
342                    "   > to send user provided text to command\n"
343                    "   * to send user provided hidden text to command\n"
344                    " End with:\n"
345                    "   | to replace message body or selection with command output\n"
346                    "   > to insert command's output without replacing old text\n"
347                    "   & to run command asynchronously\n"
348                    " Use %f for message file name\n"
349                    "   %F for the list of the file names of selected messages\n"
350                    "   %p for the selected message MIME part."));
351         gtk_misc_set_alignment(GTK_MISC(help_label), 0, 0.5);
352         gtk_label_set_justify(GTK_LABEL(help_label), GTK_JUSTIFY_LEFT);
353         gtk_widget_show(help_label);
354         gtk_box_pack_start(GTK_BOX(help_vbox), help_label, FALSE, FALSE, 0);
355         gtk_widget_hide(help_vbox);
356
357         /* register / substitute / delete */
358
359         reg_hbox = gtk_hbox_new(FALSE, 4);
360         gtk_widget_show(reg_hbox);
361         gtk_box_pack_start(GTK_BOX(vbox1), reg_hbox, FALSE, FALSE, 0);
362
363         arrow = gtk_arrow_new(GTK_ARROW_DOWN, GTK_SHADOW_OUT);
364         gtk_widget_show(arrow);
365         gtk_box_pack_start(GTK_BOX(reg_hbox), arrow, FALSE, FALSE, 0);
366         gtk_widget_set_usize(arrow, -1, 16);
367
368         btn_hbox = gtk_hbox_new(TRUE, 4);
369         gtk_widget_show(btn_hbox);
370         gtk_box_pack_start(GTK_BOX(reg_hbox), btn_hbox, FALSE, FALSE, 0);
371
372         reg_btn = gtk_button_new_with_label(_("Add"));
373         gtk_widget_show(reg_btn);
374         gtk_box_pack_start(GTK_BOX(btn_hbox), reg_btn, FALSE, TRUE, 0);
375         gtk_signal_connect(GTK_OBJECT(reg_btn), "clicked",
376                            GTK_SIGNAL_FUNC(prefs_actions_register_cb), NULL);
377
378         subst_btn = gtk_button_new_with_label(_("  Replace  "));
379         gtk_widget_show(subst_btn);
380         gtk_box_pack_start(GTK_BOX(btn_hbox), subst_btn, FALSE, TRUE, 0);
381         gtk_signal_connect(GTK_OBJECT(subst_btn), "clicked",
382                            GTK_SIGNAL_FUNC(prefs_actions_substitute_cb),
383                            NULL);
384
385         del_btn = gtk_button_new_with_label(_("Delete"));
386         gtk_widget_show(del_btn);
387         gtk_box_pack_start(GTK_BOX(btn_hbox), del_btn, FALSE, TRUE, 0);
388         gtk_signal_connect(GTK_OBJECT(del_btn), "clicked",
389                            GTK_SIGNAL_FUNC(prefs_actions_delete_cb), NULL);
390
391         help_toggle = gtk_toggle_button_new_with_label(_(" Syntax help "));
392         gtk_widget_show(help_toggle);
393         gtk_box_pack_end(GTK_BOX(reg_hbox), help_toggle, FALSE, FALSE, 0);
394         gtk_signal_connect(GTK_OBJECT(help_toggle), "toggled",
395                            GTK_SIGNAL_FUNC(prefs_actions_help_cb), help_vbox);
396
397         cond_hbox = gtk_hbox_new(FALSE, 8);
398         gtk_widget_show(cond_hbox);
399         gtk_box_pack_start(GTK_BOX(vbox1), cond_hbox, TRUE, TRUE, 0);
400
401         cond_scrolledwin = gtk_scrolled_window_new(NULL, NULL);
402         gtk_widget_show(cond_scrolledwin);
403         gtk_widget_set_usize(cond_scrolledwin, -1, 150);
404         gtk_box_pack_start(GTK_BOX(cond_hbox), cond_scrolledwin,
405                            TRUE, TRUE, 0);
406         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW (cond_scrolledwin),
407                                        GTK_POLICY_AUTOMATIC,
408                                        GTK_POLICY_AUTOMATIC);
409
410         title[0] = _("Current actions");
411         cond_clist = gtk_clist_new_with_titles(1, title);
412         gtk_widget_show(cond_clist);
413         gtk_container_add(GTK_CONTAINER (cond_scrolledwin), cond_clist);
414         gtk_clist_set_column_width(GTK_CLIST (cond_clist), 0, 80);
415         gtk_clist_set_selection_mode(GTK_CLIST (cond_clist),
416                                      GTK_SELECTION_BROWSE);
417         GTK_WIDGET_UNSET_FLAGS(GTK_CLIST(cond_clist)->column[0].button,
418                                GTK_CAN_FOCUS);
419         gtk_signal_connect(GTK_OBJECT(cond_clist), "select_row",
420                            GTK_SIGNAL_FUNC(prefs_actions_select), NULL);
421         gtk_signal_connect_after(GTK_OBJECT(cond_clist), "row_move",
422                                  GTK_SIGNAL_FUNC(prefs_actions_row_move),
423                                  NULL);
424
425         btn_vbox = gtk_vbox_new(FALSE, 8);
426         gtk_widget_show(btn_vbox);
427         gtk_box_pack_start(GTK_BOX(cond_hbox), btn_vbox, FALSE, FALSE, 0);
428
429         up_btn = gtk_button_new_with_label(_("Up"));
430         gtk_widget_show(up_btn);
431         gtk_box_pack_start(GTK_BOX(btn_vbox), up_btn, FALSE, FALSE, 0);
432         gtk_signal_connect(GTK_OBJECT(up_btn), "clicked",
433                            GTK_SIGNAL_FUNC(prefs_actions_up), NULL);
434
435         down_btn = gtk_button_new_with_label(_("Down"));
436         gtk_widget_show(down_btn);
437         gtk_box_pack_start(GTK_BOX(btn_vbox), down_btn, FALSE, FALSE, 0);
438         gtk_signal_connect(GTK_OBJECT(down_btn), "clicked",
439                            GTK_SIGNAL_FUNC(prefs_actions_down), NULL);
440
441         gtk_widget_show(window);
442
443         actions.window = window;
444         actions.ok_btn = ok_btn;
445
446         actions.name_entry = name_entry;
447         actions.cmd_entry  = cmd_entry;
448
449         actions.actions_clist = cond_clist;
450 }
451
452 static void prefs_actions_help_cb(GtkWidget *w, gpointer data)
453 {
454         if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(w)))
455                 gtk_widget_show(GTK_WIDGET(data));
456         else
457                 gtk_widget_hide(GTK_WIDGET(data));
458 }
459
460 void prefs_actions_read_config(void)
461 {
462         gchar *rcpath;
463         FILE *fp;
464         gchar buf[PREFSBUFSIZE];
465         gchar *act;
466
467         debug_print("Reading actions configurations...\n");
468
469         rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, ACTIONS_RC, NULL);
470         if ((fp = fopen(rcpath, "rb")) == NULL) {
471                 if (ENOENT != errno) FILE_OP_ERROR(rcpath, "fopen");
472                 g_free(rcpath);
473                 return;
474         }
475         g_free(rcpath);
476
477         while (prefs_common.actions_list != NULL) {
478                 act = (gchar *)prefs_common.actions_list->data;
479                 prefs_common.actions_list =
480                         g_slist_remove(prefs_common.actions_list, act);
481                 g_free(act);
482         }
483
484         while (fgets(buf, sizeof(buf), fp) != NULL) {
485                 g_strchomp(buf);
486                 act = strstr(buf, ": ");
487                 if (act && act[2] && 
488                     get_action_type(&act[2]) != ACTION_ERROR)
489                         prefs_common.actions_list =
490                                 g_slist_append(prefs_common.actions_list,
491                                                g_strdup(buf));
492         }
493         fclose(fp);
494 }
495
496 void prefs_actions_write_config(void)
497 {
498         gchar *rcpath;
499         PrefFile *pfile;
500         GSList *cur;
501
502         debug_print("Writing actions configuration...\n");
503
504         rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, ACTIONS_RC, NULL);
505         if ((pfile= prefs_write_open(rcpath)) == NULL) {
506                 g_warning("failed to write configuration to file\n");
507                 g_free(rcpath);
508                 return;
509         }
510
511         for (cur = prefs_common.actions_list; cur != NULL; cur = cur->next) {
512                 gchar *act = (gchar *)cur->data;
513                 if (fputs(act, pfile->fp) == EOF ||
514                     fputc('\n', pfile->fp) == EOF) {
515                         FILE_OP_ERROR(rcpath, "fputs || fputc");
516                         prefs_write_close_revert(pfile);
517                         g_free(rcpath);
518                         return;
519                 }
520         }
521         
522         g_free(rcpath);
523
524         if (prefs_write_close(pfile) < 0) {
525                 g_warning("failed to write configuration to file\n");
526                 return;
527         }
528 }
529
530 static guint get_action_type(gchar *action)
531 {
532         gchar *p;
533         guint action_type = ACTION_NONE;
534
535         g_return_val_if_fail(action,  ACTION_ERROR);
536         g_return_val_if_fail(*action, ACTION_ERROR);
537
538         p = action;
539
540         if (p[0] == '|') {
541                 action_type |= ACTION_PIPE_IN;
542                 p++;
543         } else if (p[0] == '>') {
544                 action_type |= ACTION_OPEN_IN;
545                 p++;
546         } else if (p[0] == '*') {
547                 action_type |= ACTION_HIDE_IN;
548                 p++;
549         }
550
551         if (p[0] == 0x00)
552                 return ACTION_ERROR;
553
554         while (*p && action_type != ACTION_ERROR) {
555                 if (p[0] == '%') {
556                         switch (p[1]) {
557                         case 'f':
558                                 action_type |= ACTION_SINGLE;
559                                 break;
560                         case 'F':
561                                 action_type |= ACTION_MULTIPLE;
562                                 break;
563                         case 'p':
564                                 action_type |= ACTION_SINGLE;
565                                 break;
566                         default:
567                                 action_type = ACTION_ERROR;
568                                 break;
569                         }
570                 } else if (p[0] == '|') {
571                         if (p[1] == 0x00)
572                                 action_type |= ACTION_PIPE_OUT;
573                 } else if (p[0] == '>') {
574                         if (p[1] == 0x00)
575                                 action_type |= ACTION_INSERT;
576                 } else if (p[0] == '&') {
577                         if (p[1] == 0x00)
578                                 action_type |= ACTION_ASYNC;
579                         else
580                                 action_type = ACTION_ERROR;
581                 }
582                 p++;
583         }
584
585         return action_type;
586 }
587
588 static gchar *parse_action_cmd(gchar *action, MsgInfo *msginfo,
589                                GtkCTree *ctree, MimeView *mimeview)
590 {
591         GString *cmd;
592         gchar *p;
593         GList *cur;
594         MsgInfo *msg;
595         
596         p = action;
597         
598         if (p[0] == '|' || p[0] == '>' || p[0] == '*')
599                 p++;
600
601         cmd = g_string_sized_new(strlen(action));
602
603         while (p[0] &&
604                !((p[0] == '|' || p[0] == '>' || p[0] == '&') && !p[1])) {
605                 if (p[0] == '%' && p[1]) {
606                         switch (p[1]) {
607                         case 'f':
608                                 if (!parse_append_filename(&cmd, msginfo)) {
609                                         g_string_free(cmd, TRUE);
610                                         return NULL;
611                                 }
612                                 p++;
613                                 break;
614                         case 'F':
615                                 for (cur = GTK_CLIST(ctree)->selection;
616                                      cur != NULL; cur = cur->next) {
617                                         msg = gtk_ctree_node_get_row_data(ctree,
618                                               GTK_CTREE_NODE(cur->data));
619                                         if (!parse_append_filename(&cmd, msg)) {
620                                                 g_string_free(cmd, TRUE);
621                                                 return NULL;
622                                         }
623                                         if (cur->next)
624                                                 cmd = g_string_append_c(cmd, ' ');
625                                 }
626                                 p++;
627                                 break;
628                         case 'p':
629                                 if (!parse_append_msgpart(&cmd, msginfo,
630                                                           mimeview)) {
631                                         g_string_free(cmd, TRUE);
632                                         return NULL;
633                                 }
634                                 p++;
635                                 break;
636                         default:
637                                 cmd = g_string_append_c(cmd, p[0]);
638                                 cmd = g_string_append_c(cmd, p[1]);
639                                 p++;
640                         }
641                 } else {
642                         cmd = g_string_append_c(cmd, p[0]);
643                 }
644                 p++;
645         }
646         if (cmd->len == 0) {
647                 g_string_free(cmd, TRUE);
648                 return NULL;
649         }
650
651         p = cmd->str;
652         g_string_free(cmd, FALSE);
653         return p;
654 }
655
656 static gboolean parse_append_filename(GString **cmd, MsgInfo *msginfo)
657 {
658         gchar *filename;
659
660         g_return_val_if_fail(msginfo, FALSE);
661
662         filename = procmsg_get_message_file(msginfo);
663
664         if (filename) {
665                 *cmd = g_string_append(*cmd, filename);
666                 g_free(filename);
667         } else {
668                 alertpanel_error(_("Could not get message file %d"),
669                                 msginfo->msgnum);
670                 return FALSE;
671         }
672
673         return TRUE;
674 }
675
676 static gboolean parse_append_msgpart(GString **cmd, MsgInfo *msginfo,
677                                      MimeView *mimeview)
678 {
679         gchar    *filename;
680         gchar    *partname;
681         MimeInfo *partinfo;
682         gint      ret;
683         FILE     *fp;
684
685         if (!mimeview) {
686 #if USE_GPGME
687                 if ((fp = procmsg_open_message_decrypted(msginfo, &partinfo))
688                     == NULL) {
689                         alertpanel_error(_("Could not get message file."));
690                         return FALSE;
691                 }
692 #else
693                 if ((fp = procmsg_open_message(msginfo)) == NULL) {
694                         alertpanel_error(_("Could not get message file."));
695                         return FALSE;
696                 }
697                 partinfo = procmime_scan_mime_header(fp);
698 #endif
699                 fclose(fp);
700                 if (!partinfo) {
701                         procmime_mimeinfo_free_all(partinfo);
702                         alertpanel_error(_("Could not get message part."));
703                         return FALSE;
704                 }
705                 filename = procmsg_get_message_file(msginfo);
706         } else {
707                 if (!mimeview->opened) {
708                         alertpanel_error(_("No message part selected."));
709                         return FALSE;
710                 }
711                 if (!mimeview->file) {
712                         alertpanel_error(_("No message file selected."));
713                         return FALSE;
714                 }
715                 partinfo = gtk_ctree_node_get_row_data
716                                 (GTK_CTREE(mimeview->ctree),
717                                  mimeview->opened);
718                 g_return_val_if_fail(partinfo != NULL, FALSE);
719                 filename = mimeview->file;
720         }
721         partname = procmime_get_tmp_file_name(partinfo);
722
723         ret = procmime_get_part(partname, filename, partinfo); 
724
725         if (!mimeview) {
726                 procmime_mimeinfo_free_all(partinfo);
727                 g_free(filename);
728         }
729
730         if (ret < 0) {
731                 alertpanel_error(_("Can't get part of multipart message"));
732                 g_free(partname);
733                 return FALSE;
734         }
735
736         *cmd = g_string_append(*cmd, partname);
737
738         g_free(partname);
739
740         return TRUE;
741 }
742
743 static void prefs_actions_set_dialog(void)
744 {
745         GtkCList *clist = GTK_CLIST(actions.actions_clist);
746         GSList *cur;
747         gchar *action_str[1];
748         gint row;
749
750         gtk_clist_freeze(clist);
751         gtk_clist_clear(clist);
752
753         action_str[0] = _("(New)");
754         row = gtk_clist_append(clist, action_str);
755         gtk_clist_set_row_data(clist, row, NULL);
756
757         for (cur = prefs_common.actions_list; cur != NULL; cur = cur->next) {
758                 gchar *action[1];
759
760                 action[0] = (gchar *)cur->data;
761                 row = gtk_clist_append(clist, action);
762                 gtk_clist_set_row_data(clist, row, action[0]);
763         }
764
765         gtk_clist_thaw(clist);
766 }
767
768 static void prefs_actions_set_list(void)
769 {
770         gint row = 1;
771         gchar *action;
772
773         g_slist_free(prefs_common.actions_list);
774         prefs_common.actions_list = NULL;
775
776         while ((action = (gchar *)gtk_clist_get_row_data
777                 (GTK_CLIST(actions.actions_clist), row)) != NULL) {
778                 prefs_common.actions_list =
779                         g_slist_append(prefs_common.actions_list, action);
780                 row++;
781         }
782 }
783
784 #define GET_ENTRY(entry) \
785         entry_text = gtk_entry_get_text(GTK_ENTRY(entry))
786
787 static gint prefs_actions_clist_set_row(gint row)
788 {
789         GtkCList *clist = GTK_CLIST(actions.actions_clist);
790         gchar *entry_text;
791         gint len;
792         gchar action[PREFSBUFSIZE];
793         gchar *buf[1];
794
795         g_return_val_if_fail(row != 0, -1);
796
797         GET_ENTRY(actions.name_entry);
798         if (entry_text[0] == '\0') {
799                 alertpanel_error(_("Menu name is not set."));
800                 return -1;
801         }
802
803         if (strchr(entry_text, ':')) {
804                 alertpanel_error(_("Colon ':' is not allowed in the menu name."));
805                 return -1;
806         }
807
808         strncpy(action, entry_text, PREFSBUFSIZE - 1);
809         g_strstrip(action);
810
811         /* Keep space for the ': ' delimiter */
812         len = strlen(action) + 2;
813         if (len >= PREFSBUFSIZE - 1) {
814                 alertpanel_error(_("Menu name is too long."));
815                 return -1;
816         }
817
818         strcat(action, ": ");
819
820         GET_ENTRY(actions.cmd_entry);
821
822         if (entry_text[0] == '\0') {
823                 alertpanel_error(_("Command line not set."));
824                 return -1;
825         }
826
827         if (len + strlen(entry_text) >= PREFSBUFSIZE - 1) {
828                 alertpanel_error(_("Menu name and command are too long."));
829                 return -1;
830         }
831
832         if (get_action_type(entry_text) == ACTION_ERROR) {
833                 alertpanel_error(_("The command\n%s\nhas a syntax error."), 
834                                  entry_text);
835                 return -1;
836         }
837
838         strcat(action, entry_text);
839
840         buf[0] = action;
841         if (row < 0)
842                 row = gtk_clist_append(clist, buf);
843         else {
844                 gchar *old_action;
845                 gtk_clist_set_text(clist, row, 0, action);
846                 old_action = (gchar *) gtk_clist_get_row_data(clist, row);
847                 if (old_action)
848                         g_free(old_action);
849         }
850
851         buf[0] = g_strdup(action);
852
853         gtk_clist_set_row_data(clist, row, buf[0]);
854
855         prefs_actions_set_list();
856
857         return 0;
858 }
859
860 /* callback functions */
861
862 static void prefs_actions_register_cb(GtkWidget *w, gpointer data)
863 {
864         prefs_actions_clist_set_row(-1);
865 }
866
867 static void prefs_actions_substitute_cb(GtkWidget *w, gpointer data)
868 {
869         GtkCList *clist = GTK_CLIST(actions.actions_clist);
870         gchar *action;
871         gint row;
872
873         if (!clist->selection) return;
874
875         row = GPOINTER_TO_INT(clist->selection->data);
876         if (row == 0) return;
877
878         action = gtk_clist_get_row_data(clist, row);
879         if (!action) return;
880
881         prefs_actions_clist_set_row(row);
882 }
883
884 static void prefs_actions_delete_cb(GtkWidget *w, gpointer data)
885 {
886         GtkCList *clist = GTK_CLIST(actions.actions_clist);
887         gchar *action;
888         gint row;
889
890         if (!clist->selection) return;
891         row = GPOINTER_TO_INT(clist->selection->data);
892         if (row == 0) return;
893
894         if (alertpanel(_("Delete action"),
895                        _("Do you really want to delete this action?"),
896                        _("Yes"), _("No"), NULL) == G_ALERTALTERNATE)
897                 return;
898
899         action = gtk_clist_get_row_data(clist, row);
900         g_free(action);
901         gtk_clist_remove(clist, row);
902         prefs_common.actions_list = g_slist_remove(prefs_common.actions_list,
903                                                    action);
904 }
905
906 static void prefs_actions_up(GtkWidget *w, gpointer data)
907 {
908         GtkCList *clist = GTK_CLIST(actions.actions_clist);
909         gint row;
910
911         if (!clist->selection) return;
912
913         row = GPOINTER_TO_INT(clist->selection->data);
914         if (row > 1)
915                 gtk_clist_row_move(clist, row, row - 1);
916 }
917
918 static void prefs_actions_down(GtkWidget *w, gpointer data)
919 {
920         GtkCList *clist = GTK_CLIST(actions.actions_clist);
921         gint row;
922
923         if (!clist->selection) return;
924
925         row = GPOINTER_TO_INT(clist->selection->data);
926         if (row > 0 && row < clist->rows - 1)
927                 gtk_clist_row_move(clist, row, row + 1);
928 }
929
930 #define ENTRY_SET_TEXT(entry, str) \
931         gtk_entry_set_text(GTK_ENTRY(entry), str ? str : "")
932
933 static void prefs_actions_select(GtkCList *clist, gint row, gint column,
934                                  GdkEvent *event)
935 {
936         gchar *action;
937         gchar *cmd;
938         gchar buf[PREFSBUFSIZE];
939         action = gtk_clist_get_row_data(clist, row);
940
941         if (!action) {
942                 ENTRY_SET_TEXT(actions.name_entry, "");
943                 ENTRY_SET_TEXT(actions.cmd_entry, "");
944                 return;
945         }
946
947         strncpy(buf, action, PREFSBUFSIZE - 1);
948         buf[PREFSBUFSIZE - 1] = 0x00;
949         cmd = strstr(buf, ": ");
950
951         if (cmd && cmd[2])
952                 ENTRY_SET_TEXT(actions.cmd_entry, &cmd[2]);
953         else
954                 return;
955
956         *cmd = 0x00;
957         ENTRY_SET_TEXT(actions.name_entry, buf);
958 }
959
960 static void prefs_actions_row_move(GtkCList *clist,
961                                    gint source_row, gint dest_row)
962 {
963         prefs_actions_set_list();
964         if (gtk_clist_row_is_visible(clist, dest_row) != GTK_VISIBILITY_FULL) {
965                 gtk_clist_moveto(clist, dest_row, -1,
966                                  source_row < dest_row ? 1.0 : 0.0, 0.0);
967         }
968 }
969
970 static gint prefs_actions_deleted(GtkWidget *widget, GdkEventAny *event,
971                                   gpointer *data)
972 {
973         prefs_actions_cancel(widget, data);
974         return TRUE;
975 }
976
977 static void prefs_actions_key_pressed(GtkWidget *widget, GdkEventKey *event,
978                                       gpointer data)
979 {
980         if (event && event->keyval == GDK_Escape)
981                 prefs_actions_cancel(widget, data);
982 }
983
984 static void prefs_actions_cancel(GtkWidget *w, gpointer data)
985 {
986         prefs_actions_read_config();
987         gtk_widget_hide(actions.window);
988         inc_unlock();
989 }
990
991 static void prefs_actions_ok(GtkWidget *widget, gpointer data)
992 {
993         GtkItemFactory *ifactory;
994         MainWindow *mainwin = (MainWindow *)data;
995
996         prefs_actions_write_config();
997         ifactory = gtk_item_factory_from_widget(mainwin->menubar);
998         update_mainwin_actions_menu(ifactory, mainwin);
999         gtk_widget_hide(actions.window);
1000         inc_unlock();
1001 }
1002
1003 void update_mainwin_actions_menu(GtkItemFactory *ifactory,
1004                                  MainWindow *mainwin)
1005 {
1006         update_actions_menu(ifactory, "/Tools/Actions",
1007                             mainwin_actions_execute_cb,
1008                             mainwin);
1009 }
1010
1011 void update_compose_actions_menu(GtkItemFactory *ifactory,
1012                                  gchar *branch_path,
1013                                  Compose *compose)
1014 {
1015         update_actions_menu(ifactory, branch_path,
1016                             compose_actions_execute_cb,
1017                             compose);
1018 }
1019
1020 void actions_execute(gpointer data, 
1021                      guint action_nb,
1022                      GtkWidget *widget,
1023                      gint source)
1024 {
1025         if (source == TOOLBAR_MAIN) 
1026                 mainwin_actions_execute_cb((MainWindow*)data, action_nb, widget);
1027
1028         else if (source == TOOLBAR_COMPOSE)
1029                 compose_actions_execute_cb((Compose*)data, action_nb, widget);
1030 }
1031
1032
1033 static void update_actions_menu(GtkItemFactory *ifactory,
1034                                 gchar *branch_path,
1035                                 gpointer callback,
1036                                 gpointer data)
1037 {
1038         GtkWidget *menuitem;
1039         gchar *menu_path;
1040         GSList *cur;
1041         gchar *action, *action_p;
1042         GList *amenu;
1043         GtkItemFactoryEntry ifentry = {NULL, NULL, NULL, 0, "<Branch>"};
1044
1045         ifentry.path = branch_path;
1046         menuitem = gtk_item_factory_get_widget(ifactory, branch_path);
1047         g_return_if_fail(menuitem != NULL);
1048
1049         amenu = GTK_MENU_SHELL(menuitem)->children;
1050         while (amenu != NULL) {
1051                 GList *alist = amenu->next;
1052                 gtk_widget_destroy(GTK_WIDGET(amenu->data));
1053                 amenu = alist;
1054         }
1055
1056         ifentry.accelerator     = NULL;
1057         ifentry.callback_action = 0;
1058         ifentry.callback        = callback;
1059         ifentry.item_type       = NULL;
1060
1061         for (cur = prefs_common.actions_list; cur; cur = cur->next) {
1062                 action   = g_strdup((gchar *)cur->data);
1063                 action_p = strstr(action, ": ");
1064                 if (action_p && action_p[2] &&
1065                     get_action_type(&action_p[2]) != ACTION_ERROR) {
1066                         action_p[0] = 0x00;
1067                         menu_path = g_strdup_printf("%s/%s", branch_path,
1068                                                     action);
1069                         ifentry.path = menu_path;
1070                         gtk_item_factory_create_item(ifactory, &ifentry, data,
1071                                                      1);
1072                         g_free(menu_path);
1073                 }
1074                 g_free(action);
1075                 ifentry.callback_action++;
1076         }
1077 }
1078
1079 static void compose_actions_execute_cb(Compose *compose, guint action_nb,
1080                                        GtkWidget *widget)
1081 {
1082         gchar *buf, *action;
1083         guint action_type;
1084
1085         g_return_if_fail(action_nb < g_slist_length(prefs_common.actions_list));
1086
1087         buf = (gchar *)g_slist_nth_data(prefs_common.actions_list, action_nb);
1088         g_return_if_fail(buf != NULL);
1089         action = strstr(buf, ": ");
1090         g_return_if_fail(action != NULL);
1091
1092         /* Point to the beginning of the command-line */
1093         action += 2;
1094
1095         action_type = get_action_type(action);
1096         if (action_type & (ACTION_SINGLE | ACTION_MULTIPLE)) {
1097                 alertpanel_warning
1098                         (_("The selected action cannot be used in the compose window\n"
1099                            "because it contains %%f, %%F or %%p."));
1100                 return;
1101         }
1102
1103         execute_actions(action, compose->window, NULL, compose->text, NULL, 0,
1104                         NULL);
1105 }
1106
1107 static void mainwin_actions_execute_cb(MainWindow *mainwin, guint action_nb,
1108                                        GtkWidget *widget)
1109 {
1110         MessageView *messageview = mainwin->messageview;
1111         TextView    *textview = NULL;
1112         gchar       *buf,
1113                     *action;
1114         MimeView    *mimeview = NULL;
1115
1116         g_return_if_fail(action_nb < g_slist_length(prefs_common.actions_list));
1117
1118         buf = (gchar *)g_slist_nth_data(prefs_common.actions_list, action_nb);
1119
1120         g_return_if_fail(buf);
1121         g_return_if_fail(action = strstr(buf, ": "));
1122
1123         /* Point to the beginning of the command-line */
1124         action += 2;
1125
1126         switch (messageview->type) {
1127         case MVIEW_TEXT:
1128                 if (messageview->textview && messageview->textview->text)
1129                         textview = messageview->textview;
1130                 break;
1131         case MVIEW_MIME:
1132                 if (messageview->mimeview) {
1133                         mimeview = messageview->mimeview;
1134                         if (messageview->mimeview->type == MIMEVIEW_TEXT &&
1135                                         messageview->mimeview->textview &&
1136                                         messageview->mimeview->textview->text)
1137                                 textview = messageview->mimeview->textview;
1138                 } 
1139                 break;
1140         }
1141
1142         execute_actions(action, mainwin->window,
1143                         GTK_CTREE(mainwin->summaryview->ctree), textview->text,
1144                         textview->msgfont, textview->body_pos, mimeview);
1145 }
1146
1147 static gboolean execute_actions(gchar *action, GtkWidget *window,
1148                                 GtkCTree *ctree, GtkWidget *text, 
1149                                 GdkFont *msgfont, gint body_pos,
1150                                 MimeView *mimeview)
1151 {
1152         GList *cur, *selection = NULL;
1153         GSList *children_list = NULL;
1154         gint is_ok  = TRUE;
1155         gint selection_len = 0;
1156         Children *children;
1157         ChildInfo *child_info;
1158         gint action_type;
1159         MsgInfo *msginfo;
1160         gchar *cmd;
1161
1162         g_return_val_if_fail(action && *action, FALSE);
1163
1164         action_type = get_action_type(action);
1165
1166         if (action_type == ACTION_ERROR)
1167                 return FALSE;         /* ERR: syntax error */
1168
1169         if (action_type & (ACTION_SINGLE | ACTION_MULTIPLE) && 
1170             !(ctree && GTK_CLIST(ctree)->selection))
1171                 return FALSE;         /* ERR: file command without selection */
1172
1173         if (ctree) {
1174                 selection = GTK_CLIST(ctree)->selection;
1175                 selection_len = g_list_length(selection);
1176         }
1177
1178         if (action_type & (ACTION_PIPE_OUT | ACTION_PIPE_IN | ACTION_INSERT)) {
1179                 if (ctree && selection_len > 1)
1180                         return FALSE; /* ERR: pipe + multiple selection */
1181                 if (!text)
1182                         return FALSE; /* ERR: pipe and no displayed text */
1183         }
1184
1185         children = g_new0(Children, 1);
1186
1187         if (action_type & ACTION_SINGLE) {
1188                 for (cur = selection; cur && is_ok == TRUE; cur = cur->next) {
1189                         msginfo = gtk_ctree_node_get_row_data(ctree,
1190                                         GTK_CTREE_NODE(cur->data));
1191                         if (!msginfo) {
1192                                 is_ok  = FALSE; /* ERR: msginfo missing */
1193                                 break;
1194                         }
1195                         cmd = parse_action_cmd(action, msginfo, ctree,
1196                                                mimeview);
1197                         if (!cmd) {
1198                                 debug_print("Action command error\n");
1199                                 is_ok  = FALSE; /* ERR: incorrect command */
1200                                 break;
1201                         }
1202                         if ((child_info = fork_child(cmd, action_type, text,
1203                                                      msgfont, body_pos,
1204                                                      children))) {
1205                                 children_list = g_slist_append(children_list,
1206                                                                child_info);
1207                                 children->open_in = (selection_len == 1) ?
1208                                                     (action_type &
1209                                                      (ACTION_OPEN_IN |
1210                                                       ACTION_HIDE_IN)) : 0;
1211                         }
1212                         g_free(cmd);
1213                 }
1214         } else {
1215                 cmd = parse_action_cmd(action, NULL, ctree, mimeview);
1216                 if (cmd) {
1217                         if ((child_info = fork_child(cmd, action_type, text,
1218                                                      msgfont, body_pos,
1219                                                      children))) {
1220                                 children_list = g_slist_append(children_list,
1221                                                                child_info);
1222                                 children->open_in = action_type &
1223                                                     (ACTION_OPEN_IN |
1224                                                      ACTION_HIDE_IN);
1225                         }
1226                         g_free(cmd);
1227                 } else
1228                         is_ok  = FALSE;         /* ERR: incorrect command */
1229         }
1230
1231         if (!children_list) {
1232                  /* If not waiting for children, return */
1233                 g_free(children);
1234         } else {
1235                 GSList *cur;
1236
1237                 children->action  = g_strdup(action);
1238                 children->window  = window;
1239                 children->dialog  = NULL;
1240                 children->list    = children_list;
1241                 children->nb      = g_slist_length(children_list);
1242
1243                 for (cur = children_list; cur; cur = cur->next) {
1244                         child_info = (ChildInfo *) cur->data;
1245                         child_info->tag_status = 
1246                                 gdk_input_add(child_info->chld_status,
1247                                               GDK_INPUT_READ,
1248                                               catch_status, child_info);
1249                 }
1250
1251                 create_io_dialog(children);
1252         }
1253
1254         return is_ok;
1255 }
1256
1257 ChildInfo *fork_child(gchar *cmd, gint action_type, GtkWidget *text,
1258                       GdkFont *msgfont, gint body_pos, Children *children)
1259 {
1260         gint chld_in[2], chld_out[2], chld_err[2], chld_status[2];
1261         gchar *cmdline[4];
1262         gint start, end, is_selection;
1263         gchar *selection;
1264         pid_t pid, gch_pid;
1265         ChildInfo *child_info;
1266         gint sync;
1267
1268         sync = !(action_type & ACTION_ASYNC);
1269
1270         chld_in[0] = chld_in[1] = chld_out[0] = chld_out[1] = chld_err[0]
1271                 = chld_err[1] = chld_status[0] = chld_status[1] = -1;
1272
1273         if (sync) {
1274                 if (pipe(chld_status) || pipe(chld_in) || pipe(chld_out) ||
1275                     pipe(chld_err)) {
1276                         alertpanel_error(_("Command could not be started. "
1277                                            "Pipe creation failed.\n%s"),
1278                                         g_strerror(errno));
1279                         /* Closing fd = -1 fails silently */
1280                         close(chld_in[0]);
1281                         close(chld_in[1]);
1282                         close(chld_out[0]);
1283                         close(chld_out[1]);
1284                         close(chld_err[0]);
1285                         close(chld_err[1]);
1286                         close(chld_status[0]);
1287                         close(chld_status[1]);
1288                         return NULL; /* Pipe error */
1289                 }
1290         }
1291
1292         debug_print("Forking child and grandchild.\n");
1293
1294         pid = fork();
1295         if (pid == 0) { /* Child */
1296                 if (setpgid(0, 0))
1297                         perror("setpgid");
1298
1299                 close(ConnectionNumber(gdk_display));
1300
1301                 gch_pid = fork();
1302
1303                 if (gch_pid == 0) {
1304                         if (setpgid(0, getppid()))
1305                                 perror("setpgid");
1306                         if (sync) {
1307                                 if (action_type &
1308                                     (ACTION_PIPE_IN |
1309                                      ACTION_OPEN_IN |
1310                                      ACTION_HIDE_IN)) {
1311                                         close(fileno(stdin));
1312                                         dup  (chld_in[0]);
1313                                 }
1314                                 close(chld_in[0]);
1315                                 close(chld_in[1]);
1316
1317                                 close(fileno(stdout));
1318                                 dup  (chld_out[1]);
1319                                 close(chld_out[0]);
1320                                 close(chld_out[1]);
1321
1322                                 close(fileno(stderr));
1323                                 dup  (chld_err[1]);
1324                                 close(chld_err[0]);
1325                                 close(chld_err[1]);
1326                         }
1327
1328                         cmdline[0] = "sh";
1329                         cmdline[1] = "-c";
1330                         cmdline[2] = cmd;
1331                         cmdline[3] = 0;
1332                         execvp("/bin/sh", cmdline);
1333
1334                         perror("execvp");
1335                         _exit(1);
1336                 } else if (gch_pid < (pid_t) 0) { /* Fork error */
1337                         if (sync)
1338                                 write(chld_status[1], "1\n", 2);
1339                         perror("fork");
1340                         _exit(1);
1341                 } else {/* Child */
1342                         if (sync) {
1343                                 close(chld_in[0]);
1344                                 close(chld_in[1]);
1345                                 close(chld_out[0]);
1346                                 close(chld_out[1]);
1347                                 close(chld_err[0]);
1348                                 close(chld_err[1]);
1349                                 close(chld_status[0]);
1350                         }
1351                         if (sync) {
1352                                 debug_print("Child: Waiting for grandchild\n");
1353                                 waitpid(gch_pid, NULL, 0);
1354                                 debug_print("Child: grandchild ended\n");
1355                                 write(chld_status[1], "0\n", 2);
1356                                 close(chld_status[1]);
1357                         }
1358                         _exit(0);
1359                 }
1360         } else if (pid < 0) { /* Fork error */
1361                 alertpanel_error(_("Could not fork to execute the following "
1362                                    "command:\n%s\n%s"),
1363                                  cmd, g_strerror(errno));
1364                 return NULL; 
1365         }
1366
1367         /* Parent */
1368
1369         if (!sync) {
1370                 waitpid(pid, NULL, 0);
1371                 return NULL;
1372         }
1373
1374         close(chld_in[0]);
1375         if (!(action_type & (ACTION_PIPE_IN | ACTION_OPEN_IN | ACTION_HIDE_IN)))
1376                 close(chld_in[1]);
1377         close(chld_out[1]);
1378         close(chld_err[1]);
1379         close(chld_status[1]);
1380
1381         child_info = g_new0(ChildInfo, 1);
1382
1383         child_info->children    = children;
1384
1385         child_info->pid         = pid;
1386         child_info->cmd         = g_strdup(cmd);
1387         child_info->type        = action_type;
1388         child_info->new_out     = FALSE;
1389         child_info->output      = g_string_sized_new(0);
1390         child_info->chld_in     =
1391                 (action_type &
1392                  (ACTION_PIPE_IN | ACTION_OPEN_IN | ACTION_HIDE_IN))
1393                         ? chld_in [1] : -1;
1394         child_info->chld_out    = chld_out[0];
1395         child_info->chld_err    = chld_err[0];
1396         child_info->chld_status = chld_status[0];
1397         child_info->tag_in      = -1;
1398         child_info->tag_out     = gdk_input_add(chld_out[0], GDK_INPUT_READ,
1399                                                 catch_output, child_info);
1400         child_info->tag_err     = gdk_input_add(chld_err[0], GDK_INPUT_READ,
1401                                                 catch_output, child_info);
1402
1403         if (!(action_type & (ACTION_PIPE_IN | ACTION_PIPE_OUT | ACTION_INSERT)))
1404                 return child_info;
1405
1406         child_info->text        = text;
1407         child_info->msgfont     = msgfont;
1408
1409         start = body_pos;
1410         end   = gtk_stext_get_length(GTK_STEXT(text));
1411
1412         if (GTK_EDITABLE(text)->has_selection) {
1413                 start = GTK_EDITABLE(text)->selection_start_pos;
1414                 end   = GTK_EDITABLE(text)->selection_end_pos;
1415                 if (start > end) {
1416                         gint tmp;
1417                         tmp = start;
1418                         start = end;
1419                         end = tmp;
1420                 }
1421                 is_selection = TRUE;
1422                 if (start == end) {
1423                         start = 0;
1424                         end = gtk_stext_get_length(GTK_STEXT(text));
1425                         is_selection = FALSE;
1426                 }
1427         }
1428
1429         selection = gtk_editable_get_chars(GTK_EDITABLE(text), start, end);
1430
1431         if (action_type & ACTION_PIPE_IN) {
1432                 write(chld_in[1], selection, strlen(selection));
1433                 if (!(action_type & (ACTION_OPEN_IN | ACTION_HIDE_IN)))
1434                         close(chld_in[1]);
1435                 child_info->chld_in = -1; /* No more input */
1436         }
1437         g_free(selection);
1438
1439         gtk_stext_freeze(GTK_STEXT(text));
1440         if (action_type & ACTION_PIPE_OUT) {
1441                 gtk_stext_set_point(GTK_STEXT(text), start);
1442                 gtk_stext_forward_delete(GTK_STEXT(text), end - start);
1443         }
1444
1445         gtk_stext_thaw(GTK_STEXT(text));
1446
1447         return child_info;
1448 }
1449
1450 static void kill_children_cb(GtkWidget *widget, gpointer data)
1451 {
1452         GSList *cur;
1453         Children *children = (Children *) data;
1454         ChildInfo *child_info;
1455
1456         for (cur = children->list; cur; cur = cur->next) {
1457                 child_info = (ChildInfo *)(cur->data);
1458                 debug_print("Killing child group id %d\n", child_info->pid);
1459                 if (child_info->pid && kill(-child_info->pid, SIGTERM) < 0)
1460                         perror("kill");
1461         }
1462 }
1463
1464 static gint wait_for_children(gpointer data)
1465 {
1466         gboolean new_output;
1467         Children *children = (Children *)data;
1468         ChildInfo *child_info;
1469         GSList *cur;
1470         gint nb = children->nb;
1471
1472         children->nb = 0;
1473
1474         cur = children->list;
1475         new_output = FALSE;
1476         while (cur) {
1477                 child_info = (ChildInfo *)cur->data;
1478                 if (child_info->pid)
1479                         children->nb++;
1480                 new_output |= child_info->new_out;
1481                 cur = cur->next;
1482         }
1483
1484         children->output |= new_output;
1485
1486         if (new_output || (children->dialog && (nb != children->nb)))
1487                 update_io_dialog(children);
1488
1489         if (children->nb)
1490                 return FALSE;
1491
1492         if (!children->dialog) {
1493                 free_children(children);
1494         } else if (!children->output) {
1495                 gtk_widget_destroy(children->dialog);
1496         }
1497
1498         return FALSE;
1499 }
1500
1501 static void send_input(GtkWidget *w, gpointer data)
1502 {
1503         Children *children = (Children *) data;
1504         ChildInfo *child_info = (ChildInfo *) children->list->data;
1505
1506         child_info->tag_in = gdk_input_add(child_info->chld_in,
1507                                            GDK_INPUT_WRITE,
1508                                            catch_input, children);
1509         gtk_widget_set_sensitive(children->input_hbox, FALSE);
1510 }
1511
1512 static gint delete_io_dialog_cb(GtkWidget *w, GdkEvent *e, gpointer data)
1513 {
1514         hide_io_dialog_cb(w, data);
1515         return TRUE;
1516 }
1517
1518 static void hide_io_dialog_cb(GtkWidget *w, gpointer data)
1519 {
1520
1521         Children *children = (Children *)data;
1522
1523         if (!children->nb) {
1524                 gtk_signal_disconnect_by_data(GTK_OBJECT(children->dialog),
1525                                               children);
1526                 gtk_widget_destroy(children->dialog);
1527                 free_children(children);
1528         }
1529 }
1530
1531 static void childinfo_close_pipes(ChildInfo *child_info)
1532 {
1533         if (child_info->tag_in > 0)
1534                 gdk_input_remove(child_info->tag_in);
1535         gdk_input_remove(child_info->tag_out);
1536         gdk_input_remove(child_info->tag_err);
1537
1538         if (child_info->chld_in >= 0)
1539                 close(child_info->chld_in);
1540         close(child_info->chld_out);
1541         close(child_info->chld_err);
1542         close(child_info->chld_status);
1543 }
1544
1545 static void free_children(Children *children)
1546 {
1547         GSList *cur;
1548         ChildInfo *child_info;
1549
1550         debug_print("Freeing children data %p\n", children);
1551
1552         g_free(children->action);
1553         for (cur = children->list; cur;) {
1554                 child_info = (ChildInfo *)cur->data;
1555                 g_free(child_info->cmd);
1556                 g_string_free(child_info->output, TRUE);
1557                 children->list = g_slist_remove(children->list, child_info);
1558                 g_free(child_info);
1559                 cur = children->list;
1560         }
1561         g_free(children);
1562 }
1563
1564 static void update_io_dialog(Children *children)
1565 {
1566         GSList *cur;
1567
1568         debug_print("Updating actions input/output dialog.\n");
1569
1570         if (!children->nb) {
1571                 gtk_widget_set_sensitive(children->abort_btn, FALSE);
1572                 gtk_widget_set_sensitive(children->close_btn, TRUE);
1573                 if (children->input_hbox)
1574                         gtk_widget_set_sensitive(children->input_hbox, FALSE);
1575         }
1576
1577         if (children->output) {
1578                 GtkWidget *text = children->text;
1579                 gchar *caption;
1580                 ChildInfo *child_info;
1581
1582                 gtk_widget_show(children->scrolledwin);
1583                 gtk_text_freeze(GTK_TEXT(text));
1584                 gtk_text_set_point(GTK_TEXT(text), 0);
1585                 gtk_text_forward_delete(GTK_TEXT(text), 
1586                                         gtk_text_get_length(GTK_TEXT(text)));
1587                 for (cur = children->list; cur; cur = cur->next) {
1588                         child_info = (ChildInfo *)cur->data;
1589                         if (child_info->pid)
1590                                 caption = g_strdup_printf
1591                                         (_("--- Running: %s\n"),
1592                                          child_info->cmd);
1593                         else
1594                                 caption = g_strdup_printf
1595                                         (_("--- Ended: %s\n"),
1596                                          child_info->cmd);
1597
1598                         gtk_text_insert(GTK_TEXT(text), NULL, NULL, NULL,
1599                                         caption, -1);
1600                         gtk_text_insert(GTK_TEXT(text), NULL, NULL, NULL,
1601                                         child_info->output->str, -1);
1602                         g_free(caption);
1603                         child_info->new_out = FALSE;
1604                 }
1605                 gtk_text_thaw(GTK_TEXT(text));
1606         }
1607 }
1608
1609 static void create_io_dialog(Children *children)
1610 {
1611         GtkWidget *dialog;
1612         GtkWidget *vbox;
1613         GtkWidget *entry = NULL;
1614         GtkWidget *input_hbox = NULL;
1615         GtkWidget *send_button;
1616         GtkWidget *label;
1617         GtkWidget *text;
1618         GtkWidget *scrolledwin;
1619         GtkWidget *hbox;
1620         GtkWidget *abort_button;
1621         GtkWidget *close_button;
1622
1623         debug_print("Creating action IO dialog\n");
1624
1625         dialog = gtk_dialog_new();
1626         gtk_container_set_border_width
1627                 (GTK_CONTAINER(GTK_DIALOG(dialog)->action_area), 5);
1628         gtk_window_set_position(GTK_WINDOW(dialog), GTK_WIN_POS_CENTER);
1629         gtk_window_set_title(GTK_WINDOW(dialog), _("Action's input/output"));
1630         gtk_window_set_modal(GTK_WINDOW(dialog), TRUE);
1631         manage_window_set_transient(GTK_WINDOW(dialog));
1632         gtk_signal_connect(GTK_OBJECT(dialog), "delete_event",
1633                         GTK_SIGNAL_FUNC(delete_io_dialog_cb), children);
1634         gtk_signal_connect(GTK_OBJECT(dialog), "destroy",
1635                         GTK_SIGNAL_FUNC(hide_io_dialog_cb),
1636                         children);
1637
1638         vbox = gtk_vbox_new(FALSE, 8);
1639         gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog)->vbox), vbox);
1640         gtk_container_set_border_width(GTK_CONTAINER(vbox), 8);
1641         gtk_widget_show(vbox);
1642
1643         label = gtk_label_new(children->action);
1644         gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 0);
1645         gtk_widget_show(label);
1646
1647         scrolledwin = gtk_scrolled_window_new(NULL, NULL);
1648         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledwin),
1649                                        GTK_POLICY_NEVER, GTK_POLICY_ALWAYS);
1650         gtk_box_pack_start(GTK_BOX(vbox), scrolledwin, TRUE, TRUE, 0);
1651         gtk_widget_set_usize(scrolledwin, 480, 200);
1652         gtk_widget_hide(scrolledwin);
1653
1654         text = gtk_text_new(gtk_scrolled_window_get_hadjustment
1655                             (GTK_SCROLLED_WINDOW(scrolledwin)),
1656                             gtk_scrolled_window_get_vadjustment
1657                             (GTK_SCROLLED_WINDOW(scrolledwin)));
1658         gtk_text_set_editable(GTK_TEXT(text), FALSE);
1659         gtk_container_add(GTK_CONTAINER(scrolledwin), text);
1660         gtk_widget_show(text);
1661
1662         if (children->open_in) {
1663                 input_hbox = gtk_hbox_new(FALSE, 8);
1664                 gtk_widget_show(input_hbox);
1665
1666                 entry = gtk_entry_new();
1667                 gtk_widget_set_usize(entry, 320, -1);
1668                 gtk_signal_connect(GTK_OBJECT(entry), "activate",
1669                                    GTK_SIGNAL_FUNC(send_input), children);
1670                 gtk_box_pack_start(GTK_BOX(input_hbox), entry, TRUE, TRUE, 0);
1671                 if (children->open_in & ACTION_HIDE_IN)
1672                         gtk_entry_set_visibility(GTK_ENTRY(entry), FALSE);
1673                 gtk_widget_show(entry);
1674
1675                 send_button = gtk_button_new_with_label(_(" Send "));
1676                 gtk_signal_connect(GTK_OBJECT(send_button), "clicked",
1677                                    GTK_SIGNAL_FUNC(send_input), children);
1678                 gtk_box_pack_start(GTK_BOX(input_hbox), send_button, FALSE,
1679                                    FALSE, 0);
1680                 gtk_widget_show(send_button);
1681
1682                 gtk_box_pack_start(GTK_BOX(vbox), input_hbox, FALSE, FALSE, 0);
1683                 gtk_widget_grab_focus(entry);
1684         }
1685
1686         gtkut_button_set_create(&hbox, &abort_button, _("Abort"),
1687                                 &close_button, _("Close"), NULL, NULL);
1688         gtk_signal_connect(GTK_OBJECT(abort_button), "clicked",
1689                         GTK_SIGNAL_FUNC(kill_children_cb), children);
1690         gtk_signal_connect(GTK_OBJECT(close_button), "clicked",
1691                         GTK_SIGNAL_FUNC(hide_io_dialog_cb), children);
1692         gtk_widget_show(hbox);
1693
1694         if (children->nb)
1695                 gtk_widget_set_sensitive(close_button, FALSE);
1696
1697         gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog)->action_area), hbox);
1698
1699         children->dialog      = dialog;
1700         children->scrolledwin = scrolledwin;
1701         children->text        = text;
1702         children->input_hbox  = children->open_in ? input_hbox : NULL;
1703         children->input_entry = children->open_in ? entry : NULL;
1704         children->abort_btn   = abort_button;
1705         children->close_btn   = close_button;
1706
1707         gtk_widget_show(dialog);
1708 }
1709
1710 static void catch_status(gpointer data, gint source, GdkInputCondition cond)
1711 {
1712         ChildInfo *child_info = (ChildInfo *)data;
1713         gchar buf;
1714         gint c;
1715
1716         gdk_input_remove(child_info->tag_status);
1717
1718         c = read(source, &buf, 1);
1719         debug_print("Child returned %c\n", buf);
1720
1721         waitpid(-child_info->pid, NULL, 0);
1722         childinfo_close_pipes(child_info);
1723         child_info->pid = 0;
1724
1725         wait_for_children(child_info->children);
1726 }
1727         
1728 static void catch_input(gpointer data, gint source, GdkInputCondition cond)
1729 {
1730         Children *children = (Children *)data;
1731         ChildInfo *child_info = (ChildInfo *)children->list->data;
1732         gchar *input;
1733         gint c;
1734
1735         debug_print("Sending input to grand child.\n");
1736         if (!(cond && GDK_INPUT_WRITE))
1737                 return;
1738
1739         gdk_input_remove(child_info->tag_in);
1740         child_info->tag_in = -1;
1741
1742         input = gtk_editable_get_chars(GTK_EDITABLE(children->input_entry),
1743                                        0, -1);
1744         c = write(child_info->chld_in, input, strlen(input));
1745
1746         g_free(input);
1747
1748         write(child_info->chld_in, "\n", 2);
1749
1750         gtk_entry_set_text(GTK_ENTRY(children->input_entry), "");
1751         gtk_widget_set_sensitive(children->input_hbox, TRUE);
1752         debug_print("Input to grand child sent.\n");
1753 }
1754
1755 static void catch_output(gpointer data, gint source, GdkInputCondition cond)
1756 {
1757         ChildInfo *child_info = (ChildInfo *)data;
1758         gint c, i;
1759         gchar buf[PREFSBUFSIZE];
1760
1761         debug_print("Catching grand child's output.\n");
1762         if (child_info->type & (ACTION_PIPE_OUT | ACTION_INSERT)
1763             && source == child_info->chld_out) {
1764                 gboolean is_selection = FALSE;
1765                 GtkWidget *text = child_info->text;
1766                 if (GTK_EDITABLE(text)->has_selection)
1767                         is_selection = TRUE;
1768                 gtk_stext_freeze(GTK_STEXT(text));
1769                 while (TRUE) {
1770                         c = read(source, buf, PREFSBUFSIZE - 1);
1771                         if (c == 0)
1772                                 break;
1773                         gtk_stext_insert(GTK_STEXT(text), child_info->msgfont,
1774                                          NULL, NULL, buf, c);
1775                 }
1776                 if (is_selection) {
1777                         /* Using the select_region draws things. Should not.
1778                          * so we just change selection position and 
1779                          * defere drawing when thawing. Hack?
1780                          */
1781                         GTK_EDITABLE(text)->selection_end_pos =
1782                                         gtk_stext_get_point(GTK_STEXT(text));
1783                 }
1784                 gtk_stext_thaw(GTK_STEXT(child_info->text));
1785         } else {
1786                 c = read(source, buf, PREFSBUFSIZE - 1);
1787                 for (i = 0; i < c; i++)
1788                         child_info->output = g_string_append_c
1789                                 (child_info->output, buf[i]);
1790                 if (c > 0)
1791                         child_info->new_out = TRUE;
1792         }
1793         wait_for_children(child_info->children);
1794 }