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