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