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