Statistics
| Revision:

root / src / action.c @ 1

History | View | Annotate | Download (31.5 KB)

1
/*
2
 * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3
 * Copyright (C) 1999-2004 Hiroyuki Yamamoto & The Sylpheed Claws Team
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
#ifdef GDK_WINDOWING_X11
30
#  include <gdk/gdkx.h>
31
#endif /* GDK_WINDOWING_X11 */
32
#include <stdio.h>
33
#include <stdlib.h>
34
#include <string.h>
35
#include <errno.h>
36
#include <sys/types.h>
37
#include <sys/wait.h>
38
#include <signal.h>
39
#include <unistd.h>
40

    
41
#include "intl.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 "inputdialog.h"
49
#include "action.h"
50
#include "compose.h"
51
#include "procmsg.h"
52
#include "textview.h"
53

    
54
typedef struct _Children                Children;
55
typedef struct _ChildInfo                ChildInfo;
56
typedef struct _UserStringDialog        UserStringDialog;
57

    
58
struct _Children
59
{
60
        GtkWidget        *dialog;
61
        GtkWidget        *text;
62
        GtkWidget        *input_entry;
63
        GtkWidget        *input_hbox;
64
        GtkWidget        *abort_btn;
65
        GtkWidget        *close_btn;
66
        GtkWidget        *scrolledwin;
67

    
68
        gchar                *action;
69
        ActionType         action_type;
70
        GSList                *list;
71
        gint                 nb;
72
        gint                 open_in;
73
        gboolean         output;
74

    
75
        GtkWidget        *msg_text;
76

    
77
        gboolean         is_selection;
78
};
79

    
80
struct _ChildInfo
81
{
82
        Children        *children;
83
        gchar                *cmd;
84
        pid_t                 pid;
85
        gint                 chld_in;
86
        gint                 chld_out;
87
        gint                 chld_err;
88
        gint                 chld_status;
89
        gint                 tag_in;
90
        gint                 tag_out;
91
        gint                 tag_err;
92
        gint                 tag_status;
93
        gint                 new_out;
94

    
95
        GString                *output;
96
};
97

    
98
static void action_update_menu                (GtkItemFactory        *ifactory,
99
                                         gchar                *branch_path,
100
                                         gpointer         callback,
101
                                         gpointer         data);
102
static void compose_actions_execute_cb        (Compose        *compose,
103
                                         guint                 action_nb,
104
                                         GtkWidget        *widget);
105
static void mainwin_actions_execute_cb         (MainWindow        *mainwin,
106
                                         guint                 action_nb,
107
                                         GtkWidget         *widget);
108
static void msgview_actions_execute_cb        (MessageView        *msgview,
109
                                         guint                 action_nb,
110
                                         GtkWidget        *widget);
111
static void message_actions_execute        (MessageView        *msgview,
112
                                         guint                 action_nb,
113
                                         GSList                *msg_list);
114

    
115
static gboolean execute_actions                (gchar                *action, 
116
                                         GSList                *msg_list, 
117
                                         GtkWidget        *text,
118
                                         gint                 body_pos,
119
                                         MimeInfo        *partinfo);
120

    
121
static gchar *parse_action_cmd                (gchar                *action,
122
                                         MsgInfo        *msginfo,
123
                                         GSList                *msg_list,
124
                                         MimeInfo        *partinfo,
125
                                         const gchar        *user_str,
126
                                         const gchar        *user_hidden_str,
127
                                         const gchar        *sel_str);
128
static gboolean parse_append_filename        (GString        *cmd,
129
                                         MsgInfo        *msginfo);
130

    
131
static gboolean parse_append_msgpart        (GString        *cmd,
132
                                         MsgInfo        *msginfo,
133
                                         MimeInfo        *partinfo);
134

    
135
static ChildInfo *fork_child                (gchar                *cmd,
136
                                         const gchar        *msg_str,
137
                                         Children        *children);
138

    
139
static gint wait_for_children                (Children        *children);
140

    
141
static void free_children                (Children        *children);
142

    
143
static void childinfo_close_pipes        (ChildInfo        *child_info);
144

    
145
static void create_io_dialog                (Children        *children);
146
static void update_io_dialog                (Children        *children);
147

    
148
static void hide_io_dialog_cb                (GtkWidget        *widget,
149
                                         gpointer         data);
150
static gint io_dialog_key_pressed_cb        (GtkWidget        *widget,
151
                                         GdkEventKey        *event,
152
                                         gpointer         data);
153

    
154
static void catch_output                (gpointer                 data,
155
                                         gint                         source,
156
                                         GdkInputCondition         cond);
157
static void catch_input                        (gpointer                 data, 
158
                                         gint                         source,
159
                                         GdkInputCondition         cond);
160
static void catch_status                (gpointer                 data,
161
                                         gint                         source,
162
                                         GdkInputCondition         cond);
163

    
164
static gchar *get_user_string                (const gchar        *action,
165
                                         ActionType         type);
166

    
167

    
168
ActionType action_get_type(const gchar *action_str)
169
{
170
        const gchar *p;
171
        ActionType action_type = ACTION_NONE;
172

    
173
        g_return_val_if_fail(action_str,  ACTION_ERROR);
174
        g_return_val_if_fail(*action_str, ACTION_ERROR);
175

    
176
        p = action_str;
177

    
178
        if (p[0] == '|') {
179
                action_type |= ACTION_PIPE_IN;
180
                p++;
181
        } else if (p[0] == '>') {
182
                action_type |= ACTION_USER_IN;
183
                p++;
184
        } else if (p[0] == '*') {
185
                action_type |= ACTION_USER_HIDDEN_IN;
186
                p++;
187
        }
188

    
189
        if (p[0] == '\0')
190
                return ACTION_ERROR;
191

    
192
        while (*p && action_type != ACTION_ERROR) {
193
                if (p[0] == '%') {
194
                        switch (p[1]) {
195
                        case 'f':
196
                                action_type |= ACTION_SINGLE;
197
                                break;
198
                        case 'F':
199
                                action_type |= ACTION_MULTIPLE;
200
                                break;
201
                        case 'p':
202
                                action_type |= ACTION_SINGLE;
203
                                break;
204
                        case 's':
205
                                action_type |= ACTION_SELECTION_STR;
206
                                break;
207
                        case 'u':
208
                                action_type |= ACTION_USER_STR;
209
                                break;
210
                        case 'h':
211
                                action_type |= ACTION_USER_HIDDEN_STR;
212
                                break;
213
                        default:
214
                                action_type = ACTION_ERROR;
215
                                break;
216
                        }
217
                } else if (p[0] == '|') {
218
                        if (p[1] == '\0')
219
                                action_type |= ACTION_PIPE_OUT;
220
                } else if (p[0] == '>') {
221
                        if (p[1] == '\0')
222
                                action_type |= ACTION_INSERT;
223
                } else if (p[0] == '&') {
224
                        if (p[1] == '\0')
225
                                action_type |= ACTION_ASYNC;
226
                }
227
                p++;
228
        }
229

    
230
        return action_type;
231
}
232

    
233
static gchar *parse_action_cmd(gchar *action, MsgInfo *msginfo,
234
                               GSList *msg_list, MimeInfo *partinfo,
235
                               const gchar *user_str,
236
                               const gchar *user_hidden_str,
237
                               const gchar *sel_str)
238
{
239
        GString *cmd;
240
        gchar *p;
241
        GSList *cur;
242
        
243
        p = action;
244
        
245
        if (p[0] == '|' || p[0] == '>' || p[0] == '*')
246
                p++;
247

    
248
        cmd = g_string_sized_new(strlen(action));
249

    
250
        while (p[0] &&
251
               !((p[0] == '|' || p[0] == '>' || p[0] == '&') && !p[1])) {
252
                if (p[0] == '%' && p[1]) {
253
                        switch (p[1]) {
254
                        case 'f':
255
                                if (!parse_append_filename(cmd, msginfo)) {
256
                                        g_string_free(cmd, TRUE);
257
                                        return NULL;
258
                                }
259
                                p++;
260
                                break;
261
                        case 'F':
262
                                for (cur = msg_list; cur != NULL;
263
                                     cur = cur->next) {
264
                                        MsgInfo *msg = (MsgInfo *)cur->data;
265

    
266
                                        if (!parse_append_filename(cmd, msg)) {
267
                                                g_string_free(cmd, TRUE);
268
                                                return NULL;
269
                                        }
270
                                        if (cur->next)
271
                                                g_string_append_c(cmd, ' ');
272
                                }
273
                                p++;
274
                                break;
275
                        case 'p':
276
                                if (!parse_append_msgpart(cmd, msginfo,
277
                                                          partinfo)) {
278
                                        g_string_free(cmd, TRUE);
279
                                        return NULL;
280
                                }
281
                                p++;
282
                                break;
283
                        case 's':
284
                                if (sel_str)
285
                                        g_string_append(cmd, sel_str);
286
                                p++;
287
                                break;
288
                        case 'u':
289
                                if (user_str)
290
                                        g_string_append(cmd, user_str);
291
                                p++;
292
                                break;
293
                        case 'h':
294
                                if (user_hidden_str)
295
                                        g_string_append(cmd, user_hidden_str);
296
                                p++;
297
                                break;
298
                        default:
299
                                g_string_append_c(cmd, p[0]);
300
                                g_string_append_c(cmd, p[1]);
301
                                p++;
302
                        }
303
                } else {
304
                        g_string_append_c(cmd, p[0]);
305
                }
306
                p++;
307
        }
308
        if (cmd->len == 0) {
309
                g_string_free(cmd, TRUE);
310
                return NULL;
311
        }
312

    
313
        p = cmd->str;
314
        g_string_free(cmd, FALSE);
315
        return p;
316
}
317

    
318
static gboolean parse_append_filename(GString *cmd, MsgInfo *msginfo)
319
{
320
        gchar *filename;
321
        gchar *p, *q;
322
        gchar escape_ch[] = "\\ ";
323

    
324
        g_return_val_if_fail(msginfo, FALSE);
325

    
326
        filename = procmsg_get_message_file(msginfo);
327

    
328
        if (!filename) {
329
                alertpanel_error(_("Could not get message file %d"),
330
                                 msginfo->msgnum);
331
                return FALSE;
332
        }
333

    
334
        p = filename;
335
        while ((q = strpbrk(p, "$\"`'\\ \t*?[]&|;<>()!#~")) != NULL) {
336
                escape_ch[1] = *q;
337
                *q = '\0';
338
                g_string_append(cmd, p);
339
                g_string_append(cmd, escape_ch);
340
                p = q + 1;
341
        }
342
        g_string_append(cmd, p);
343

    
344
        g_free(filename);
345

    
346
        return TRUE;
347
}
348

    
349
static gboolean parse_append_msgpart(GString *cmd, MsgInfo *msginfo,
350
                                     MimeInfo *partinfo)
351
{
352
        gboolean single_part = FALSE;
353
        gchar *filename;
354
        gchar *part_filename;
355
        gint ret;
356

    
357
        if (!partinfo) {
358
                partinfo = procmime_scan_message(msginfo);
359
                if (!partinfo) {
360
                        alertpanel_error(_("Could not get message part."));
361
                        return FALSE;
362
                }
363

    
364
                single_part = TRUE;
365
        }
366

    
367
        filename = procmsg_get_message_file_path(msginfo);
368
        part_filename = procmime_get_tmp_file_name(partinfo);
369

    
370
        ret = procmime_get_part(part_filename, filename, partinfo); 
371

    
372
        if (single_part)
373
                procmime_mimeinfo_free_all(partinfo);
374
        g_free(filename);
375

    
376
        if (ret < 0) {
377
                alertpanel_error(_("Can't get part of multipart message"));
378
                g_free(part_filename);
379
                return FALSE;
380
        }
381

    
382
        g_string_append(cmd, part_filename);
383

    
384
        g_free(part_filename);
385

    
386
        return TRUE;
387
}
388

    
389
void action_update_mainwin_menu(GtkItemFactory *ifactory, MainWindow *mainwin)
390
{
391
        action_update_menu(ifactory, "/Tools/Actions",
392
                           mainwin_actions_execute_cb, mainwin);
393
}
394

    
395
void action_update_msgview_menu(GtkItemFactory *ifactory, MessageView *msgview)
396
{
397
        action_update_menu(ifactory, "/Tools/Actions",
398
                           msgview_actions_execute_cb, msgview);
399
}
400

    
401
void action_update_compose_menu(GtkItemFactory *ifactory, Compose *compose)
402
{
403
        action_update_menu(ifactory, "/Tools/Actions",
404
                           compose_actions_execute_cb, compose);
405
}
406

    
407
static void action_update_menu(GtkItemFactory *ifactory, gchar *branch_path,
408
                               gpointer callback, gpointer data)
409
{
410
        GtkWidget *menuitem;
411
        gchar *menu_path;
412
        GSList *cur;
413
        gchar *action, *action_p;
414
        GList *amenu;
415
        GtkItemFactoryEntry ifentry = {NULL, NULL, NULL, 0, "<Branch>"};
416

    
417
        ifentry.path = branch_path;
418
        menuitem = gtk_item_factory_get_widget(ifactory, branch_path);
419
        g_return_if_fail(menuitem != NULL);
420

    
421
        amenu = GTK_MENU_SHELL(menuitem)->children;
422
        while (amenu != NULL) {
423
                GList *alist = amenu->next;
424
                gtk_widget_destroy(GTK_WIDGET(amenu->data));
425
                amenu = alist;
426
        }
427

    
428
        ifentry.accelerator     = NULL;
429
        ifentry.callback_action = 0;
430
        ifentry.callback        = callback;
431
        ifentry.item_type       = NULL;
432

    
433
        for (cur = prefs_common.actions_list; cur; cur = cur->next) {
434
                action   = g_strdup((gchar *)cur->data);
435
                action_p = strstr(action, ": ");
436
                if (action_p && action_p[2] &&
437
                    action_get_type(&action_p[2]) != ACTION_ERROR) {
438
                        action_p[0] = '\0';
439
                        menu_path = g_strdup_printf("%s/%s", branch_path,
440
                                                    action);
441
                        ifentry.path = menu_path;
442
                        gtk_item_factory_create_item(ifactory, &ifentry, data,
443
                                                     1);
444
                        g_free(menu_path);
445
                }
446
                g_free(action);
447
                ifentry.callback_action++;
448
        }
449
}
450

    
451
static void compose_actions_execute_cb(Compose *compose, guint action_nb,
452
                                       GtkWidget *widget)
453
{
454
        gchar *buf, *action;
455
        ActionType action_type;
456

    
457
        g_return_if_fail(action_nb < g_slist_length(prefs_common.actions_list));
458

    
459
        buf = (gchar *)g_slist_nth_data(prefs_common.actions_list, action_nb);
460
        g_return_if_fail(buf != NULL);
461
        action = strstr(buf, ": ");
462
        g_return_if_fail(action != NULL);
463

    
464
        /* Point to the beginning of the command-line */
465
        action += 2;
466

    
467
        action_type = action_get_type(action);
468
        if (action_type & (ACTION_SINGLE | ACTION_MULTIPLE)) {
469
                alertpanel_warning
470
                        (_("The selected action cannot be used in the compose window\n"
471
                           "because it contains %%f, %%F or %%p."));
472
                return;
473
        }
474

    
475
        execute_actions(action, NULL, compose->text, 0, NULL);
476
}
477

    
478
static void mainwin_actions_execute_cb(MainWindow *mainwin, guint action_nb,
479
                                       GtkWidget *widget)
480
{
481
        GSList *msg_list;
482

    
483
        msg_list = summary_get_selected_msg_list(mainwin->summaryview);
484
        message_actions_execute(mainwin->messageview, action_nb, msg_list);
485
        g_slist_free(msg_list);
486
}
487

    
488
static void msgview_actions_execute_cb(MessageView *msgview, guint action_nb,
489
                                       GtkWidget *widget)
490
{
491
        GSList *msg_list = NULL;
492

    
493
        if (msgview->msginfo)
494
                msg_list = g_slist_append(msg_list, msgview->msginfo);
495
        message_actions_execute(msgview, action_nb, msg_list);
496
        g_slist_free(msg_list);
497
}
498

    
499
static void message_actions_execute(MessageView *msgview, guint action_nb,
500
                                    GSList *msg_list)
501
{
502
        TextView *textview;
503
        MimeInfo *partinfo;
504
        gchar *buf;
505
        gchar *action;
506
        GtkWidget *text = NULL;
507
        guint body_pos = 0;
508

    
509
        g_return_if_fail(action_nb < g_slist_length(prefs_common.actions_list));
510

    
511
        buf = (gchar *)g_slist_nth_data(prefs_common.actions_list, action_nb);
512

    
513
        g_return_if_fail(buf);
514
        g_return_if_fail((action = strstr(buf, ": ")));
515

    
516
        /* Point to the beginning of the command-line */
517
        action += 2;
518

    
519
        textview = messageview_get_current_textview(msgview);
520
        if (textview) {
521
                text     = textview->text;
522
                body_pos = textview->body_pos;
523
        }
524
        partinfo = messageview_get_selected_mime_part(msgview);
525

    
526
        execute_actions(action, msg_list, text, body_pos, partinfo);
527
}
528

    
529
static gboolean execute_actions(gchar *action, GSList *msg_list,
530
                                GtkWidget *text, gint body_pos,
531
                                MimeInfo *partinfo)
532
{
533
        GSList *children_list = NULL;
534
        gint is_ok  = TRUE;
535
        gint msg_list_len;
536
        Children *children;
537
        ChildInfo *child_info;
538
        ActionType action_type;
539
        MsgInfo *msginfo;
540
        gchar *cmd;
541
        gchar *sel_str = NULL;
542
        gchar *msg_str = NULL;
543
        gchar *user_str = NULL;
544
        gchar *user_hidden_str = NULL;
545
        GtkTextIter start_iter, end_iter;
546
        gboolean is_selection = FALSE;
547

    
548
        g_return_val_if_fail(action && *action, FALSE);
549

    
550
        action_type = action_get_type(action);
551

    
552
        if (action_type == ACTION_ERROR)
553
                return FALSE;         /* ERR: syntax error */
554

    
555
        if (action_type & (ACTION_SINGLE | ACTION_MULTIPLE) && !msg_list)
556
                return FALSE;         /* ERR: file command without selection */
557

    
558
        msg_list_len = g_slist_length(msg_list);
559

    
560
        if (action_type & (ACTION_PIPE_OUT | ACTION_PIPE_IN | ACTION_INSERT)) {
561
                if (msg_list_len > 1)
562
                        return FALSE; /* ERR: pipe + multiple selection */
563
                if (!text)
564
                        return FALSE; /* ERR: pipe and no displayed text */
565
        }
566

    
567
        if (action_type & ACTION_SELECTION_STR) {
568
                if (!text)
569
                        return FALSE; /* ERR: selection string but no text */
570
        }
571

    
572
        if (text) {
573
                GtkTextBuffer *textbuf;
574

    
575
                textbuf = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
576
                is_selection = gtk_text_buffer_get_selection_bounds
577
                        (textbuf, &start_iter, &end_iter);
578
                if (!is_selection) {
579
                        gtk_text_buffer_get_start_iter(textbuf, &start_iter);
580
                        gtk_text_buffer_get_end_iter(textbuf, &end_iter);
581
                }
582
                msg_str = gtk_text_buffer_get_text
583
                        (textbuf, &start_iter, &end_iter, FALSE);
584
                if (is_selection)
585
                        sel_str = g_strdup(msg_str);
586
        }
587

    
588
        if (action_type & ACTION_USER_STR) {
589
                if (!(user_str = get_user_string(action, ACTION_USER_STR))) {
590
                        g_free(msg_str);
591
                        g_free(sel_str);
592
                        return FALSE;
593
                }
594
        }
595

    
596
        if (action_type & ACTION_USER_HIDDEN_STR) {
597
                if (!(user_hidden_str =
598
                        get_user_string(action, ACTION_USER_HIDDEN_STR))) {
599
                        g_free(msg_str);
600
                        g_free(sel_str);
601
                        g_free(user_str);
602
                        return FALSE;
603
                }
604
        }
605

    
606
        if (text && (action_type & ACTION_PIPE_OUT)) {
607
                GtkTextBuffer *textbuf;
608
                textbuf = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
609
                gtk_text_buffer_delete(textbuf, &start_iter, &end_iter);
610
        }
611

    
612
        children = g_new0(Children, 1);
613

    
614
        children->action       = g_strdup(action);
615
        children->action_type  = action_type;
616
        children->msg_text     = text;
617
        children->is_selection = is_selection;
618

    
619
        if ((action_type & (ACTION_USER_IN | ACTION_USER_HIDDEN_IN)) &&
620
            ((action_type & ACTION_SINGLE) == 0 || msg_list_len == 1))
621
                children->open_in = 1;
622

    
623
        if (action_type & ACTION_SINGLE) {
624
                GSList *cur;
625

    
626
                for (cur = msg_list; cur && is_ok == TRUE; cur = cur->next) {
627
                        msginfo = (MsgInfo *)cur->data;
628
                        if (!msginfo) {
629
                                is_ok  = FALSE; /* ERR: msginfo missing */
630
                                break;
631
                        }
632
                        cmd = parse_action_cmd(action, msginfo, msg_list,
633
                                               partinfo, user_str,
634
                                               user_hidden_str, sel_str);
635
                        if (!cmd) {
636
                                debug_print("Action command error\n");
637
                                is_ok  = FALSE; /* ERR: incorrect command */
638
                                break;
639
                        }
640
                        if ((child_info = fork_child(cmd, msg_str, children))) {
641
                                children_list = g_slist_append(children_list,
642
                                                               child_info);
643
                        }
644
                        g_free(cmd);
645
                }
646
        } else {
647
                cmd = parse_action_cmd(action, NULL, msg_list, partinfo,
648
                                       user_str, user_hidden_str, sel_str);
649
                if (cmd) {
650
                        if ((child_info = fork_child(cmd, msg_str, children))) {
651
                                children_list = g_slist_append(children_list,
652
                                                               child_info);
653
                        }
654
                        g_free(cmd);
655
                } else
656
                        is_ok  = FALSE;         /* ERR: incorrect command */
657
        }
658

    
659
        g_free(msg_str);
660
        g_free(sel_str);
661
        g_free(user_str);
662
        g_free(user_hidden_str);
663

    
664
        if (!children_list) {
665
                 /* If not waiting for children, return */
666
                free_children(children);
667
        } else {
668
                GSList *cur;
669

    
670
                children->list              = children_list;
671
                children->nb              = g_slist_length(children_list);
672

    
673
                for (cur = children_list; cur; cur = cur->next) {
674
                        child_info = (ChildInfo *) cur->data;
675
                        child_info->tag_status = 
676
                                gdk_input_add(child_info->chld_status,
677
                                              GDK_INPUT_READ,
678
                                              catch_status, child_info);
679
                }
680

    
681
                create_io_dialog(children);
682
        }
683

    
684
        return is_ok;
685
}
686

    
687
static ChildInfo *fork_child(gchar *cmd, const gchar *msg_str,
688
                             Children *children)
689
{
690
        gint chld_in[2], chld_out[2], chld_err[2], chld_status[2];
691
        gchar *cmdline[4];
692
        pid_t pid, gch_pid;
693
        ChildInfo *child_info;
694
        gint sync;
695

    
696
        sync = !(children->action_type & ACTION_ASYNC);
697

    
698
        chld_in[0] = chld_in[1] = chld_out[0] = chld_out[1] = chld_err[0]
699
                = chld_err[1] = chld_status[0] = chld_status[1] = -1;
700

    
701
        if (sync) {
702
                if (pipe(chld_status) || pipe(chld_in) || pipe(chld_out) ||
703
                    pipe(chld_err)) {
704
                        alertpanel_error(_("Command could not be started. "
705
                                           "Pipe creation failed.\n%s"),
706
                                        g_strerror(errno));
707
                        /* Closing fd = -1 fails silently */
708
                        close(chld_in[0]);
709
                        close(chld_in[1]);
710
                        close(chld_out[0]);
711
                        close(chld_out[1]);
712
                        close(chld_err[0]);
713
                        close(chld_err[1]);
714
                        close(chld_status[0]);
715
                        close(chld_status[1]);
716
                        return NULL; /* Pipe error */
717
                }
718
        }
719

    
720
        debug_print("Forking child and grandchild.\n");
721
        debug_print("Executing: /bin/sh -c %s\n", cmd);
722

    
723
        pid = fork();
724
        if (pid == 0) { /* Child */
725
                if (setpgid(0, 0))
726
                        perror("setpgid");
727

    
728
#ifdef GDK_WINDOWING_X11
729
                close(ConnectionNumber(gdk_display));
730
#endif /* GDK_WINDOWING_X11 */
731

    
732
                gch_pid = fork();
733

    
734
                if (gch_pid == 0) {
735
                        if (setpgid(0, getppid()))
736
                                perror("setpgid");
737

    
738
                        if (sync) {
739
                                if (children->action_type &
740
                                    (ACTION_PIPE_IN |
741
                                     ACTION_USER_IN |
742
                                     ACTION_USER_HIDDEN_IN)) {
743
                                        close(fileno(stdin));
744
                                        dup  (chld_in[0]);
745
                                }
746
                                close(chld_in[0]);
747
                                close(chld_in[1]);
748

    
749
                                close(fileno(stdout));
750
                                dup  (chld_out[1]);
751
                                close(chld_out[0]);
752
                                close(chld_out[1]);
753

    
754
                                close(fileno(stderr));
755
                                dup  (chld_err[1]);
756
                                close(chld_err[0]);
757
                                close(chld_err[1]);
758
                        }
759

    
760
                        cmdline[0] = "sh";
761
                        cmdline[1] = "-c";
762
                        cmdline[2] = cmd;
763
                        cmdline[3] = NULL;
764
                        execvp("/bin/sh", cmdline);
765

    
766
                        perror("execvp");
767
                        _exit(1);
768
                } else if (gch_pid < (pid_t) 0) { /* Fork error */
769
                        if (sync)
770
                                write(chld_status[1], "1\n", 2);
771
                        perror("fork");
772
                        _exit(1);
773
                } else { /* Child */
774
                        if (sync) {
775
                                close(chld_in[0]);
776
                                close(chld_in[1]);
777
                                close(chld_out[0]);
778
                                close(chld_out[1]);
779
                                close(chld_err[0]);
780
                                close(chld_err[1]);
781
                                close(chld_status[0]);
782

    
783
                                debug_print("Child: Waiting for grandchild\n");
784
                                waitpid(gch_pid, NULL, 0);
785
                                debug_print("Child: grandchild ended\n");
786
                                write(chld_status[1], "0\n", 2);
787
                                close(chld_status[1]);
788
                        }
789
                        _exit(0);
790
                }
791
        } else if (pid < 0) { /* Fork error */
792
                alertpanel_error(_("Could not fork to execute the following "
793
                                   "command:\n%s\n%s"),
794
                                 cmd, g_strerror(errno));
795
                return NULL; 
796
        }
797

    
798
        /* Parent */
799

    
800
        if (!sync) {
801
                waitpid(pid, NULL, 0);
802
                return NULL;
803
        }
804

    
805
        close(chld_in[0]);
806
        if (!(children->action_type &
807
              (ACTION_PIPE_IN | ACTION_USER_IN | ACTION_USER_HIDDEN_IN)))
808
                close(chld_in[1]);
809
        close(chld_out[1]);
810
        close(chld_err[1]);
811
        close(chld_status[1]);
812

    
813
        child_info = g_new0(ChildInfo, 1);
814

    
815
        child_info->children    = children;
816

    
817
        child_info->pid         = pid;
818
        child_info->cmd         = g_strdup(cmd);
819
        child_info->new_out     = FALSE;
820
        child_info->output      = g_string_new(NULL);
821
        child_info->chld_in     =
822
                (children->action_type &
823
                 (ACTION_PIPE_IN | ACTION_USER_IN | ACTION_USER_HIDDEN_IN))
824
                        ? chld_in [1] : -1;
825
        child_info->chld_out    = chld_out[0];
826
        child_info->chld_err    = chld_err[0];
827
        child_info->chld_status = chld_status[0];
828
        child_info->tag_in      = -1;
829
        child_info->tag_out     = gdk_input_add(chld_out[0], GDK_INPUT_READ,
830
                                                catch_output, child_info);
831
        child_info->tag_err     = gdk_input_add(chld_err[0], GDK_INPUT_READ,
832
                                                catch_output, child_info);
833

    
834
        if (!(children->action_type &
835
              (ACTION_PIPE_IN | ACTION_PIPE_OUT | ACTION_INSERT)))
836
                return child_info;
837

    
838
        if ((children->action_type & ACTION_PIPE_IN) && msg_str) {
839
                write(chld_in[1], msg_str, strlen(msg_str));
840
                if (!(children->action_type &
841
                      (ACTION_USER_IN | ACTION_USER_HIDDEN_IN)))
842
                        close(chld_in[1]);
843
                child_info->chld_in = -1; /* No more input */
844
        }
845

    
846
        return child_info;
847
}
848

    
849
static void kill_children_cb(GtkWidget *widget, gpointer data)
850
{
851
        GSList *cur;
852
        Children *children = (Children *) data;
853
        ChildInfo *child_info;
854

    
855
        for (cur = children->list; cur; cur = cur->next) {
856
                child_info = (ChildInfo *)(cur->data);
857
                debug_print("Killing child group id %d\n", child_info->pid);
858
                if (child_info->pid && kill(-child_info->pid, SIGTERM) < 0)
859
                        perror("kill");
860
        }
861
}
862

    
863
static gint wait_for_children(Children *children)
864
{
865
        gboolean new_output;
866
        ChildInfo *child_info;
867
        GSList *cur;
868
        gint nb = children->nb;
869

    
870
        children->nb = 0;
871

    
872
        cur = children->list;
873
        new_output = FALSE;
874
        while (cur) {
875
                child_info = (ChildInfo *)cur->data;
876
                if (child_info->pid)
877
                        children->nb++;
878
                new_output |= child_info->new_out;
879
                cur = cur->next;
880
        }
881

    
882
        children->output |= new_output;
883

    
884
        if (new_output || (children->dialog && (nb != children->nb)))
885
                update_io_dialog(children);
886

    
887
        if (children->nb)
888
                return FALSE;
889

    
890
        if (!children->dialog) {
891
                free_children(children);
892
        } else if (!children->output) {
893
                gtk_widget_destroy(children->dialog);
894
        }
895

    
896
        return FALSE;
897
}
898

    
899
static void send_input(GtkWidget *w, gpointer data)
900
{
901
        Children *children = (Children *) data;
902
        ChildInfo *child_info = (ChildInfo *) children->list->data;
903

    
904
        child_info->tag_in = gdk_input_add(child_info->chld_in,
905
                                           GDK_INPUT_WRITE,
906
                                           catch_input, children);
907
        gtk_widget_set_sensitive(children->input_hbox, FALSE);
908
}
909

    
910
static gint delete_io_dialog_cb(GtkWidget *w, GdkEvent *e, gpointer data)
911
{
912
        hide_io_dialog_cb(w, data);
913
        return TRUE;
914
}
915

    
916
static void hide_io_dialog_cb(GtkWidget *w, gpointer data)
917
{
918

    
919
        Children *children = (Children *)data;
920

    
921
        if (!children->nb) {
922
                g_signal_handlers_disconnect_matched
923
                        (G_OBJECT(children->dialog),
924
                         (GSignalMatchType)G_SIGNAL_MATCH_DATA,
925
                         0, 0, NULL, NULL, children);
926
                gtk_widget_destroy(children->dialog);
927
                free_children(children);
928
        }
929
}
930

    
931
static gint io_dialog_key_pressed_cb(GtkWidget *widget, GdkEventKey *event,
932
                                     gpointer data)
933
{
934
        if (event && event->keyval == GDK_Escape)
935
                hide_io_dialog_cb(widget, data);
936
        return TRUE;
937
}
938

    
939
static void childinfo_close_pipes(ChildInfo *child_info)
940
{
941
        /* stdout and stderr pipes are guaranteed to be removed by
942
         * their handler, but in case where we receive child exit notification
943
         * before grand-child's pipes closing signals, we check them and close
944
         * them if necessary
945
         */
946
        if (child_info->tag_in > 0)
947
                gdk_input_remove(child_info->tag_in);
948
        if (child_info->tag_out > 0)
949
                gdk_input_remove(child_info->tag_out);
950
        if (child_info->tag_err > 0)
951
                gdk_input_remove(child_info->tag_err);
952

    
953
        if (child_info->chld_in >= 0)
954
                close(child_info->chld_in);
955
        if (child_info->chld_out >= 0)
956
                close(child_info->chld_out);
957
        if (child_info->chld_err >= 0)
958
                close(child_info->chld_err);
959

    
960
        close(child_info->chld_status);
961
}
962

    
963
static void free_children(Children *children)
964
{
965
        ChildInfo *child_info;
966

    
967
        debug_print("Freeing children data %p\n", children);
968

    
969
        g_free(children->action);
970
        while (children->list != NULL) {
971
                child_info = (ChildInfo *)children->list->data;
972
                g_free(child_info->cmd);
973
                g_string_free(child_info->output, TRUE);
974
                children->list = g_slist_remove(children->list, child_info);
975
                g_free(child_info);
976
        }
977
        g_free(children);
978
}
979

    
980
static void update_io_dialog(Children *children)
981
{
982
        GSList *cur;
983

    
984
        debug_print("Updating actions input/output dialog.\n");
985

    
986
        if (!children->nb) {
987
                gtk_widget_set_sensitive(children->abort_btn, FALSE);
988
                gtk_widget_set_sensitive(children->close_btn, TRUE);
989
                if (children->input_hbox)
990
                        gtk_widget_set_sensitive(children->input_hbox, FALSE);
991
                gtk_widget_grab_focus(children->close_btn);
992
                g_signal_connect(G_OBJECT(children->dialog),
993
                                 "key_press_event",
994
                                 G_CALLBACK(io_dialog_key_pressed_cb),
995
                                 children);
996
        }
997

    
998
        if (children->output) {
999
                GtkWidget *text = children->text;
1000
                GtkTextBuffer *textbuf;
1001
                GtkTextIter iter, start_iter, end_iter;
1002
                gchar *caption;
1003
                ChildInfo *child_info;
1004

    
1005
                gtk_widget_show(children->scrolledwin);
1006
                textbuf = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
1007
                gtk_text_buffer_get_start_iter(textbuf, &start_iter);
1008
                gtk_text_buffer_get_end_iter(textbuf, &end_iter);
1009
                iter = start_iter;
1010

    
1011
                for (cur = children->list; cur; cur = cur->next) {
1012
                        child_info = (ChildInfo *)cur->data;
1013
                        if (child_info->pid)
1014
                                caption = g_strdup_printf
1015
                                        (_("--- Running: %s\n"),
1016
                                         child_info->cmd);
1017
                        else
1018
                                caption = g_strdup_printf
1019
                                        (_("--- Ended: %s\n"),
1020
                                         child_info->cmd);
1021

    
1022
                        gtk_text_buffer_insert(textbuf, &iter, caption, -1);
1023
                        gtk_text_buffer_insert(textbuf, &iter,
1024
                                               child_info->output->str, -1);
1025
                        g_free(caption);
1026
                        child_info->new_out = FALSE;
1027
                }
1028
        }
1029
}
1030

    
1031
static void create_io_dialog(Children *children)
1032
{
1033
        GtkWidget *dialog;
1034
        GtkWidget *vbox;
1035
        GtkWidget *entry = NULL;
1036
        GtkWidget *input_hbox = NULL;
1037
        GtkWidget *send_button;
1038
        GtkWidget *label;
1039
        GtkWidget *text;
1040
        GtkWidget *scrolledwin;
1041
        GtkWidget *hbox;
1042
        GtkWidget *abort_button;
1043
        GtkWidget *close_button;
1044

    
1045
        debug_print("Creating action IO dialog\n");
1046

    
1047
        dialog = gtk_dialog_new();
1048
        gtk_container_set_border_width
1049
                (GTK_CONTAINER(GTK_DIALOG(dialog)->action_area), 5);
1050
        gtk_window_set_position(GTK_WINDOW(dialog), GTK_WIN_POS_CENTER);
1051
        gtk_window_set_title(GTK_WINDOW(dialog), _("Action's input/output"));
1052
        gtk_window_set_modal(GTK_WINDOW(dialog), TRUE);
1053
        manage_window_set_transient(GTK_WINDOW(dialog));
1054
        g_signal_connect(G_OBJECT(dialog), "delete_event",
1055
                         G_CALLBACK(delete_io_dialog_cb), children);
1056
        g_signal_connect(G_OBJECT(dialog), "destroy",
1057
                         G_CALLBACK(hide_io_dialog_cb),
1058
                         children);
1059

    
1060
        vbox = gtk_vbox_new(FALSE, 8);
1061
        gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog)->vbox), vbox);
1062
        gtk_container_set_border_width(GTK_CONTAINER(vbox), 8);
1063
        gtk_widget_show(vbox);
1064

    
1065
        label = gtk_label_new(children->action);
1066
        gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 0);
1067
        gtk_widget_show(label);
1068

    
1069
        scrolledwin = gtk_scrolled_window_new(NULL, NULL);
1070
        gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledwin),
1071
                                       GTK_POLICY_NEVER, GTK_POLICY_ALWAYS);
1072
        gtk_box_pack_start(GTK_BOX(vbox), scrolledwin, TRUE, TRUE, 0);
1073
        gtk_widget_set_size_request(scrolledwin, 480, 200);
1074
        gtk_widget_hide(scrolledwin);
1075

    
1076
        text = gtk_text_view_new();
1077
        gtk_text_view_set_editable(GTK_TEXT_VIEW(text), FALSE);
1078
        gtk_container_add(GTK_CONTAINER(scrolledwin), text);
1079
        gtk_widget_show(text);
1080

    
1081
        if (children->open_in) {
1082
                input_hbox = gtk_hbox_new(FALSE, 8);
1083
                gtk_widget_show(input_hbox);
1084

    
1085
                entry = gtk_entry_new();
1086
                gtk_widget_set_size_request(entry, 320, -1);
1087
                g_signal_connect(G_OBJECT(entry), "activate",
1088
                                 G_CALLBACK(send_input), children);
1089
                gtk_box_pack_start(GTK_BOX(input_hbox), entry, TRUE, TRUE, 0);
1090
                if (children->action_type & ACTION_USER_HIDDEN_IN)
1091
                        gtk_entry_set_visibility(GTK_ENTRY(entry), FALSE);
1092
                gtk_widget_show(entry);
1093

    
1094
                send_button = gtk_button_new_with_label(_(" Send "));
1095
                g_signal_connect(G_OBJECT(send_button), "clicked",
1096
                                 G_CALLBACK(send_input), children);
1097
                gtk_box_pack_start(GTK_BOX(input_hbox), send_button, FALSE,
1098
                                   FALSE, 0);
1099
                gtk_widget_show(send_button);
1100

    
1101
                gtk_box_pack_start(GTK_BOX(vbox), input_hbox, FALSE, FALSE, 0);
1102
                gtk_widget_grab_focus(entry);
1103
        }
1104

    
1105
        gtkut_button_set_create(&hbox, &abort_button, _("Abort"),
1106
                                &close_button, _("Close"), NULL, NULL);
1107
        g_signal_connect(G_OBJECT(abort_button), "clicked",
1108
                         G_CALLBACK(kill_children_cb), children);
1109
        g_signal_connect(G_OBJECT(close_button), "clicked",
1110
                         G_CALLBACK(hide_io_dialog_cb), children);
1111
        gtk_widget_show(hbox);
1112

    
1113
        if (children->nb)
1114
                gtk_widget_set_sensitive(close_button, FALSE);
1115

    
1116
        gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog)->action_area), hbox);
1117

    
1118
        children->dialog      = dialog;
1119
        children->scrolledwin = scrolledwin;
1120
        children->text        = text;
1121
        children->input_hbox  = children->open_in ? input_hbox : NULL;
1122
        children->input_entry = children->open_in ? entry : NULL;
1123
        children->abort_btn   = abort_button;
1124
        children->close_btn   = close_button;
1125

    
1126
        gtk_widget_show(dialog);
1127
}
1128

    
1129
static void catch_status(gpointer data, gint source, GdkInputCondition cond)
1130
{
1131
        ChildInfo *child_info = (ChildInfo *)data;
1132
        gchar buf;
1133
        gint c;
1134

    
1135
        gdk_input_remove(child_info->tag_status);
1136

    
1137
        c = read(source, &buf, 1);
1138
        debug_print("Child returned %c\n", buf);
1139

    
1140
        waitpid(-child_info->pid, NULL, 0);
1141
        childinfo_close_pipes(child_info);
1142
        child_info->pid = 0;
1143

    
1144
        wait_for_children(child_info->children);
1145
}
1146
        
1147
static void catch_input(gpointer data, gint source, GdkInputCondition cond)
1148
{
1149
        Children *children = (Children *)data;
1150
        ChildInfo *child_info = (ChildInfo *)children->list->data;
1151
        gchar *input;
1152
        gint c, count, len;
1153

    
1154
        debug_print("Sending input to grand child.\n");
1155
        if (!(cond && GDK_INPUT_WRITE))
1156
                return;
1157

    
1158
        gdk_input_remove(child_info->tag_in);
1159
        child_info->tag_in = -1;
1160

    
1161
        input = gtk_editable_get_chars(GTK_EDITABLE(children->input_entry),
1162
                                       0, -1);
1163
        len = strlen(input);
1164
        count = 0;
1165

    
1166
        do {
1167
                c = write(child_info->chld_in, input + count, len - count);
1168
                if (c >= 0)
1169
                        count += c;
1170
        } while (c >= 0 && count < len);
1171

    
1172
        if (c >= 0)
1173
                write(child_info->chld_in, "\n", 2);
1174

    
1175
        g_free(input);
1176

    
1177
        gtk_entry_set_text(GTK_ENTRY(children->input_entry), "");
1178
        gtk_widget_set_sensitive(children->input_hbox, TRUE);
1179
        close(child_info->chld_in);
1180
        child_info->chld_in = -1;
1181
        debug_print("Input to grand child sent.\n");
1182
}
1183

    
1184
static void catch_output(gpointer data, gint source, GdkInputCondition cond)
1185
{
1186
        ChildInfo *child_info = (ChildInfo *)data;
1187
        gint c, i;
1188
        gchar buf[BUFFSIZE];
1189

    
1190
        debug_print("Catching grand child's output.\n");
1191
        if (child_info->children->action_type &
1192
            (ACTION_PIPE_OUT | ACTION_INSERT)
1193
            && source == child_info->chld_out) {
1194
                GtkTextView *text =
1195
                        GTK_TEXT_VIEW(child_info->children->msg_text);
1196
                GtkTextBuffer *textbuf = gtk_text_view_get_buffer(text);
1197
                GtkTextIter iter1, iter2;
1198
                GtkTextMark *mark;
1199

    
1200
                mark = gtk_text_buffer_get_insert(textbuf);
1201
                gtk_text_buffer_get_iter_at_mark(textbuf, &iter1, mark);
1202
                gtk_text_buffer_get_iter_at_mark(textbuf, &iter2, mark);
1203

    
1204
                while (TRUE) {
1205
                        c = read(source, buf, sizeof(buf) - 1);
1206
                        if (c == 0)
1207
                                break;
1208
                        gtk_text_buffer_insert(textbuf, &iter2, buf, c);
1209
                }
1210

    
1211
                if (child_info->children->is_selection) {
1212
                        gtk_text_buffer_place_cursor(textbuf, &iter1);
1213
                        gtk_text_buffer_move_mark_by_name
1214
                                (textbuf, "selection_bound", &iter2);
1215
                }
1216
        } else {
1217
                c = read(source, buf, sizeof(buf) - 1);
1218
                for (i = 0; i < c; i++)
1219
                        g_string_append_c(child_info->output, buf[i]);
1220
                if (c > 0)
1221
                        child_info->new_out = TRUE;
1222
        }
1223
        if (c == 0) {
1224
                if (source == child_info->chld_out) {
1225
                        gdk_input_remove(child_info->tag_out);
1226
                        child_info->tag_out = -1;
1227
                        close(child_info->chld_out);
1228
                        child_info->chld_out = -1;
1229
                } else {
1230
                        gdk_input_remove(child_info->tag_err);
1231
                        child_info->tag_err = -1;
1232
                        close(child_info->chld_err);
1233
                        child_info->chld_err = -1;
1234
                }
1235
        }
1236
        
1237
        wait_for_children(child_info->children);
1238
}
1239

    
1240
static gchar *get_user_string(const gchar *action, ActionType type)
1241
{
1242
        gchar *message;
1243
        gchar *user_str = NULL;
1244

    
1245
        switch (type) {
1246
        case ACTION_USER_HIDDEN_STR:
1247
                message = g_strdup_printf
1248
                        (_("Enter the argument for the following action:\n"
1249
                           "(`%%h' will be replaced with the argument)\n"
1250
                           "  %s"),
1251
                         action);
1252
                user_str = input_dialog_with_invisible
1253
                        (_("Action's hidden user argument"), message, NULL);
1254
                break;
1255
        case ACTION_USER_STR:
1256
                message = g_strdup_printf
1257
                        (_("Enter the argument for the following action:\n"
1258
                           "(`%%u' will be replaced with the argument)\n"
1259
                           "  %s"),
1260
                         action);
1261
                user_str = input_dialog
1262
                        (_("Action's user argument"), message, NULL);
1263
                break;
1264
        default:
1265
                g_warning("Unsupported action type %d", type);
1266
        }
1267

    
1268
        return user_str;
1269
}