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