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