2012-12-03 [wwp] 3.9.0cvs39
[claws.git] / src / action.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2012 Hiroyuki Yamamoto & The Claws Mail 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 3 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, see <http://www.gnu.org/licenses/>.
17  * 
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #include "claws-features.h"
23 #endif
24
25 #include "defs.h"
26
27 #include <glib.h>
28 #include <glib/gi18n.h>
29 #include <gtk/gtk.h>
30 #include <gdk/gdkkeysyms.h>
31 #ifdef GDK_WINDOWING_X11
32 #  include <gdk/gdkx.h>
33 #endif /* GDK_WINDOWING_X11 */
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <errno.h>
38 #include <sys/types.h>
39 #if HAVE_SYS_WAIT_H
40 #  include <sys/wait.h>
41 #endif
42 #include <signal.h>
43 #include <unistd.h>
44
45 #include "utils.h"
46 #include "gtkutils.h"
47 #include "manage_window.h"
48 #include "mainwindow.h"
49 #include "prefs_common.h"
50 #include "alertpanel.h"
51 #include "inputdialog.h"
52 #include "action.h"
53 #include "compose.h"
54 #include "procmsg.h"
55 #include "msgcache.h"
56 #include "textview.h"
57 #include "matcher_parser.h" /* CLAWS */
58 #include "filtering.h"
59 #include "procheader.h"
60
61 typedef struct _Children                Children;
62 typedef struct _ChildInfo               ChildInfo;
63 typedef struct _UserStringDialog        UserStringDialog;
64
65 struct _Children
66 {
67         GtkWidget       *dialog;
68         GtkWidget       *text;
69         GtkWidget       *input_entry;
70         GtkWidget       *input_hbox;
71         GtkWidget       *progress_bar;
72         GtkWidget       *abort_btn;
73         GtkWidget       *close_btn;
74         GtkWidget       *scrolledwin;
75
76         gchar           *action;
77         ActionType       action_type;
78         GSList          *list;
79         gint             nb;
80         gint             initial_nb;
81         gint             open_in;
82         gboolean         output;
83
84         GtkWidget       *msg_text;
85
86         gboolean         is_selection;
87 };
88
89 struct _ChildInfo
90 {
91         Children        *children;
92         gchar           *cmd;
93         pid_t            pid;
94         gint             next_sig;
95         gint             chld_in;
96         gint             chld_out;
97         gint             chld_err;
98         gint             chld_status;
99         gint             tag_in;
100         gint             tag_out;
101         gint             tag_err;
102         gint             tag_status;
103         gint             new_out;
104
105         GString         *output;
106         void (*callback)(void *data);
107         void *data;
108
109         GSList          *msginfo_list;
110 };
111
112 static void action_update_menu          (GtkUIManager   *ui_manager,
113                                          const gchar    *accel_group,
114                                          gchar          *branch_path,
115                                          gpointer        callback,
116                                          gpointer        data);
117 static void compose_actions_execute_cb  (GtkWidget      *widget, 
118                                          gpointer        data);
119 static void compose_actions_execute     (Compose        *compose,
120                                          guint           action_nb,
121                                          GtkWidget      *widget);
122
123 static void mainwin_actions_execute_cb  (GtkWidget      *widget, 
124                                          gpointer        data);
125 static void mainwin_actions_execute     (MainWindow     *mainwin,
126                                          guint           action_nb,
127                                          GtkWidget      *widget);
128
129 static void msgview_actions_execute_cb  (GtkWidget      *widget, 
130                                          gpointer        data);
131 static void msgview_actions_execute     (MessageView    *msgview,
132                                          guint           action_nb,
133                                          GtkWidget      *widget);
134
135 static void message_actions_execute     (MessageView    *msgview,
136                                          guint           action_nb,
137                                          GSList         *msg_list);
138
139 static gboolean execute_filtering_actions(gchar         *action, 
140                                           GSList        *msglist);
141
142 static gboolean execute_actions         (gchar          *action, 
143                                          GSList         *msg_list, 
144                                          GtkWidget      *text,
145                                          gint            body_pos,
146                                          MimeInfo       *partinfo, 
147                                          void (*callback)(void *data),
148                                          void *data);
149
150 static gchar *parse_action_cmd          (gchar          *action,
151                                          MsgInfo        *msginfo,
152                                          GSList         *msg_list,
153                                          MimeInfo       *partinfo,
154                                          const gchar    *user_str,
155                                          const gchar    *user_hidden_str,
156                                          const gchar    *sel_str);
157 static gboolean parse_append_filename   (GString        *cmd,
158                                          MsgInfo        *msginfo);
159
160 static gboolean parse_append_msgpart    (GString        *cmd,
161                                          MsgInfo        *msginfo,
162                                          MimeInfo       *partinfo);
163
164 static ChildInfo *fork_child            (gchar          *cmd,
165                                          const gchar    *msg_str,
166                                          Children       *children);
167
168 static gint wait_for_children           (Children       *children);
169
170 static void free_children               (Children       *children);
171
172 static void childinfo_close_pipes       (ChildInfo      *child_info);
173
174 static void create_io_dialog            (Children       *children);
175 static void update_io_dialog            (Children       *children);
176
177 static void hide_io_dialog_cb           (GtkWidget      *widget,
178                                          gpointer        data);
179 static gint io_dialog_key_pressed_cb    (GtkWidget      *widget,
180                                          GdkEventKey    *event,
181                                          gpointer        data);
182
183 static void catch_output                (gpointer                data,
184                                          gint                    source,
185                                          GIOCondition            cond);
186 static void catch_input                 (gpointer                data, 
187                                          gint                    source,
188                                          GIOCondition            cond);
189 static void catch_status                (gpointer                data,
190                                          gint                    source,
191                                          GIOCondition            cond);
192
193 static gchar *get_user_string           (const gchar    *action,
194                                          ActionType      type);
195
196
197 ActionType action_get_type(const gchar *action_str)
198 {
199         const gchar *p;
200         gboolean in_filtering_action = FALSE;
201         ActionType action_type = ACTION_NONE;
202
203         cm_return_val_if_fail(action_str,  ACTION_ERROR);
204         cm_return_val_if_fail(*action_str, ACTION_ERROR);
205
206         p = action_str;
207
208         if (p[0] == '|') {
209                 action_type |= ACTION_PIPE_IN;
210                 p++;
211         } else if (p[0] == '>') {
212                 action_type |= ACTION_USER_IN;
213                 p++;
214         } else if (p[0] == '*') {
215                 action_type |= ACTION_USER_HIDDEN_IN;
216                 p++;
217         }
218
219         if (p[0] == '\0')
220                 return ACTION_ERROR;
221
222         while (*p && action_type != ACTION_ERROR) {
223                 if (!in_filtering_action) {
224                         if (p[0] == '%' && p[1]) {
225                                 switch (p[1]) {
226                                 case 'a':
227                                         /* CLAWS: filtering action is a mutually exclusive
228                                         * action. we can enable others if needed later. we
229                                         * add ACTION_SINGLE | ACTION_MULTIPLE so it will
230                                         * only be executed from the main window toolbar */
231                                         if (p[2] == 's')  /* source messages */
232                                                 action_type = ACTION_FILTERING_ACTION 
233                                                                 | ACTION_SINGLE 
234                                                                 | ACTION_MULTIPLE;
235                                         in_filtering_action = TRUE;
236                                         break;
237                                 case 'f':
238                                         action_type |= ACTION_SINGLE;
239                                         break;
240                                 case 'F':
241                                         action_type |= ACTION_MULTIPLE;
242                                         break;
243                                 case 'p':
244                                         action_type |= ACTION_SINGLE;
245                                         break;
246                                 case 's':
247                                         action_type |= ACTION_SELECTION_STR;
248                                         break;
249                                 case 'u':
250                                         action_type |= ACTION_USER_STR;
251                                         break;
252                                 case 'h':
253                                         action_type |= ACTION_USER_HIDDEN_STR;
254                                         break;
255                                 case '%':
256                                         /* literal '%' */
257                                         break;
258                                 default:
259                                         action_type = ACTION_ERROR;
260                                         break;
261                                 }
262                                 p++;
263                         } else if (p[0] == '|') {
264                                 if (p[1] == '\0')
265                                         action_type |= ACTION_PIPE_OUT;
266                         } else if (p[0] == '>') {
267                                 if (p[1] == '\0')
268                                         action_type |= ACTION_INSERT;
269                         } else if (p[0] == '&') {
270                                 if (p[1] == '\0')
271                                         action_type |= ACTION_ASYNC;
272                         } else if (p[0] == '}') {
273                                 in_filtering_action = FALSE;
274                         }
275                 }
276                         p++;
277         }
278
279         return action_type;
280 }
281
282 static gchar *parse_action_cmd(gchar *action, MsgInfo *msginfo,
283                                GSList *msg_list, MimeInfo *partinfo,
284                                const gchar *user_str,
285                                const gchar *user_hidden_str,
286                                const gchar *sel_str)
287 {
288         GString *cmd;
289         gchar *p;
290         GSList *cur;
291         
292         p = action;
293         
294         if (p[0] == '|' || p[0] == '>' || p[0] == '*')
295                 p++;
296
297         cmd = g_string_sized_new(strlen(action));
298
299         while (p[0] &&
300                !((p[0] == '|' || p[0] == '>' || p[0] == '&') && !p[1])) {
301                 if (p[0] == '%' && p[1]) {
302                         switch (p[1]) {
303                         case 'f':
304                                 if (!parse_append_filename(cmd, msginfo)) {
305                                         g_string_free(cmd, TRUE);
306                                         return NULL;
307                                 }
308                                 p++;
309                                 break;
310                         case 'F':
311                                 for (cur = msg_list; cur != NULL;
312                                      cur = cur->next) {
313                                         MsgInfo *msg = (MsgInfo *)cur->data;
314
315                                         if (!parse_append_filename(cmd, msg)) {
316                                                 g_string_free(cmd, TRUE);
317                                                 return NULL;
318                                         }
319                                         if (cur->next)
320                                                 g_string_append_c(cmd, ' ');
321                                 }
322                                 p++;
323                                 break;
324                         case 'p':
325                                 if (!parse_append_msgpart(cmd, msginfo,
326                                                           partinfo)) {
327                                         g_string_free(cmd, TRUE);
328                                         return NULL;
329                                 }
330                                 p++;
331                                 break;
332                         case 's':
333                                 if (sel_str)
334                                         g_string_append(cmd, sel_str);
335                                 p++;
336                                 break;
337                         case 'u':
338                                 if (user_str)
339                                         g_string_append(cmd, user_str);
340                                 p++;
341                                 break;
342                         case 'h':
343                                 if (user_hidden_str)
344                                         g_string_append(cmd, user_hidden_str);
345                                 p++;
346                                 break;
347                         case '%':
348                                 g_string_append_c(cmd, p[1]);
349                                 p++;
350                                 break;
351                         default:
352                                 g_string_append_c(cmd, p[0]);
353                                 g_string_append_c(cmd, p[1]);
354                                 p++;
355                         }
356                 } else {
357                         g_string_append_c(cmd, p[0]);
358                 }
359                 p++;
360         }
361         if (cmd->len == 0) {
362                 g_string_free(cmd, TRUE);
363                 return NULL;
364         }
365
366         p = cmd->str;
367         g_string_free(cmd, FALSE);
368         return p;
369 }
370
371 static gboolean parse_append_filename(GString *cmd, MsgInfo *msginfo)
372 {
373         gchar *filename;
374         gchar *p, *q;
375         gchar escape_ch[] = "\\ ";
376
377         cm_return_val_if_fail(msginfo, FALSE);
378
379         filename = procmsg_get_message_file(msginfo);
380
381         if (!filename) {
382                 alertpanel_error(_("Could not get message file %d"),
383                                  msginfo->msgnum);
384                 return FALSE;
385         }
386
387         p = filename;
388         while ((q = strpbrk(p, "$\"`'\\ \t*?[]&|;<>()!#~")) != NULL) {
389                 escape_ch[1] = *q;
390                 *q = '\0';
391                 g_string_append(cmd, p);
392                 g_string_append(cmd, escape_ch);
393                 p = q + 1;
394         }
395         g_string_append(cmd, p);
396
397         g_free(filename);
398
399         return TRUE;
400 }
401
402 static gboolean parse_append_msgpart(GString *cmd, MsgInfo *msginfo,
403                                      MimeInfo *partinfo)
404 {
405         gboolean single_part = FALSE;
406         gchar *filename;
407         gchar *part_filename;
408         gint ret;
409
410         if (!partinfo) {
411                 partinfo = procmime_scan_message(msginfo);
412                 if (!partinfo) {
413                         alertpanel_error(_("Could not get message part."));
414                         return FALSE;
415                 }
416
417                 single_part = TRUE;
418         }
419
420         filename = procmsg_get_message_file_path(msginfo);
421         part_filename = procmime_get_tmp_file_name(partinfo);
422
423         ret = procmime_get_part(part_filename, partinfo);
424
425         if (single_part)
426                 procmime_mimeinfo_free_all(partinfo);
427         g_free(filename);
428
429         if (ret < 0) {
430                 alertpanel_error(_("Can't get part of multipart message: %s"), strerror(-ret));
431                 g_free(part_filename);
432                 return FALSE;
433         }
434
435         g_string_append(cmd, part_filename);
436
437         g_free(part_filename);
438
439         return TRUE;
440 }
441
442 void actions_execute(gpointer data, 
443                      guint action_nb,
444                      GtkWidget *widget,
445                      gint source)
446 {
447         if (source == TOOLBAR_MAIN) 
448                 mainwin_actions_execute((MainWindow*)data, action_nb, widget);
449         else if (source == TOOLBAR_COMPOSE)
450                 compose_actions_execute((Compose*)data, action_nb, widget);
451         else if (source == TOOLBAR_MSGVIEW)
452                 msgview_actions_execute((MessageView*)data, action_nb, widget); 
453 }
454
455 void action_update_mainwin_menu(GtkUIManager *ui_manager,
456                                 gchar *branch_path,
457                                 MainWindow *mainwin)
458 {
459         action_update_menu(ui_manager, "<MainwinActions>", branch_path,
460                            mainwin_actions_execute_cb, mainwin);
461 }
462
463 void action_update_msgview_menu(GtkUIManager    *ui_manager,
464                                 gchar *branch_path,
465                                 MessageView *msgview)
466 {
467         action_update_menu(ui_manager, "<MsgviewActions>", branch_path,
468                            msgview_actions_execute_cb, msgview);
469 }
470
471 void action_update_compose_menu(GtkUIManager *ui_manager, 
472                                 gchar *branch_path,
473                                 Compose *compose)
474 {
475         action_update_menu(ui_manager, "<ComposeActions>", branch_path,
476                            compose_actions_execute_cb, compose);
477 }
478
479 static GtkWidget *find_item_in_menu(GtkWidget *menu, gchar *name)
480 {
481         GList *children = gtk_container_get_children(GTK_CONTAINER(GTK_MENU_SHELL(menu)));
482         GList *amenu = children;
483         const gchar *existing_name;
484         while (amenu) {
485                 GtkWidget *item = GTK_WIDGET(amenu->data);
486                 if ((existing_name = g_object_get_data(G_OBJECT(item), "s_name")) != NULL &&
487                     !strcmp2(name, existing_name))
488                 {
489                         g_list_free(children);
490                          return item;
491                 }
492                 amenu = amenu->next;
493         }
494
495         g_list_free(children);
496
497         return NULL;
498 }
499
500 static GtkWidget *create_submenus(GtkWidget *menu, const gchar *action)
501 {
502         gchar *submenu = g_strdup(action);
503         GtkWidget *new_menu = NULL;
504         
505         if (strchr(submenu, '/')) {
506                 const gchar *end = (strchr(submenu, '/')+1);
507                 GtkWidget *menu_item = NULL;
508                 if (end && *end) {
509                         *strchr(submenu, '/') = '\0';
510                         if ((menu_item = find_item_in_menu(menu, submenu)) == NULL) {
511                                 menu_item = gtk_menu_item_new_with_mnemonic(submenu);
512                                 g_object_set_data_full(G_OBJECT(menu_item), "s_name", g_strdup(submenu), g_free);
513                                 gtk_widget_show(menu_item);
514                                 gtk_menu_shell_append(GTK_MENU_SHELL(menu), menu_item);         
515                                 new_menu = gtk_menu_new();
516                                 gtk_widget_show(new_menu);
517                                 gtk_menu_item_set_submenu(GTK_MENU_ITEM(menu_item), new_menu);
518                         } else {
519                                 new_menu = gtk_menu_item_get_submenu(GTK_MENU_ITEM(menu_item));
520                         }
521                         new_menu = create_submenus(new_menu, end);
522                 }
523         }
524         g_free(submenu);
525         return new_menu ? new_menu : menu;
526 }
527
528 static void action_update_menu(GtkUIManager *ui_manager,
529                                const gchar *accel_group,
530                                gchar *branch_path,
531                                gpointer callback, gpointer data)
532 {
533         GSList *cur;
534         gchar *action, *action_p;
535         int callback_action = 0;
536         GtkWidget *menu = gtk_menu_new();
537         GtkWidget *item;
538
539         for (cur = prefs_common.actions_list; cur != NULL; cur = cur->next) {
540                 GtkWidget *cur_menu = menu;
541                 const gchar *action_name = NULL;
542                 action   = g_strdup((gchar *)cur->data);
543                 action_p = strstr(action, ": ");
544                 if (action_p && action_p[2] &&
545                     (action_get_type(&action_p[2]) != ACTION_ERROR) &&
546                     (action[0] != '/')) {
547                         gchar *accel_path = NULL;
548
549                         action_p[0] = '\0';
550                         if (strchr(action, '/')) {
551                                 cur_menu = create_submenus(cur_menu, action);
552                                 action_name = strrchr(action, '/')+1;
553                         } else {
554                                 action_name = action;
555                         }
556                         gtk_menu_set_accel_group (GTK_MENU (cur_menu), 
557                                 gtk_ui_manager_get_accel_group(ui_manager));
558                         item = gtk_menu_item_new_with_label(action_name);
559                         gtk_menu_shell_append(GTK_MENU_SHELL(cur_menu), item);
560                         g_signal_connect(G_OBJECT(item), "activate",
561                                          G_CALLBACK(callback), data);
562                         g_object_set_data(G_OBJECT(item), "action_num", GINT_TO_POINTER(callback_action));
563                         gtk_widget_show(item);
564                         accel_path = g_strconcat(accel_group,branch_path, "/", action, NULL);
565                         gtk_menu_item_set_accel_path(GTK_MENU_ITEM(item), accel_path);
566                         g_free(accel_path);
567
568                 }
569                 g_free(action);
570                 callback_action++;
571         }
572
573         gtk_widget_show(menu);
574         gtk_menu_item_set_submenu(GTK_MENU_ITEM(gtk_ui_manager_get_widget(ui_manager, branch_path)), menu);
575 }
576
577 static void compose_actions_execute_cb(GtkWidget *widget, gpointer data)
578 {
579         Compose *compose = (Compose *)data;
580         gint action_nb = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(widget), "action_num"));
581         compose_actions_execute(compose, action_nb, NULL);
582 }
583
584 static void compose_actions_execute(Compose *compose, guint action_nb, GtkWidget *widget)
585 {
586         gchar *buf, *action;
587         ActionType action_type;
588
589         cm_return_if_fail(action_nb < g_slist_length(prefs_common.actions_list));
590
591         buf = (gchar *)g_slist_nth_data(prefs_common.actions_list, action_nb);
592         cm_return_if_fail(buf != NULL);
593         action = strstr(buf, ": ");
594         cm_return_if_fail(action != NULL);
595
596         /* Point to the beginning of the command-line */
597         action += 2;
598
599         action_type = action_get_type(action);
600         if (action_type & (ACTION_SINGLE | ACTION_MULTIPLE)) {
601                 alertpanel_warning
602                         (_("The selected action cannot be used in the compose window\n"
603                            "because it contains %%f, %%F, %%as or %%p."));
604                 return;
605         }
606
607         execute_actions(action, NULL, compose->text, 0, NULL, 
608                 compose_action_cb, compose);
609 }
610
611 static void mainwin_actions_execute_cb(GtkWidget *widget, gpointer data)
612 {
613         MainWindow *mainwin = (MainWindow *)data;
614         gint action_nb = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(widget), "action_num"));
615         mainwin_actions_execute(mainwin, action_nb, NULL);
616 }
617
618 static void mainwin_actions_execute(MainWindow *mainwin, guint action_nb,
619                                        GtkWidget *widget)
620 {
621         GSList *msg_list;
622
623         msg_list = summary_get_selected_msg_list(mainwin->summaryview);
624         message_actions_execute(mainwin->messageview, action_nb, msg_list);
625         g_slist_free(msg_list);
626 }
627
628 static void msgview_actions_execute_cb(GtkWidget *widget, gpointer data)
629 {
630         MessageView *msgview = (MessageView *)data;
631         gint action_nb = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(widget), "action_num"));
632         msgview_actions_execute(msgview, action_nb, NULL);
633 }
634
635 static void msgview_actions_execute(MessageView *msgview, guint action_nb,
636                                        GtkWidget *widget)
637 {
638         GSList *msg_list = NULL;
639
640         if (msgview->msginfo)
641                 msg_list = g_slist_append(msg_list, msgview->msginfo);
642         message_actions_execute(msgview, action_nb, msg_list);
643         g_slist_free(msg_list);
644 }
645
646 static void message_actions_execute(MessageView *msgview, guint action_nb,
647                                     GSList *msg_list)
648 {
649         TextView *textview;
650         MimeInfo *partinfo;
651         gchar *buf;
652         gchar *action;
653         GtkWidget *text = NULL;
654         guint body_pos = 0;
655         ActionType action_type;
656         
657         cm_return_if_fail(action_nb < g_slist_length(prefs_common.actions_list));
658
659         buf = (gchar *)g_slist_nth_data(prefs_common.actions_list, action_nb);
660
661         cm_return_if_fail(buf);
662         cm_return_if_fail((action = strstr(buf, ": ")));
663
664         /* Point to the beginning of the command-line */
665         action += 2;
666
667         textview = messageview_get_current_textview(msgview);
668         if (textview) {
669                 text     = textview->text;
670                 body_pos = textview->body_pos;
671         }
672         partinfo = messageview_get_selected_mime_part(msgview);
673
674         /* this command will alter the message text */
675         action_type = action_get_type(action);
676         if (action_type & (ACTION_PIPE_OUT | ACTION_INSERT))
677                 msgview->filtered = TRUE;
678
679         if (action_type & ACTION_FILTERING_ACTION) 
680                 /* CLAWS: most of the above code is not necessary for applying
681                  * filtering */
682                 execute_filtering_actions(action, msg_list);
683         else
684                 execute_actions(action, msg_list, text, body_pos, partinfo,
685                         NULL, NULL);
686 }
687
688 static gboolean execute_filtering_actions(gchar *action, GSList *msglist)
689 {
690         GSList *action_list, *p;
691         const gchar *sbegin, *send;
692         gchar *action_string;
693         SummaryView *summaryview = NULL;
694         MainWindow *mainwin = NULL;
695
696         if (mainwindow_get_mainwindow()) {
697                 summaryview = mainwindow_get_mainwindow()->summaryview;
698                 mainwin = mainwindow_get_mainwindow();
699         }
700
701         if (NULL == (sbegin = strstr2(action, "%as{")))
702                 return FALSE;
703         sbegin += sizeof "%as{" - 1;
704         if (NULL == (send = strrchr(sbegin, '}')))
705                 return FALSE;
706         action_string = g_strndup(sbegin, send - sbegin);
707         
708         action_list = matcher_parser_get_action_list(action_string);
709         if (action_list == NULL) {
710                 gchar *tmp = g_strdup(action_string);
711
712                 g_strstrip(tmp);
713                 if (*tmp == '\0')
714                         alertpanel_error(_("There is no filtering action set"));
715                 else
716                         alertpanel_error(_("Invalid filtering action(s):\n%s"), tmp);
717                 g_free(action_string);
718                 g_free(tmp);
719                 return FALSE;
720         }
721         g_free(action_string);
722         
723         /* apply actions on each message info */
724         for (p = msglist; p && p->data; p = g_slist_next(p)) {
725                 filteringaction_apply_action_list(action_list, (MsgInfo *) p->data);
726         }
727
728         if (summaryview) {
729                 summary_lock(summaryview);                              
730                 main_window_cursor_wait(mainwin);               
731                 summary_freeze(summaryview);    
732                 folder_item_update_freeze();                            
733         }
734
735         filtering_move_and_copy_msgs(msglist);
736
737         if (summaryview) {
738                 folder_item_update_thaw();                              
739                 summary_thaw(summaryview);              
740                 main_window_cursor_normal(mainwin);     
741                 summary_unlock(summaryview);                            
742                 summary_show(summaryview, summaryview->folder_item);
743         }
744         for (p = action_list; p; p = g_slist_next(p))
745                 if (p->data) filteringaction_free(p->data);     
746         g_slist_free(action_list);              
747         return TRUE;    
748 }
749
750 static gboolean execute_actions(gchar *action, GSList *msg_list,
751                                 GtkWidget *text,
752                                 gint body_pos, MimeInfo *partinfo,
753                                 void (*callback)(void *data), void *data)
754 {
755         GSList *children_list = NULL;
756         gint is_ok  = TRUE;
757         gint msg_list_len;
758         Children *children;
759         ChildInfo *child_info;
760         ActionType action_type;
761         MsgInfo *msginfo;
762         gchar *cmd;
763         gchar *sel_str = NULL;
764         gchar *msg_str = NULL;
765         gchar *user_str = NULL;
766         gchar *user_hidden_str = NULL;
767         GtkTextIter start_iter, end_iter;
768         gboolean is_selection = FALSE;
769
770         cm_return_val_if_fail(action && *action, FALSE);
771
772         action_type = action_get_type(action);
773
774         if (action_type == ACTION_ERROR)
775                 return FALSE;         /* ERR: syntax error */
776
777         if (action_type & (ACTION_SINGLE | ACTION_MULTIPLE) && !msg_list)
778                 return FALSE;         /* ERR: file command without selection */
779
780         msg_list_len = g_slist_length(msg_list);
781
782         if (action_type & (ACTION_PIPE_OUT | ACTION_PIPE_IN | ACTION_INSERT)) {
783                 if (msg_list_len > 1)
784                         return FALSE; /* ERR: pipe + multiple selection */
785                 if (!text)
786                         return FALSE; /* ERR: pipe and no displayed text */
787         }
788
789         if (action_type & ACTION_SELECTION_STR) {
790                 if (!text)
791                         return FALSE; /* ERR: selection string but no text */
792         }
793
794         if (text) {
795                 GtkTextBuffer *textbuf;
796
797                 textbuf = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
798                 is_selection = gtk_text_buffer_get_selection_bounds
799                         (textbuf, &start_iter, &end_iter);
800                 if (!is_selection) {
801                         gtk_text_buffer_get_iter_at_offset
802                                 (textbuf, &start_iter, body_pos);
803                         gtk_text_buffer_get_end_iter(textbuf, &end_iter);
804                 }
805                 msg_str = gtk_text_buffer_get_text
806                         (textbuf, &start_iter, &end_iter, FALSE);
807                 if (is_selection)
808                         sel_str = g_strdup(msg_str);
809         }
810
811         if (action_type & ACTION_USER_STR) {
812                 if (!(user_str = get_user_string(action, ACTION_USER_STR))) {
813                         g_free(msg_str);
814                         g_free(sel_str);
815                         return FALSE;
816                 }
817         }
818
819         if (action_type & ACTION_USER_HIDDEN_STR) {
820                 if (!(user_hidden_str =
821                         get_user_string(action, ACTION_USER_HIDDEN_STR))) {
822                         g_free(msg_str);
823                         g_free(sel_str);
824                         g_free(user_str);
825                         return FALSE;
826                 }
827         }
828
829         if (text && (action_type & ACTION_PIPE_OUT)) {
830                 GtkTextBuffer *textbuf;
831                 textbuf = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
832                 gtk_text_buffer_delete(textbuf, &start_iter, &end_iter);
833         }
834
835         children = g_new0(Children, 1);
836
837         children->action      = g_strdup(action);
838         children->action_type = action_type;
839         children->msg_text    = text;
840         children->is_selection = is_selection;
841
842         if ((action_type & (ACTION_USER_IN | ACTION_USER_HIDDEN_IN)) &&
843             ((action_type & ACTION_SINGLE) == 0 || msg_list_len == 1))
844                 children->open_in = 1;
845
846         if (action_type & ACTION_SINGLE) {
847                 GSList *cur;
848
849                 for (cur = msg_list; cur && is_ok == TRUE; cur = cur->next) {
850                         msginfo = (MsgInfo *)cur->data;
851                         if (!msginfo) {
852                                 is_ok  = FALSE; /* ERR: msginfo missing */
853                                 break;
854                         }
855                         cmd = parse_action_cmd(action, msginfo, msg_list,
856                                                partinfo, user_str,
857                                                user_hidden_str, sel_str);
858                         if (!cmd) {
859                                 debug_print("Action command error\n");
860                                 is_ok  = FALSE; /* ERR: incorrect command */
861                                 break;
862                         }
863                         if ((child_info = fork_child(cmd, msg_str, children))) {
864                                 /* Pass msginfo to catch_status () */
865                                 if (!(action_type & (ACTION_PIPE_OUT | ACTION_INSERT)))
866                                         child_info->msginfo_list = 
867                                                 g_slist_append (NULL, msginfo);
868                                 children_list = g_slist_append(children_list,
869                                                                child_info);
870                         }
871                         g_free(cmd);
872                 }
873         } else {
874                 cmd = parse_action_cmd(action, NULL, msg_list, partinfo,
875                                        user_str, user_hidden_str, sel_str);
876                 if (cmd) {
877                         if ((child_info = fork_child(cmd, msg_str, children))) {
878                                 if (!(action_type & (ACTION_PIPE_OUT | ACTION_INSERT)))
879                                         child_info->msginfo_list = 
880                                                 g_slist_copy (msg_list);
881                                 children_list = g_slist_append(children_list,
882                                                                 child_info);
883                         }
884                         g_free(cmd);
885                 } else
886                         is_ok  = FALSE;         /* ERR: incorrect command */
887         }
888
889         g_free(msg_str);
890         g_free(sel_str);
891         g_free(user_str);
892         g_free(user_hidden_str);
893
894         if (!children_list) {
895                  /* If not waiting for children, return */
896                 free_children(children);
897         } else {
898                 GSList *cur;
899
900                 children->list        = children_list;
901                 children->nb          = g_slist_length(children_list);
902                 children->initial_nb  = children->nb;
903
904                 for (cur = children_list; cur; cur = cur->next) {
905                         child_info = (ChildInfo *) cur->data;
906                         child_info->callback = callback;
907                         child_info->data = data;
908                         child_info->tag_status = 
909                                 claws_input_add(child_info->chld_status,
910                                               G_IO_IN | G_IO_HUP | G_IO_ERR,
911                                               catch_status, child_info,
912                                               FALSE);
913                 }
914
915                 create_io_dialog(children);
916         }
917         return is_ok;
918 }
919
920 static ChildInfo *fork_child(gchar *cmd, const gchar *msg_str,
921                              Children *children)
922 {
923 #ifdef G_OS_UNIX
924         gint chld_in[2], chld_out[2], chld_err[2], chld_status[2];
925         gchar *cmdline[4], *ret_str;
926         pid_t pid, gch_pid;
927         ChildInfo *child_info;
928         gint sync;
929         gssize by_written = 0, by_read = 0;
930
931         sync = !(children->action_type & ACTION_ASYNC);
932
933         chld_in[0] = chld_in[1] = chld_out[0] = chld_out[1] = chld_err[0]
934                 = chld_err[1] = chld_status[0] = chld_status[1] = -1;
935
936         if (sync) {
937                 if (pipe(chld_status) || pipe(chld_in) || pipe(chld_out) ||
938                     pipe(chld_err)) {
939                         alertpanel_error(_("Command could not be started. "
940                                            "Pipe creation failed.\n%s"),
941                                         g_strerror(errno));
942                         /* Closing fd = -1 fails silently */
943                         (void)close(chld_in[0]);
944                         (void)close(chld_in[1]);
945                         (void)close(chld_out[0]);
946                         (void)close(chld_out[1]);
947                         (void)close(chld_err[0]);
948                         (void)close(chld_err[1]);
949                         (void)close(chld_status[0]);
950                         (void)close(chld_status[1]);
951                         return NULL; /* Pipe error */
952                 }
953         }
954
955         debug_print("Forking child and grandchild.\n");
956         debug_print("Executing: /bin/sh -c %s\n", cmd);
957
958         pid = fork();
959         if (pid == 0) { /* Child */
960                 int r = 0;
961                 if (setpgid(0, 0))
962                         perror("setpgid");
963
964                 gch_pid = fork();
965
966                 if (gch_pid == 0) {
967                         if (setpgid(0, getppid()))
968                                 perror("setpgid");
969
970                         if (sync) {
971                                 if (children->action_type &
972                                     (ACTION_PIPE_IN |
973                                      ACTION_USER_IN |
974                                      ACTION_USER_HIDDEN_IN)) {
975                                         r |= close(fileno(stdin));
976                                         if (dup(chld_in[0]) < 0)
977                                                 r = -1;
978                                 }
979                                 r |= close(chld_in[0]);
980                                 r |= close(chld_in[1]);
981
982                                 r |= close(fileno(stdout));
983                                 if (dup(chld_out[1]) < 0)
984                                         r = -1;
985
986                                 r |= close(chld_out[0]);
987                                 r |= close(chld_out[1]);
988
989                                 r |= close(fileno(stderr));
990                                 if (dup(chld_err[1]) < 0)
991                                         r = -1;
992
993                                 r |= close(chld_err[0]);
994                                 r |= close(chld_err[1]);
995
996                                 if (r != 0)
997                                         debug_print("%s(%d)", strerror(errno), errno);
998                         }
999
1000                         cmdline[0] = "sh";
1001                         cmdline[1] = "-c";
1002                         ret_str = g_locale_from_utf8(cmd, strlen(cmd),
1003                                                      &by_read, &by_written,
1004                                                      NULL);
1005                         if (ret_str && by_written)
1006                                 cmdline[2] = ret_str;
1007                         else
1008                                 cmdline[2] = cmd;
1009                         cmdline[3] = NULL;
1010                         execvp("/bin/sh", cmdline);
1011
1012                         perror("execvp");
1013                         g_free(ret_str);
1014                         _exit(1);
1015                 } else if (gch_pid < (pid_t) 0) { /* Fork error */
1016                         if (sync)
1017                                 r = write(chld_status[1], "1\n", 2);
1018                         if (r != 0)
1019                                 debug_print("%s(%d)", strerror(errno), errno);
1020                         perror("fork");
1021                         _exit(1);
1022                 } else { /* Child */
1023                         if (sync) {
1024                                 r |= close(chld_in[0]);
1025                                 r |= close(chld_in[1]);
1026                                 r |= close(chld_out[0]);
1027                                 r |= close(chld_out[1]);
1028                                 r |= close(chld_err[0]);
1029                                 r |= close(chld_err[1]);
1030                                 r |= close(chld_status[0]);
1031
1032                                 debug_print("Child: waiting for grandchild\n");
1033                                 r |= waitpid(gch_pid, NULL, 0);
1034                                 debug_print("Child: grandchild ended\n");
1035                                 r |= write(chld_status[1], "0\n", 2);
1036                                 r |= close(chld_status[1]);
1037
1038                                 if (r != 0)
1039                                         debug_print("%s(%d)", strerror(errno), errno);
1040                         }
1041                         _exit(0);
1042                 }
1043         } else if (pid < 0) { /* Fork error */
1044                 alertpanel_error(_("Could not fork to execute the following "
1045                                    "command:\n%s\n%s"),
1046                                  cmd, g_strerror(errno));
1047                 return NULL; 
1048         }
1049
1050         /* Parent */
1051
1052         if (!sync) {
1053                 waitpid(pid, NULL, 0);
1054                 return NULL;
1055         }
1056
1057         (void)close(chld_in[0]);
1058         if (!(children->action_type &
1059               (ACTION_PIPE_IN | ACTION_USER_IN | ACTION_USER_HIDDEN_IN)))
1060                 (void)close(chld_in[1]);
1061         (void)close(chld_out[1]);
1062         (void)close(chld_err[1]);
1063         (void)close(chld_status[1]);
1064
1065         child_info = g_new0(ChildInfo, 1);
1066
1067         child_info->children    = children;
1068
1069         child_info->pid         = pid;
1070         child_info->next_sig    = SIGTERM;
1071         child_info->cmd         = g_strdup(cmd);
1072         child_info->new_out     = FALSE;
1073         child_info->output      = g_string_new(NULL);
1074         child_info->chld_in     =
1075                 (children->action_type &
1076                  (ACTION_PIPE_IN | ACTION_USER_IN | ACTION_USER_HIDDEN_IN))
1077                         ? chld_in [1] : -1;
1078         child_info->chld_out    = chld_out[0];
1079         child_info->chld_err    = chld_err[0];
1080         child_info->chld_status = chld_status[0];
1081         child_info->tag_in      = -1;
1082         child_info->tag_out     = claws_input_add(chld_out[0], G_IO_IN | G_IO_HUP | G_IO_ERR,
1083                                                 catch_output, child_info, FALSE);
1084         child_info->tag_err     = claws_input_add(chld_err[0], G_IO_IN | G_IO_HUP | G_IO_ERR,
1085                                                 catch_output, child_info, FALSE);
1086
1087         if (!(children->action_type &
1088               (ACTION_PIPE_IN | ACTION_PIPE_OUT | ACTION_INSERT)))
1089                 return child_info;
1090
1091         if ((children->action_type & ACTION_PIPE_IN) && msg_str) {
1092                 int r;
1093                 ret_str = g_locale_from_utf8(msg_str, strlen(msg_str),
1094                                              &by_read, &by_written, NULL);
1095                 if (ret_str && by_written) {
1096                         r = write(chld_in[1], ret_str, strlen(ret_str));
1097                         g_free(ret_str);
1098                 } else
1099                         r = write(chld_in[1], msg_str, strlen(msg_str));
1100                 if (!(children->action_type &
1101                       (ACTION_USER_IN | ACTION_USER_HIDDEN_IN)))
1102                         r = close(chld_in[1]);
1103                 child_info->chld_in = -1; /* No more input */
1104                 if (r != 0)
1105                         debug_print("%s(%d)", strerror(errno), errno);
1106         }
1107
1108         return child_info;
1109 #else
1110         return NULL;
1111 #endif /* G_OS_UNIX */
1112 }
1113
1114 static void kill_children_cb(GtkWidget *widget, gpointer data)
1115 {
1116 #ifdef G_OS_UNIX
1117         GSList *cur;
1118         Children *children = (Children *) data;
1119         ChildInfo *child_info;
1120
1121         for (cur = children->list; cur; cur = cur->next) {
1122                 child_info = (ChildInfo *)(cur->data);
1123                 debug_print("Killing child group id %d\n", child_info->pid);
1124                 if (child_info->pid && kill(-child_info->pid, child_info->next_sig) < 0)
1125                         perror("kill");
1126                 child_info->next_sig = SIGKILL;
1127         }
1128 #endif /* G_OS_UNIX */
1129 }
1130
1131 static gint wait_for_children(Children *children)
1132 {
1133         gboolean new_output;
1134         ChildInfo *child_info;
1135         GSList *cur;
1136
1137         cur = children->list;
1138         new_output = FALSE;
1139         while (cur) {
1140                 child_info = (ChildInfo *)cur->data;
1141                 new_output |= child_info->new_out;
1142                 cur = cur->next;
1143         }
1144
1145         children->output |= new_output;
1146
1147         if (new_output || (children->dialog && (children->initial_nb != children->nb)))
1148                 update_io_dialog(children);
1149
1150         if (children->nb)
1151                 return FALSE;
1152
1153         if (!children->dialog) {
1154                 free_children(children);
1155         } else if (!children->output) {
1156                 gtk_widget_destroy(children->dialog);
1157         }
1158
1159         return FALSE;
1160 }
1161
1162 static void send_input(GtkWidget *w, gpointer data)
1163 {
1164         Children *children = (Children *) data;
1165         ChildInfo *child_info = (ChildInfo *) children->list->data;
1166
1167         child_info->tag_in = claws_input_add(child_info->chld_in,
1168                                            G_IO_OUT | G_IO_ERR,
1169                                            catch_input, children, FALSE);
1170 }
1171
1172 static gint delete_io_dialog_cb(GtkWidget *w, GdkEvent *e, gpointer data)
1173 {
1174         hide_io_dialog_cb(w, data);
1175         return TRUE;
1176 }
1177
1178 static void hide_io_dialog_cb(GtkWidget *w, gpointer data)
1179 {
1180
1181         Children *children = (Children *)data;
1182
1183         if (!children->nb) {
1184                 g_signal_handlers_disconnect_matched
1185                         (G_OBJECT(children->dialog), G_SIGNAL_MATCH_DATA,
1186                          0, 0, NULL, NULL, children);
1187                 gtk_widget_destroy(children->dialog);
1188                 free_children(children);
1189         }
1190 }
1191
1192 static gint io_dialog_key_pressed_cb(GtkWidget *widget, GdkEventKey *event,
1193                                      gpointer data)
1194 {
1195         if (event && (event->keyval == GDK_KEY_Escape ||
1196                       event->keyval == GDK_KEY_Return ||
1197                           event->keyval == GDK_KEY_KP_Enter))
1198                 hide_io_dialog_cb(widget, data);
1199         return TRUE;
1200 }
1201
1202 static void childinfo_close_pipes(ChildInfo *child_info)
1203 {
1204         /* stdout and stderr pipes are guaranteed to be removed by
1205          * their handler, but in case where we receive child exit notification
1206          * before grand-child's pipes closing signals, we check them and close
1207          * them if necessary
1208          */
1209         if (child_info->tag_in > 0)
1210                 g_source_remove(child_info->tag_in);
1211         if (child_info->tag_out > 0)
1212                 g_source_remove(child_info->tag_out);
1213         if (child_info->tag_err > 0)
1214                 g_source_remove(child_info->tag_err);
1215
1216         if (child_info->chld_in >= 0)
1217                 (void)close(child_info->chld_in);
1218         if (child_info->chld_out >= 0)
1219                 (void)close(child_info->chld_out);
1220         if (child_info->chld_err >= 0)
1221                 (void)close(child_info->chld_err);
1222
1223         (void)close(child_info->chld_status);
1224 }
1225
1226 static void free_children(Children *children)
1227 {
1228         ChildInfo *child_info;
1229         void (*callback)(void *data) = NULL;
1230         void *data = NULL;
1231
1232         debug_print("Freeing children data %p\n", children);
1233
1234         g_free(children->action);
1235         while (children->list != NULL) {
1236                 child_info = (ChildInfo *)children->list->data;
1237                 g_free(child_info->cmd);
1238                 g_string_free(child_info->output, TRUE);
1239                 children->list = g_slist_remove(children->list, child_info);
1240                 callback = child_info->callback;
1241                 data = child_info->data;
1242                 g_free(child_info);
1243         }
1244
1245         if (callback)
1246                 callback(data);
1247         
1248         g_free(children);
1249 }
1250
1251 static void update_io_dialog(Children *children)
1252 {
1253         GSList *cur;
1254
1255         debug_print("Updating actions input/output dialog.\n");
1256
1257         if (children->progress_bar) {
1258                 gchar *text;
1259 #ifdef GENERIC_UMPC
1260                 /* use a more compact format */
1261                 const gchar *format = "%s %d/%d";
1262 #else
1263                 const gchar *format = "%s %d / %d";
1264 #endif
1265                 
1266                 gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(children->progress_bar),
1267                                                   (children->initial_nb == 0) ? 0 :
1268                                               (gdouble) (children->initial_nb - children->nb) /
1269                                               (gdouble) children->initial_nb);
1270                 text = g_strdup_printf(format, _("Completed"), 
1271                                        children->initial_nb - children->nb,
1272                                        children->initial_nb);
1273                 gtk_progress_bar_set_text(GTK_PROGRESS_BAR(children->progress_bar), text);
1274                 g_free(text);
1275         }
1276
1277         if (!children->nb) {
1278                 gtk_widget_set_sensitive(children->abort_btn, FALSE);
1279                 gtk_widget_set_sensitive(children->close_btn, TRUE);
1280                 if (children->input_hbox)
1281                         gtk_widget_set_sensitive(children->input_hbox, FALSE);
1282                 gtk_widget_grab_focus(children->close_btn);
1283                 g_signal_connect(G_OBJECT(children->dialog),
1284                                  "key_press_event",
1285                                  G_CALLBACK(io_dialog_key_pressed_cb),
1286                                  children);
1287         }
1288
1289         if (children->output) {
1290                 GtkWidget *text = children->text;
1291                 GtkTextBuffer *textbuf;
1292                 GtkTextIter iter, start_iter, end_iter;
1293                 gchar *caption;
1294                 ChildInfo *child_info;
1295
1296                 gtk_widget_show(children->scrolledwin);
1297                 textbuf = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
1298                 gtk_text_buffer_get_bounds(textbuf, &start_iter, &end_iter);
1299                 gtk_text_buffer_delete(textbuf, &start_iter, &end_iter);
1300                 gtk_text_buffer_get_start_iter(textbuf, &iter);
1301
1302                 for (cur = children->list; cur; cur = cur->next) {
1303                         child_info = (ChildInfo *)cur->data;
1304                         if (child_info->pid)
1305                                 caption = g_strdup_printf
1306                                         (_("--- Running: %s\n"),
1307                                          child_info->cmd);
1308                         else
1309                                 caption = g_strdup_printf
1310                                         (_("--- Ended: %s\n"),
1311                                          child_info->cmd);
1312
1313                         gtk_text_buffer_insert(textbuf, &iter, caption, -1);
1314                         gtk_text_buffer_insert(textbuf, &iter,
1315                                                child_info->output->str, -1);
1316                         g_free(caption);
1317                         child_info->new_out = FALSE;
1318                 }
1319         }
1320 }
1321
1322 static void create_io_dialog(Children *children)
1323 {
1324         GtkWidget *dialog;
1325         GtkWidget *vbox;
1326         GtkWidget *entry = NULL;
1327         GtkWidget *input_hbox = NULL;
1328         GtkWidget *send_button;
1329         GtkWidget *label;
1330         GtkWidget *text;
1331         GtkWidget *scrolledwin;
1332         GtkWidget *hbox;
1333         GtkWidget *progress_bar = NULL;
1334         GtkWidget *abort_button;
1335         GtkWidget *close_button;
1336
1337         debug_print("Creating action IO dialog\n");
1338
1339         dialog = gtk_dialog_new();
1340         gtk_container_set_border_width
1341                 (GTK_CONTAINER(gtk_dialog_get_action_area(GTK_DIALOG(dialog))), 5);
1342         gtk_window_set_position(GTK_WINDOW(dialog), GTK_WIN_POS_CENTER);
1343         gtk_window_set_title(GTK_WINDOW(dialog), _("Action's input/output"));
1344         gtk_window_set_modal(GTK_WINDOW(dialog), TRUE);
1345         manage_window_set_transient(GTK_WINDOW(dialog));
1346         g_signal_connect(G_OBJECT(dialog), "delete_event",
1347                          G_CALLBACK(delete_io_dialog_cb), children);
1348         g_signal_connect(G_OBJECT(dialog), "destroy",
1349                          G_CALLBACK(hide_io_dialog_cb),
1350                          children);
1351
1352         vbox = gtk_vbox_new(FALSE, 8);
1353         gtk_container_add(GTK_CONTAINER(
1354                                 gtk_dialog_get_content_area(GTK_DIALOG(dialog))), vbox);
1355         gtk_container_set_border_width(GTK_CONTAINER(vbox), 8);
1356         gtk_widget_show(vbox);
1357
1358         label = gtk_label_new(children->action);
1359         gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 0);
1360         gtk_widget_show(label);
1361
1362         scrolledwin = gtk_scrolled_window_new(NULL, NULL);
1363         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledwin),
1364                                        GTK_POLICY_AUTOMATIC,
1365                                        GTK_POLICY_AUTOMATIC);
1366         gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scrolledwin),
1367                                             GTK_SHADOW_IN);
1368         gtk_box_pack_start(GTK_BOX(vbox), scrolledwin, TRUE, TRUE, 0);
1369         gtk_widget_set_size_request(scrolledwin, 560, 200);
1370         gtk_widget_hide(scrolledwin);
1371
1372         text = gtk_text_view_new();
1373
1374         if (prefs_common.textfont) {
1375                 PangoFontDescription *font_desc;
1376                 font_desc = pango_font_description_from_string
1377                         (prefs_common.textfont);
1378                 if (font_desc) {
1379                         gtk_widget_modify_font(text, font_desc);
1380                         pango_font_description_free(font_desc);
1381                 }
1382         }
1383
1384         gtk_text_view_set_editable(GTK_TEXT_VIEW(text), FALSE);
1385         gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(text), GTK_WRAP_WORD);
1386         gtk_text_view_set_left_margin(GTK_TEXT_VIEW(text), 6);
1387         gtk_text_view_set_right_margin(GTK_TEXT_VIEW(text), 6);
1388         gtk_container_add(GTK_CONTAINER(scrolledwin), text);
1389         gtk_widget_show(text);
1390
1391         if (children->open_in) {
1392                 input_hbox = gtk_hbox_new(FALSE, 8);
1393                 gtk_widget_show(input_hbox);
1394
1395                 entry = gtk_entry_new();
1396                 gtk_widget_set_size_request(entry, 320, -1);
1397                 g_signal_connect(G_OBJECT(entry), "activate",
1398                                  G_CALLBACK(send_input), children);
1399                 gtk_box_pack_start(GTK_BOX(input_hbox), entry, TRUE, TRUE, 0);
1400                 if (children->action_type & ACTION_USER_HIDDEN_IN) {
1401                         gtk_entry_set_visibility(GTK_ENTRY(entry), FALSE);
1402 #ifdef MAEMO
1403                         hildon_gtk_entry_set_input_mode(GTK_ENTRY(entry), 
1404                                 HILDON_GTK_INPUT_MODE_FULL | 
1405                                 HILDON_GTK_INPUT_MODE_INVISIBLE);
1406 #endif
1407                 }
1408                 gtk_widget_show(entry);
1409
1410                 send_button = gtk_button_new_from_stock(GTK_STOCK_EXECUTE);
1411                 g_signal_connect(G_OBJECT(send_button), "clicked",
1412                                  G_CALLBACK(send_input), children);
1413                 gtk_box_pack_start(GTK_BOX(input_hbox), send_button, FALSE,
1414                                    FALSE, 0);
1415                 gtk_widget_show(send_button);
1416
1417                 gtk_box_pack_start(GTK_BOX(vbox), input_hbox, FALSE, FALSE, 0);
1418                 gtk_widget_grab_focus(entry);
1419         }
1420
1421         if (children->initial_nb > 1) {
1422                 gchar *text;
1423 #ifdef GENERIC_UMPC
1424                 /* use a more compact format */
1425                 const gchar *format = "%s 0/%d\n";
1426 #else
1427                 const gchar *format = "%s 0 / %d\n";
1428 #endif
1429                 
1430                 progress_bar = gtk_progress_bar_new();
1431 #if !GTK_CHECK_VERSION(3, 0, 0)
1432                 gtk_progress_bar_set_orientation(GTK_PROGRESS_BAR(progress_bar),
1433                                 GTK_PROGRESS_LEFT_TO_RIGHT);
1434 #else
1435                 gtk_orientable_set_orientation(GTK_ORIENTABLE(progress_bar),
1436                                 GTK_ORIENTATION_HORIZONTAL);
1437                 gtk_progress_bar_set_inverted(GTK_PROGRESS_BAR(progress_bar),
1438                                 FALSE);
1439 #endif
1440                 text = g_strdup_printf(format, _("Completed"), 
1441                                        children->initial_nb);
1442                 gtk_progress_bar_set_text(GTK_PROGRESS_BAR(progress_bar),
1443                                           text);
1444                 g_free(text);
1445                 gtk_box_pack_start(GTK_BOX(vbox), progress_bar, FALSE, FALSE, 0);
1446                 gtk_widget_show(progress_bar);
1447         }
1448
1449         gtkut_stock_button_set_create(&hbox, &abort_button, GTK_STOCK_STOP,
1450                                       &close_button, GTK_STOCK_CLOSE, NULL, NULL);
1451         g_signal_connect(G_OBJECT(abort_button), "clicked",
1452                          G_CALLBACK(kill_children_cb), children);
1453         g_signal_connect(G_OBJECT(close_button), "clicked",
1454                          G_CALLBACK(hide_io_dialog_cb), children);
1455         gtk_widget_show(hbox);
1456
1457         if (children->nb)
1458                 gtk_widget_set_sensitive(close_button, FALSE);
1459
1460         gtk_container_add(GTK_CONTAINER(
1461                         gtk_dialog_get_action_area(GTK_DIALOG(dialog))), hbox);
1462
1463         children->dialog       = dialog;
1464         children->scrolledwin  = scrolledwin;
1465         children->text         = text;
1466         children->input_hbox   = children->open_in ? input_hbox : NULL;
1467         children->input_entry  = children->open_in ? entry : NULL;
1468         children->progress_bar = progress_bar;
1469         children->abort_btn    = abort_button;
1470         children->close_btn    = close_button;
1471
1472         gtk_widget_show(dialog);
1473 }
1474
1475 static void catch_status(gpointer data, gint source, GIOCondition cond)
1476 {
1477         ChildInfo *child_info = (ChildInfo *)data;
1478         gchar buf;
1479         gint c;
1480
1481         g_source_remove(child_info->tag_status);
1482
1483         c = read(source, &buf, 1);
1484         if (c != 1) {
1485                 g_message("error reading child return status\n");
1486         }
1487         debug_print("Child returned %c\n", buf);
1488
1489 #ifdef G_OS_UNIX
1490         waitpid(-child_info->pid, NULL, 0);
1491 #endif
1492         childinfo_close_pipes(child_info);
1493         child_info->pid = 0;
1494
1495         if (child_info->children->action_type & (ACTION_SINGLE | ACTION_MULTIPLE)
1496             && child_info->msginfo_list) {
1497                 /* Actions on message *files* might change size and
1498                 * time stamp, and thus invalidate the cache */
1499                 SummaryView *summaryview  = NULL;
1500                 GSList      *cur;
1501                 MsgInfo     *msginfo, *nmi;     /* newmsginfo */
1502                 char        *file;
1503                 gboolean     modified_something = FALSE;
1504                 FolderItem  *last_item = NULL;
1505                 if (mainwindow_get_mainwindow ())
1506                         summaryview = mainwindow_get_mainwindow ()->summaryview;
1507                 for (cur = child_info->msginfo_list; cur; cur = cur->next) {
1508                         msginfo = (MsgInfo *)cur->data;
1509                         if (!(msginfo && /* Stuff used valid? */
1510                             msginfo->folder && msginfo->folder->cache)) 
1511                                 continue;
1512                         file = procmsg_get_message_file_path (msginfo);
1513                         if (!file) 
1514                                 continue;
1515                         nmi = procheader_parse_file (file, msginfo->flags, TRUE, FALSE);
1516                         if (!nmi) 
1517                                 continue; /* Deleted? */
1518                         if (msginfo->mtime != nmi->mtime || msginfo->size != nmi->size) {
1519                                 nmi->folder = msginfo->folder;
1520                                 nmi->msgnum = msginfo->msgnum;
1521                                 msgcache_update_msg (msginfo->folder->cache, nmi);
1522                                 modified_something = TRUE;
1523                                 last_item = nmi->folder;
1524                         }
1525                         procmsg_msginfo_free (nmi);
1526                         if (summaryview && summaryview->displayed &&
1527                             summaryview->folder_item == msginfo->folder &&
1528                             summary_get_msgnum(summaryview, summaryview->displayed) == msginfo->msgnum)
1529                                 summary_redisplay_msg(summaryview);
1530                                         
1531                 }
1532                 if (modified_something && last_item && 
1533                     summaryview && summaryview->folder_item == last_item) {
1534                         summary_show (summaryview, summaryview->folder_item);
1535                 }
1536                 g_slist_free (child_info->msginfo_list);
1537                 child_info->msginfo_list = NULL;
1538         }
1539
1540         if (!child_info->pid)
1541                 child_info->children->nb--;
1542
1543         wait_for_children(child_info->children);
1544 }
1545         
1546 static void catch_input(gpointer data, gint source, GIOCondition cond)
1547 {
1548         Children *children = (Children *)data;
1549         ChildInfo *child_info = (ChildInfo *)children->list->data;
1550         gchar *input, *ret_str;
1551         gint c, count, len, r;
1552         gssize by_read = 0, by_written = 0;
1553
1554         debug_print("Sending input to grand child.\n");
1555         if (!(cond & (G_IO_OUT | G_IO_ERR)))
1556                 return;
1557
1558         gtk_widget_set_sensitive(children->input_hbox, FALSE);
1559         gtk_widget_grab_focus(children->abort_btn);
1560
1561         g_source_remove(child_info->tag_in);
1562         child_info->tag_in = -1;
1563
1564         input = gtk_editable_get_chars(GTK_EDITABLE(children->input_entry),
1565                                        0, -1);
1566         ret_str = g_locale_from_utf8(input, strlen(input), &by_read,
1567                                      &by_written, NULL);
1568         if (ret_str && by_written) {
1569                 g_free(input);
1570                 input = ret_str;
1571         }
1572
1573         len = strlen(input);
1574         count = 0;
1575
1576         do {
1577                 c = write(child_info->chld_in, input + count, len - count);
1578                 if (c >= 0)
1579                         count += c;
1580         } while (c >= 0 && count < len);
1581
1582         if (c >= 0)
1583                 r = write(child_info->chld_in, "\n", 2);
1584
1585         g_free(input);
1586
1587         r = close(child_info->chld_in);
1588         if (r != 0)
1589                 debug_print("%s(%d)", strerror(errno), errno);
1590         child_info->chld_in = -1;
1591         debug_print("Input to grand child sent.\n");
1592 }
1593
1594 static void catch_output(gpointer data, gint source, GIOCondition cond)
1595 {
1596         ChildInfo *child_info = (ChildInfo *)data;
1597         gint c;
1598         gchar buf[BUFFSIZE];
1599
1600         debug_print("Catching grand child's output.\n");
1601         if (child_info->children->action_type &
1602             (ACTION_PIPE_OUT | ACTION_INSERT)
1603             && source == child_info->chld_out) {
1604                 GtkTextView *text =
1605                         GTK_TEXT_VIEW(child_info->children->msg_text);
1606                 GtkTextBuffer *textbuf = gtk_text_view_get_buffer(text);
1607                 GtkTextIter iter;
1608                 GtkTextMark *mark;
1609                 gint ins_pos;
1610
1611                 mark = gtk_text_buffer_get_insert(textbuf);
1612                 gtk_text_buffer_get_iter_at_mark(textbuf, &iter, mark);
1613                 ins_pos = gtk_text_iter_get_offset(&iter);
1614
1615                 while (TRUE) {
1616                         gsize bytes_read = 0, bytes_written = 0;
1617                         gchar *ret_str;
1618
1619                         c = read(source, buf, sizeof(buf) - 1);
1620                         if (c == 0)
1621                                 break;
1622
1623                         ret_str = g_locale_to_utf8
1624                                 (buf, c, &bytes_read, &bytes_written, NULL);
1625                         if (ret_str && bytes_written > 0) {
1626                                 gtk_text_buffer_insert
1627                                         (textbuf, &iter, ret_str,
1628                                          -1);
1629                                 g_free(ret_str);
1630                         } else
1631                                 gtk_text_buffer_insert(textbuf, &iter, buf, c);
1632                 }
1633
1634                 if (child_info->children->is_selection) {
1635                         GtkTextIter ins;
1636
1637                         gtk_text_buffer_get_iter_at_offset
1638                                 (textbuf, &ins, ins_pos);
1639                         gtk_text_buffer_select_range(textbuf, &ins, &iter);
1640                 }
1641         } else {
1642                 c = read(source, buf, sizeof(buf) - 1);
1643                 if (c > 0) {
1644                         gsize bytes_read = 0, bytes_written = 0;
1645                         gchar *ret_str;
1646
1647                         ret_str = g_locale_to_utf8
1648                                 (buf, c, &bytes_read, &bytes_written, NULL);
1649                         if (ret_str && bytes_written > 0) {
1650                                 g_string_append_len
1651                                         (child_info->output, ret_str,
1652                                          bytes_written);
1653                                 g_free(ret_str);
1654                         } else
1655                                 g_string_append_len(child_info->output, buf, c);
1656
1657                         child_info->new_out = TRUE;
1658                 }
1659         }
1660         if (c == 0) {
1661                 if (source == child_info->chld_out) {
1662                         g_source_remove(child_info->tag_out);
1663                         child_info->tag_out = -1;
1664                         (void)close(child_info->chld_out);
1665                         child_info->chld_out = -1;
1666                 } else {
1667                         g_source_remove(child_info->tag_err);
1668                         child_info->tag_err = -1;
1669                         (void)close(child_info->chld_err);
1670                         child_info->chld_err = -1;
1671                 }
1672         }
1673         
1674         wait_for_children(child_info->children);
1675 }
1676
1677 static gchar *get_user_string(const gchar *action, ActionType type)
1678 {
1679         gchar *message;
1680         gchar *user_str = NULL;
1681
1682         switch (type) {
1683         case ACTION_USER_HIDDEN_STR:
1684                 message = g_strdup_printf
1685                         (_("Enter the argument for the following action:\n"
1686                            "('%%h' will be replaced with the argument)\n"
1687                            "  %s"),
1688                          action);
1689                 user_str = input_dialog_with_invisible
1690                         (_("Action's hidden user argument"), message, NULL);
1691                 break;
1692         case ACTION_USER_STR:
1693                 message = g_strdup_printf
1694                         (_("Enter the argument for the following action:\n"
1695                            "('%%u' will be replaced with the argument)\n"
1696                            "  %s"),
1697                          action);
1698                 user_str = input_dialog
1699                         (_("Action's user argument"), message, NULL);
1700                 break;
1701         default:
1702                 g_warning("Unsupported action type %d", type);
1703         }
1704
1705         return user_str;
1706 }