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