src/prefs_actions.c:
[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
553                                 action_type  = ACTION_ERROR;
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[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                                         cmd = g_string_append_c(cmd, ' ');
596                                      }
597                                      p++;
598                                      break;
599                            case 'p':
600                                      tmpcmd = parse_append_msgpart(cmd,
601                                                                    msginfo, 
602                                                                    mimeview);
603                                      if (tmpcmd)
604                                              cmd = tmpcmd;
605                                      else {
606                                              g_string_free(cmd, TRUE);
607                                              return NULL;
608                                      }
609                                              
610                                      p++;
611                                      break;
612                            default: cmd = g_string_append_c(cmd, p[0]);
613                                     cmd = g_string_append_c(cmd, p[1]);
614                                     p++;
615                         }
616                 } else {
617                         cmd = g_string_append_c(cmd, p[0]);
618                 }
619                 p++;
620         }
621         if (!cmd->len) {
622                 g_string_free(cmd, TRUE);
623                 return NULL;
624         }
625
626         p = cmd->str;
627         g_string_free(cmd, FALSE);
628         return p;
629 }
630
631 static GString *parse_append_filename(GString *cmd, MsgInfo *msginfo)
632 {
633         gchar *filename;
634
635         g_return_val_if_fail(msginfo, cmd);
636
637         filename = procmsg_get_message_file(msginfo);
638
639         if (filename) {
640                 cmd = g_string_append(cmd, filename);
641                 g_free(filename);
642         } 
643
644         return cmd;
645 }
646
647 static GString *parse_append_msgpart(GString *cmd, MsgInfo *msginfo,
648                                      MimeView *mimeview)
649 {
650         gchar    *filename;
651         gchar    *partname;
652         MimeInfo *partinfo;
653         gint      ret;
654         FILE     *fp;
655         
656         if (!mimeview) {
657 #if USE_GPGME
658                 if ((fp = procmsg_open_message_decrypted(msginfo, &partinfo))
659                     == NULL) {
660                         alertpanel_error(_("Could not get message file."));
661                         return NULL;
662                 }
663 #else
664                 if ((fp = procmsg_open_message(msginfo)) == NULL)
665                 {
666                         alertpanel_error(_("Could not get message file."));
667                         return NULL;
668                 }
669                 partinfo = procmime_scan_mime_header(fp);
670 #endif
671                 fclose(fp);
672                 if (!partinfo) {
673                         procmime_mimeinfo_free(partinfo);
674                         alertpanel_error(_("Could not get message part."));
675                         return NULL;
676                 }
677                 filename = procmsg_get_message_file(msginfo);
678         } else {
679                 if (!mimeview->opened) {
680                         alertpanel_error(_("No message part selected."));
681                         return NULL;
682                 }
683                 if (!mimeview->file) {
684                         alertpanel_error(_("No message file selected."));
685                         return NULL;
686                 }
687                 partinfo = gtk_ctree_node_get_row_data
688                                 (GTK_CTREE(mimeview->ctree),
689                                  mimeview->opened);
690                 g_return_val_if_fail(partinfo != NULL, cmd);
691                 filename = mimeview->file;
692         }
693         partname = procmime_get_tmp_file_name(partinfo);
694
695         ret = procmime_get_part(partname, filename, partinfo); 
696
697         if (!mimeview) {
698                 procmime_mimeinfo_free(partinfo);
699                 g_free(filename);
700         }
701
702         if (ret < 0) {
703                 alertpanel_error(_("Can't get part of multipart message"));
704                 g_free(partname);
705                 return NULL;
706         }
707
708         cmd = g_string_append(cmd,partname);
709         
710         g_free(partname);
711         
712         return cmd;
713         
714 }
715
716 static void prefs_actions_set_dialog    (void)
717 {
718         GtkCList *clist = GTK_CLIST(actions.actions_clist);
719         GSList *cur;
720         gchar *action_str[1];
721         gint row;
722
723         gtk_clist_freeze(clist);
724         gtk_clist_clear(clist);
725
726         action_str[0] = _("(New)");
727         row = gtk_clist_append(clist, action_str);
728         gtk_clist_set_row_data(clist, row, NULL);
729
730         for (cur = prefs_common.actionslst; cur != NULL; cur = cur->next) {
731                 gchar *action[1];
732                 action[0] = (gchar *) cur->data;
733
734                 row = gtk_clist_append(clist, action);
735                 gtk_clist_set_row_data(clist, row, action[0]);
736         }
737         
738         gtk_clist_thaw(clist);
739 }
740 static void prefs_actions_set_list(void)
741 {
742         gint row = 1;
743         gchar *action;
744         
745         g_slist_free(prefs_common.actionslst);
746         prefs_common.actionslst = NULL;
747
748         while ( (action = (gchar *) gtk_clist_get_row_data(GTK_CLIST(
749                                                  actions.actions_clist), row))
750                 != NULL) {
751                 prefs_common.actionslst = g_slist_append(prefs_common.actionslst,
752                                                          action);
753                 row++;
754         }
755 }
756                 
757
758 #define GET_ENTRY(entry) \
759         entry_text = gtk_entry_get_text(GTK_ENTRY(entry))
760 static gint prefs_actions_clist_set_row (gint row)
761 {
762         GtkCList *clist = GTK_CLIST(actions.actions_clist);
763         gchar *entry_text;
764         gint len;
765         gchar action[PREFSBUFSIZE];
766         gchar *buf[1];
767         
768         
769         g_return_val_if_fail(row != 0, -1);
770
771         
772
773         GET_ENTRY(actions.name_entry);
774         if (entry_text[0] == '\0') {
775                 alertpanel_error(_("Menu name is not set."));
776                 return -1;
777         }
778
779         if (strchr(entry_text, ':')) {
780                 alertpanel_error(_("Colon ':' is not allowed in the menu name."));
781                 return -1;
782         }
783         
784         strncpy(action, entry_text, PREFSBUFSIZE - 1);
785         g_strstrip(action);
786
787         /* Keep space for the ': ' delimiter */
788         len = strlen(action) + 2;
789         if (len >= PREFSBUFSIZE - 1) {
790                 alertpanel_error(_("Menu name is too long."));
791                 return -1;
792         }
793
794         strcat(action, ": ");
795
796         GET_ENTRY(actions.cmd_entry);
797
798         if (entry_text[0] == '\0') {
799                 alertpanel_error(_("Command line not set."));
800                 return -1;
801         }
802
803         if (len + strlen(entry_text) >= PREFSBUFSIZE - 1) {
804                 alertpanel_error(_("Menu name and command are too long."));
805                 return -1;
806         }
807
808         if (get_action_type(entry_text) == ACTION_ERROR) {
809                 alertpanel_error(_("The command\n%s\nhas a syntax error."), 
810                                  entry_text);
811                 return -1;
812         }
813         
814         strcat(action, entry_text);
815
816         buf[0] = action;
817         if (row < 0)
818                 row = gtk_clist_append(clist, buf);
819         else {
820                 gchar *old_action;
821                 gtk_clist_set_text(clist, row, 0, action);
822                 old_action = (gchar *) gtk_clist_get_row_data(clist, row);
823                 if (old_action)
824                         g_free(old_action);
825         }
826
827         buf[0] = g_strdup(action);
828         
829         gtk_clist_set_row_data(clist, row, buf[0]);
830
831         prefs_actions_set_list();
832
833         return 0;
834 }
835         
836 /* callback functions */
837 static void prefs_actions_register_cb   (GtkWidget *w, gpointer data)
838 {
839         prefs_actions_clist_set_row(-1);
840 }
841
842 static void prefs_actions_substitute_cb (GtkWidget *w, gpointer data)
843 {
844         GtkCList *clist = GTK_CLIST(actions.actions_clist);
845         gchar *action;
846         gint row;
847
848         if (!clist->selection) return;
849
850         row = GPOINTER_TO_INT(clist->selection->data);
851         if (row == 0) return;
852
853         action = gtk_clist_get_row_data(clist, row);
854         if (!action) return;
855         
856         prefs_actions_clist_set_row(row);
857 }
858
859 static void prefs_actions_delete_cb     (GtkWidget *w, gpointer data)
860 {
861         GtkCList *clist = GTK_CLIST(actions.actions_clist);
862         gchar *action;
863         gint row;
864
865         if (!clist->selection) return;
866         row = GPOINTER_TO_INT(clist->selection->data);
867         if (row == 0) return;
868
869         if (alertpanel(_("Delete action"),
870                        _("Do you really want to delete this action?"),
871                        _("Yes"), _("No"), NULL) == G_ALERTALTERNATE)
872                 return;
873
874         action = gtk_clist_get_row_data(clist, row);
875         g_free(action);
876         gtk_clist_remove(clist, row);
877         prefs_common.actionslst = g_slist_remove(prefs_common.actionslst, action);
878 }
879
880 static void prefs_actions_up            (GtkWidget *w, gpointer data)
881 {
882         GtkCList *clist = GTK_CLIST(actions.actions_clist);
883         gint row;
884
885         if (!clist->selection) return;
886
887         row = GPOINTER_TO_INT(clist->selection->data);
888         if (row > 1)
889                 gtk_clist_row_move(clist, row, row - 1);
890 }
891
892 static void prefs_actions_down          (GtkWidget *w, gpointer data)
893 {
894         GtkCList *clist = GTK_CLIST(actions.actions_clist);
895         gint row;
896
897         if (!clist->selection) return;
898
899         row = GPOINTER_TO_INT(clist->selection->data);
900         if (row > 0 && row < clist->rows - 1)
901                 gtk_clist_row_move(clist, row, row + 1);
902 }
903
904 #define ENTRY_SET_TEXT(entry, str) \
905         gtk_entry_set_text(GTK_ENTRY(entry), str ? str : "")
906 static void prefs_actions_select        (GtkCList       *clist,
907                                          gint            row,
908                                          gint            column,
909                                          GdkEvent       *event)
910 {
911         gchar *action;
912         gchar *cmd;
913         gchar buf[PREFSBUFSIZE];
914         action = gtk_clist_get_row_data(clist, row);
915
916         if (!action) {
917                 ENTRY_SET_TEXT(actions.name_entry, "");
918                 ENTRY_SET_TEXT(actions.cmd_entry, "");
919                 return;
920         }
921         
922         strncpy(buf, action, PREFSBUFSIZE - 1);
923         buf[PREFSBUFSIZE - 1] = 0x00;
924         cmd = strstr2(buf, ": ");
925
926         if (cmd && cmd[2])
927                 ENTRY_SET_TEXT(actions.cmd_entry, &cmd[2]);
928         else
929                 return;
930
931         *cmd = 0x00;
932         ENTRY_SET_TEXT(actions.name_entry, buf);
933 }
934         
935 static void prefs_actions_row_move      (GtkCList       *clist,
936                                          gint            source_row,
937                                          gint            dest_row)
938 {
939         prefs_actions_set_list();
940         if (gtk_clist_row_is_visible(clist, dest_row) != GTK_VISIBILITY_FULL) {
941                 gtk_clist_moveto(clist, dest_row, -1,
942                                  source_row < dest_row ? 1.0 : 0.0, 0.0);
943         }
944 }
945
946 static gint prefs_actions_deleted       (GtkWidget      *widget,
947                                          GdkEventAny    *event,
948                                          gpointer       *data)
949 {
950         prefs_actions_cancel(widget, data);
951         return TRUE;
952 }
953
954 static void prefs_actions_key_pressed   (GtkWidget      *widget,
955                                          GdkEventKey    *event,
956                                          gpointer        data)
957 {
958         if (event && event->keyval == GDK_Escape)
959                 prefs_actions_cancel(widget, data);
960 }
961
962 static void prefs_actions_cancel        (GtkWidget *w, gpointer data)
963 {
964         prefs_actions_read_config();
965         gtk_widget_hide(actions.window);
966         inc_unlock();
967 }
968
969 static void prefs_actions_ok            (GtkWidget *widget, gpointer data)
970 {
971         GtkItemFactory *ifactory;
972         MainWindow *mainwin = (MainWindow *) data;
973
974         prefs_actions_write_config();
975         ifactory = gtk_item_factory_from_widget(mainwin->menubar);
976         update_mainwin_actions_menu(ifactory, mainwin);
977         gtk_widget_hide(actions.window);
978         inc_unlock();
979 }
980
981 void update_mainwin_actions_menu(GtkItemFactory *ifactory, 
982                                  MainWindow *mainwin)
983 {
984         update_actions_menu(ifactory, "/Tools/Actions", 
985                             mainwin_actions_execute_cb, 
986                             mainwin);
987 }
988
989 void update_compose_actions_menu(GtkItemFactory *ifactory, 
990                                  gchar *branch_path,
991                                  Compose *compose)
992 {
993         update_actions_menu(ifactory, branch_path, 
994                             compose_actions_execute_cb, 
995                             compose);
996 }
997                                  
998 static void update_actions_menu(GtkItemFactory *ifactory,
999                                 gchar *branch_path,
1000                                 gpointer callback,
1001                                 gpointer data)
1002 {
1003         GtkWidget *menuitem;
1004         gchar *menu_path;
1005         GSList *cur;
1006         gchar *action, *action_p;
1007         GtkWidget *menu;
1008         
1009         GtkItemFactoryEntry ifentry = {
1010                 NULL, NULL, NULL, 0, "<Branch>"};
1011         ifentry.path = branch_path;
1012         menuitem = gtk_item_factory_get_item(ifactory, branch_path);    
1013         g_return_if_fail(menuitem);
1014         /* FIXME: is there a better way to remove unknown submenu items? */
1015         /* Deleting and recreating the parent looses the translation */
1016         menu = GTK_WIDGET(GTK_MENU_ITEM(menuitem)->submenu);
1017         if (GTK_MENU_SHELL(menu)->children) {
1018                 GList *amenu, *alist;
1019                 for (amenu = (GTK_MENU_SHELL(menu)->children); amenu; ) {
1020                         alist = amenu->next;
1021                         gtk_widget_destroy(GTK_WIDGET(amenu->data));
1022                         amenu = alist;
1023                 }
1024         }
1025
1026         ifentry.accelerator     = NULL;
1027         ifentry.callback_action = 0;
1028         ifentry.callback        = callback;
1029         ifentry.item_type       = NULL;
1030
1031         for (cur = prefs_common.actionslst; cur; cur = cur->next) {
1032                 action   = g_strdup((gchar *) cur->data);
1033                 action_p = strstr(action, ": ");
1034                 if (action_p && action_p[2] &&
1035                     get_action_type(&action_p[2]) != ACTION_ERROR) {
1036                         action_p[0] = 0x00;
1037                         menu_path = g_strdup_printf("%s/%s", branch_path, 
1038                                                     action);
1039                         ifentry.path = menu_path;
1040                         gtk_item_factory_create_item(ifactory, &ifentry, data,
1041                                                      1);
1042                         g_free(menu_path);
1043                 }
1044                 g_free(action);
1045                 ifentry.callback_action++;      
1046         }
1047 }
1048
1049 static void compose_actions_execute_cb  (Compose        *compose,
1050                                          guint           action_nb,
1051                                          GtkWidget      *widget)
1052 {
1053         gchar *buf, *action;
1054         guint action_type;      
1055
1056         g_return_if_fail(action_nb < g_slist_length(prefs_common.actionslst));
1057         
1058         buf = (gchar *) g_slist_nth_data(prefs_common.actionslst, action_nb);
1059         
1060         g_return_if_fail(buf);
1061         g_return_if_fail(action = strstr(buf, ": "));
1062
1063         /* Point to the beginning of the command-line */
1064         action++;
1065         action++;
1066         
1067         action_type = get_action_type(action);
1068         if (action_type & ACTION_MULTIPLE ||
1069             action_type & ACTION_SINGLE   ) {           
1070                 alertpanel_warning(_("The selected action is not a pipe "
1071                                      "action.\n You can only use pipe actions "
1072                                      "when composing a message."));
1073                 return;
1074         }
1075
1076         execute_actions(action, compose->window, NULL, compose->text, NULL);
1077 }
1078
1079 static void mainwin_actions_execute_cb  (MainWindow     *mainwin,
1080                                          guint           action_nb,
1081                                          GtkWidget      *widget)
1082 {
1083         MessageView *messageview = mainwin->messageview;
1084         GtkWidget   *text = NULL;
1085         gchar       *buf,
1086                     *action;
1087         MimeView    *mimeview = NULL;
1088
1089         g_return_if_fail (action_nb < g_slist_length(prefs_common.actionslst));
1090
1091         buf = (gchar *) g_slist_nth_data(prefs_common.actionslst, action_nb);
1092         
1093         g_return_if_fail(buf);
1094         g_return_if_fail(action = strstr(buf, ": "));
1095
1096         /* Point to the beginning of the command-line */
1097         action++;
1098         action++;
1099
1100         switch (messageview->type) {
1101                 case MVIEW_TEXT:
1102                         if (messageview->textview && 
1103                             messageview->textview->text)
1104                                 text = messageview->textview->text;
1105                         break;
1106                 case MVIEW_MIME:
1107                         if (messageview->mimeview &&
1108                             messageview->mimeview->type == MIMEVIEW_TEXT &&
1109                             messageview->mimeview->textview &&
1110                             messageview->mimeview->textview->text) {
1111                                 text = messageview->mimeview->textview->text;
1112                                 mimeview = messageview->mimeview;
1113                         }
1114                         break;
1115         }
1116
1117         execute_actions(action, mainwin->window,
1118                         GTK_CTREE(mainwin->summaryview->ctree), text, mimeview);
1119 }
1120
1121 static gboolean execute_actions(gchar     *action, 
1122                                 GtkWidget *window,
1123                                 GtkCTree  *ctree, 
1124                                 GtkWidget *text,
1125                                 MimeView  *mimeview)
1126 {
1127         GList *cur, *selection;
1128         GSList *children_list = NULL;
1129         gint is_ok  = TRUE;
1130         gint selection_len;
1131         Children *children;
1132         ChildInfo *child_info;
1133         gint action_type;
1134         MsgInfo *msginfo;
1135         gchar *cmd;
1136
1137         g_return_val_if_fail(action && *action, FALSE);
1138
1139         action_type = get_action_type(action);
1140
1141         if (action_type == ACTION_ERROR)
1142                 return FALSE;         /* ERR: syntax error */
1143
1144         if (action_type & (ACTION_SINGLE | ACTION_MULTIPLE) && 
1145             !(ctree && GTK_CLIST(ctree)->selection))
1146                 return FALSE;         /* ERR: file command without selection */
1147
1148         if (ctree) {
1149                 selection = GTK_CLIST(ctree)->selection;
1150                 selection_len = g_list_length(selection);
1151         }
1152         
1153         if ((action_type & (ACTION_PIPE_OUT | ACTION_PIPE_IN))) {
1154                 if (ctree && selection_len > 1)
1155                         return FALSE; /* ERR: pipe + multiple selection */
1156                 if (!text)
1157                         return FALSE; /* ERR: pipe and no displayed text */
1158         }
1159
1160         if (!(action_type & ACTION_ASYNC) && window) {
1161                 gtk_widget_set_sensitive(window, FALSE);
1162         }
1163
1164         children = g_new0(Children, 1);
1165
1166         if (action_type & ACTION_SINGLE) {
1167                 for (cur = selection; cur && is_ok == TRUE; cur = cur->next) {
1168                         msginfo = gtk_ctree_node_get_row_data(ctree,
1169                                         GTK_CTREE_NODE(cur->data));
1170                         if (!msginfo) {
1171                                 is_ok  = FALSE; /* ERR: msginfo missing */
1172                                 break;
1173                         }
1174                         cmd = parse_action_cmd(action, msginfo, ctree,
1175                                                mimeview);
1176                         if (!cmd) {
1177                                 debug_print(_("Action command error\n"));
1178                                 is_ok  = FALSE; /* ERR: incorrect command */
1179                                 break;
1180                         }
1181                         if ((child_info = fork_child(cmd, action_type, text,
1182                                                      children))) {
1183                                 children_list = g_slist_append(children_list,
1184                                                                child_info);
1185                                 children->open_in = (selection_len == 1) ? 
1186                                                     (action_type & 
1187                                                      (ACTION_OPEN_IN |
1188                                                       ACTION_HIDE_IN)) : 0;
1189                         }
1190                         g_free(cmd);
1191                 }
1192         } else {
1193                 cmd = parse_action_cmd(action, NULL, ctree, mimeview);
1194                 if (cmd) {
1195                         if ((child_info = fork_child(cmd, action_type, text,
1196                                                      children))) {
1197                                 children_list = g_slist_append(children_list,
1198                                                                child_info);
1199                                 children->open_in = action_type &
1200                                                     (ACTION_OPEN_IN |
1201                                                      ACTION_HIDE_IN);
1202                         }
1203                         g_free(cmd);
1204                 } else
1205                         is_ok  = FALSE;         /* ERR: incorrect command */
1206         }
1207
1208         if (!children_list) {
1209                  /* If not waiting for children, return */
1210                 g_free(children);
1211                 if (!(action_type & ACTION_ASYNC) && window) {
1212                         gtk_widget_set_sensitive(window, TRUE);
1213                 }
1214         } else {
1215                 GSList *cur;
1216                 
1217                 children->action  = g_strdup(action);
1218                 children->window  = window;
1219                 children->dialog  = NULL;
1220                 children->list    = children_list;
1221                 children->nb      = g_slist_length(children_list);
1222
1223                 for (cur = children_list; cur; cur = cur->next) {
1224                         child_info = (ChildInfo *) cur->data;
1225                         child_info->tag_status = 
1226                                 gdk_input_add(child_info->chld_status,
1227                                               GDK_INPUT_READ,
1228                                               catch_status, child_info);
1229                 }
1230                 children->timer = children->open_in ? 0 :
1231                                   gtk_timeout_add(WAIT_LAP, wait_for_children,
1232                                                   children);
1233         }
1234         if (children->open_in)
1235                 create_io_dialog(children);
1236
1237         return is_ok ;
1238 }
1239
1240 ChildInfo *fork_child(gchar *cmd,
1241                       gint action_type,
1242                       GtkWidget *text,
1243                       Children *children)
1244 {
1245         gint chld_in[2], chld_out[2], chld_err[2], chld_status[2];
1246         gchar **cmdline;
1247         gint start, end, is_selection;
1248         gchar *selection;
1249         pid_t pid_c, pid_gc;
1250         ChildInfo *child_info;
1251
1252         if (action_type & ACTION_ASYNC) {
1253                 execute_command_line(cmd, TRUE);
1254                 return NULL; /* Asynchronous command */
1255         }
1256
1257         if (pipe(chld_in) || pipe(chld_out) || pipe(chld_err) ||
1258             pipe(chld_status)) {
1259                 alertpanel_error(_("Command could not started. Pipe creation"
1260                                    " failed.\n%s"), g_strerror(errno));
1261                 return NULL; /* Pipe error */
1262         }
1263         
1264         debug_print(_("Forking child and grandchild.\n"));
1265
1266         pid_c = fork();
1267         if (pid_c == (pid_t) 0) {/* Child */
1268                 if (setpgid(0, 0))
1269                         perror("setpgid");
1270
1271                 close(ConnectionNumber(gdk_display));
1272
1273                 pid_gc = fork();
1274
1275                 if (pid_gc == 0) {
1276                         if (setpgid(0, getppid()))
1277                                 perror("setpgid");
1278                         if (action_type & 
1279                            (ACTION_PIPE_IN | ACTION_OPEN_IN | ACTION_HIDE_IN)) {
1280                         close(fileno(stdin));
1281                         dup  (chld_in[0]);
1282                         }
1283                         close(chld_in[0]);
1284                         close(chld_in[1]);
1285
1286                         close(fileno(stdout));
1287                         dup  (chld_out[1]);
1288                         close(chld_out[0]);
1289                         close(chld_out[1]);
1290
1291                         close(fileno(stderr));
1292                         dup  (chld_err[1]);
1293                         close(chld_err[0]);
1294                         close(chld_err[1]);
1295
1296                         cmdline = strsplit_with_quote(cmd, " ", 1024);
1297
1298                         execvp(cmdline[0], cmdline);
1299                         perror("execvp");
1300                         g_strfreev(cmdline);
1301
1302                         _exit(1);
1303                 } else if (pid_gc < (pid_t) 0) {/* Fork erro */
1304                         write(chld_status[1], "1\n", 2);
1305                         perror("fork");
1306                         _exit(1);
1307                 } else {/* Child */
1308                         close(chld_in[0]);
1309                         close(chld_in[1]);
1310                         close(chld_out[0]);
1311                         close(chld_out[1]);
1312                         close(chld_err[0]);
1313                         close(chld_err[1]);
1314
1315                         close(chld_status[0]);
1316                         debug_print(_("Child: Waiting for grandchild\n"));
1317                         waitpid(pid_gc, NULL, 0);
1318                         debug_print(_("Child: grandchild ended\n"));
1319                         write(chld_status[1], "0\n", 2);
1320                         close(chld_status[1]);
1321                         _exit(0);
1322                 }
1323         } else if (pid_c < (pid_t) 0) {/* Fork error */
1324                 alertpanel_error(_("Could not fork to execute the following "
1325                                    "command:\n%s\n%s"), 
1326                                  cmd, g_strerror(errno));
1327                 return NULL; 
1328         }
1329         /* Parent */
1330
1331         close(chld_in[0]);
1332         if (!(action_type & (ACTION_PIPE_IN | ACTION_OPEN_IN | ACTION_HIDE_IN)))
1333                 close(chld_in[1]);
1334         close(chld_out[1]);
1335         close(chld_err[1]);
1336         close(chld_status[1]);
1337
1338         child_info = g_new0(ChildInfo, 1);
1339
1340         child_info->children = children;
1341         
1342         child_info->pid      = pid_c;
1343         child_info->cmd      = g_strdup(cmd);
1344         child_info->type     = action_type;
1345         child_info->new_out  = FALSE;
1346         child_info->output   = g_string_sized_new(0);
1347         child_info->chld_in  = (action_type & (ACTION_PIPE_IN | ACTION_OPEN_IN
1348                                 | ACTION_HIDE_IN))
1349                                ? chld_in [1] : -1;
1350         child_info->chld_out = chld_out[0];
1351         child_info->chld_err = chld_err[0];
1352         child_info->chld_status = chld_status[0];
1353         child_info->tag_in   = -1;
1354         child_info->tag_out  = gdk_input_add(chld_out[0], GDK_INPUT_READ,
1355                                              catch_output, child_info);
1356         child_info->tag_err  = gdk_input_add(chld_err[0], GDK_INPUT_READ,
1357                                              catch_output, child_info);
1358
1359         if (!(action_type & (ACTION_PIPE_IN | ACTION_PIPE_OUT)))
1360                 return child_info;
1361
1362         child_info->text     = text;
1363
1364         start = 0;
1365         end   = gtk_stext_get_length(GTK_STEXT(text));
1366
1367         if (GTK_EDITABLE(text)->has_selection) {
1368                 start = GTK_EDITABLE(text)->selection_start_pos;
1369                 end   = GTK_EDITABLE(text)->selection_end_pos;
1370                 if (start > end) {
1371                         gint tmp;
1372                         tmp = start;
1373                         start = end;
1374                         end = tmp;
1375                 }
1376                 is_selection = TRUE;
1377                 if (start == end) {
1378                         start = 0;
1379                         end   = gtk_stext_get_length(GTK_STEXT(text));
1380                         is_selection = FALSE;
1381                 }
1382         }
1383
1384         selection = gtk_editable_get_chars(GTK_EDITABLE(text), start, end);
1385
1386
1387         if (action_type & ACTION_PIPE_IN) {
1388                 write(chld_in[1], selection, strlen(selection));
1389                 if (!(action_type & (ACTION_OPEN_IN | ACTION_HIDE_IN)))
1390                         close(chld_in[1]);
1391                 child_info->chld_in = -1; /* No more input */
1392         }
1393         g_free(selection);
1394
1395         gtk_stext_freeze(GTK_STEXT(text));
1396         if (action_type & ACTION_PIPE_OUT) {
1397                 gtk_stext_set_point(GTK_STEXT(text), start);
1398                 gtk_stext_forward_delete(GTK_STEXT(text), end - start);
1399         }
1400
1401         gtk_stext_thaw(GTK_STEXT(text));
1402         
1403         return child_info;
1404 }
1405         
1406 static void kill_children_cb(GtkWidget *widget, gpointer data)
1407 {
1408         GSList *cur;
1409         Children *children = (Children *) data;
1410         ChildInfo *child_info;
1411
1412         for (cur = children->list; cur; cur = cur->next) {
1413                 child_info = (ChildInfo *)(cur->data);
1414                 debug_print(_("Killing child group id %d\n"), child_info->pid);
1415                 if (child_info->pid && (kill(-child_info->pid, SIGTERM) < 0))
1416                                 perror("kill");
1417         }
1418 }
1419
1420 static gint wait_for_children(gpointer data)
1421 {
1422         gboolean new_output;
1423         Children *children = (Children *) data;
1424         ChildInfo *child_info;
1425         GSList *cur;
1426         gint nb = children->nb;
1427
1428         children->nb = 0;
1429                 
1430         cur = children->list;
1431         new_output = FALSE;
1432         while (cur) {
1433                 child_info = (ChildInfo *) cur->data;
1434                 if (child_info->pid)
1435                         children->nb++;
1436                 new_output |= child_info->new_out;
1437                 cur = cur->next;
1438         }
1439
1440         if (!children->dialog && 
1441             (new_output || children->timer))
1442                 create_io_dialog(children);
1443         
1444         if (children->timer) {
1445                 gtk_timeout_remove(children->timer);
1446                 children->timer = 0;
1447         }
1448         children->output |= new_output;
1449
1450         if (new_output || (children->dialog && (nb != children->nb)))
1451                 update_io_dialog(children);
1452
1453         if (children->nb)
1454                 return FALSE;
1455
1456         if (!children->dialog) {
1457                 gtk_widget_set_sensitive(children->window, TRUE);
1458                 free_children(children);
1459         } else if (!children->output) {
1460                 gtk_widget_destroy(children->dialog);
1461         }
1462         return FALSE;
1463 }
1464
1465 static void send_input(GtkWidget *w, gpointer data)
1466 {
1467         Children *children = (Children *) data;
1468         ChildInfo *child_info = (ChildInfo *) children->list->data;
1469         
1470         child_info->tag_in = gdk_input_add(child_info->chld_in,
1471                                            GDK_INPUT_WRITE,
1472                                            catch_input, children);
1473         gtk_widget_set_sensitive(children->input_hbox, FALSE);
1474 }
1475
1476 static gint delete_io_dialog_cb(GtkWidget *w, GdkEvent *e, gpointer data)
1477 {
1478         hide_io_dialog_cb(w, data);
1479         return TRUE;
1480 }
1481
1482 static void hide_io_dialog_cb(GtkWidget *w, gpointer data)
1483 {
1484
1485         Children *children = (Children *) data;
1486
1487         if (!children->nb) {
1488                 gtk_widget_set_sensitive(children->window, TRUE);
1489                 gtk_signal_disconnect_by_data(GTK_OBJECT(children->dialog),
1490                                               children);
1491                 gtk_widget_destroy(children->dialog);
1492                 free_children(children);
1493         }
1494 }
1495
1496 static void childinfo_close_pipes(ChildInfo *child_info)
1497 {
1498         if (child_info->tag_in > 0)
1499                 gdk_input_remove(child_info->tag_in);
1500         gdk_input_remove(child_info->tag_out);
1501         gdk_input_remove(child_info->tag_err);
1502
1503         if (child_info->chld_in >= 0)
1504                 close(child_info->chld_in);
1505         close(child_info->chld_out);
1506         close(child_info->chld_err);
1507         close(child_info->chld_status);
1508 }
1509
1510 static void free_children(Children *children)
1511 {
1512         GSList *cur;
1513         ChildInfo *child_info;
1514
1515         debug_print(_("Freeing children data %x\n"), (guint) children);
1516                                 
1517         g_free(children->action);
1518         for (cur = children->list; cur;) {
1519                 child_info = (ChildInfo *) cur->data;
1520                 g_free(child_info->cmd);
1521                 g_string_free(child_info->output, TRUE);
1522                 children->list = g_slist_remove(children->list, child_info);
1523                 g_free(child_info);
1524                 cur = children->list;
1525         }
1526         g_free(children);
1527 }       
1528
1529 static void update_io_dialog(Children *children)
1530 {
1531         GSList *cur;
1532
1533         debug_print(_("Updating actions input/output dialog.\n"));
1534
1535         if (!children->nb) {
1536                 gtk_widget_set_sensitive(children->abort_btn, FALSE);
1537                 gtk_widget_set_sensitive(children->hide_btn, TRUE);
1538                 gtk_widget_set_sensitive(children->window, TRUE);
1539                 if (children->input_hbox)
1540                         gtk_widget_set_sensitive(children->input_hbox, FALSE);
1541         }
1542
1543         if (children->output) {
1544                 GtkWidget *text = children->text;
1545                 gchar *caption;
1546                 ChildInfo *child_info;
1547
1548                 gtk_widget_show(children->scrolledwin);
1549                 gtk_text_freeze(GTK_TEXT(text));
1550                 gtk_text_set_point(GTK_TEXT(text), 0);
1551                 gtk_text_forward_delete(GTK_TEXT(text), 
1552                                         gtk_text_get_length(GTK_TEXT(text)));
1553                 for (cur = children->list; cur; cur = cur->next)
1554                 {
1555                         child_info = (ChildInfo *) cur->data;
1556                         if (child_info->pid)
1557                                 caption = g_strdup_printf(_("--- Running: %s\n")
1558                                                     , child_info->cmd);
1559                         else
1560                                 caption = g_strdup_printf(_("--- Ended: %s\n")
1561                                                     , child_info->cmd);
1562                         
1563                         gtk_text_insert(GTK_TEXT(text), NULL, NULL, NULL,
1564                                          caption, -1);
1565                         gtk_text_insert(GTK_TEXT(text), NULL, NULL, NULL,
1566                                          child_info->output->str, -1);
1567                         g_free(caption);
1568                         child_info->new_out = FALSE;
1569                 }
1570                 gtk_text_thaw(GTK_TEXT(text));
1571         }
1572 }
1573         
1574         
1575 static void create_io_dialog(Children *children)
1576 {
1577         GtkWidget *dialog;
1578         GtkWidget *entry;
1579         GtkWidget *input_hbox;
1580         GtkWidget *send_button;
1581         GtkWidget *label;
1582         GtkWidget *text;
1583         GtkWidget *scrolledwin;
1584         GtkWidget *hbox;
1585         GtkWidget *abort_button;
1586         GtkWidget *hide_button;
1587         
1588         debug_print(_("Creating actions dialog\n"));
1589
1590         dialog = gtk_dialog_new();
1591         label = gtk_label_new(children->action);
1592         gtk_misc_set_padding(GTK_MISC(label), 8, 8);
1593         gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->vbox), label, FALSE, 
1594                            FALSE, 0);
1595
1596         gtk_window_set_title(GTK_WINDOW(dialog), _("Actions' input/output"));
1597         gtk_signal_connect(GTK_OBJECT(dialog), "delete_event",
1598                         GTK_SIGNAL_FUNC(delete_io_dialog_cb), children);
1599         gtk_signal_connect(GTK_OBJECT(dialog), "destroy",
1600                         GTK_SIGNAL_FUNC(hide_io_dialog_cb),
1601                         children);
1602
1603         scrolledwin = gtk_scrolled_window_new(NULL, NULL);
1604         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledwin),
1605                                        GTK_POLICY_NEVER, GTK_POLICY_ALWAYS);
1606         gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->vbox), scrolledwin, TRUE,
1607                            TRUE, 0);
1608         gtk_widget_set_usize(scrolledwin, 600, 200);
1609         gtk_widget_hide(scrolledwin);
1610
1611         text = gtk_text_new(gtk_scrolled_window_get_hadjustment
1612                             (GTK_SCROLLED_WINDOW(scrolledwin)),
1613                             gtk_scrolled_window_get_vadjustment
1614                             (GTK_SCROLLED_WINDOW(scrolledwin)));
1615         gtk_text_set_editable(GTK_TEXT(text), FALSE);
1616         gtk_container_add(GTK_CONTAINER(scrolledwin), text);
1617         gtk_widget_show(text);
1618
1619         if (children->open_in) {
1620                 input_hbox = gtk_hbox_new(FALSE, 8);
1621                 gtk_widget_show(input_hbox);
1622
1623                 entry = gtk_entry_new();
1624                 gtk_signal_connect(GTK_OBJECT(entry), "activate",
1625                                    GTK_SIGNAL_FUNC(send_input), children);
1626                 gtk_box_pack_start(GTK_BOX(input_hbox), entry, TRUE, TRUE, 8);
1627                 if (children->open_in & ACTION_HIDE_IN)
1628                         gtk_entry_set_visibility(GTK_ENTRY(entry), FALSE);
1629                 gtk_widget_show(entry);
1630
1631                 send_button = gtk_button_new_with_label(_("Send"));
1632                 gtk_signal_connect(GTK_OBJECT(send_button), "clicked",
1633                                    GTK_SIGNAL_FUNC(send_input), children);
1634                 gtk_box_pack_start(GTK_BOX(input_hbox), send_button, FALSE, 
1635                                    FALSE, 8);
1636                 gtk_widget_show(send_button);
1637
1638                 gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->vbox), 
1639                                 input_hbox, FALSE, FALSE, 8);
1640                 gtk_widget_grab_focus(entry);
1641         }
1642
1643         hbox = gtk_hbox_new(TRUE, 0);
1644         gtk_widget_show(hbox);
1645
1646         abort_button = gtk_button_new_with_label(_("Abort actions"));
1647         gtk_signal_connect(GTK_OBJECT(abort_button), "clicked",
1648                         GTK_SIGNAL_FUNC(kill_children_cb), children);
1649         gtk_box_pack_start(GTK_BOX(hbox), abort_button, TRUE, TRUE, 8);
1650         gtk_widget_show(abort_button);
1651
1652         hide_button = gtk_button_new_with_label(_("Close window"));
1653         gtk_signal_connect(GTK_OBJECT(hide_button), "clicked",
1654                         GTK_SIGNAL_FUNC(hide_io_dialog_cb), children);
1655         gtk_box_pack_start(GTK_BOX(hbox), hide_button, TRUE, TRUE, 8);
1656         gtk_widget_show(hide_button);
1657
1658         if (children->nb)
1659                 gtk_widget_set_sensitive(hide_button, FALSE);
1660
1661         gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog)->action_area), 
1662                           hbox);
1663
1664         children->dialog      = dialog;
1665         children->scrolledwin = scrolledwin;
1666         children->text        = text;
1667         children->input_hbox  = children->open_in ? input_hbox : NULL;
1668         children->input_entry = children->open_in ? entry : NULL;
1669         children->abort_btn   = abort_button;
1670         children->hide_btn    = hide_button;
1671
1672         gtk_widget_show(dialog);
1673 }
1674
1675 static void catch_status(gpointer data, gint source, GdkInputCondition cond)
1676 {
1677         ChildInfo *child_info = (ChildInfo *) data;
1678         gchar buf;
1679         gint c;
1680
1681         gdk_input_remove(child_info->tag_status);
1682
1683         c = read(source, &buf, 1);
1684         debug_print(_("Child returned %c\n"), buf);
1685
1686         waitpid(-child_info->pid, NULL, 0);
1687         childinfo_close_pipes(child_info);
1688         child_info->pid = 0;
1689         
1690         wait_for_children(child_info->children);
1691 }
1692         
1693 static void catch_input(gpointer data, gint source, GdkInputCondition cond)
1694 {
1695         Children *children = (Children *) data;
1696         ChildInfo *child_info = (ChildInfo *) children->list->data;
1697         gchar *input;
1698         gint c;
1699
1700         debug_print(_("Sending input to grand child.\n"));
1701         if (!(cond && GDK_INPUT_WRITE))
1702                 return;
1703         
1704         gdk_input_remove(child_info->tag_in);
1705         child_info->tag_in = -1;
1706
1707         input = gtk_editable_get_chars(GTK_EDITABLE(children->input_entry), 0,
1708                                        -1);
1709         c = write(child_info->chld_in, input, strlen(input));
1710
1711         g_free(input);
1712
1713         write(child_info->chld_in, "\n", 2);
1714
1715         gtk_entry_set_text(GTK_ENTRY(children->input_entry), "");
1716         gtk_widget_set_sensitive(children->input_hbox, TRUE);
1717         debug_print(_("Input to grand child sent.\n"));
1718 }
1719
1720 static void catch_output(gpointer data, gint source, GdkInputCondition cond)
1721 {
1722         ChildInfo *child_info = (ChildInfo *) data;
1723         gint c, i;
1724         gchar buf[PREFSBUFSIZE];
1725
1726         debug_print(_("Catching grand child's output.\n"));
1727         if (child_info->type & ACTION_PIPE_OUT
1728             && source == child_info->chld_out) {
1729                 gboolean is_selection = FALSE;
1730                 GtkWidget *text = child_info->text;
1731                 if (GTK_EDITABLE(text)->has_selection)
1732                         is_selection = TRUE;
1733                 gtk_stext_freeze(GTK_STEXT(text));
1734                 while (TRUE) {
1735                         c =read(source, buf, PREFSBUFSIZE - 1);
1736                         if (c == 0)
1737                                 break;
1738                         gtk_stext_insert(GTK_STEXT(text), NULL, NULL, NULL,
1739                                          buf, c);
1740                 }
1741                 if (is_selection) {
1742                         /* Using the select_region draws things. Should not.
1743                          * so we just change selection position and 
1744                          * defere drawing when thawing. Hack?
1745                          */
1746                         GTK_EDITABLE(text)->selection_end_pos = 
1747                                         gtk_stext_get_point(GTK_STEXT(text));
1748                 }
1749                 gtk_stext_thaw(GTK_STEXT(child_info->text));
1750         } else {
1751                 c = read(source, buf, PREFSBUFSIZE - 1);
1752                 for (i = 0; i < c; i++)
1753                         child_info->output = g_string_append_c(
1754                                         child_info->output, buf[i]);
1755                 if (c > 0)
1756                         child_info->new_out = TRUE;
1757                         
1758                 
1759         }
1760 }