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